@promptci/cli 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.cjs +143 -134
  2. package/package.json +1 -1
package/dist/cli.cjs CHANGED
@@ -1,134 +1,143 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var hy=Object.create;var hl=Object.defineProperty;var my=Object.getOwnPropertyDescriptor;var gy=Object.getOwnPropertyNames;var yy=Object.getPrototypeOf,by=Object.prototype.hasOwnProperty;var T=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var wy=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of gy(e))!by.call(t,i)&&i!==n&&hl(t,i,{get:()=>e[i],enumerable:!(s=my(e,i))||s.enumerable});return t};var R=(t,e,n)=>(n=t!=null?hy(yy(t)):{},wy(e||!t||!t.__esModule?hl(n,"default",{value:t,enumerable:!0}):n,t));var _l=T(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.splitWhen=ln.flatten=void 0;function Sy(t){return t.reduce((e,n)=>[].concat(e,n),[])}ln.flatten=Sy;function Ey(t,e){let n=[[]],s=0;for(let i of t)e(i)?(s++,n[s]=[]):n[s].push(i);return n}ln.splitWhen=Ey});var Sl=T(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});Fs.isEnoentCodeError=void 0;function ky(t){return t.code==="ENOENT"}Fs.isEnoentCodeError=ky});var El=T(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.createDirentFromStats=void 0;var pr=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 Ry(t,e){return new pr(t,e)}Hs.createDirentFromStats=Ry});var Al=T(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.convertPosixPathToPattern=se.convertWindowsPathToPattern=se.convertPathToPattern=se.escapePosixPath=se.escapeWindowsPath=se.escape=se.removeLeadingDotSegment=se.makeAbsolute=se.unixify=void 0;var Cy=require("os"),Ay=require("path"),kl=Cy.platform()==="win32",$y=2,Py=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,Ty=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,Iy=/^\\\\([.?])/,Oy=/\\(?![!()+@[\]{}])/g;function Ly(t){return t.replace(/\\/g,"/")}se.unixify=Ly;function Ny(t,e){return Ay.resolve(t,e)}se.makeAbsolute=Ny;function jy(t){if(t.charAt(0)==="."){let e=t.charAt(1);if(e==="/"||e==="\\")return t.slice($y)}return t}se.removeLeadingDotSegment=jy;se.escape=kl?hr:mr;function hr(t){return t.replace(Ty,"\\$2")}se.escapeWindowsPath=hr;function mr(t){return t.replace(Py,"\\$2")}se.escapePosixPath=mr;se.convertPathToPattern=kl?Rl:Cl;function Rl(t){return hr(t).replace(Iy,"//$1").replace(Oy,"/")}se.convertWindowsPathToPattern=Rl;function Cl(t){return mr(t)}se.convertPosixPathToPattern=Cl});var Pl=T((CT,$l)=>{$l.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 Ol=T((AT,Il)=>{var My=Pl(),Tl={"{":"}","(":")","[":"]"},Dy=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=Tl[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=Tl[n];if(s){var i=t.indexOf(s,e);i!==-1&&(e=i+1)}if(t[e]==="!")return!0}else e++}return!1};Il.exports=function(e,n){if(typeof e!="string"||e==="")return!1;if(My(e))return!0;var s=Dy;return n&&n.strict===!1&&(s=Fy),s(e)}});var Nl=T(($T,Ll)=>{"use strict";var Hy=Ol(),By=require("path").posix.dirname,Wy=require("os").platform()==="win32",gr="/",Gy=/\\/g,Uy=/[\{\[].*[\}\]]$/,Vy=/(^|[^\\])([\{\[]|\([^\)]+$)/,zy=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Ll.exports=function(e,n){var s=Object.assign({flipBackslashes:!0},n);s.flipBackslashes&&Wy&&e.indexOf(gr)<0&&(e=e.replace(Gy,gr)),Uy.test(e)&&(e+=gr),e+="a";do e=By(e);while(Hy(e)||Vy.test(e));return e.replace(zy,"$1")}});var Bs=T(je=>{"use strict";je.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;je.find=(t,e)=>t.nodes.find(n=>n.type===e);je.exceedsLimit=(t,e,n=1,s)=>s===!1||!je.isInteger(t)||!je.isInteger(e)?!1:(Number(e)-Number(t))/Number(n)>=s;je.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)};je.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;je.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;je.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;je.reduce=t=>t.reduce((e,n)=>(n.type==="text"&&e.push(n.value),n.type==="range"&&(n.type="text"),e),[]);je.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 Ws=T((TT,Ml)=>{"use strict";var jl=Bs();Ml.exports=(t,e={})=>{let n=(s,i={})=>{let r=e.escapeInvalid&&jl.isInvalidBrace(i),o=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(r||o)&&jl.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 Fl=T((IT,Dl)=>{"use strict";Dl.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var Kl=T((OT,ql)=>{"use strict";var Hl=Fl(),Dt=(t,e,n)=>{if(Hl(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(Hl(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(Dt.cache.hasOwnProperty(c))return Dt.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=zl(t)||zl(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=Bl(m,Math.abs(l),d,s),l=d.a=0}return u>=0&&(p=Bl(l,u,d,s)),d.negatives=h,d.positives=p,d.result=qy(h,p,s),s.capture===!0?d.result=`(${d.result})`:s.wrap!==!1&&p.length+h.length>1&&(d.result=`(?:${d.result})`),Dt.cache[c]=d,d.result};function qy(t,e,n){let s=yr(t,e,"-",!1,n)||[],i=yr(e,t,"",!1,n)||[],r=yr(t,e,"-?",!0,n)||[];return s.concat(r).concat(i).join("|")}function Ky(t,e){let n=1,s=1,i=Gl(t,n),r=new Set([e]);for(;t<=i&&i<=e;)r.add(i),n+=1,i=Gl(t,n);for(i=Ul(e+1,s)-1;t<i&&i<=e;)r.add(i),s+=1,i=Ul(e+1,s)-1;return r=[...r],r.sort(Xy),r}function Yy(t,e,n){if(t===e)return{pattern:t,count:[],digits:0};let s=Jy(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+=Zy(c,l,n):o++}return o&&(r+=n.shorthand===!0?"\\d":"[0-9]"),{pattern:r,count:[o],digits:i}}function Bl(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=Yy(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+Vl(a.count),o=l+1;continue}n.isPadded&&(f=Qy(l,n,s)),u.string=f+u.pattern+Vl(u.count),r.push(u),o=l+1,a=u}return r}function yr(t,e,n,s,i){let r=[];for(let o of t){let{string:a}=o;!s&&!Wl(e,"string",a)&&r.push(n+a),s&&Wl(e,"string",a)&&r.push(n+a)}return r}function Jy(t,e){let n=[];for(let s=0;s<t.length;s++)n.push([t[s],e[s]]);return n}function Xy(t,e){return t>e?1:e>t?-1:0}function Wl(t,e,n){return t.some(s=>s[e]===n)}function Gl(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function Ul(t,e){return t-t%Math.pow(10,e)}function Vl(t){let[e=0,n=""]=t;return n||e>1?`{${e+(n?","+n:"")}}`:""}function Zy(t,e,n){return`[${t}${e-t===1?"":"-"}${e}]`}function zl(t){return/^-?(0+)\d/.test(t)}function Qy(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}}`}}Dt.cache={};Dt.clearCache=()=>Dt.cache={};ql.exports=Dt});var vr=T((LT,tu)=>{"use strict";var eb=require("util"),Jl=Kl(),Yl=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),tb=t=>e=>t===!0?Number(e):String(e),br=t=>typeof t=="number"||typeof t=="string"&&t!=="",Mn=t=>Number.isInteger(+t),wr=t=>{let e=`${t}`,n=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++n]==="0";);return n>0},nb=(t,e,n)=>typeof t=="string"||typeof e=="string"?!0:n.stringify===!0,sb=(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},Us=(t,e)=>{let n=t[0]==="-"?"-":"";for(n&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return n?"-"+t:t},ib=(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=>Us(String(a),n)).join("|")),t.negatives.length&&(r=`-(${s}${t.negatives.map(a=>Us(String(a),n)).join("|")})`),i&&r?o=`${i}|${r}`:o=i||r,e.wrap?`(${s}${o})`:o},Xl=(t,e,n,s)=>{if(n)return Jl(t,e,{wrap:!1,...s});let i=String.fromCharCode(t);if(t===e)return i;let r=String.fromCharCode(e);return`[${i}-${r}]`},Zl=(t,e,n)=>{if(Array.isArray(t)){let s=n.wrap===!0,i=n.capture?"":"?:";return s?`(${i}${t.join("|")})`:t.join("|")}return Jl(t,e,n)},Ql=(...t)=>new RangeError("Invalid range arguments: "+eb.inspect(...t)),eu=(t,e,n)=>{if(n.strictRanges===!0)throw Ql([t,e]);return[]},rb=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},ob=(t,e,n=1,s={})=>{let i=Number(t),r=Number(e);if(!Number.isInteger(i)||!Number.isInteger(r)){if(s.strictRanges===!0)throw Ql([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=wr(a)||wr(c)||wr(l),f=u?Math.max(a.length,c.length,l.length):0,d=u===!1&&nb(t,e,s)===!1,p=s.transform||tb(d);if(s.toRegex&&n===1)return Xl(Us(t,f),Us(e,f),!0,s);let h={negatives:[],positives:[]},m=b=>h[b<0?"negatives":"positives"].push(Math.abs(b)),g=[],y=0;for(;o?i>=r:i<=r;)s.toRegex===!0&&n>1?m(i):g.push(sb(p(i,y),f,d)),i=o?i-n:i+n,y++;return s.toRegex===!0?n>1?ib(h,s,f):Zl(g,null,{wrap:!1,...s}):g},ab=(t,e,n=1,s={})=>{if(!Mn(t)&&t.length>1||!Mn(e)&&e.length>1)return eu(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 Xl(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?Zl(u,null,{wrap:!1,options:s}):u},Gs=(t,e,n,s={})=>{if(e==null&&br(t))return[t];if(!br(t)||!br(e))return eu(t,e,s);if(typeof n=="function")return Gs(t,e,1,{transform:n});if(Yl(n))return Gs(t,e,0,n);let i={...s};return i.capture===!0&&(i.wrap=!0),n=n||i.step||1,Mn(n)?Mn(t)&&Mn(e)?ob(t,e,n,i):ab(t,e,Math.max(Math.abs(n),1),i):n!=null&&!Yl(n)?rb(n,i):Gs(t,e,1,n)};tu.exports=Gs});var iu=T((NT,su)=>{"use strict";var cb=vr(),nu=Bs(),lb=(t,e={})=>{let n=(s,i={})=>{let r=nu.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=nu.reduce(s.nodes),f=cb(...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)};su.exports=lb});var au=T((jT,ou)=>{"use strict";var ub=vr(),ru=Ws(),un=Bs(),Ft=(t="",e="",n=!1)=>{let s=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return n?un.flatten(e).map(i=>`{${i}}`):e;for(let i of t)if(Array.isArray(i))for(let r of i)s.push(Ft(r,e,n));else for(let r of e)n===!0&&typeof r=="string"&&(r=`{${r}}`),s.push(Array.isArray(r)?Ft(i,r,n):i+r);return un.flatten(s)},fb=(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(Ft(a.pop(),ru(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(Ft(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let f=un.reduce(i.nodes);if(un.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=ub(...f,e);d.length===0&&(d=ru(i,e)),a.push(Ft(a.pop(),d)),i.nodes=[];return}let c=un.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(Ft(a.pop(),l,c));continue}if(d.value&&d.type!=="open"){l.push(Ft(l.pop(),d.value));continue}d.nodes&&s(d,i)}return l};return un.flatten(s(t))};ou.exports=fb});var lu=T((MT,cu)=>{"use strict";cu.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 hu=T((DT,pu)=>{"use strict";var db=Ws(),{MAX_LENGTH:uu,CHAR_BACKSLASH:xr,CHAR_BACKTICK:pb,CHAR_COMMA:hb,CHAR_DOT:mb,CHAR_LEFT_PARENTHESES:gb,CHAR_RIGHT_PARENTHESES:yb,CHAR_LEFT_CURLY_BRACE:bb,CHAR_RIGHT_CURLY_BRACE:wb,CHAR_LEFT_SQUARE_BRACKET:fu,CHAR_RIGHT_SQUARE_BRACKET:du,CHAR_DOUBLE_QUOTE:vb,CHAR_SINGLE_QUOTE:xb,CHAR_NO_BREAK_SPACE:_b,CHAR_ZERO_WIDTH_NOBREAK_SPACE:Sb}=lu(),Eb=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let n=e||{},s=typeof n.maxLength=="number"?Math.min(uu,n.maxLength):uu;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===Sb||d===_b)){if(d===xr){h({type:"text",value:(e.keepEscaping?d:"")+p()});continue}if(d===du){h({type:"text",value:"\\"+d});continue}if(d===fu){c++;let m;for(;u<l&&(m=p());){if(d+=m,m===fu){c++;continue}if(m===xr){d+=p();continue}if(m===du&&(c--,c===0))break}h({type:"text",value:d});continue}if(d===gb){o=h({type:"paren",nodes:[]}),r.push(o),h({type:"text",value:d});continue}if(d===yb){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===vb||d===xb||d===pb){let m=d,g;for(e.keepQuotes!==!0&&(d="");u<l&&(g=p());){if(g===xr){d+=g+p();continue}if(g===m){e.keepQuotes===!0&&(d+=g);break}d+=g}h({type:"text",value:d});continue}if(d===bb){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===wb){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===hb&&f>0){if(o.ranges>0){o.ranges=0;let m=o.nodes.shift();o.nodes=[m,{type:"text",value:db(o)}]}h({type:"comma",value:d}),o.commas++;continue}if(d===mb&&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(y=>{y.nodes||(y.type==="open"&&(y.isOpen=!0),y.type==="close"&&(y.isClose=!0),y.nodes||(y.type="text"),y.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};pu.exports=Eb});var yu=T((FT,gu)=>{"use strict";var mu=Ws(),kb=iu(),Rb=au(),Cb=hu(),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={})=>Cb(t,e);Oe.stringify=(t,e={})=>mu(typeof t=="string"?Oe.parse(t,e):t,e);Oe.compile=(t,e={})=>(typeof t=="string"&&(t=Oe.parse(t,e)),kb(t,e));Oe.expand=(t,e={})=>{typeof t=="string"&&(t=Oe.parse(t,e));let n=Rb(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);gu.exports=Oe});var Dn=T((HT,_u)=>{"use strict";var Ab=require("path"),et="\\\\/",bu=`[^${et}]`,$b=0,ut="\\.",Pb="\\+",Tb="\\?",Vs="\\/",Ib="(?=.)",wu="[^/]",_r=`(?:${Vs}|$)`,vu=`(?:^|${Vs})`,Sr=`${ut}{1,2}${_r}`,Ob=`(?!${ut})`,Lb=`(?!${vu}${Sr})`,Nb=`(?!${ut}{0,1}${_r})`,jb=`(?!${Sr})`,Mb=`[^.${Vs}]`,Db=`${wu}*?`,xu={DOT_LITERAL:ut,PLUS_LITERAL:Pb,QMARK_LITERAL:Tb,SLASH_LITERAL:Vs,ONE_CHAR:Ib,QMARK:wu,END_ANCHOR:_r,DOTS_SLASH:Sr,NO_DOT:Ob,NO_DOTS:Lb,NO_DOT_SLASH:Nb,NO_DOTS_SLASH:jb,QMARK_NO_DOT:Mb,STAR:Db,START_ANCHOR:vu},Fb={...xu,SLASH_LITERAL:`[${et}]`,QMARK:bu,STAR:`${bu}*?`,DOTS_SLASH:`${ut}{1,2}(?:[${et}]|$)`,NO_DOT:`(?!${ut})`,NO_DOTS:`(?!(?:^|[${et}])${ut}{1,2}(?:[${et}]|$))`,NO_DOT_SLASH:`(?!${ut}{0,1}(?:[${et}]|$))`,NO_DOTS_SLASH:`(?!${ut}{1,2}(?:[${et}]|$))`,QMARK_NO_DOT:`[^.${et}]`,START_ANCHOR:`(?:^|[${et}])`,END_ANCHOR:`(?:[${et}]|$)`},Hb={__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"};_u.exports={DEFAULT_MAX_EXTGLOB_RECURSION:$b,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Hb,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:Ab.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:xu}}});var Fn=T(Ae=>{"use strict";var Bb=require("path"),Wb=process.platform==="win32",{REGEX_BACKSLASH:Gb,REGEX_REMOVE_BACKSLASH:Ub,REGEX_SPECIAL_CHARS:Vb,REGEX_SPECIAL_CHARS_GLOBAL:zb}=Dn();Ae.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);Ae.hasRegexChars=t=>Vb.test(t);Ae.isRegexChar=t=>t.length===1&&Ae.hasRegexChars(t);Ae.escapeRegex=t=>t.replace(zb,"\\$1");Ae.toPosixSlashes=t=>t.replace(Gb,"/");Ae.removeBackslashes=t=>t.replace(Ub,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 Pu=T((WT,$u)=>{"use strict";var Su=Fn(),{CHAR_ASTERISK:Er,CHAR_AT:qb,CHAR_BACKWARD_SLASH:Hn,CHAR_COMMA:Kb,CHAR_DOT:kr,CHAR_EXCLAMATION_MARK:Rr,CHAR_FORWARD_SLASH:Au,CHAR_LEFT_CURLY_BRACE:Cr,CHAR_LEFT_PARENTHESES:Ar,CHAR_LEFT_SQUARE_BRACKET:Yb,CHAR_PLUS:Jb,CHAR_QUESTION_MARK:Eu,CHAR_RIGHT_CURLY_BRACE:Xb,CHAR_RIGHT_PARENTHESES:ku,CHAR_RIGHT_SQUARE_BRACKET:Zb}=Dn(),Ru=t=>t===Au||t===Hn,Cu=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},Qb=(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,y=!1,b=!1,v=!1,x=!1,w=!1,_=0,A,C,O={value:"",depth:0,isGlob:!1},M=()=>l>=s,E=()=>c.charCodeAt(l+1),U=()=>(A=C,c.charCodeAt(++l));for(;l<s;){C=U();let j;if(C===Hn){b=O.backslashes=!0,C=U(),C===Cr&&(y=!0);continue}if(y===!0||C===Cr){for(_++;M()!==!0&&(C=U());){if(C===Hn){b=O.backslashes=!0,U();continue}if(C===Cr){_++;continue}if(y!==!0&&C===kr&&(C=U())===kr){if(d=O.isBrace=!0,h=O.isGlob=!0,w=!0,i===!0)continue;break}if(y!==!0&&C===Kb){if(d=O.isBrace=!0,h=O.isGlob=!0,w=!0,i===!0)continue;break}if(C===Xb&&(_--,_===0)){y=!1,d=O.isBrace=!0,w=!0;break}}if(i===!0)continue;break}if(C===Au){if(r.push(l),o.push(O),O={value:"",depth:0,isGlob:!1},w===!0)continue;if(A===kr&&l===u+1){u+=2;continue}f=l+1;continue}if(n.noext!==!0&&(C===Jb||C===qb||C===Er||C===Eu||C===Rr)===!0&&E()===Ar){if(h=O.isGlob=!0,m=O.isExtglob=!0,w=!0,C===Rr&&l===u&&(x=!0),i===!0){for(;M()!==!0&&(C=U());){if(C===Hn){b=O.backslashes=!0,C=U();continue}if(C===ku){h=O.isGlob=!0,w=!0;break}}continue}break}if(C===Er){if(A===Er&&(g=O.isGlobstar=!0),h=O.isGlob=!0,w=!0,i===!0)continue;break}if(C===Eu){if(h=O.isGlob=!0,w=!0,i===!0)continue;break}if(C===Yb){for(;M()!==!0&&(j=U());){if(j===Hn){b=O.backslashes=!0,U();continue}if(j===Zb){p=O.isBracket=!0,h=O.isGlob=!0,w=!0;break}}if(i===!0)continue;break}if(n.nonegate!==!0&&C===Rr&&l===u){v=O.negated=!0,u++;continue}if(n.noparen!==!0&&C===Ar){if(h=O.isGlob=!0,i===!0){for(;M()!==!0&&(C=U());){if(C===Ar){b=O.backslashes=!0,C=U();continue}if(C===ku){w=!0;break}}continue}break}if(h===!0){if(w=!0,i===!0)continue;break}}n.noext===!0&&(m=!1,h=!1);let H=c,ne="",S="";u>0&&(ne=c.slice(0,u),c=c.slice(u),f-=u),H&&h===!0&&f>0?(H=c.slice(0,f),S=c.slice(f)):h===!0?(H="",S=c):H=c,H&&H!==""&&H!=="/"&&H!==c&&Ru(H.charCodeAt(H.length-1))&&(H=H.slice(0,-1)),n.unescape===!0&&(S&&(S=Su.removeBackslashes(S)),H&&b===!0&&(H=Su.removeBackslashes(H)));let k={prefix:ne,input:t,start:u,base:H,glob:S,isBrace:d,isBracket:p,isGlob:h,isExtglob:m,isGlobstar:g,negated:v,negatedExtglob:x};if(n.tokens===!0&&(k.maxDepth=0,Ru(C)||o.push(O),k.tokens=o),n.parts===!0||n.tokens===!0){let j;for(let I=0;I<r.length;I++){let ee=j?j+1:u,re=r[I],_e=t.slice(ee,re);n.tokens&&(I===0&&u!==0?(o[I].isPrefix=!0,o[I].value=ne):o[I].value=_e,Cu(o[I]),k.maxDepth+=o[I].depth),(I!==0||_e!=="")&&a.push(_e),j=re}if(j&&j+1<t.length){let I=t.slice(j+1);a.push(I),n.tokens&&(o[o.length-1].value=I,Cu(o[o.length-1]),k.maxDepth+=o[o.length-1].depth)}k.slashes=r,k.parts=a}return k};$u.exports=Qb});var Nu=T((GT,Lu)=>{"use strict";var Bn=Dn(),me=Fn(),{MAX_LENGTH:zs,POSIX_REGEX_SOURCE:ew,REGEX_NON_SPECIAL_CHARS:tw,REGEX_SPECIAL_CHARS_BACKREF:nw,REPLACEMENTS:Tu}=Bn,sw=(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=>me.escapeRegex(i)).join("..")}return n},fn=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,Iu=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},iw=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},Ou=t=>{let e=t.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=!0);if(iw(e))return e.replace(/\\(.)/g,"$1")},rw=t=>{let e=t.map(Ou).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},$r=(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}}}}},ow=t=>{let e=0,n=[];for(;e<t.length;){let i=$r(t.slice(e),!1);if(!i||i.type!=="*")return;let r=Iu(i.body).map(a=>a.trim());if(r.length!==1)return;let o=Ou(r[0]);if(!o||o.length!==1)return;n.push(o),e+=i.end+1}return n.length<1?void 0:`${n.length===1?me.escapeRegex(n[0]):`[${n.map(i=>me.escapeRegex(i)).join("")}]`}*`},aw=t=>{let e=0,n=t.trim(),s=$r(n);for(;s;)e++,n=s.body.trim(),s=$r(n);return e},cw=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Bn.DEFAULT_MAX_EXTGLOB_RECURSION,s=Iu(t).map(i=>i.trim());if(s.length>1&&(s.some(i=>i==="")||s.some(i=>/^[*?]+$/.test(i))||rw(s)))return{risky:!0};for(let i of s){let r=ow(i);if(r)return{risky:!0,safeOutput:r};if(aw(i)>n)return{risky:!0}}return{risky:!1}},Pr=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=Tu[t]||t;let n={...e},s=typeof n.maxLength=="number"?Math.min(zs,n.maxLength):zs,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=me.isWindows(e),l=Bn.globChars(c),u=Bn.extglobChars(l),{DOT_LITERAL:f,PLUS_LITERAL:d,SLASH_LITERAL:p,ONE_CHAR:h,DOTS_SLASH:m,NO_DOT:g,NO_DOT_SLASH:y,NO_DOTS_SLASH:b,QMARK:v,QMARK_NO_DOT:x,STAR:w,START_ANCHOR:_}=l,A=P=>`(${a}(?:(?!${_}${P.dot?m:f}).)*?)`,C=n.dot?"":g,O=n.dot?v:x,M=n.bash===!0?A(n):w;n.capture&&(M=`(${M})`),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=me.removePrefix(t,E),i=t.length;let U=[],H=[],ne=[],S=r,k,j=()=>E.index===i-1,I=E.peek=(P=1)=>t[E.index+P],ee=E.advance=()=>t[++E.index]||"",re=()=>t.slice(E.index+1),_e=(P="",J=0)=>{E.consumed+=P,E.index+=J},lt=P=>{E.output+=P.output!=null?P.output:P.value,_e(P.value)},dy=()=>{let P=1;for(;I()==="!"&&(I(2)!=="("||I(3)==="?");)ee(),E.start++,P++;return P%2===0?!1:(E.negated=!0,E.start++,!0)},Os=P=>{E[P]++,ne.push(P)},bt=P=>{E[P]--,ne.pop()},F=P=>{if(S.type==="globstar"){let J=E.braces>0&&(P.type==="comma"||P.type==="brace"),$=P.extglob===!0||U.length&&(P.type==="pipe"||P.type==="paren");P.type!=="slash"&&P.type!=="paren"&&!J&&!$&&(E.output=E.output.slice(0,-S.output.length),S.type="star",S.value="*",S.output=M,E.output+=S.output)}if(U.length&&P.type!=="paren"&&(U[U.length-1].inner+=P.value),(P.value||P.output)&&lt(P),S&&S.type==="text"&&P.type==="text"){S.value+=P.value,S.output=(S.output||"")+P.value;return}P.prev=S,o.push(P),S=P},Ls=(P,J)=>{let $={...u[J],conditions:1,inner:""};$.prev=S,$.parens=E.parens,$.output=E.output,$.startIndex=E.index,$.tokensIndex=o.length;let D=(n.capture?"(":"")+$.open;Os("parens"),F({type:P,value:J,output:E.output?"":h}),F({type:"paren",extglob:!0,value:ee(),output:D}),U.push($)},py=P=>{let J=t.slice(P.startIndex,E.index+1),$=t.slice(P.startIndex+2,E.index),D=cw($,n);if((P.type==="plus"||P.type==="star")&&D.risky){let q=D.safeOutput?(P.output?"":h)+(n.capture?`(${D.safeOutput})`:D.safeOutput):void 0,Xe=o[P.tokensIndex];Xe.type="text",Xe.value=J,Xe.output=q||me.escapeRegex(J);for(let Ze=P.tokensIndex+1;Ze<o.length;Ze++)o[Ze].value="",o[Ze].output="",delete o[Ze].suffix;E.output=P.output+Xe.output,E.backtrack=!0,F({type:"paren",extglob:!0,value:k,output:""}),bt("parens");return}let K=P.close+(n.capture?")":""),oe;if(P.type==="negate"){let q=M;if(P.inner&&P.inner.length>1&&P.inner.includes("/")&&(q=A(n)),(q!==M||j()||/^\)+$/.test(re()))&&(K=P.close=`)$))${q}`),P.inner.includes("*")&&(oe=re())&&/^\.[^\\/.]+$/.test(oe)){let Xe=Pr(oe,{...e,fastpaths:!1}).output;K=P.close=`)${Xe})${q})`}P.prev.type==="bos"&&(E.negatedExtglob=!0)}F({type:"paren",extglob:!0,value:k,output:K}),bt("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let P=!1,J=t.replace(nw,($,D,K,oe,q,Xe)=>oe==="\\"?(P=!0,$):oe==="?"?D?D+oe+(q?v.repeat(q.length):""):Xe===0?O+(q?v.repeat(q.length):""):v.repeat(K.length):oe==="."?f.repeat(K.length):oe==="*"?D?D+oe+(q?M:""):M:D?$:`\\${$}`);return P===!0&&(n.unescape===!0?J=J.replace(/\\/g,""):J=J.replace(/\\+/g,$=>$.length%2===0?"\\\\":$?"\\":"")),J===t&&n.contains===!0?(E.output=t,E):(E.output=me.wrapOutput(J,E,e),E)}for(;!j();){if(k=ee(),k==="\0")continue;if(k==="\\"){let $=I();if($==="/"&&n.bash!==!0||$==="."||$===";")continue;if(!$){k+="\\",F({type:"text",value:k});continue}let D=/^\\+/.exec(re()),K=0;if(D&&D[0].length>2&&(K=D[0].length,E.index+=K,K%2!==0&&(k+="\\")),n.unescape===!0?k=ee():k+=ee(),E.brackets===0){F({type:"text",value:k});continue}}if(E.brackets>0&&(k!=="]"||S.value==="["||S.value==="[^")){if(n.posix!==!1&&k===":"){let $=S.value.slice(1);if($.includes("[")&&(S.posix=!0,$.includes(":"))){let D=S.value.lastIndexOf("["),K=S.value.slice(0,D),oe=S.value.slice(D+2),q=ew[oe];if(q){S.value=K+q,E.backtrack=!0,ee(),!r.output&&o.indexOf(S)===1&&(r.output=h);continue}}}(k==="["&&I()!==":"||k==="-"&&I()==="]")&&(k=`\\${k}`),k==="]"&&(S.value==="["||S.value==="[^")&&(k=`\\${k}`),n.posix===!0&&k==="!"&&S.value==="["&&(k="^"),S.value+=k,lt({value:k});continue}if(E.quotes===1&&k!=='"'){k=me.escapeRegex(k),S.value+=k,lt({value:k});continue}if(k==='"'){E.quotes=E.quotes===1?0:1,n.keepQuotes===!0&&F({type:"text",value:k});continue}if(k==="("){Os("parens"),F({type:"paren",value:k});continue}if(k===")"){if(E.parens===0&&n.strictBrackets===!0)throw new SyntaxError(fn("opening","("));let $=U[U.length-1];if($&&E.parens===$.parens+1){py(U.pop());continue}F({type:"paren",value:k,output:E.parens?")":"\\)"}),bt("parens");continue}if(k==="["){if(n.nobracket===!0||!re().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(fn("closing","]"));k=`\\${k}`}else Os("brackets");F({type:"bracket",value:k});continue}if(k==="]"){if(n.nobracket===!0||S&&S.type==="bracket"&&S.value.length===1){F({type:"text",value:k,output:`\\${k}`});continue}if(E.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(fn("opening","["));F({type:"text",value:k,output:`\\${k}`});continue}bt("brackets");let $=S.value.slice(1);if(S.posix!==!0&&$[0]==="^"&&!$.includes("/")&&(k=`/${k}`),S.value+=k,lt({value:k}),n.literalBrackets===!1||me.hasRegexChars($))continue;let D=me.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(k==="{"&&n.nobrace!==!0){Os("braces");let $={type:"brace",value:k,output:"(",outputIndex:E.output.length,tokensIndex:E.tokens.length};H.push($),F($);continue}if(k==="}"){let $=H[H.length-1];if(n.nobrace===!0||!$){F({type:"text",value:k,output:k});continue}let D=")";if($.dots===!0){let K=o.slice(),oe=[];for(let q=K.length-1;q>=0&&(o.pop(),K[q].type!=="brace");q--)K[q].type!=="dots"&&oe.unshift(K[q].value);D=sw(oe,n),E.backtrack=!0}if($.comma!==!0&&$.dots!==!0){let K=E.output.slice(0,$.outputIndex),oe=E.tokens.slice($.tokensIndex);$.value=$.output="\\{",k=D="\\}",E.output=K;for(let q of oe)E.output+=q.output||q.value}F({type:"brace",value:k,output:D}),bt("braces"),H.pop();continue}if(k==="|"){U.length>0&&U[U.length-1].conditions++,F({type:"text",value:k});continue}if(k===","){let $=k,D=H[H.length-1];D&&ne[ne.length-1]==="braces"&&(D.comma=!0,$="|"),F({type:"comma",value:k,output:$});continue}if(k==="/"){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:k,output:p});continue}if(k==="."){if(E.braces>0&&S.type==="dot"){S.value==="."&&(S.output=f);let $=H[H.length-1];S.type="dots",S.output+=k,S.value+=k,$.dots=!0;continue}if(E.braces+E.parens===0&&S.type!=="bos"&&S.type!=="slash"){F({type:"text",value:k,output:f});continue}F({type:"dot",value:k,output:f});continue}if(k==="?"){if(!(S&&S.value==="(")&&n.noextglob!==!0&&I()==="("&&I(2)!=="?"){Ls("qmark",k);continue}if(S&&S.type==="paren"){let D=I(),K=k;if(D==="<"&&!me.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(S.value==="("&&!/[!=<:]/.test(D)||D==="<"&&!/<([!=]|\w+>)/.test(re()))&&(K=`\\${k}`),F({type:"text",value:k,output:K});continue}if(n.dot!==!0&&(S.type==="slash"||S.type==="bos")){F({type:"qmark",value:k,output:x});continue}F({type:"qmark",value:k,output:v});continue}if(k==="!"){if(n.noextglob!==!0&&I()==="("&&(I(2)!=="?"||!/[!=<:]/.test(I(3)))){Ls("negate",k);continue}if(n.nonegate!==!0&&E.index===0){dy();continue}}if(k==="+"){if(n.noextglob!==!0&&I()==="("&&I(2)!=="?"){Ls("plus",k);continue}if(S&&S.value==="("||n.regex===!1){F({type:"plus",value:k,output:d});continue}if(S&&(S.type==="bracket"||S.type==="paren"||S.type==="brace")||E.parens>0){F({type:"plus",value:k});continue}F({type:"plus",value:d});continue}if(k==="@"){if(n.noextglob!==!0&&I()==="("&&I(2)!=="?"){F({type:"at",extglob:!0,value:k,output:""});continue}F({type:"text",value:k});continue}if(k!=="*"){(k==="$"||k==="^")&&(k=`\\${k}`);let $=tw.exec(re());$&&(k+=$[0],E.index+=$[0].length),F({type:"text",value:k});continue}if(S&&(S.type==="globstar"||S.star===!0)){S.type="star",S.star=!0,S.value+=k,S.output=M,E.backtrack=!0,E.globstar=!0,_e(k);continue}let P=re();if(n.noextglob!==!0&&/^\([^?]/.test(P)){Ls("star",k);continue}if(S.type==="star"){if(n.noglobstar===!0){_e(k);continue}let $=S.prev,D=$.prev,K=$.type==="slash"||$.type==="bos",oe=D&&(D.type==="star"||D.type==="globstar");if(n.bash===!0&&(!K||P[0]&&P[0]!=="/")){F({type:"star",value:k,output:""});continue}let q=E.braces>0&&($.type==="comma"||$.type==="brace"),Xe=U.length&&($.type==="pipe"||$.type==="paren");if(!K&&$.type!=="paren"&&!q&&!Xe){F({type:"star",value:k,output:""});continue}for(;P.slice(0,3)==="/**";){let Ze=t[E.index+4];if(Ze&&Ze!=="/")break;P=P.slice(3),_e("/**",3)}if($.type==="bos"&&j()){S.type="globstar",S.value+=k,S.output=A(n),E.output=S.output,E.globstar=!0,_e(k);continue}if($.type==="slash"&&$.prev.type!=="bos"&&!oe&&j()){E.output=E.output.slice(0,-($.output+S.output).length),$.output=`(?:${$.output}`,S.type="globstar",S.output=A(n)+(n.strictSlashes?")":"|$)"),S.value+=k,E.globstar=!0,E.output+=$.output+S.output,_e(k);continue}if($.type==="slash"&&$.prev.type!=="bos"&&P[0]==="/"){let Ze=P[1]!==void 0?"|$":"";E.output=E.output.slice(0,-($.output+S.output).length),$.output=`(?:${$.output}`,S.type="globstar",S.output=`${A(n)}${p}|${p}${Ze})`,S.value+=k,E.output+=$.output+S.output,E.globstar=!0,_e(k+ee()),F({type:"slash",value:"/",output:""});continue}if($.type==="bos"&&P[0]==="/"){S.type="globstar",S.value+=k,S.output=`(?:^|${p}|${A(n)}${p})`,E.output=S.output,E.globstar=!0,_e(k+ee()),F({type:"slash",value:"/",output:""});continue}E.output=E.output.slice(0,-S.output.length),S.type="globstar",S.output=A(n),S.value+=k,E.output+=S.output,E.globstar=!0,_e(k);continue}let J={type:"star",value:k,output:M};if(n.bash===!0){J.output=".*?",(S.type==="bos"||S.type==="slash")&&(J.output=C+J.output),F(J);continue}if(S&&(S.type==="bracket"||S.type==="paren")&&n.regex===!0){J.output=k,F(J);continue}(E.index===E.start||S.type==="slash"||S.type==="dot")&&(S.type==="dot"?(E.output+=y,S.output+=y):n.dot===!0?(E.output+=b,S.output+=b):(E.output+=C,S.output+=C),I()!=="*"&&(E.output+=h,S.output+=h)),F(J)}for(;E.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(fn("closing","]"));E.output=me.escapeLast(E.output,"["),bt("brackets")}for(;E.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(fn("closing",")"));E.output=me.escapeLast(E.output,"("),bt("parens")}for(;E.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(fn("closing","}"));E.output=me.escapeLast(E.output,"{"),bt("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 P of E.tokens)E.output+=P.output!=null?P.output:P.value,P.suffix&&(E.output+=P.suffix)}return E};Pr.fastpaths=(t,e)=>{let n={...e},s=typeof n.maxLength=="number"?Math.min(zs,n.maxLength):zs,i=t.length;if(i>s)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${s}`);t=Tu[t]||t;let r=me.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}=Bn.globChars(r),m=n.dot?f:u,g=n.dot?d:u,y=n.capture?"":"?:",b={negated:!1,prefix:""},v=n.bash===!0?".*?":p;n.capture&&(v=`(${v})`);let x=C=>C.noglobstar===!0?v:`(${y}(?:(?!${h}${C.dot?l:o}).)*?)`,w=C=>{switch(C){case"*":return`${m}${c}${v}`;case".*":return`${o}${c}${v}`;case"*.*":return`${m}${v}${o}${c}${v}`;case"*/*":return`${m}${v}${a}${c}${g}${v}`;case"**":return m+x(n);case"**/*":return`(?:${m}${x(n)}${a})?${g}${c}${v}`;case"**/*.*":return`(?:${m}${x(n)}${a})?${g}${v}${o}${c}${v}`;case"**/.*":return`(?:${m}${x(n)}${a})?${o}${c}${v}`;default:{let O=/^(.*?)\.(\w+)$/.exec(C);if(!O)return;let M=w(O[1]);return M?M+o+O[2]:void 0}}},_=me.removePrefix(t,b),A=w(_);return A&&n.strictSlashes!==!0&&(A+=`${a}?`),A};Lu.exports=Pr});var Mu=T((UT,ju)=>{"use strict";var lw=require("path"),uw=Pu(),Tr=Nu(),Ir=Fn(),fw=Dn(),dw=t=>t&&typeof t=="object"&&!Array.isArray(t),te=(t,e,n=!1)=>{if(Array.isArray(t)){let u=t.map(d=>te(d,e,n));return d=>{for(let p of u){let h=p(d);if(h)return h}return!1}}let s=dw(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=Ir.isWindows(e),o=s?te.compileRe(t,e):te.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=te(i.ignore,u,n)}let l=(u,f=!1)=>{let{isMatch:d,match:p,output:h}=te.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};te.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?Ir.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=te.matchBase(t,e,n,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};te.matchBase=(t,e,n,s=Ir.isWindows(n))=>(e instanceof RegExp?e:te.makeRe(e,n)).test(lw.basename(t));te.isMatch=(t,e,n)=>te(e,n)(t);te.parse=(t,e)=>Array.isArray(t)?t.map(n=>te.parse(n,e)):Tr(t,{...e,fastpaths:!1});te.scan=(t,e)=>uw(t,e);te.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=te.toRegex(a,e);return s===!0&&(c.state=t),c};te.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=Tr.fastpaths(t,e)),i.output||(i=Tr(t,e)),te.compileRe(i,e,n,s)};te.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/$^/}};te.constants=fw;ju.exports=te});var Fu=T((VT,Du)=>{"use strict";Du.exports=Mu()});var ft=T((zT,Uu)=>{"use strict";var Bu=require("util"),Wu=yu(),tt=Fu(),Or=Fn(),Hu=t=>t===""||t==="./",Gu=t=>{let e=t.indexOf("{");return e>-1&&t.indexOf("}",e)>-1},Y=(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=tt(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};Y.match=Y;Y.matcher=(t,e)=>tt(t,e);Y.isMatch=(t,e,n)=>tt(e,n)(t);Y.any=Y.isMatch;Y.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(Y(t,e,{...n,onResult:r}));for(let a of i)o.has(a)||s.add(a);return[...s]};Y.contains=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${Bu.inspect(t)}"`);if(Array.isArray(e))return e.some(s=>Y.contains(t,s,n));if(typeof e=="string"){if(Hu(t)||Hu(e))return!1;if(t.includes(e)||t.startsWith("./")&&t.slice(2).includes(e))return!0}return Y.isMatch(t,e,{...n,contains:!0})};Y.matchKeys=(t,e,n)=>{if(!Or.isObject(t))throw new TypeError("Expected the first argument to be an object");let s=Y(Object.keys(t),e,n),i={};for(let r of s)i[r]=t[r];return i};Y.some=(t,e,n)=>{let s=[].concat(t);for(let i of[].concat(e)){let r=tt(String(i),n);if(s.some(o=>r(o)))return!0}return!1};Y.every=(t,e,n)=>{let s=[].concat(t);for(let i of[].concat(e)){let r=tt(String(i),n);if(!s.every(o=>r(o)))return!1}return!0};Y.all=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${Bu.inspect(t)}"`);return[].concat(e).every(s=>tt(s,n)(t))};Y.capture=(t,e,n)=>{let s=Or.isWindows(n),r=tt.makeRe(String(t),{...n,capture:!0}).exec(s?Or.toPosixSlashes(e):e);if(r)return r.slice(1).map(o=>o===void 0?"":o)};Y.makeRe=(...t)=>tt.makeRe(...t);Y.scan=(...t)=>tt.scan(...t);Y.parse=(t,e)=>{let n=[];for(let s of[].concat(t||[]))for(let i of Wu(String(s),e))n.push(tt.parse(i,e));return n};Y.braces=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return e&&e.nobrace===!0||!Gu(t)?[t]:Wu(t,e)};Y.braceExpand=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return Y.braces(t,{...e,expand:!0})};Y.hasBraces=Gu;Uu.exports=Y});var ef=T(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.isAbsolute=L.partitionAbsoluteAndRelative=L.removeDuplicateSlashes=L.matchAny=L.convertPatternsToRe=L.makeRe=L.getPatternParts=L.expandBraceExpansion=L.expandPatternsWithBraceExpansion=L.isAffectDepthOfReadingPattern=L.endsWithSlashGlobStar=L.hasGlobStar=L.getBaseDirectory=L.isPatternRelatedToParentDirectory=L.getPatternsOutsideCurrentDirectory=L.getPatternsInsideCurrentDirectory=L.getPositivePatterns=L.getNegativePatterns=L.isPositivePattern=L.isNegativePattern=L.convertToNegativePattern=L.convertToPositivePattern=L.isDynamicPattern=L.isStaticPattern=void 0;var Vu=require("path"),pw=Nl(),Lr=ft(),zu="**",hw="\\",mw=/[*?]|^!/,gw=/\[[^[]*]/,yw=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,bw=/[!*+?@]\([^(]*\)/,ww=/,|\.\./,vw=/(?!^)\/{2,}/g;function qu(t,e={}){return!Ku(t,e)}L.isStaticPattern=qu;function Ku(t,e={}){return t===""?!1:!!(e.caseSensitiveMatch===!1||t.includes(hw)||mw.test(t)||gw.test(t)||yw.test(t)||e.extglob!==!1&&bw.test(t)||e.braceExpansion!==!1&&xw(t))}L.isDynamicPattern=Ku;function xw(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 ww.test(s)}function _w(t){return qs(t)?t.slice(1):t}L.convertToPositivePattern=_w;function Sw(t){return"!"+t}L.convertToNegativePattern=Sw;function qs(t){return t.startsWith("!")&&t[1]!=="("}L.isNegativePattern=qs;function Yu(t){return!qs(t)}L.isPositivePattern=Yu;function Ew(t){return t.filter(qs)}L.getNegativePatterns=Ew;function kw(t){return t.filter(Yu)}L.getPositivePatterns=kw;function Rw(t){return t.filter(e=>!Nr(e))}L.getPatternsInsideCurrentDirectory=Rw;function Cw(t){return t.filter(Nr)}L.getPatternsOutsideCurrentDirectory=Cw;function Nr(t){return t.startsWith("..")||t.startsWith("./..")}L.isPatternRelatedToParentDirectory=Nr;function Aw(t){return pw(t,{flipBackslashes:!1})}L.getBaseDirectory=Aw;function $w(t){return t.includes(zu)}L.hasGlobStar=$w;function Ju(t){return t.endsWith("/"+zu)}L.endsWithSlashGlobStar=Ju;function Pw(t){let e=Vu.basename(t);return Ju(t)||qu(e)}L.isAffectDepthOfReadingPattern=Pw;function Tw(t){return t.reduce((e,n)=>e.concat(Xu(n)),[])}L.expandPatternsWithBraceExpansion=Tw;function Xu(t){let e=Lr.braces(t,{expand:!0,nodupes:!0,keepEscaping:!0});return e.sort((n,s)=>n.length-s.length),e.filter(n=>n!=="")}L.expandBraceExpansion=Xu;function Iw(t,e){let{parts:n}=Lr.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}L.getPatternParts=Iw;function Zu(t,e){return Lr.makeRe(t,e)}L.makeRe=Zu;function Ow(t,e){return t.map(n=>Zu(n,e))}L.convertPatternsToRe=Ow;function Lw(t,e){return e.some(n=>n.test(t))}L.matchAny=Lw;function Nw(t){return t.replace(vw,"/")}L.removeDuplicateSlashes=Nw;function jw(t){let e=[],n=[];for(let s of t)Qu(s)?e.push(s):n.push(s);return[e,n]}L.partitionAbsoluteAndRelative=jw;function Qu(t){return Vu.isAbsolute(t)}L.isAbsolute=Qu});var rf=T((KT,sf)=>{"use strict";var Mw=require("stream"),tf=Mw.PassThrough,Dw=Array.prototype.slice;sf.exports=Fw;function Fw(){let t=[],e=Dw.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=tf(s);function a(){for(let u=0,f=arguments.length;u<f;u++)t.push(nf(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(y){o.emit("error",y)}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 nf(t,e){if(Array.isArray(t))for(let n=0,s=t.length;n<s;n++)t[n]=nf(t[n],e);else{if(!t._readableState&&t.pipe&&(t=t.pipe(tf(e))),!t._readableState||!t.pause||!t.pipe)throw new Error("Only readable stream can be merged.");t.pause()}return t}});var af=T(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.merge=void 0;var Hw=rf();function Bw(t){let e=Hw(t);return t.forEach(n=>{n.once("error",s=>e.emit("error",s))}),e.once("close",()=>of(t)),e.once("end",()=>of(t)),e}Ks.merge=Bw;function of(t){t.forEach(e=>e.emit("close"))}});var cf=T(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.isEmpty=dn.isString=void 0;function Ww(t){return typeof t=="string"}dn.isString=Ww;function Gw(t){return t===""}dn.isEmpty=Gw});var dt=T(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.string=ge.stream=ge.pattern=ge.path=ge.fs=ge.errno=ge.array=void 0;var Uw=_l();ge.array=Uw;var Vw=Sl();ge.errno=Vw;var zw=El();ge.fs=zw;var qw=Al();ge.path=qw;var Kw=ef();ge.pattern=Kw;var Yw=af();ge.stream=Yw;var Jw=cf();ge.string=Jw});var df=T(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.convertPatternGroupToTask=ye.convertPatternGroupsToTasks=ye.groupPatternsByBaseDirectory=ye.getNegativePatternsAsPositive=ye.getPositivePatterns=ye.convertPatternsToTasks=ye.generate=void 0;var Ve=dt();function Xw(t,e){let n=lf(t,e),s=lf(e.ignore,e),i=uf(n),r=ff(n,s),o=i.filter(u=>Ve.pattern.isStaticPattern(u,e)),a=i.filter(u=>Ve.pattern.isDynamicPattern(u,e)),c=jr(o,r,!1),l=jr(a,r,!0);return c.concat(l)}ye.generate=Xw;function lf(t,e){let n=t;return e.braceExpansion&&(n=Ve.pattern.expandPatternsWithBraceExpansion(n)),e.baseNameMatch&&(n=n.map(s=>s.includes("/")?s:`**/${s}`)),n.map(s=>Ve.pattern.removeDuplicateSlashes(s))}function jr(t,e,n){let s=[],i=Ve.pattern.getPatternsOutsideCurrentDirectory(t),r=Ve.pattern.getPatternsInsideCurrentDirectory(t),o=Mr(i),a=Mr(r);return s.push(...Dr(o,e,n)),"."in a?s.push(Fr(".",r,e,n)):s.push(...Dr(a,e,n)),s}ye.convertPatternsToTasks=jr;function uf(t){return Ve.pattern.getPositivePatterns(t)}ye.getPositivePatterns=uf;function ff(t,e){return Ve.pattern.getNegativePatterns(t).concat(e).map(Ve.pattern.convertToPositivePattern)}ye.getNegativePatternsAsPositive=ff;function Mr(t){let e={};return t.reduce((n,s)=>{let i=Ve.pattern.getBaseDirectory(s);return i in n?n[i].push(s):n[i]=[s],n},e)}ye.groupPatternsByBaseDirectory=Mr;function Dr(t,e,n){return Object.keys(t).map(s=>Fr(s,t[s],e,n))}ye.convertPatternGroupsToTasks=Dr;function Fr(t,e,n,s){return{dynamic:s,positive:e,negative:n,base:t,patterns:[].concat(e,n.map(Ve.pattern.convertToNegativePattern))}}ye.convertPatternGroupToTask=Fr});var hf=T(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.read=void 0;function Zw(t,e,n){e.fs.lstat(t,(s,i)=>{if(s!==null){pf(n,s);return}if(!i.isSymbolicLink()||!e.followSymbolicLink){Hr(n,i);return}e.fs.stat(t,(r,o)=>{if(r!==null){if(e.throwErrorOnBrokenSymbolicLink){pf(n,r);return}Hr(n,i);return}e.markSymbolicLink&&(o.isSymbolicLink=()=>!0),Hr(n,o)})})}Ys.read=Zw;function pf(t,e){t(e)}function Hr(t,e){t(null,e)}});var mf=T(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.read=void 0;function Qw(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}}Js.read=Qw});var gf=T(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.createFileSystemAdapter=vt.FILE_SYSTEM_ADAPTER=void 0;var Xs=require("fs");vt.FILE_SYSTEM_ADAPTER={lstat:Xs.lstat,stat:Xs.stat,lstatSync:Xs.lstatSync,statSync:Xs.statSync};function ev(t){return t===void 0?vt.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},vt.FILE_SYSTEM_ADAPTER),t)}vt.createFileSystemAdapter=ev});var yf=T(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});var tv=gf(),Br=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=tv.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}};Wr.default=Br});var Ht=T(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.statSync=xt.stat=xt.Settings=void 0;var bf=hf(),nv=mf(),Gr=yf();xt.Settings=Gr.default;function sv(t,e,n){if(typeof e=="function"){bf.read(t,Ur(),e);return}bf.read(t,Ur(e),n)}xt.stat=sv;function iv(t,e){let n=Ur(e);return nv.read(t,n)}xt.statSync=iv;function Ur(t={}){return t instanceof Gr.default?t:new Gr.default(t)}});var xf=T((iI,vf)=>{var wf;vf.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:global):t=>(wf||(wf=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var Sf=T((rI,_f)=>{_f.exports=ov;var rv=xf();function ov(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?rv(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 Vr=T(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var Zs=process.versions.node.split(".");if(Zs[0]===void 0||Zs[1]===void 0)throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var Ef=Number.parseInt(Zs[0],10),av=Number.parseInt(Zs[1],10),kf=10,cv=10,lv=Ef>kf,uv=Ef===kf&&av>=cv;Qs.IS_SUPPORT_READDIR_WITH_FILE_TYPES=lv||uv});var Rf=T(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.createDirentFromStats=void 0;var zr=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 fv(t,e){return new zr(t,e)}ei.createDirentFromStats=fv});var qr=T(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.fs=void 0;var dv=Rf();ti.fs=dv});var Kr=T(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.joinPathSegments=void 0;function pv(t,e,n){return t.endsWith(n)?t+e:t+n+e}ni.joinPathSegments=pv});var If=T(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.readdir=_t.readdirWithFileTypes=_t.read=void 0;var hv=Ht(),Cf=Sf(),mv=Vr(),Af=qr(),$f=Kr();function gv(t,e,n){if(!e.stats&&mv.IS_SUPPORT_READDIR_WITH_FILE_TYPES){Pf(t,e,n);return}Tf(t,e,n)}_t.read=gv;function Pf(t,e,n){e.fs.readdir(t,{withFileTypes:!0},(s,i)=>{if(s!==null){si(n,s);return}let r=i.map(a=>({dirent:a,name:a.name,path:$f.joinPathSegments(t,a.name,e.pathSegmentSeparator)}));if(!e.followSymbolicLinks){Yr(n,r);return}let o=r.map(a=>yv(a,e));Cf(o,(a,c)=>{if(a!==null){si(n,a);return}Yr(n,c)})})}_t.readdirWithFileTypes=Pf;function yv(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=Af.fs.createDirentFromStats(t.name,i),n(null,t)})}}function Tf(t,e,n){e.fs.readdir(t,(s,i)=>{if(s!==null){si(n,s);return}let r=i.map(o=>{let a=$f.joinPathSegments(t,o,e.pathSegmentSeparator);return c=>{hv.stat(a,e.fsStatSettings,(l,u)=>{if(l!==null){c(l);return}let f={name:o,path:a,dirent:Af.fs.createDirentFromStats(o,u)};e.stats&&(f.stats=u),c(null,f)})}});Cf(r,(o,a)=>{if(o!==null){si(n,o);return}Yr(n,a)})})}_t.readdir=Tf;function si(t,e){t(e)}function Yr(t,e){t(null,e)}});var Mf=T(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.readdir=St.readdirWithFileTypes=St.read=void 0;var bv=Ht(),wv=Vr(),Of=qr(),Lf=Kr();function vv(t,e){return!e.stats&&wv.IS_SUPPORT_READDIR_WITH_FILE_TYPES?Nf(t,e):jf(t,e)}St.read=vv;function Nf(t,e){return e.fs.readdirSync(t,{withFileTypes:!0}).map(s=>{let i={dirent:s,name:s.name,path:Lf.joinPathSegments(t,s.name,e.pathSegmentSeparator)};if(i.dirent.isSymbolicLink()&&e.followSymbolicLinks)try{let r=e.fs.statSync(i.path);i.dirent=Of.fs.createDirentFromStats(i.name,r)}catch(r){if(e.throwErrorOnBrokenSymbolicLink)throw r}return i})}St.readdirWithFileTypes=Nf;function jf(t,e){return e.fs.readdirSync(t).map(s=>{let i=Lf.joinPathSegments(t,s,e.pathSegmentSeparator),r=bv.statSync(i,e.fsStatSettings),o={name:s,path:i,dirent:Of.fs.createDirentFromStats(s,r)};return e.stats&&(o.stats=r),o})}St.readdir=jf});var Df=T(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.createFileSystemAdapter=Et.FILE_SYSTEM_ADAPTER=void 0;var pn=require("fs");Et.FILE_SYSTEM_ADAPTER={lstat:pn.lstat,stat:pn.stat,lstatSync:pn.lstatSync,statSync:pn.statSync,readdir:pn.readdir,readdirSync:pn.readdirSync};function xv(t){return t===void 0?Et.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},Et.FILE_SYSTEM_ADAPTER),t)}Et.createFileSystemAdapter=xv});var Ff=T(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});var _v=require("path"),Sv=Ht(),Ev=Df(),Jr=class{constructor(e={}){this._options=e,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=Ev.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,_v.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new Sv.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue(e,n){return e??n}};Xr.default=Jr});var ii=T(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.Settings=kt.scandirSync=kt.scandir=void 0;var Hf=If(),kv=Mf(),Zr=Ff();kt.Settings=Zr.default;function Rv(t,e,n){if(typeof e=="function"){Hf.read(t,Qr(),e);return}Hf.read(t,Qr(e),n)}kt.scandir=Rv;function Cv(t,e){let n=Qr(e);return kv.read(t,n)}kt.scandirSync=Cv;function Qr(t={}){return t instanceof Zr.default?t:new Zr.default(t)}});var Wf=T((mI,Bf)=>{"use strict";function Av(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}}Bf.exports=Av});var Uf=T((gI,eo)=>{"use strict";var $v=Wf();function Gf(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=$v(Pv),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(_){if(!(_>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(n=_,!c.paused)for(;i&&o<n;)o++,y()},running:l,resume:p,idle:h,length:f,getQueue:d,unshift:g,empty:$e,kill:b,killAndDrain:v,error:w,abort:x};return c;function l(){return o}function u(){c.paused=!0}function f(){for(var _=i,A=0;_;)_=_.next,A++;return A}function d(){for(var _=i,A=[];_;)A.push(_.value),_=_.next;return A}function p(){if(c.paused){if(c.paused=!1,i===null){o++,y();return}for(;i&&o<n;)o++,y()}}function h(){return o===0&&c.length()===0}function m(_,A){var C=s.get();C.context=t,C.release=y,C.value=_,C.callback=A||$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(_,A){var C=s.get();C.context=t,C.release=y,C.value=_,C.callback=A||$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 y(_){_&&s.release(_);var A=i;A&&o<=n?c.paused?o--:(r===i&&(r=null),i=A.next,A.next=null,e.call(t,A.value,A.worked),r===null&&c.empty()):--o===0&&c.drain()}function b(){i=null,r=null,c.drain=$e}function v(){i=null,r=null,c.drain(),c.drain=$e}function x(){var _=i;for(i=null,r=null;_;){var A=_.next,C=_.callback,O=_.errorHandler,M=_.value,E=_.context;_.value=null,_.callback=$e,_.errorHandler=null,O&&O(new Error("abort"),M),C.call(E,new Error("abort")),_.release(_),_=A}c.drain=$e}function w(_){a=_}}function $e(){}function Pv(){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 Tv(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=Gf(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}}eo.exports=Gf;eo.exports.promise=Tv});var ri=T(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.joinPathSegments=nt.replacePathSegmentSeparator=nt.isAppliedFilter=nt.isFatalError=void 0;function Iv(t,e){return t.errorFilter===null?!0:!t.errorFilter(e)}nt.isFatalError=Iv;function Ov(t,e){return t===null||t(e)}nt.isAppliedFilter=Ov;function Lv(t,e){return t.split(/[/\\]/).join(e)}nt.replacePathSegmentSeparator=Lv;function Nv(t,e,n){return t===""?e:t.endsWith(n)?t+e:t+n+e}nt.joinPathSegments=Nv});var so=T(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});var jv=ri(),to=class{constructor(e,n){this._root=e,this._settings=n,this._root=jv.replacePathSegmentSeparator(e,n.pathSegmentSeparator)}};no.default=to});var oo=T(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});var Mv=require("events"),Dv=ii(),Fv=Uf(),oi=ri(),Hv=so(),io=class extends Hv.default{constructor(e,n){super(e,n),this._settings=n,this._scandir=Dv.scandir,this._emitter=new Mv.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||!oi.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=oi.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),oi.isAppliedFilter(this._settings.entryFilter,e)&&this._emitEntry(e),e.dirent.isDirectory()&&oi.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(s,n===void 0?void 0:e.path)}_emitEntry(e){this._emitter.emit("entry",e)}};ro.default=io});var Vf=T(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});var Bv=oo(),ao=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(()=>{Gv(e,this._storage)}),this._reader.read()}};co.default=ao;function Wv(t,e){t(e)}function Gv(t,e){t(null,e)}});var zf=T(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});var Uv=require("stream"),Vv=oo(),lo=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new Vv.default(this._root,this._settings),this._stream=new Uv.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}};uo.default=lo});var qf=T(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});var zv=ii(),ai=ri(),qv=so(),fo=class extends qv.default{constructor(){super(...arguments),this._scandir=zv.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(ai.isFatalError(this._settings,e))throw e}_handleEntry(e,n){let s=e.path;n!==void 0&&(e.path=ai.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),ai.isAppliedFilter(this._settings.entryFilter,e)&&this._pushToStorage(e),e.dirent.isDirectory()&&ai.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(s,n===void 0?void 0:e.path)}_pushToStorage(e){this._storage.push(e)}};po.default=fo});var Kf=T(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});var Kv=qf(),ho=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new Kv.default(this._root,this._settings)}read(){return this._reader.read()}};mo.default=ho});var Yf=T(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});var Yv=require("path"),Jv=ii(),go=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,Yv.sep),this.fsScandirSettings=new Jv.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}};yo.default=go});var li=T(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.Settings=st.walkStream=st.walkSync=st.walk=void 0;var Jf=Vf(),Xv=zf(),Zv=Kf(),bo=Yf();st.Settings=bo.default;function Qv(t,e,n){if(typeof e=="function"){new Jf.default(t,ci()).read(e);return}new Jf.default(t,ci(e)).read(n)}st.walk=Qv;function e0(t,e){let n=ci(e);return new Zv.default(t,n).read()}st.walkSync=e0;function t0(t,e){let n=ci(e);return new Xv.default(t,n).read()}st.walkStream=t0;function ci(t={}){return t instanceof bo.default?t:new bo.default(t)}});var ui=T(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});var n0=require("path"),s0=Ht(),Xf=dt(),wo=class{constructor(e){this._settings=e,this._fsStatSettings=new s0.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return n0.resolve(this._settings.cwd,e)}_makeEntry(e,n){let s={name:n,path:n,dirent:Xf.fs.createDirentFromStats(n,e)};return this._settings.stats&&(s.stats=e),s}_isFatalError(e){return!Xf.errno.isEnoentCodeError(e)&&!this._settings.suppressErrors}};vo.default=wo});var So=T(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});var i0=require("stream"),r0=Ht(),o0=li(),a0=ui(),xo=class extends a0.default{constructor(){super(...arguments),this._walkStream=o0.walkStream,this._stat=r0.stat}dynamic(e,n){return this._walkStream(e,n)}static(e,n){let s=e.map(this._getFullEntryPath,this),i=new i0.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))})}};_o.default=xo});var Zf=T(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});var c0=li(),l0=ui(),u0=So(),Eo=class extends l0.default{constructor(){super(...arguments),this._walkAsync=c0.walk,this._readerStream=new u0.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))})}};ko.default=Eo});var Qf=T(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});var Wn=dt(),Ro=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 Wn.pattern.getPatternParts(e,this._micromatchOptions).map(s=>Wn.pattern.isDynamicPattern(s,this._settings)?{dynamic:!0,pattern:s,patternRe:Wn.pattern.makeRe(s,this._micromatchOptions)}:{dynamic:!1,pattern:s})}_splitSegmentsIntoSections(e){return Wn.array.splitWhen(e,n=>n.dynamic&&Wn.pattern.hasGlobStar(n.pattern))}};Co.default=Ro});var ed=T($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});var f0=Qf(),Ao=class extends f0.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}};$o.default=Ao});var td=T(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});var fi=dt(),d0=ed(),Po=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 d0.default(e,this._settings,this._micromatchOptions)}_getNegativePatternsRe(e){let n=e.filter(fi.pattern.isAffectDepthOfReadingPattern);return fi.pattern.convertPatternsToRe(n,this._micromatchOptions)}_filter(e,n,s,i){if(this._isSkippedByDeep(e,n.path)||this._isSkippedSymbolicLink(n))return!1;let r=fi.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!fi.pattern.matchAny(e,n)}};To.default=Po});var nd=T(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});var Rt=dt(),Io=class{constructor(e,n){this._settings=e,this._micromatchOptions=n,this.index=new Map}getFilter(e,n){let[s,i]=Rt.pattern.partitionAbsoluteAndRelative(n),r={positive:{all:Rt.pattern.convertPatternsToRe(e,this._micromatchOptions)},negative:{absolute:Rt.pattern.convertPatternsToRe(s,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:Rt.pattern.convertPatternsToRe(i,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return o=>this._filter(o,r)}_filter(e,n){let s=Rt.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=Rt.path.makeAbsolute(this._settings.cwd,e);return this._isMatchToPatterns(i,n,s)}_isMatchToPatterns(e,n,s){if(n.length===0)return!1;let i=Rt.pattern.matchAny(e,n);return!i&&s?Rt.pattern.matchAny(e+"/",n):i}};Oo.default=Io});var sd=T(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});var p0=dt(),Lo=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return p0.errno.isEnoentCodeError(e)||this._settings.suppressErrors}};No.default=Lo});var rd=T(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});var id=dt(),jo=class{constructor(e){this._settings=e}getTransformer(){return e=>this._transform(e)}_transform(e){let n=e.path;return this._settings.absolute&&(n=id.path.makeAbsolute(this._settings.cwd,n),n=id.path.unixify(n)),this._settings.markDirectories&&e.dirent.isDirectory()&&(n+="/"),this._settings.objectMode?Object.assign(Object.assign({},e),{path:n}):n}};Mo.default=jo});var di=T(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});var h0=require("path"),m0=td(),g0=nd(),y0=sd(),b0=rd(),Do=class{constructor(e){this._settings=e,this.errorFilter=new y0.default(this._settings),this.entryFilter=new g0.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new m0.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new b0.default(this._settings)}_getRootDirectory(e){return h0.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}}};Fo.default=Do});var od=T(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});var w0=Zf(),v0=di(),Ho=class extends v0.default{constructor(){super(...arguments),this._reader=new w0.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)}};Bo.default=Ho});var ad=T(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});var x0=require("stream"),_0=So(),S0=di(),Wo=class extends S0.default{constructor(){super(...arguments),this._reader=new _0.default(this._settings)}read(e){let n=this._getRootDirectory(e),s=this._getReaderOptions(e),i=this.api(n,e,s),r=new x0.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)}};Go.default=Wo});var cd=T(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});var E0=Ht(),k0=li(),R0=ui(),Uo=class extends R0.default{constructor(){super(...arguments),this._walkSync=k0.walkSync,this._statSync=E0.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)}};Vo.default=Uo});var ld=T(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});var C0=cd(),A0=di(),zo=class extends A0.default{constructor(){super(...arguments),this._reader=new C0.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)}};qo.default=zo});var ud=T(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var hn=require("fs"),$0=require("os"),P0=Math.max($0.cpus().length,1);mn.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:hn.lstat,lstatSync:hn.lstatSync,stat:hn.stat,statSync:hn.statSync,readdir:hn.readdir,readdirSync:hn.readdirSync};var Ko=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,P0),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({},mn.DEFAULT_FILE_SYSTEM_ADAPTER),e)}};mn.default=Ko});var Gn=T((BI,dd)=>{"use strict";var fd=df(),T0=od(),I0=ad(),O0=ld(),Yo=ud(),Me=dt();async function Jo(t,e){ze(t);let n=Xo(t,T0.default,e),s=await Promise.all(n);return Me.array.flatten(s)}(function(t){t.glob=t,t.globSync=e,t.globStream=n,t.async=t;function e(l,u){ze(l);let f=Xo(l,O0.default,u);return Me.array.flatten(f)}t.sync=e;function n(l,u){ze(l);let f=Xo(l,I0.default,u);return Me.stream.merge(f)}t.stream=n;function s(l,u){ze(l);let f=[].concat(l),d=new Yo.default(u);return fd.generate(f,d)}t.generateTasks=s;function i(l,u){ze(l);let f=new Yo.default(u);return Me.pattern.isDynamicPattern(l,f)}t.isDynamicPattern=i;function r(l){return ze(l),Me.path.escape(l)}t.escapePath=r;function o(l){return ze(l),Me.path.convertPathToPattern(l)}t.convertPathToPattern=o;let a;(function(l){function u(d){return ze(d),Me.path.escapePosixPath(d)}l.escapePath=u;function f(d){return ze(d),Me.path.convertPosixPathToPattern(d)}l.convertPathToPattern=f})(a=t.posix||(t.posix={}));let c;(function(l){function u(d){return ze(d),Me.path.escapeWindowsPath(d)}l.escapePath=u;function f(d){return ze(d),Me.path.convertWindowsPathToPattern(d)}l.convertPathToPattern=f})(c=t.win32||(t.win32={}))})(Jo||(Jo={}));function Xo(t,e,n){let s=[].concat(t),i=new Yo.default(n),r=fd.generate(s,i),o=new e(i);return r.map(o.read,o)}function ze(t){if(![].concat(t).every(s=>Me.string.isString(s)&&!Me.string.isEmpty(s)))throw new TypeError("Patterns must be a string (non empty) or an array of strings")}dd.exports=Jo});var ll=T((LD,j1)=>{j1.exports={name:"@promptci/cli",version:"0.3.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.1.0"},publishConfig:{access:"public"}}});var wt=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}},Mt=class extends wt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var Ln=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 Mt(`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 Ns(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}var wl=require("node:events"),Ms=R(require("node:child_process"),1),Qe=R(require("node:path"),1),jn=R(require("node:fs"),1),W=R(require("node:process"),1),vl=require("node:util");var ml=require("node:util"),Nn=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=>Ns(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,ml.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
- `+" ".repeat(n+c)),o+a+" ".repeat(c)+f.replace(/\n/g,`
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 an=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=vy(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 Mt(`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?gl(this.name().replace(/^no-/,"")):gl(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}},js=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 gl(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function vy(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}
2
+ "use strict";var Tb=Object.create;var Xl=Object.defineProperty;var Pb=Object.getOwnPropertyDescriptor;var $b=Object.getOwnPropertyNames;var Ib=Object.getPrototypeOf,Ob=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Lb=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of $b(e))!Ob.call(t,i)&&i!==n&&Xl(t,i,{get:()=>e[i],enumerable:!(s=Pb(e,i))||s.enumerable});return t};var R=(t,e,n)=>(n=t!=null?Tb(Ib(t)):{},Lb(e||!t||!t.__esModule?Xl(n,"default",{value:t,enumerable:!0}):n,t));var iu=I(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.splitWhen=kn.flatten=void 0;function Db(t){return t.reduce((e,n)=>[].concat(e,n),[])}kn.flatten=Db;function Fb(t,e){let n=[[]],s=0;for(let i of t)e(i)?(s++,n[s]=[]):n[s].push(i);return n}kn.splitWhen=Fb});var ou=I(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.isEnoentCodeError=void 0;function Hb(t){return t.code==="ENOENT"}ni.isEnoentCodeError=Hb});var ru=I(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.createDirentFromStats=void 0;var No=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 Bb(t,e){return new No(t,e)}si.createDirentFromStats=Bb});var uu=I(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.convertPosixPathToPattern=fe.convertWindowsPathToPattern=fe.convertPathToPattern=fe.escapePosixPath=fe.escapeWindowsPath=fe.escape=fe.removeLeadingDotSegment=fe.makeAbsolute=fe.unixify=void 0;var Gb=require("os"),Wb=require("path"),au=Gb.platform()==="win32",Vb=2,Ub=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,zb=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,qb=/^\\\\([.?])/,Kb=/\\(?![!()+@[\]{}])/g;function Yb(t){return t.replace(/\\/g,"/")}fe.unixify=Yb;function Xb(t,e){return Wb.resolve(t,e)}fe.makeAbsolute=Xb;function Jb(t){if(t.charAt(0)==="."){let e=t.charAt(1);if(e==="/"||e==="\\")return t.slice(Vb)}return t}fe.removeLeadingDotSegment=Jb;fe.escape=au?Mo:jo;function Mo(t){return t.replace(zb,"\\$2")}fe.escapeWindowsPath=Mo;function jo(t){return t.replace(Ub,"\\$2")}fe.escapePosixPath=jo;fe.convertPathToPattern=au?cu:lu;function cu(t){return Mo(t).replace(qb,"//$1").replace(Kb,"/")}fe.convertWindowsPathToPattern=cu;function lu(t){return jo(t)}fe.convertPosixPathToPattern=lu});var pu=I((kL,du)=>{du.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 mu=I((EL,hu)=>{var Zb=pu(),fu={"{":"}","(":")","[":"]"},Qb=function(t){if(t[0]==="!")return!0;for(var e=0,n=-2,s=-2,i=-2,o=-2,r=-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&&(r===-1||r>s||(r=t.indexOf("\\",e),r===-1||r>s)))||i!==-1&&t[e]==="{"&&t[e+1]!=="}"&&(i=t.indexOf("}",e),i>e&&(r=t.indexOf("\\",e),r===-1||r>i))||o!==-1&&t[e]==="("&&t[e+1]==="?"&&/[:!=]/.test(t[e+2])&&t[e+3]!==")"&&(o=t.indexOf(")",e),o>e&&(r=t.indexOf("\\",e),r===-1||r>o))||n!==-1&&t[e]==="("&&t[e+1]!=="|"&&(n<e&&(n=t.indexOf("|",e)),n!==-1&&t[n+1]!==")"&&(o=t.indexOf(")",n),o>n&&(r=t.indexOf("\\",n),r===-1||r>o))))return!0;if(t[e]==="\\"){var a=t[e+1];e+=2;var c=fu[a];if(c){var l=t.indexOf(c,e);l!==-1&&(e=l+1)}if(t[e]==="!")return!0}else e++}return!1},ew=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=fu[n];if(s){var i=t.indexOf(s,e);i!==-1&&(e=i+1)}if(t[e]==="!")return!0}else e++}return!1};hu.exports=function(e,n){if(typeof e!="string"||e==="")return!1;if(Zb(e))return!0;var s=Qb;return n&&n.strict===!1&&(s=ew),s(e)}});var yu=I((AL,gu)=>{"use strict";var tw=mu(),nw=require("path").posix.dirname,sw=require("os").platform()==="win32",Do="/",iw=/\\/g,ow=/[\{\[].*[\}\]]$/,rw=/(^|[^\\])([\{\[]|\([^\)]+$)/,aw=/\\([\!\*\?\|\[\]\(\)\{\}])/g;gu.exports=function(e,n){var s=Object.assign({flipBackslashes:!0},n);s.flipBackslashes&&sw&&e.indexOf(Do)<0&&(e=e.replace(iw,Do)),ow.test(e)&&(e+=Do),e+="a";do e=nw(e);while(tw(e)||rw.test(e));return e.replace(aw,"$1")}});var ii=I(qe=>{"use strict";qe.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;qe.find=(t,e)=>t.nodes.find(n=>n.type===e);qe.exceedsLimit=(t,e,n=1,s)=>s===!1||!qe.isInteger(t)||!qe.isInteger(e)?!1:(Number(e)-Number(t))/Number(n)>=s;qe.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)};qe.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;qe.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;qe.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;qe.reduce=t=>t.reduce((e,n)=>(n.type==="text"&&e.push(n.value),n.type==="range"&&(n.type="text"),e),[]);qe.flatten=(...t)=>{let e=[],n=s=>{for(let i=0;i<s.length;i++){let o=s[i];if(Array.isArray(o)){n(o);continue}o!==void 0&&e.push(o)}return e};return n(t),e}});var oi=I((RL,wu)=>{"use strict";var bu=ii();wu.exports=(t,e={})=>{let n=(s,i={})=>{let o=e.escapeInvalid&&bu.isInvalidBrace(i),r=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(o||r)&&bu.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 Su=I((TL,vu)=>{"use strict";vu.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var Pu=I((PL,Tu)=>{"use strict";var _u=Su(),Jt=(t,e,n)=>{if(_u(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(_u(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),o=String(s.shorthand),r=String(s.capture),a=String(s.wrap),c=t+":"+e+"="+i+o+r+a;if(Jt.cache.hasOwnProperty(c))return Jt.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 p=Ru(t)||Ru(e),d={min:t,max:e,a:l,b:u},h=[],f=[];if(p&&(d.isPadded=p,d.maxLen=String(d.max).length),l<0){let m=u<0?Math.abs(u):1;f=xu(m,Math.abs(l),d,s),l=d.a=0}return u>=0&&(h=xu(l,u,d,s)),d.negatives=f,d.positives=h,d.result=cw(f,h,s),s.capture===!0?d.result=`(${d.result})`:s.wrap!==!1&&h.length+f.length>1&&(d.result=`(?:${d.result})`),Jt.cache[c]=d,d.result};function cw(t,e,n){let s=Fo(t,e,"-",!1,n)||[],i=Fo(e,t,"",!1,n)||[],o=Fo(t,e,"-?",!0,n)||[];return s.concat(o).concat(i).join("|")}function lw(t,e){let n=1,s=1,i=Eu(t,n),o=new Set([e]);for(;t<=i&&i<=e;)o.add(i),n+=1,i=Eu(t,n);for(i=Au(e+1,s)-1;t<i&&i<=e;)o.add(i),s+=1,i=Au(e+1,s)-1;return o=[...o],o.sort(pw),o}function uw(t,e,n){if(t===e)return{pattern:t,count:[],digits:0};let s=dw(t,e),i=s.length,o="",r=0;for(let a=0;a<i;a++){let[c,l]=s[a];c===l?o+=c:c!=="0"||l!=="9"?o+=fw(c,l,n):r++}return r&&(o+=n.shorthand===!0?"\\d":"[0-9]"),{pattern:o,count:[r],digits:i}}function xu(t,e,n,s){let i=lw(t,e),o=[],r=t,a;for(let c=0;c<i.length;c++){let l=i[c],u=uw(String(r),String(l),s),p="";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+Cu(a.count),r=l+1;continue}n.isPadded&&(p=hw(l,n,s)),u.string=p+u.pattern+Cu(u.count),o.push(u),r=l+1,a=u}return o}function Fo(t,e,n,s,i){let o=[];for(let r of t){let{string:a}=r;!s&&!ku(e,"string",a)&&o.push(n+a),s&&ku(e,"string",a)&&o.push(n+a)}return o}function dw(t,e){let n=[];for(let s=0;s<t.length;s++)n.push([t[s],e[s]]);return n}function pw(t,e){return t>e?1:e>t?-1:0}function ku(t,e,n){return t.some(s=>s[e]===n)}function Eu(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function Au(t,e){return t-t%Math.pow(10,e)}function Cu(t){let[e=0,n=""]=t;return n||e>1?`{${e+(n?","+n:"")}}`:""}function fw(t,e,n){return`[${t}${e-t===1?"":"-"}${e}]`}function Ru(t){return/^-?(0+)\d/.test(t)}function hw(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}}`}}Jt.cache={};Jt.clearCache=()=>Jt.cache={};Tu.exports=Jt});var Go=I(($L,ju)=>{"use strict";var mw=require("util"),Iu=Pu(),$u=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),gw=t=>e=>t===!0?Number(e):String(e),Ho=t=>typeof t=="number"||typeof t=="string"&&t!=="",es=t=>Number.isInteger(+t),Bo=t=>{let e=`${t}`,n=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++n]==="0";);return n>0},yw=(t,e,n)=>typeof t=="string"||typeof e=="string"?!0:n.stringify===!0,bw=(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},ai=(t,e)=>{let n=t[0]==="-"?"-":"";for(n&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return n?"-"+t:t},ww=(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="",o="",r;return t.positives.length&&(i=t.positives.map(a=>ai(String(a),n)).join("|")),t.negatives.length&&(o=`-(${s}${t.negatives.map(a=>ai(String(a),n)).join("|")})`),i&&o?r=`${i}|${o}`:r=i||o,e.wrap?`(${s}${r})`:r},Ou=(t,e,n,s)=>{if(n)return Iu(t,e,{wrap:!1,...s});let i=String.fromCharCode(t);if(t===e)return i;let o=String.fromCharCode(e);return`[${i}-${o}]`},Lu=(t,e,n)=>{if(Array.isArray(t)){let s=n.wrap===!0,i=n.capture?"":"?:";return s?`(${i}${t.join("|")})`:t.join("|")}return Iu(t,e,n)},Nu=(...t)=>new RangeError("Invalid range arguments: "+mw.inspect(...t)),Mu=(t,e,n)=>{if(n.strictRanges===!0)throw Nu([t,e]);return[]},vw=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},Sw=(t,e,n=1,s={})=>{let i=Number(t),o=Number(e);if(!Number.isInteger(i)||!Number.isInteger(o)){if(s.strictRanges===!0)throw Nu([t,e]);return[]}i===0&&(i=0),o===0&&(o=0);let r=i>o,a=String(t),c=String(e),l=String(n);n=Math.max(Math.abs(n),1);let u=Bo(a)||Bo(c)||Bo(l),p=u?Math.max(a.length,c.length,l.length):0,d=u===!1&&yw(t,e,s)===!1,h=s.transform||gw(d);if(s.toRegex&&n===1)return Ou(ai(t,p),ai(e,p),!0,s);let f={negatives:[],positives:[]},m=b=>f[b<0?"negatives":"positives"].push(Math.abs(b)),g=[],y=0;for(;r?i>=o:i<=o;)s.toRegex===!0&&n>1?m(i):g.push(bw(h(i,y),p,d)),i=r?i-n:i+n,y++;return s.toRegex===!0?n>1?ww(f,s,p):Lu(g,null,{wrap:!1,...s}):g},_w=(t,e,n=1,s={})=>{if(!es(t)&&t.length>1||!es(e)&&e.length>1)return Mu(t,e,s);let i=s.transform||(d=>String.fromCharCode(d)),o=`${t}`.charCodeAt(0),r=`${e}`.charCodeAt(0),a=o>r,c=Math.min(o,r),l=Math.max(o,r);if(s.toRegex&&n===1)return Ou(c,l,!1,s);let u=[],p=0;for(;a?o>=r:o<=r;)u.push(i(o,p)),o=a?o-n:o+n,p++;return s.toRegex===!0?Lu(u,null,{wrap:!1,options:s}):u},ri=(t,e,n,s={})=>{if(e==null&&Ho(t))return[t];if(!Ho(t)||!Ho(e))return Mu(t,e,s);if(typeof n=="function")return ri(t,e,1,{transform:n});if($u(n))return ri(t,e,0,n);let i={...s};return i.capture===!0&&(i.wrap=!0),n=n||i.step||1,es(n)?es(t)&&es(e)?Sw(t,e,n,i):_w(t,e,Math.max(Math.abs(n),1),i):n!=null&&!$u(n)?vw(n,i):ri(t,e,1,n)};ju.exports=ri});var Hu=I((IL,Fu)=>{"use strict";var xw=Go(),Du=ii(),kw=(t,e={})=>{let n=(s,i={})=>{let o=Du.isInvalidBrace(i),r=s.invalid===!0&&e.escapeInvalid===!0,a=o===!0||r===!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=Du.reduce(s.nodes),p=xw(...u,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(p.length!==0)return u.length>1&&p.length>1?`(${p})`:p}if(s.nodes)for(let u of s.nodes)l+=n(u,s);return l};return n(t)};Fu.exports=kw});var Wu=I((OL,Gu)=>{"use strict";var Ew=Go(),Bu=oi(),En=ii(),Zt=(t="",e="",n=!1)=>{let s=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return n?En.flatten(e).map(i=>`{${i}}`):e;for(let i of t)if(Array.isArray(i))for(let o of i)s.push(Zt(o,e,n));else for(let o of e)n===!0&&typeof o=="string"&&(o=`{${o}}`),s.push(Array.isArray(o)?Zt(i,o,n):i+o);return En.flatten(s)},Aw=(t,e={})=>{let n=e.rangeLimit===void 0?1e3:e.rangeLimit,s=(i,o={})=>{i.queue=[];let r=o,a=o.queue;for(;r.type!=="brace"&&r.type!=="root"&&r.parent;)r=r.parent,a=r.queue;if(i.invalid||i.dollar){a.push(Zt(a.pop(),Bu(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(Zt(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let p=En.reduce(i.nodes);if(En.exceedsLimit(...p,e.step,n))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let d=Ew(...p,e);d.length===0&&(d=Bu(i,e)),a.push(Zt(a.pop(),d)),i.nodes=[];return}let c=En.encloseBrace(i),l=i.queue,u=i;for(;u.type!=="brace"&&u.type!=="root"&&u.parent;)u=u.parent,l=u.queue;for(let p=0;p<i.nodes.length;p++){let d=i.nodes[p];if(d.type==="comma"&&i.type==="brace"){p===1&&l.push(""),l.push("");continue}if(d.type==="close"){a.push(Zt(a.pop(),l,c));continue}if(d.value&&d.type!=="open"){l.push(Zt(l.pop(),d.value));continue}d.nodes&&s(d,i)}return l};return En.flatten(s(t))};Gu.exports=Aw});var Uu=I((LL,Vu)=>{"use strict";Vu.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 Xu=I((NL,Yu)=>{"use strict";var Cw=oi(),{MAX_LENGTH:zu,CHAR_BACKSLASH:Wo,CHAR_BACKTICK:Rw,CHAR_COMMA:Tw,CHAR_DOT:Pw,CHAR_LEFT_PARENTHESES:$w,CHAR_RIGHT_PARENTHESES:Iw,CHAR_LEFT_CURLY_BRACE:Ow,CHAR_RIGHT_CURLY_BRACE:Lw,CHAR_LEFT_SQUARE_BRACKET:qu,CHAR_RIGHT_SQUARE_BRACKET:Ku,CHAR_DOUBLE_QUOTE:Nw,CHAR_SINGLE_QUOTE:Mw,CHAR_NO_BREAK_SPACE:jw,CHAR_ZERO_WIDTH_NOBREAK_SPACE:Dw}=Uu(),Fw=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let n=e||{},s=typeof n.maxLength=="number"?Math.min(zu,n.maxLength):zu;if(t.length>s)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${s})`);let i={type:"root",input:t,nodes:[]},o=[i],r=i,a=i,c=0,l=t.length,u=0,p=0,d,h=()=>t[u++],f=m=>{if(m.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&m.type==="text"){a.value+=m.value;return}return r.nodes.push(m),m.parent=r,m.prev=a,a=m,m};for(f({type:"bos"});u<l;)if(r=o[o.length-1],d=h(),!(d===Dw||d===jw)){if(d===Wo){f({type:"text",value:(e.keepEscaping?d:"")+h()});continue}if(d===Ku){f({type:"text",value:"\\"+d});continue}if(d===qu){c++;let m;for(;u<l&&(m=h());){if(d+=m,m===qu){c++;continue}if(m===Wo){d+=h();continue}if(m===Ku&&(c--,c===0))break}f({type:"text",value:d});continue}if(d===$w){r=f({type:"paren",nodes:[]}),o.push(r),f({type:"text",value:d});continue}if(d===Iw){if(r.type!=="paren"){f({type:"text",value:d});continue}r=o.pop(),f({type:"text",value:d}),r=o[o.length-1];continue}if(d===Nw||d===Mw||d===Rw){let m=d,g;for(e.keepQuotes!==!0&&(d="");u<l&&(g=h());){if(g===Wo){d+=g+h();continue}if(g===m){e.keepQuotes===!0&&(d+=g);break}d+=g}f({type:"text",value:d});continue}if(d===Ow){p++;let g={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||r.dollar===!0,depth:p,commas:0,ranges:0,nodes:[]};r=f(g),o.push(r),f({type:"open",value:d});continue}if(d===Lw){if(r.type!=="brace"){f({type:"text",value:d});continue}let m="close";r=o.pop(),r.close=!0,f({type:m,value:d}),p--,r=o[o.length-1];continue}if(d===Tw&&p>0){if(r.ranges>0){r.ranges=0;let m=r.nodes.shift();r.nodes=[m,{type:"text",value:Cw(r)}]}f({type:"comma",value:d}),r.commas++;continue}if(d===Pw&&p>0&&r.commas===0){let m=r.nodes;if(p===0||m.length===0){f({type:"text",value:d});continue}if(a.type==="dot"){if(r.range=[],a.value+=d,a.type="range",r.nodes.length!==3&&r.nodes.length!==5){r.invalid=!0,r.ranges=0,a.type="text";continue}r.ranges++,r.args=[];continue}if(a.type==="range"){m.pop();let g=m[m.length-1];g.value+=a.value+d,a=g,r.ranges--;continue}f({type:"dot",value:d});continue}f({type:"text",value:d})}do if(r=o.pop(),r.type!=="root"){r.nodes.forEach(y=>{y.nodes||(y.type==="open"&&(y.isOpen=!0),y.type==="close"&&(y.isClose=!0),y.nodes||(y.type="text"),y.invalid=!0)});let m=o[o.length-1],g=m.nodes.indexOf(r);m.nodes.splice(g,1,...r.nodes)}while(o.length>0);return f({type:"eos"}),i};Yu.exports=Fw});var Qu=I((ML,Zu)=>{"use strict";var Ju=oi(),Hw=Hu(),Bw=Wu(),Gw=Xu(),Ve=(t,e={})=>{let n=[];if(Array.isArray(t))for(let s of t){let i=Ve.create(s,e);Array.isArray(i)?n.push(...i):n.push(i)}else n=[].concat(Ve.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(n=[...new Set(n)]),n};Ve.parse=(t,e={})=>Gw(t,e);Ve.stringify=(t,e={})=>Ju(typeof t=="string"?Ve.parse(t,e):t,e);Ve.compile=(t,e={})=>(typeof t=="string"&&(t=Ve.parse(t,e)),Hw(t,e));Ve.expand=(t,e={})=>{typeof t=="string"&&(t=Ve.parse(t,e));let n=Bw(t,e);return e.noempty===!0&&(n=n.filter(Boolean)),e.nodupes===!0&&(n=[...new Set(n)]),n};Ve.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?Ve.compile(t,e):Ve.expand(t,e);Zu.exports=Ve});var ts=I((jL,id)=>{"use strict";var Ww=require("path"),dt="\\\\/",ed=`[^${dt}]`,Vw=0,St="\\.",Uw="\\+",zw="\\?",ci="\\/",qw="(?=.)",td="[^/]",Vo=`(?:${ci}|$)`,nd=`(?:^|${ci})`,Uo=`${St}{1,2}${Vo}`,Kw=`(?!${St})`,Yw=`(?!${nd}${Uo})`,Xw=`(?!${St}{0,1}${Vo})`,Jw=`(?!${Uo})`,Zw=`[^.${ci}]`,Qw=`${td}*?`,sd={DOT_LITERAL:St,PLUS_LITERAL:Uw,QMARK_LITERAL:zw,SLASH_LITERAL:ci,ONE_CHAR:qw,QMARK:td,END_ANCHOR:Vo,DOTS_SLASH:Uo,NO_DOT:Kw,NO_DOTS:Yw,NO_DOT_SLASH:Xw,NO_DOTS_SLASH:Jw,QMARK_NO_DOT:Zw,STAR:Qw,START_ANCHOR:nd},ev={...sd,SLASH_LITERAL:`[${dt}]`,QMARK:ed,STAR:`${ed}*?`,DOTS_SLASH:`${St}{1,2}(?:[${dt}]|$)`,NO_DOT:`(?!${St})`,NO_DOTS:`(?!(?:^|[${dt}])${St}{1,2}(?:[${dt}]|$))`,NO_DOT_SLASH:`(?!${St}{0,1}(?:[${dt}]|$))`,NO_DOTS_SLASH:`(?!${St}{1,2}(?:[${dt}]|$))`,QMARK_NO_DOT:`[^.${dt}]`,START_ANCHOR:`(?:^|[${dt}])`,END_ANCHOR:`(?:[${dt}]|$)`},tv={__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"};id.exports={DEFAULT_MAX_EXTGLOB_RECURSION:Vw,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:tv,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:Ww.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?ev:sd}}});var ns=I(De=>{"use strict";var nv=require("path"),sv=process.platform==="win32",{REGEX_BACKSLASH:iv,REGEX_REMOVE_BACKSLASH:ov,REGEX_SPECIAL_CHARS:rv,REGEX_SPECIAL_CHARS_GLOBAL:av}=ts();De.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);De.hasRegexChars=t=>rv.test(t);De.isRegexChar=t=>t.length===1&&De.hasRegexChars(t);De.escapeRegex=t=>t.replace(av,"\\$1");De.toPosixSlashes=t=>t.replace(iv,"/");De.removeBackslashes=t=>t.replace(ov,e=>e==="\\"?"":e);De.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};De.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:sv===!0||nv.sep==="\\";De.escapeLast=(t,e,n)=>{let s=t.lastIndexOf(e,n);return s===-1?t:t[s-1]==="\\"?De.escapeLast(t,e,s-1):`${t.slice(0,s)}\\${t.slice(s)}`};De.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};De.wrapOutput=(t,e={},n={})=>{let s=n.contains?"":"^",i=n.contains?"":"$",o=`${s}(?:${t})${i}`;return e.negated===!0&&(o=`(?:^(?!${o}).*$)`),o}});var pd=I((FL,dd)=>{"use strict";var od=ns(),{CHAR_ASTERISK:zo,CHAR_AT:cv,CHAR_BACKWARD_SLASH:ss,CHAR_COMMA:lv,CHAR_DOT:qo,CHAR_EXCLAMATION_MARK:Ko,CHAR_FORWARD_SLASH:ud,CHAR_LEFT_CURLY_BRACE:Yo,CHAR_LEFT_PARENTHESES:Xo,CHAR_LEFT_SQUARE_BRACKET:uv,CHAR_PLUS:dv,CHAR_QUESTION_MARK:rd,CHAR_RIGHT_CURLY_BRACE:pv,CHAR_RIGHT_PARENTHESES:ad,CHAR_RIGHT_SQUARE_BRACKET:fv}=ts(),cd=t=>t===ud||t===ss,ld=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},hv=(t,e)=>{let n=e||{},s=t.length-1,i=n.parts===!0||n.scanToEnd===!0,o=[],r=[],a=[],c=t,l=-1,u=0,p=0,d=!1,h=!1,f=!1,m=!1,g=!1,y=!1,b=!1,w=!1,S=!1,C=!1,v=0,_,A,O={value:"",depth:0,isGlob:!1},j=()=>l>=s,x=()=>c.charCodeAt(l+1),D=()=>(_=A,c.charCodeAt(++l));for(;l<s;){A=D();let M;if(A===ss){b=O.backslashes=!0,A=D(),A===Yo&&(y=!0);continue}if(y===!0||A===Yo){for(v++;j()!==!0&&(A=D());){if(A===ss){b=O.backslashes=!0,D();continue}if(A===Yo){v++;continue}if(y!==!0&&A===qo&&(A=D())===qo){if(d=O.isBrace=!0,f=O.isGlob=!0,C=!0,i===!0)continue;break}if(y!==!0&&A===lv){if(d=O.isBrace=!0,f=O.isGlob=!0,C=!0,i===!0)continue;break}if(A===pv&&(v--,v===0)){y=!1,d=O.isBrace=!0,C=!0;break}}if(i===!0)continue;break}if(A===ud){if(o.push(l),r.push(O),O={value:"",depth:0,isGlob:!1},C===!0)continue;if(_===qo&&l===u+1){u+=2;continue}p=l+1;continue}if(n.noext!==!0&&(A===dv||A===cv||A===zo||A===rd||A===Ko)===!0&&x()===Xo){if(f=O.isGlob=!0,m=O.isExtglob=!0,C=!0,A===Ko&&l===u&&(S=!0),i===!0){for(;j()!==!0&&(A=D());){if(A===ss){b=O.backslashes=!0,A=D();continue}if(A===ad){f=O.isGlob=!0,C=!0;break}}continue}break}if(A===zo){if(_===zo&&(g=O.isGlobstar=!0),f=O.isGlob=!0,C=!0,i===!0)continue;break}if(A===rd){if(f=O.isGlob=!0,C=!0,i===!0)continue;break}if(A===uv){for(;j()!==!0&&(M=D());){if(M===ss){b=O.backslashes=!0,D();continue}if(M===fv){h=O.isBracket=!0,f=O.isGlob=!0,C=!0;break}}if(i===!0)continue;break}if(n.nonegate!==!0&&A===Ko&&l===u){w=O.negated=!0,u++;continue}if(n.noparen!==!0&&A===Xo){if(f=O.isGlob=!0,i===!0){for(;j()!==!0&&(A=D());){if(A===Xo){b=O.backslashes=!0,A=D();continue}if(A===ad){C=!0;break}}continue}break}if(f===!0){if(C=!0,i===!0)continue;break}}n.noext===!0&&(m=!1,f=!1);let U=c,te="",k="";u>0&&(te=c.slice(0,u),c=c.slice(u),p-=u),U&&f===!0&&p>0?(U=c.slice(0,p),k=c.slice(p)):f===!0?(U="",k=c):U=c,U&&U!==""&&U!=="/"&&U!==c&&cd(U.charCodeAt(U.length-1))&&(U=U.slice(0,-1)),n.unescape===!0&&(k&&(k=od.removeBackslashes(k)),U&&b===!0&&(U=od.removeBackslashes(U)));let E={prefix:te,input:t,start:u,base:U,glob:k,isBrace:d,isBracket:h,isGlob:f,isExtglob:m,isGlobstar:g,negated:w,negatedExtglob:S};if(n.tokens===!0&&(E.maxDepth=0,cd(A)||r.push(O),E.tokens=r),n.parts===!0||n.tokens===!0){let M;for(let T=0;T<o.length;T++){let ne=M?M+1:u,de=o[T],be=t.slice(ne,de);n.tokens&&(T===0&&u!==0?(r[T].isPrefix=!0,r[T].value=te):r[T].value=be,ld(r[T]),E.maxDepth+=r[T].depth),(T!==0||be!=="")&&a.push(be),M=de}if(M&&M+1<t.length){let T=t.slice(M+1);a.push(T),n.tokens&&(r[r.length-1].value=T,ld(r[r.length-1]),E.maxDepth+=r[r.length-1].depth)}E.slashes=o,E.parts=a}return E};dd.exports=hv});var yd=I((HL,gd)=>{"use strict";var is=ts(),Ce=ns(),{MAX_LENGTH:li,POSIX_REGEX_SOURCE:mv,REGEX_NON_SPECIAL_CHARS:gv,REGEX_SPECIAL_CHARS_BACKREF:yv,REPLACEMENTS:fd}=is,bv=(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=>Ce.escapeRegex(i)).join("..")}return n},An=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,hd=t=>{let e=[],n=0,s=0,i=0,o="",r=!1;for(let a of t){if(r===!0){o+=a,r=!1;continue}if(a==="\\"){o+=a,r=!0;continue}if(a==='"'){i=i===1?0:1,o+=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(o),o="";continue}}}o+=a}return e.push(o),e},wv=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},md=t=>{let e=t.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=!0);if(wv(e))return e.replace(/\\(.)/g,"$1")},vv=t=>{let e=t.map(md).filter(Boolean);for(let n=0;n<e.length;n++)for(let s=n+1;s<e.length;s++){let i=e[n],o=e[s],r=i[0];if(!(!r||i!==r.repeat(i.length)||o!==r.repeat(o.length))&&(i===o||i.startsWith(o)||o.startsWith(i)))return!0}return!1},Jo=(t,e=!0)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let n=0,s=0,i=0,o=!1;for(let r=1;r<t.length;r++){let a=t[r];if(o===!0){o=!1;continue}if(a==="\\"){o=!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&&r!==t.length-1?void 0:{type:t[0],body:t.slice(2,r),end:r}}}}},Sv=t=>{let e=0,n=[];for(;e<t.length;){let i=Jo(t.slice(e),!1);if(!i||i.type!=="*")return;let o=hd(i.body).map(a=>a.trim());if(o.length!==1)return;let r=md(o[0]);if(!r||r.length!==1)return;n.push(r),e+=i.end+1}return n.length<1?void 0:`${n.length===1?Ce.escapeRegex(n[0]):`[${n.map(i=>Ce.escapeRegex(i)).join("")}]`}*`},_v=t=>{let e=0,n=t.trim(),s=Jo(n);for(;s;)e++,n=s.body.trim(),s=Jo(n);return e},xv=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:is.DEFAULT_MAX_EXTGLOB_RECURSION,s=hd(t).map(i=>i.trim());if(s.length>1&&(s.some(i=>i==="")||s.some(i=>/^[*?]+$/.test(i))||vv(s)))return{risky:!0};for(let i of s){let o=Sv(i);if(o)return{risky:!0,safeOutput:o};if(_v(i)>n)return{risky:!0}}return{risky:!1}},Zo=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=fd[t]||t;let n={...e},s=typeof n.maxLength=="number"?Math.min(li,n.maxLength):li,i=t.length;if(i>s)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${s}`);let o={type:"bos",value:"",output:n.prepend||""},r=[o],a=n.capture?"":"?:",c=Ce.isWindows(e),l=is.globChars(c),u=is.extglobChars(l),{DOT_LITERAL:p,PLUS_LITERAL:d,SLASH_LITERAL:h,ONE_CHAR:f,DOTS_SLASH:m,NO_DOT:g,NO_DOT_SLASH:y,NO_DOTS_SLASH:b,QMARK:w,QMARK_NO_DOT:S,STAR:C,START_ANCHOR:v}=l,_=$=>`(${a}(?:(?!${v}${$.dot?m:p}).)*?)`,A=n.dot?"":g,O=n.dot?w:S,j=n.bash===!0?_(n):C;n.capture&&(j=`(${j})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let x={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:r};t=Ce.removePrefix(t,x),i=t.length;let D=[],U=[],te=[],k=o,E,M=()=>x.index===i-1,T=x.peek=($=1)=>t[x.index+$],ne=x.advance=()=>t[++x.index]||"",de=()=>t.slice(x.index+1),be=($="",le=0)=>{x.consumed+=$,x.index+=le},vt=$=>{x.output+=$.output!=null?$.output:$.value,be($.value)},Cb=()=>{let $=1;for(;T()==="!"&&(T(2)!=="("||T(3)==="?");)ne(),x.start++,$++;return $%2===0?!1:(x.negated=!0,x.start++,!0)},Xs=$=>{x[$]++,te.push($)},Tt=$=>{x[$]--,te.pop()},q=$=>{if(k.type==="globstar"){let le=x.braces>0&&($.type==="comma"||$.type==="brace"),P=$.extglob===!0||D.length&&($.type==="pipe"||$.type==="paren");$.type!=="slash"&&$.type!=="paren"&&!le&&!P&&(x.output=x.output.slice(0,-k.output.length),k.type="star",k.value="*",k.output=j,x.output+=k.output)}if(D.length&&$.type!=="paren"&&(D[D.length-1].inner+=$.value),($.value||$.output)&&vt($),k&&k.type==="text"&&$.type==="text"){k.value+=$.value,k.output=(k.output||"")+$.value;return}$.prev=k,r.push($),k=$},Js=($,le)=>{let P={...u[le],conditions:1,inner:""};P.prev=k,P.parens=x.parens,P.output=x.output,P.startIndex=x.index,P.tokensIndex=r.length;let z=(n.capture?"(":"")+P.open;Xs("parens"),q({type:$,value:le,output:x.output?"":f}),q({type:"paren",extglob:!0,value:ne(),output:z}),D.push(P)},Rb=$=>{let le=t.slice($.startIndex,x.index+1),P=t.slice($.startIndex+2,x.index),z=xv(P,n);if(($.type==="plus"||$.type==="star")&&z.risky){let oe=z.safeOutput?($.output?"":f)+(n.capture?`(${z.safeOutput})`:z.safeOutput):void 0,ct=r[$.tokensIndex];ct.type="text",ct.value=le,ct.output=oe||Ce.escapeRegex(le);for(let lt=$.tokensIndex+1;lt<r.length;lt++)r[lt].value="",r[lt].output="",delete r[lt].suffix;x.output=$.output+ct.output,x.backtrack=!0,q({type:"paren",extglob:!0,value:E,output:""}),Tt("parens");return}let re=$.close+(n.capture?")":""),me;if($.type==="negate"){let oe=j;if($.inner&&$.inner.length>1&&$.inner.includes("/")&&(oe=_(n)),(oe!==j||M()||/^\)+$/.test(de()))&&(re=$.close=`)$))${oe}`),$.inner.includes("*")&&(me=de())&&/^\.[^\\/.]+$/.test(me)){let ct=Zo(me,{...e,fastpaths:!1}).output;re=$.close=`)${ct})${oe})`}$.prev.type==="bos"&&(x.negatedExtglob=!0)}q({type:"paren",extglob:!0,value:E,output:re}),Tt("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let $=!1,le=t.replace(yv,(P,z,re,me,oe,ct)=>me==="\\"?($=!0,P):me==="?"?z?z+me+(oe?w.repeat(oe.length):""):ct===0?O+(oe?w.repeat(oe.length):""):w.repeat(re.length):me==="."?p.repeat(re.length):me==="*"?z?z+me+(oe?j:""):j:z?P:`\\${P}`);return $===!0&&(n.unescape===!0?le=le.replace(/\\/g,""):le=le.replace(/\\+/g,P=>P.length%2===0?"\\\\":P?"\\":"")),le===t&&n.contains===!0?(x.output=t,x):(x.output=Ce.wrapOutput(le,x,e),x)}for(;!M();){if(E=ne(),E==="\0")continue;if(E==="\\"){let P=T();if(P==="/"&&n.bash!==!0||P==="."||P===";")continue;if(!P){E+="\\",q({type:"text",value:E});continue}let z=/^\\+/.exec(de()),re=0;if(z&&z[0].length>2&&(re=z[0].length,x.index+=re,re%2!==0&&(E+="\\")),n.unescape===!0?E=ne():E+=ne(),x.brackets===0){q({type:"text",value:E});continue}}if(x.brackets>0&&(E!=="]"||k.value==="["||k.value==="[^")){if(n.posix!==!1&&E===":"){let P=k.value.slice(1);if(P.includes("[")&&(k.posix=!0,P.includes(":"))){let z=k.value.lastIndexOf("["),re=k.value.slice(0,z),me=k.value.slice(z+2),oe=mv[me];if(oe){k.value=re+oe,x.backtrack=!0,ne(),!o.output&&r.indexOf(k)===1&&(o.output=f);continue}}}(E==="["&&T()!==":"||E==="-"&&T()==="]")&&(E=`\\${E}`),E==="]"&&(k.value==="["||k.value==="[^")&&(E=`\\${E}`),n.posix===!0&&E==="!"&&k.value==="["&&(E="^"),k.value+=E,vt({value:E});continue}if(x.quotes===1&&E!=='"'){E=Ce.escapeRegex(E),k.value+=E,vt({value:E});continue}if(E==='"'){x.quotes=x.quotes===1?0:1,n.keepQuotes===!0&&q({type:"text",value:E});continue}if(E==="("){Xs("parens"),q({type:"paren",value:E});continue}if(E===")"){if(x.parens===0&&n.strictBrackets===!0)throw new SyntaxError(An("opening","("));let P=D[D.length-1];if(P&&x.parens===P.parens+1){Rb(D.pop());continue}q({type:"paren",value:E,output:x.parens?")":"\\)"}),Tt("parens");continue}if(E==="["){if(n.nobracket===!0||!de().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(An("closing","]"));E=`\\${E}`}else Xs("brackets");q({type:"bracket",value:E});continue}if(E==="]"){if(n.nobracket===!0||k&&k.type==="bracket"&&k.value.length===1){q({type:"text",value:E,output:`\\${E}`});continue}if(x.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(An("opening","["));q({type:"text",value:E,output:`\\${E}`});continue}Tt("brackets");let P=k.value.slice(1);if(k.posix!==!0&&P[0]==="^"&&!P.includes("/")&&(E=`/${E}`),k.value+=E,vt({value:E}),n.literalBrackets===!1||Ce.hasRegexChars(P))continue;let z=Ce.escapeRegex(k.value);if(x.output=x.output.slice(0,-k.value.length),n.literalBrackets===!0){x.output+=z,k.value=z;continue}k.value=`(${a}${z}|${k.value})`,x.output+=k.value;continue}if(E==="{"&&n.nobrace!==!0){Xs("braces");let P={type:"brace",value:E,output:"(",outputIndex:x.output.length,tokensIndex:x.tokens.length};U.push(P),q(P);continue}if(E==="}"){let P=U[U.length-1];if(n.nobrace===!0||!P){q({type:"text",value:E,output:E});continue}let z=")";if(P.dots===!0){let re=r.slice(),me=[];for(let oe=re.length-1;oe>=0&&(r.pop(),re[oe].type!=="brace");oe--)re[oe].type!=="dots"&&me.unshift(re[oe].value);z=bv(me,n),x.backtrack=!0}if(P.comma!==!0&&P.dots!==!0){let re=x.output.slice(0,P.outputIndex),me=x.tokens.slice(P.tokensIndex);P.value=P.output="\\{",E=z="\\}",x.output=re;for(let oe of me)x.output+=oe.output||oe.value}q({type:"brace",value:E,output:z}),Tt("braces"),U.pop();continue}if(E==="|"){D.length>0&&D[D.length-1].conditions++,q({type:"text",value:E});continue}if(E===","){let P=E,z=U[U.length-1];z&&te[te.length-1]==="braces"&&(z.comma=!0,P="|"),q({type:"comma",value:E,output:P});continue}if(E==="/"){if(k.type==="dot"&&x.index===x.start+1){x.start=x.index+1,x.consumed="",x.output="",r.pop(),k=o;continue}q({type:"slash",value:E,output:h});continue}if(E==="."){if(x.braces>0&&k.type==="dot"){k.value==="."&&(k.output=p);let P=U[U.length-1];k.type="dots",k.output+=E,k.value+=E,P.dots=!0;continue}if(x.braces+x.parens===0&&k.type!=="bos"&&k.type!=="slash"){q({type:"text",value:E,output:p});continue}q({type:"dot",value:E,output:p});continue}if(E==="?"){if(!(k&&k.value==="(")&&n.noextglob!==!0&&T()==="("&&T(2)!=="?"){Js("qmark",E);continue}if(k&&k.type==="paren"){let z=T(),re=E;if(z==="<"&&!Ce.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(k.value==="("&&!/[!=<:]/.test(z)||z==="<"&&!/<([!=]|\w+>)/.test(de()))&&(re=`\\${E}`),q({type:"text",value:E,output:re});continue}if(n.dot!==!0&&(k.type==="slash"||k.type==="bos")){q({type:"qmark",value:E,output:S});continue}q({type:"qmark",value:E,output:w});continue}if(E==="!"){if(n.noextglob!==!0&&T()==="("&&(T(2)!=="?"||!/[!=<:]/.test(T(3)))){Js("negate",E);continue}if(n.nonegate!==!0&&x.index===0){Cb();continue}}if(E==="+"){if(n.noextglob!==!0&&T()==="("&&T(2)!=="?"){Js("plus",E);continue}if(k&&k.value==="("||n.regex===!1){q({type:"plus",value:E,output:d});continue}if(k&&(k.type==="bracket"||k.type==="paren"||k.type==="brace")||x.parens>0){q({type:"plus",value:E});continue}q({type:"plus",value:d});continue}if(E==="@"){if(n.noextglob!==!0&&T()==="("&&T(2)!=="?"){q({type:"at",extglob:!0,value:E,output:""});continue}q({type:"text",value:E});continue}if(E!=="*"){(E==="$"||E==="^")&&(E=`\\${E}`);let P=gv.exec(de());P&&(E+=P[0],x.index+=P[0].length),q({type:"text",value:E});continue}if(k&&(k.type==="globstar"||k.star===!0)){k.type="star",k.star=!0,k.value+=E,k.output=j,x.backtrack=!0,x.globstar=!0,be(E);continue}let $=de();if(n.noextglob!==!0&&/^\([^?]/.test($)){Js("star",E);continue}if(k.type==="star"){if(n.noglobstar===!0){be(E);continue}let P=k.prev,z=P.prev,re=P.type==="slash"||P.type==="bos",me=z&&(z.type==="star"||z.type==="globstar");if(n.bash===!0&&(!re||$[0]&&$[0]!=="/")){q({type:"star",value:E,output:""});continue}let oe=x.braces>0&&(P.type==="comma"||P.type==="brace"),ct=D.length&&(P.type==="pipe"||P.type==="paren");if(!re&&P.type!=="paren"&&!oe&&!ct){q({type:"star",value:E,output:""});continue}for(;$.slice(0,3)==="/**";){let lt=t[x.index+4];if(lt&&lt!=="/")break;$=$.slice(3),be("/**",3)}if(P.type==="bos"&&M()){k.type="globstar",k.value+=E,k.output=_(n),x.output=k.output,x.globstar=!0,be(E);continue}if(P.type==="slash"&&P.prev.type!=="bos"&&!me&&M()){x.output=x.output.slice(0,-(P.output+k.output).length),P.output=`(?:${P.output}`,k.type="globstar",k.output=_(n)+(n.strictSlashes?")":"|$)"),k.value+=E,x.globstar=!0,x.output+=P.output+k.output,be(E);continue}if(P.type==="slash"&&P.prev.type!=="bos"&&$[0]==="/"){let lt=$[1]!==void 0?"|$":"";x.output=x.output.slice(0,-(P.output+k.output).length),P.output=`(?:${P.output}`,k.type="globstar",k.output=`${_(n)}${h}|${h}${lt})`,k.value+=E,x.output+=P.output+k.output,x.globstar=!0,be(E+ne()),q({type:"slash",value:"/",output:""});continue}if(P.type==="bos"&&$[0]==="/"){k.type="globstar",k.value+=E,k.output=`(?:^|${h}|${_(n)}${h})`,x.output=k.output,x.globstar=!0,be(E+ne()),q({type:"slash",value:"/",output:""});continue}x.output=x.output.slice(0,-k.output.length),k.type="globstar",k.output=_(n),k.value+=E,x.output+=k.output,x.globstar=!0,be(E);continue}let le={type:"star",value:E,output:j};if(n.bash===!0){le.output=".*?",(k.type==="bos"||k.type==="slash")&&(le.output=A+le.output),q(le);continue}if(k&&(k.type==="bracket"||k.type==="paren")&&n.regex===!0){le.output=E,q(le);continue}(x.index===x.start||k.type==="slash"||k.type==="dot")&&(k.type==="dot"?(x.output+=y,k.output+=y):n.dot===!0?(x.output+=b,k.output+=b):(x.output+=A,k.output+=A),T()!=="*"&&(x.output+=f,k.output+=f)),q(le)}for(;x.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(An("closing","]"));x.output=Ce.escapeLast(x.output,"["),Tt("brackets")}for(;x.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(An("closing",")"));x.output=Ce.escapeLast(x.output,"("),Tt("parens")}for(;x.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(An("closing","}"));x.output=Ce.escapeLast(x.output,"{"),Tt("braces")}if(n.strictSlashes!==!0&&(k.type==="star"||k.type==="bracket")&&q({type:"maybe_slash",value:"",output:`${h}?`}),x.backtrack===!0){x.output="";for(let $ of x.tokens)x.output+=$.output!=null?$.output:$.value,$.suffix&&(x.output+=$.suffix)}return x};Zo.fastpaths=(t,e)=>{let n={...e},s=typeof n.maxLength=="number"?Math.min(li,n.maxLength):li,i=t.length;if(i>s)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${s}`);t=fd[t]||t;let o=Ce.isWindows(e),{DOT_LITERAL:r,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:l,NO_DOT:u,NO_DOTS:p,NO_DOTS_SLASH:d,STAR:h,START_ANCHOR:f}=is.globChars(o),m=n.dot?p:u,g=n.dot?d:u,y=n.capture?"":"?:",b={negated:!1,prefix:""},w=n.bash===!0?".*?":h;n.capture&&(w=`(${w})`);let S=A=>A.noglobstar===!0?w:`(${y}(?:(?!${f}${A.dot?l:r}).)*?)`,C=A=>{switch(A){case"*":return`${m}${c}${w}`;case".*":return`${r}${c}${w}`;case"*.*":return`${m}${w}${r}${c}${w}`;case"*/*":return`${m}${w}${a}${c}${g}${w}`;case"**":return m+S(n);case"**/*":return`(?:${m}${S(n)}${a})?${g}${c}${w}`;case"**/*.*":return`(?:${m}${S(n)}${a})?${g}${w}${r}${c}${w}`;case"**/.*":return`(?:${m}${S(n)}${a})?${r}${c}${w}`;default:{let O=/^(.*?)\.(\w+)$/.exec(A);if(!O)return;let j=C(O[1]);return j?j+r+O[2]:void 0}}},v=Ce.removePrefix(t,b),_=C(v);return _&&n.strictSlashes!==!0&&(_+=`${a}?`),_};gd.exports=Zo});var wd=I((BL,bd)=>{"use strict";var kv=require("path"),Ev=pd(),Qo=yd(),er=ns(),Av=ts(),Cv=t=>t&&typeof t=="object"&&!Array.isArray(t),pe=(t,e,n=!1)=>{if(Array.isArray(t)){let u=t.map(d=>pe(d,e,n));return d=>{for(let h of u){let f=h(d);if(f)return f}return!1}}let s=Cv(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||{},o=er.isWindows(e),r=s?pe.compileRe(t,e):pe.makeRe(t,e,!1,!0),a=r.state;delete r.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=pe(i.ignore,u,n)}let l=(u,p=!1)=>{let{isMatch:d,match:h,output:f}=pe.test(u,r,e,{glob:t,posix:o}),m={glob:t,state:a,regex:r,posix:o,input:u,output:f,match:h,isMatch:d};return typeof i.onResult=="function"&&i.onResult(m),d===!1?(m.isMatch=!1,p?m:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(m),m.isMatch=!1,p?m:!1):(typeof i.onMatch=="function"&&i.onMatch(m),p?m:!0)};return n&&(l.state=a),l};pe.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 o=n||{},r=o.format||(i?er.toPosixSlashes:null),a=t===s,c=a&&r?r(t):t;return a===!1&&(c=r?r(t):t,a=c===s),(a===!1||o.capture===!0)&&(o.matchBase===!0||o.basename===!0?a=pe.matchBase(t,e,n,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};pe.matchBase=(t,e,n,s=er.isWindows(n))=>(e instanceof RegExp?e:pe.makeRe(e,n)).test(kv.basename(t));pe.isMatch=(t,e,n)=>pe(e,n)(t);pe.parse=(t,e)=>Array.isArray(t)?t.map(n=>pe.parse(n,e)):Qo(t,{...e,fastpaths:!1});pe.scan=(t,e)=>Ev(t,e);pe.compileRe=(t,e,n=!1,s=!1)=>{if(n===!0)return t.output;let i=e||{},o=i.contains?"":"^",r=i.contains?"":"$",a=`${o}(?:${t.output})${r}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let c=pe.toRegex(a,e);return s===!0&&(c.state=t),c};pe.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=Qo.fastpaths(t,e)),i.output||(i=Qo(t,e)),pe.compileRe(i,e,n,s)};pe.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/$^/}};pe.constants=Av;bd.exports=pe});var Sd=I((GL,vd)=>{"use strict";vd.exports=wd()});var _t=I((WL,Ad)=>{"use strict";var xd=require("util"),kd=Qu(),pt=Sd(),tr=ns(),_d=t=>t===""||t==="./",Ed=t=>{let e=t.indexOf("{");return e>-1&&t.indexOf("}",e)>-1},ae=(t,e,n)=>{e=[].concat(e),t=[].concat(t);let s=new Set,i=new Set,o=new Set,r=0,a=u=>{o.add(u.output),n&&n.onResult&&n.onResult(u)};for(let u=0;u<e.length;u++){let p=pt(String(e[u]),{...n,onResult:a},!0),d=p.state.negated||p.state.negatedExtglob;d&&r++;for(let h of t){let f=p(h,!0);(d?!f.isMatch:f.isMatch)&&(d?s.add(f.output):(s.delete(f.output),i.add(f.output)))}}let l=(r===e.length?[...o]:[...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};ae.match=ae;ae.matcher=(t,e)=>pt(t,e);ae.isMatch=(t,e,n)=>pt(e,n)(t);ae.any=ae.isMatch;ae.not=(t,e,n={})=>{e=[].concat(e).map(String);let s=new Set,i=[],o=a=>{n.onResult&&n.onResult(a),i.push(a.output)},r=new Set(ae(t,e,{...n,onResult:o}));for(let a of i)r.has(a)||s.add(a);return[...s]};ae.contains=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${xd.inspect(t)}"`);if(Array.isArray(e))return e.some(s=>ae.contains(t,s,n));if(typeof e=="string"){if(_d(t)||_d(e))return!1;if(t.includes(e)||t.startsWith("./")&&t.slice(2).includes(e))return!0}return ae.isMatch(t,e,{...n,contains:!0})};ae.matchKeys=(t,e,n)=>{if(!tr.isObject(t))throw new TypeError("Expected the first argument to be an object");let s=ae(Object.keys(t),e,n),i={};for(let o of s)i[o]=t[o];return i};ae.some=(t,e,n)=>{let s=[].concat(t);for(let i of[].concat(e)){let o=pt(String(i),n);if(s.some(r=>o(r)))return!0}return!1};ae.every=(t,e,n)=>{let s=[].concat(t);for(let i of[].concat(e)){let o=pt(String(i),n);if(!s.every(r=>o(r)))return!1}return!0};ae.all=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${xd.inspect(t)}"`);return[].concat(e).every(s=>pt(s,n)(t))};ae.capture=(t,e,n)=>{let s=tr.isWindows(n),o=pt.makeRe(String(t),{...n,capture:!0}).exec(s?tr.toPosixSlashes(e):e);if(o)return o.slice(1).map(r=>r===void 0?"":r)};ae.makeRe=(...t)=>pt.makeRe(...t);ae.scan=(...t)=>pt.scan(...t);ae.parse=(t,e)=>{let n=[];for(let s of[].concat(t||[]))for(let i of kd(String(s),e))n.push(pt.parse(i,e));return n};ae.braces=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return e&&e.nobrace===!0||!Ed(t)?[t]:kd(t,e)};ae.braceExpand=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return ae.braces(t,{...e,expand:!0})};ae.hasBraces=Ed;Ad.exports=ae});var Md=I(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.isAbsolute=B.partitionAbsoluteAndRelative=B.removeDuplicateSlashes=B.matchAny=B.convertPatternsToRe=B.makeRe=B.getPatternParts=B.expandBraceExpansion=B.expandPatternsWithBraceExpansion=B.isAffectDepthOfReadingPattern=B.endsWithSlashGlobStar=B.hasGlobStar=B.getBaseDirectory=B.isPatternRelatedToParentDirectory=B.getPatternsOutsideCurrentDirectory=B.getPatternsInsideCurrentDirectory=B.getPositivePatterns=B.getNegativePatterns=B.isPositivePattern=B.isNegativePattern=B.convertToNegativePattern=B.convertToPositivePattern=B.isDynamicPattern=B.isStaticPattern=void 0;var Cd=require("path"),Rv=yu(),nr=_t(),Rd="**",Tv="\\",Pv=/[*?]|^!/,$v=/\[[^[]*]/,Iv=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,Ov=/[!*+?@]\([^(]*\)/,Lv=/,|\.\./,Nv=/(?!^)\/{2,}/g;function Td(t,e={}){return!Pd(t,e)}B.isStaticPattern=Td;function Pd(t,e={}){return t===""?!1:!!(e.caseSensitiveMatch===!1||t.includes(Tv)||Pv.test(t)||$v.test(t)||Iv.test(t)||e.extglob!==!1&&Ov.test(t)||e.braceExpansion!==!1&&Mv(t))}B.isDynamicPattern=Pd;function Mv(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 Lv.test(s)}function jv(t){return ui(t)?t.slice(1):t}B.convertToPositivePattern=jv;function Dv(t){return"!"+t}B.convertToNegativePattern=Dv;function ui(t){return t.startsWith("!")&&t[1]!=="("}B.isNegativePattern=ui;function $d(t){return!ui(t)}B.isPositivePattern=$d;function Fv(t){return t.filter(ui)}B.getNegativePatterns=Fv;function Hv(t){return t.filter($d)}B.getPositivePatterns=Hv;function Bv(t){return t.filter(e=>!sr(e))}B.getPatternsInsideCurrentDirectory=Bv;function Gv(t){return t.filter(sr)}B.getPatternsOutsideCurrentDirectory=Gv;function sr(t){return t.startsWith("..")||t.startsWith("./..")}B.isPatternRelatedToParentDirectory=sr;function Wv(t){return Rv(t,{flipBackslashes:!1})}B.getBaseDirectory=Wv;function Vv(t){return t.includes(Rd)}B.hasGlobStar=Vv;function Id(t){return t.endsWith("/"+Rd)}B.endsWithSlashGlobStar=Id;function Uv(t){let e=Cd.basename(t);return Id(t)||Td(e)}B.isAffectDepthOfReadingPattern=Uv;function zv(t){return t.reduce((e,n)=>e.concat(Od(n)),[])}B.expandPatternsWithBraceExpansion=zv;function Od(t){let e=nr.braces(t,{expand:!0,nodupes:!0,keepEscaping:!0});return e.sort((n,s)=>n.length-s.length),e.filter(n=>n!=="")}B.expandBraceExpansion=Od;function qv(t,e){let{parts:n}=nr.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}B.getPatternParts=qv;function Ld(t,e){return nr.makeRe(t,e)}B.makeRe=Ld;function Kv(t,e){return t.map(n=>Ld(n,e))}B.convertPatternsToRe=Kv;function Yv(t,e){return e.some(n=>n.test(t))}B.matchAny=Yv;function Xv(t){return t.replace(Nv,"/")}B.removeDuplicateSlashes=Xv;function Jv(t){let e=[],n=[];for(let s of t)Nd(s)?e.push(s):n.push(s);return[e,n]}B.partitionAbsoluteAndRelative=Jv;function Nd(t){return Cd.isAbsolute(t)}B.isAbsolute=Nd});var Hd=I((UL,Fd)=>{"use strict";var Zv=require("stream"),jd=Zv.PassThrough,Qv=Array.prototype.slice;Fd.exports=e0;function e0(){let t=[],e=Qv.call(arguments),n=!1,s=e[e.length-1];s&&!Array.isArray(s)&&s.pipe==null?e.pop():s={};let i=s.end!==!1,o=s.pipeError===!0;s.objectMode==null&&(s.objectMode=!0),s.highWaterMark==null&&(s.highWaterMark=64*1024);let r=jd(s);function a(){for(let u=0,p=arguments.length;u<p;u++)t.push(Dd(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 p=u.length+1;function d(){--p>0||(n=!1,c())}function h(f){function m(){f.removeListener("merge2UnpipeEnd",m),f.removeListener("end",m),o&&f.removeListener("error",g),d()}function g(y){r.emit("error",y)}if(f._readableState.endEmitted)return d();f.on("merge2UnpipeEnd",m),f.on("end",m),o&&f.on("error",g),f.pipe(r,{end:!1}),f.resume()}for(let f=0;f<u.length;f++)h(u[f]);d()}function l(){n=!1,r.emit("queueDrain"),i&&r.end()}return r.setMaxListeners(0),r.add=a,r.on("unpipe",function(u){u.emit("merge2UnpipeEnd")}),e.length&&a.apply(null,e),r}function Dd(t,e){if(Array.isArray(t))for(let n=0,s=t.length;n<s;n++)t[n]=Dd(t[n],e);else{if(!t._readableState&&t.pipe&&(t=t.pipe(jd(e))),!t._readableState||!t.pause||!t.pipe)throw new Error("Only readable stream can be merged.");t.pause()}return t}});var Gd=I(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.merge=void 0;var t0=Hd();function n0(t){let e=t0(t);return t.forEach(n=>{n.once("error",s=>e.emit("error",s))}),e.once("close",()=>Bd(t)),e.once("end",()=>Bd(t)),e}di.merge=n0;function Bd(t){t.forEach(e=>e.emit("close"))}});var Wd=I(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.isEmpty=Cn.isString=void 0;function s0(t){return typeof t=="string"}Cn.isString=s0;function i0(t){return t===""}Cn.isEmpty=i0});var xt=I(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.string=Re.stream=Re.pattern=Re.path=Re.fs=Re.errno=Re.array=void 0;var o0=iu();Re.array=o0;var r0=ou();Re.errno=r0;var a0=ru();Re.fs=a0;var c0=uu();Re.path=c0;var l0=Md();Re.pattern=l0;var u0=Gd();Re.stream=u0;var d0=Wd();Re.string=d0});var qd=I(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.convertPatternGroupToTask=Te.convertPatternGroupsToTasks=Te.groupPatternsByBaseDirectory=Te.getNegativePatternsAsPositive=Te.getPositivePatterns=Te.convertPatternsToTasks=Te.generate=void 0;var tt=xt();function p0(t,e){let n=Vd(t,e),s=Vd(e.ignore,e),i=Ud(n),o=zd(n,s),r=i.filter(u=>tt.pattern.isStaticPattern(u,e)),a=i.filter(u=>tt.pattern.isDynamicPattern(u,e)),c=ir(r,o,!1),l=ir(a,o,!0);return c.concat(l)}Te.generate=p0;function Vd(t,e){let n=t;return e.braceExpansion&&(n=tt.pattern.expandPatternsWithBraceExpansion(n)),e.baseNameMatch&&(n=n.map(s=>s.includes("/")?s:`**/${s}`)),n.map(s=>tt.pattern.removeDuplicateSlashes(s))}function ir(t,e,n){let s=[],i=tt.pattern.getPatternsOutsideCurrentDirectory(t),o=tt.pattern.getPatternsInsideCurrentDirectory(t),r=or(i),a=or(o);return s.push(...rr(r,e,n)),"."in a?s.push(ar(".",o,e,n)):s.push(...rr(a,e,n)),s}Te.convertPatternsToTasks=ir;function Ud(t){return tt.pattern.getPositivePatterns(t)}Te.getPositivePatterns=Ud;function zd(t,e){return tt.pattern.getNegativePatterns(t).concat(e).map(tt.pattern.convertToPositivePattern)}Te.getNegativePatternsAsPositive=zd;function or(t){let e={};return t.reduce((n,s)=>{let i=tt.pattern.getBaseDirectory(s);return i in n?n[i].push(s):n[i]=[s],n},e)}Te.groupPatternsByBaseDirectory=or;function rr(t,e,n){return Object.keys(t).map(s=>ar(s,t[s],e,n))}Te.convertPatternGroupsToTasks=rr;function ar(t,e,n,s){return{dynamic:s,positive:e,negative:n,base:t,patterns:[].concat(e,n.map(tt.pattern.convertToNegativePattern))}}Te.convertPatternGroupToTask=ar});var Yd=I(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});pi.read=void 0;function f0(t,e,n){e.fs.lstat(t,(s,i)=>{if(s!==null){Kd(n,s);return}if(!i.isSymbolicLink()||!e.followSymbolicLink){cr(n,i);return}e.fs.stat(t,(o,r)=>{if(o!==null){if(e.throwErrorOnBrokenSymbolicLink){Kd(n,o);return}cr(n,i);return}e.markSymbolicLink&&(r.isSymbolicLink=()=>!0),cr(n,r)})})}pi.read=f0;function Kd(t,e){t(e)}function cr(t,e){t(null,e)}});var Xd=I(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.read=void 0;function h0(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}}fi.read=h0});var Jd=I($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.createFileSystemAdapter=$t.FILE_SYSTEM_ADAPTER=void 0;var hi=require("fs");$t.FILE_SYSTEM_ADAPTER={lstat:hi.lstat,stat:hi.stat,lstatSync:hi.lstatSync,statSync:hi.statSync};function m0(t){return t===void 0?$t.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},$t.FILE_SYSTEM_ADAPTER),t)}$t.createFileSystemAdapter=m0});var Zd=I(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});var g0=Jd(),lr=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=g0.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}};ur.default=lr});var Qt=I(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.statSync=It.stat=It.Settings=void 0;var Qd=Yd(),y0=Xd(),dr=Zd();It.Settings=dr.default;function b0(t,e,n){if(typeof e=="function"){Qd.read(t,pr(),e);return}Qd.read(t,pr(e),n)}It.stat=b0;function w0(t,e){let n=pr(e);return y0.read(t,n)}It.statSync=w0;function pr(t={}){return t instanceof dr.default?t:new dr.default(t)}});var np=I((tN,tp)=>{var ep;tp.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:global):t=>(ep||(ep=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var ip=I((nN,sp)=>{sp.exports=S0;var v0=np();function S0(t,e){let n,s,i,o=!0;Array.isArray(t)?(n=[],s=t.length):(i=Object.keys(t),n={},s=i.length);function r(c){function l(){e&&e(c,n),e=null}o?v0(l):l()}function a(c,l,u){n[c]=u,(--s===0||l)&&r(l)}s?i?i.forEach(function(c){t[c](function(l,u){a(c,l,u)})}):t.forEach(function(c,l){c(function(u,p){a(l,u,p)})}):r(null),o=!1}});var fr=I(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var mi=process.versions.node.split(".");if(mi[0]===void 0||mi[1]===void 0)throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var op=Number.parseInt(mi[0],10),_0=Number.parseInt(mi[1],10),rp=10,x0=10,k0=op>rp,E0=op===rp&&_0>=x0;gi.IS_SUPPORT_READDIR_WITH_FILE_TYPES=k0||E0});var ap=I(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.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 A0(t,e){return new hr(t,e)}yi.createDirentFromStats=A0});var mr=I(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.fs=void 0;var C0=ap();bi.fs=C0});var gr=I(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.joinPathSegments=void 0;function R0(t,e,n){return t.endsWith(n)?t+e:t+n+e}wi.joinPathSegments=R0});var fp=I(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.readdir=Ot.readdirWithFileTypes=Ot.read=void 0;var T0=Qt(),cp=ip(),P0=fr(),lp=mr(),up=gr();function $0(t,e,n){if(!e.stats&&P0.IS_SUPPORT_READDIR_WITH_FILE_TYPES){dp(t,e,n);return}pp(t,e,n)}Ot.read=$0;function dp(t,e,n){e.fs.readdir(t,{withFileTypes:!0},(s,i)=>{if(s!==null){vi(n,s);return}let o=i.map(a=>({dirent:a,name:a.name,path:up.joinPathSegments(t,a.name,e.pathSegmentSeparator)}));if(!e.followSymbolicLinks){yr(n,o);return}let r=o.map(a=>I0(a,e));cp(r,(a,c)=>{if(a!==null){vi(n,a);return}yr(n,c)})})}Ot.readdirWithFileTypes=dp;function I0(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=lp.fs.createDirentFromStats(t.name,i),n(null,t)})}}function pp(t,e,n){e.fs.readdir(t,(s,i)=>{if(s!==null){vi(n,s);return}let o=i.map(r=>{let a=up.joinPathSegments(t,r,e.pathSegmentSeparator);return c=>{T0.stat(a,e.fsStatSettings,(l,u)=>{if(l!==null){c(l);return}let p={name:r,path:a,dirent:lp.fs.createDirentFromStats(r,u)};e.stats&&(p.stats=u),c(null,p)})}});cp(o,(r,a)=>{if(r!==null){vi(n,r);return}yr(n,a)})})}Ot.readdir=pp;function vi(t,e){t(e)}function yr(t,e){t(null,e)}});var bp=I(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.readdir=Lt.readdirWithFileTypes=Lt.read=void 0;var O0=Qt(),L0=fr(),hp=mr(),mp=gr();function N0(t,e){return!e.stats&&L0.IS_SUPPORT_READDIR_WITH_FILE_TYPES?gp(t,e):yp(t,e)}Lt.read=N0;function gp(t,e){return e.fs.readdirSync(t,{withFileTypes:!0}).map(s=>{let i={dirent:s,name:s.name,path:mp.joinPathSegments(t,s.name,e.pathSegmentSeparator)};if(i.dirent.isSymbolicLink()&&e.followSymbolicLinks)try{let o=e.fs.statSync(i.path);i.dirent=hp.fs.createDirentFromStats(i.name,o)}catch(o){if(e.throwErrorOnBrokenSymbolicLink)throw o}return i})}Lt.readdirWithFileTypes=gp;function yp(t,e){return e.fs.readdirSync(t).map(s=>{let i=mp.joinPathSegments(t,s,e.pathSegmentSeparator),o=O0.statSync(i,e.fsStatSettings),r={name:s,path:i,dirent:hp.fs.createDirentFromStats(s,o)};return e.stats&&(r.stats=o),r})}Lt.readdir=yp});var wp=I(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.createFileSystemAdapter=Nt.FILE_SYSTEM_ADAPTER=void 0;var Rn=require("fs");Nt.FILE_SYSTEM_ADAPTER={lstat:Rn.lstat,stat:Rn.stat,lstatSync:Rn.lstatSync,statSync:Rn.statSync,readdir:Rn.readdir,readdirSync:Rn.readdirSync};function M0(t){return t===void 0?Nt.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},Nt.FILE_SYSTEM_ADAPTER),t)}Nt.createFileSystemAdapter=M0});var vp=I(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});var j0=require("path"),D0=Qt(),F0=wp(),br=class{constructor(e={}){this._options=e,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=F0.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,j0.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new D0.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue(e,n){return e??n}};wr.default=br});var Si=I(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.Settings=Mt.scandirSync=Mt.scandir=void 0;var Sp=fp(),H0=bp(),vr=vp();Mt.Settings=vr.default;function B0(t,e,n){if(typeof e=="function"){Sp.read(t,Sr(),e);return}Sp.read(t,Sr(e),n)}Mt.scandir=B0;function G0(t,e){let n=Sr(e);return H0.read(t,n)}Mt.scandirSync=G0;function Sr(t={}){return t instanceof vr.default?t:new vr.default(t)}});var xp=I((pN,_p)=>{"use strict";function W0(t){var e=new t,n=e;function s(){var o=e;return o.next?e=o.next:(e=new t,n=e),o.next=null,o}function i(o){n.next=o,n=o}return{get:s,release:i}}_p.exports=W0});var Ep=I((fN,_r)=>{"use strict";var V0=xp();function kp(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=V0(U0),i=null,o=null,r=0,a=null,c={push:m,drain:Fe,saturated:Fe,pause:u,paused:!1,get concurrency(){return n},set concurrency(v){if(!(v>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(n=v,!c.paused)for(;i&&r<n;)r++,y()},running:l,resume:h,idle:f,length:p,getQueue:d,unshift:g,empty:Fe,kill:b,killAndDrain:w,error:C,abort:S};return c;function l(){return r}function u(){c.paused=!0}function p(){for(var v=i,_=0;v;)v=v.next,_++;return _}function d(){for(var v=i,_=[];v;)_.push(v.value),v=v.next;return _}function h(){if(c.paused){if(c.paused=!1,i===null){r++,y();return}for(;i&&r<n;)r++,y()}}function f(){return r===0&&c.length()===0}function m(v,_){var A=s.get();A.context=t,A.release=y,A.value=v,A.callback=_||Fe,A.errorHandler=a,r>=n||c.paused?o?(o.next=A,o=A):(i=A,o=A,c.saturated()):(r++,e.call(t,A.value,A.worked))}function g(v,_){var A=s.get();A.context=t,A.release=y,A.value=v,A.callback=_||Fe,A.errorHandler=a,r>=n||c.paused?i?(A.next=i,i=A):(i=A,o=A,c.saturated()):(r++,e.call(t,A.value,A.worked))}function y(v){v&&s.release(v);var _=i;_&&r<=n?c.paused?r--:(o===i&&(o=null),i=_.next,_.next=null,e.call(t,_.value,_.worked),o===null&&c.empty()):--r===0&&c.drain()}function b(){i=null,o=null,c.drain=Fe}function w(){i=null,o=null,c.drain(),c.drain=Fe}function S(){var v=i;for(i=null,o=null;v;){var _=v.next,A=v.callback,O=v.errorHandler,j=v.value,x=v.context;v.value=null,v.callback=Fe,v.errorHandler=null,O&&O(new Error("abort"),j),A.call(x,new Error("abort")),v.release(v),v=_}c.drain=Fe}function C(v){a=v}}function Fe(){}function U0(){this.value=null,this.callback=Fe,this.next=null,this.release=Fe,this.context=null,this.errorHandler=null;var t=this;this.worked=function(n,s){var i=t.callback,o=t.errorHandler,r=t.value;t.value=null,t.callback=Fe,t.errorHandler&&o(n,r),i.call(t.context,n,s),t.release(t)}}function z0(t,e,n){typeof t=="function"&&(n=e,e=t,t=null);function s(u,p){e.call(this,u).then(function(d){p(null,d)},p)}var i=kp(t,s,n),o=i.push,r=i.unshift;return i.push=a,i.unshift=c,i.drained=l,i;function a(u){var p=new Promise(function(d,h){o(u,function(f,m){if(f){h(f);return}d(m)})});return p.catch(Fe),p}function c(u){var p=new Promise(function(d,h){r(u,function(f,m){if(f){h(f);return}d(m)})});return p.catch(Fe),p}function l(){var u=new Promise(function(p){process.nextTick(function(){if(i.idle())p();else{var d=i.drain;i.drain=function(){typeof d=="function"&&d(),p(),i.drain=d}}})});return u}}_r.exports=kp;_r.exports.promise=z0});var _i=I(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.joinPathSegments=ft.replacePathSegmentSeparator=ft.isAppliedFilter=ft.isFatalError=void 0;function q0(t,e){return t.errorFilter===null?!0:!t.errorFilter(e)}ft.isFatalError=q0;function K0(t,e){return t===null||t(e)}ft.isAppliedFilter=K0;function Y0(t,e){return t.split(/[/\\]/).join(e)}ft.replacePathSegmentSeparator=Y0;function X0(t,e,n){return t===""?e:t.endsWith(n)?t+e:t+n+e}ft.joinPathSegments=X0});var Er=I(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});var J0=_i(),xr=class{constructor(e,n){this._root=e,this._settings=n,this._root=J0.replacePathSegmentSeparator(e,n.pathSegmentSeparator)}};kr.default=xr});var Rr=I(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});var Z0=require("events"),Q0=Si(),eS=Ep(),xi=_i(),tS=Er(),Ar=class extends tS.default{constructor(e,n){super(e,n),this._settings=n,this._scandir=Q0.scandir,this._emitter=new Z0.EventEmitter,this._queue=eS(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 o of i)this._handleEntry(o,e.base);n(null,void 0)})}_handleError(e){this._isDestroyed||!xi.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=xi.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),xi.isAppliedFilter(this._settings.entryFilter,e)&&this._emitEntry(e),e.dirent.isDirectory()&&xi.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(s,n===void 0?void 0:e.path)}_emitEntry(e){this._emitter.emit("entry",e)}};Cr.default=Ar});var Ap=I(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});var nS=Rr(),Tr=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new nS.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(n=>{sS(e,n)}),this._reader.onEntry(n=>{this._storage.push(n)}),this._reader.onEnd(()=>{iS(e,this._storage)}),this._reader.read()}};Pr.default=Tr;function sS(t,e){t(e)}function iS(t,e){t(null,e)}});var Cp=I(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});var oS=require("stream"),rS=Rr(),$r=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new rS.default(this._root,this._settings),this._stream=new oS.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}};Ir.default=$r});var Rp=I(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0});var aS=Si(),ki=_i(),cS=Er(),Or=class extends cS.default{constructor(){super(...arguments),this._scandir=aS.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(ki.isFatalError(this._settings,e))throw e}_handleEntry(e,n){let s=e.path;n!==void 0&&(e.path=ki.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),ki.isAppliedFilter(this._settings.entryFilter,e)&&this._pushToStorage(e),e.dirent.isDirectory()&&ki.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(s,n===void 0?void 0:e.path)}_pushToStorage(e){this._storage.push(e)}};Lr.default=Or});var Tp=I(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});var lS=Rp(),Nr=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new lS.default(this._root,this._settings)}read(){return this._reader.read()}};Mr.default=Nr});var Pp=I(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});var uS=require("path"),dS=Si(),jr=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,uS.sep),this.fsScandirSettings=new dS.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}};Dr.default=jr});var Ai=I(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.Settings=ht.walkStream=ht.walkSync=ht.walk=void 0;var $p=Ap(),pS=Cp(),fS=Tp(),Fr=Pp();ht.Settings=Fr.default;function hS(t,e,n){if(typeof e=="function"){new $p.default(t,Ei()).read(e);return}new $p.default(t,Ei(e)).read(n)}ht.walk=hS;function mS(t,e){let n=Ei(e);return new fS.default(t,n).read()}ht.walkSync=mS;function gS(t,e){let n=Ei(e);return new pS.default(t,n).read()}ht.walkStream=gS;function Ei(t={}){return t instanceof Fr.default?t:new Fr.default(t)}});var Ci=I(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});var yS=require("path"),bS=Qt(),Ip=xt(),Hr=class{constructor(e){this._settings=e,this._fsStatSettings=new bS.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return yS.resolve(this._settings.cwd,e)}_makeEntry(e,n){let s={name:n,path:n,dirent:Ip.fs.createDirentFromStats(n,e)};return this._settings.stats&&(s.stats=e),s}_isFatalError(e){return!Ip.errno.isEnoentCodeError(e)&&!this._settings.suppressErrors}};Br.default=Hr});var Vr=I(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});var wS=require("stream"),vS=Qt(),SS=Ai(),_S=Ci(),Gr=class extends _S.default{constructor(){super(...arguments),this._walkStream=SS.walkStream,this._stat=vS.stat}dynamic(e,n){return this._walkStream(e,n)}static(e,n){let s=e.map(this._getFullEntryPath,this),i=new wS.PassThrough({objectMode:!0});i._write=(o,r,a)=>this._getEntry(s[o],e[o],n).then(c=>{c!==null&&n.entryFilter(c)&&i.push(c),o===s.length-1&&i.end(),a()}).catch(a);for(let o=0;o<s.length;o++)i.write(o);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,o)=>i===null?n(o):s(i))})}};Wr.default=Gr});var Op=I(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});var xS=Ai(),kS=Ci(),ES=Vr(),Ur=class extends kS.default{constructor(){super(...arguments),this._walkAsync=xS.walk,this._readerStream=new ES.default(this._settings)}dynamic(e,n){return new Promise((s,i)=>{this._walkAsync(e,n,(o,r)=>{o===null?s(r):i(o)})})}async static(e,n){let s=[],i=this._readerStream.static(e,n);return new Promise((o,r)=>{i.once("error",r),i.on("data",a=>s.push(a)),i.once("end",()=>o(s))})}};zr.default=Ur});var Lp=I(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});var os=xt(),qr=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 os.pattern.getPatternParts(e,this._micromatchOptions).map(s=>os.pattern.isDynamicPattern(s,this._settings)?{dynamic:!0,pattern:s,patternRe:os.pattern.makeRe(s,this._micromatchOptions)}:{dynamic:!1,pattern:s})}_splitSegmentsIntoSections(e){return os.array.splitWhen(e,n=>n.dynamic&&os.pattern.hasGlobStar(n.pattern))}};Kr.default=qr});var Np=I(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});var AS=Lp(),Yr=class extends AS.default{match(e){let n=e.split("/"),s=n.length,i=this._storage.filter(o=>!o.complete||o.segments.length>s);for(let o of i){let r=o.sections[0];if(!o.complete&&s>r.length||n.every((c,l)=>{let u=o.segments[l];return!!(u.dynamic&&u.patternRe.test(c)||!u.dynamic&&u.pattern===c)}))return!0}return!1}};Xr.default=Yr});var Mp=I(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});var Ri=xt(),CS=Np(),Jr=class{constructor(e,n){this._settings=e,this._micromatchOptions=n}getFilter(e,n,s){let i=this._getMatcher(n),o=this._getNegativePatternsRe(s);return r=>this._filter(e,r,i,o)}_getMatcher(e){return new CS.default(e,this._settings,this._micromatchOptions)}_getNegativePatternsRe(e){let n=e.filter(Ri.pattern.isAffectDepthOfReadingPattern);return Ri.pattern.convertPatternsToRe(n,this._micromatchOptions)}_filter(e,n,s,i){if(this._isSkippedByDeep(e,n.path)||this._isSkippedSymbolicLink(n))return!1;let o=Ri.path.removeLeadingDotSegment(n.path);return this._isSkippedByPositivePatterns(o,s)?!1:this._isSkippedByNegativePatterns(o,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!Ri.pattern.matchAny(e,n)}};Zr.default=Jr});var jp=I(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});var jt=xt(),Qr=class{constructor(e,n){this._settings=e,this._micromatchOptions=n,this.index=new Map}getFilter(e,n){let[s,i]=jt.pattern.partitionAbsoluteAndRelative(n),o={positive:{all:jt.pattern.convertPatternsToRe(e,this._micromatchOptions)},negative:{absolute:jt.pattern.convertPatternsToRe(s,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:jt.pattern.convertPatternsToRe(i,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return r=>this._filter(r,o)}_filter(e,n){let s=jt.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=jt.path.makeAbsolute(this._settings.cwd,e);return this._isMatchToPatterns(i,n,s)}_isMatchToPatterns(e,n,s){if(n.length===0)return!1;let i=jt.pattern.matchAny(e,n);return!i&&s?jt.pattern.matchAny(e+"/",n):i}};ea.default=Qr});var Dp=I(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});var RS=xt(),ta=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return RS.errno.isEnoentCodeError(e)||this._settings.suppressErrors}};na.default=ta});var Hp=I(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});var Fp=xt(),sa=class{constructor(e){this._settings=e}getTransformer(){return e=>this._transform(e)}_transform(e){let n=e.path;return this._settings.absolute&&(n=Fp.path.makeAbsolute(this._settings.cwd,n),n=Fp.path.unixify(n)),this._settings.markDirectories&&e.dirent.isDirectory()&&(n+="/"),this._settings.objectMode?Object.assign(Object.assign({},e),{path:n}):n}};ia.default=sa});var Ti=I(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});var TS=require("path"),PS=Mp(),$S=jp(),IS=Dp(),OS=Hp(),oa=class{constructor(e){this._settings=e,this.errorFilter=new IS.default(this._settings),this.entryFilter=new $S.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new PS.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new OS.default(this._settings)}_getRootDirectory(e){return TS.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}}};ra.default=oa});var Bp=I(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});var LS=Op(),NS=Ti(),aa=class extends NS.default{constructor(){super(...arguments),this._reader=new LS.default(this._settings)}async read(e){let n=this._getRootDirectory(e),s=this._getReaderOptions(e);return(await this.api(n,e,s)).map(o=>s.transform(o))}api(e,n,s){return n.dynamic?this._reader.dynamic(e,s):this._reader.static(n.patterns,s)}};ca.default=aa});var Gp=I(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});var MS=require("stream"),jS=Vr(),DS=Ti(),la=class extends DS.default{constructor(){super(...arguments),this._reader=new jS.default(this._settings)}read(e){let n=this._getRootDirectory(e),s=this._getReaderOptions(e),i=this.api(n,e,s),o=new MS.Readable({objectMode:!0,read:()=>{}});return i.once("error",r=>o.emit("error",r)).on("data",r=>o.emit("data",s.transform(r))).once("end",()=>o.emit("end")),o.once("close",()=>i.destroy()),o}api(e,n,s){return n.dynamic?this._reader.dynamic(e,s):this._reader.static(n.patterns,s)}};ua.default=la});var Wp=I(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});var FS=Qt(),HS=Ai(),BS=Ci(),da=class extends BS.default{constructor(){super(...arguments),this._walkSync=HS.walkSync,this._statSync=FS.statSync}dynamic(e,n){return this._walkSync(e,n)}static(e,n){let s=[];for(let i of e){let o=this._getFullEntryPath(i),r=this._getEntry(o,i,n);r===null||!n.entryFilter(r)||s.push(r)}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)}};pa.default=da});var Vp=I(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});var GS=Wp(),WS=Ti(),fa=class extends WS.default{constructor(){super(...arguments),this._reader=new GS.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)}};ha.default=fa});var Up=I(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var Tn=require("fs"),VS=require("os"),US=Math.max(VS.cpus().length,1);Pn.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:Tn.lstat,lstatSync:Tn.lstatSync,stat:Tn.stat,statSync:Tn.statSync,readdir:Tn.readdir,readdirSync:Tn.readdirSync};var ma=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,US),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({},Pn.DEFAULT_FILE_SYSTEM_ADAPTER),e)}};Pn.default=ma});var rs=I((DN,qp)=>{"use strict";var zp=qd(),zS=Bp(),qS=Gp(),KS=Vp(),ga=Up(),Ke=xt();async function ya(t,e){nt(t);let n=ba(t,zS.default,e),s=await Promise.all(n);return Ke.array.flatten(s)}(function(t){t.glob=t,t.globSync=e,t.globStream=n,t.async=t;function e(l,u){nt(l);let p=ba(l,KS.default,u);return Ke.array.flatten(p)}t.sync=e;function n(l,u){nt(l);let p=ba(l,qS.default,u);return Ke.stream.merge(p)}t.stream=n;function s(l,u){nt(l);let p=[].concat(l),d=new ga.default(u);return zp.generate(p,d)}t.generateTasks=s;function i(l,u){nt(l);let p=new ga.default(u);return Ke.pattern.isDynamicPattern(l,p)}t.isDynamicPattern=i;function o(l){return nt(l),Ke.path.escape(l)}t.escapePath=o;function r(l){return nt(l),Ke.path.convertPathToPattern(l)}t.convertPathToPattern=r;let a;(function(l){function u(d){return nt(d),Ke.path.escapePosixPath(d)}l.escapePath=u;function p(d){return nt(d),Ke.path.convertPosixPathToPattern(d)}l.convertPathToPattern=p})(a=t.posix||(t.posix={}));let c;(function(l){function u(d){return nt(d),Ke.path.escapeWindowsPath(d)}l.escapePath=u;function p(d){return nt(d),Ke.path.convertWindowsPathToPattern(d)}l.convertPathToPattern=p})(c=t.win32||(t.win32={}))})(ya||(ya={}));function ba(t,e,n){let s=[].concat(t),i=new ga.default(n),o=zp.generate(s,i),r=new e(i);return o.map(r.read,r)}function nt(t){if(![].concat(t).every(s=>Ke.string.isString(s)&&!Ke.string.isEmpty(s)))throw new TypeError("Patterns must be a string (non empty) or an array of strings")}qp.exports=ya});var Ul=I((aB,OO)=>{OO.exports={name:"@promptci/cli",version:"0.4.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.1.0"},publishConfig:{access:"public"}}});var Pt=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}},Xt=class extends Pt{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 Xt(`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 Zs(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}var tu=require("node:events"),ei=R(require("node:child_process"),1),ut=R(require("node:path"),1),Qn=R(require("node:fs"),1),X=R(require("node:process"),1),nu=require("node:util");var Jl=require("node:util"),Zn=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,o)=>i.name().localeCompare(o.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),o=s.long&&e._findOption(s.long);!i&&!o?n.push(s):s.long&&!o?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(o=>!o.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=>Zs(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(o=>{let r=s(o);i.has(r)||i.set(r,[])}),n.forEach(o=>{let r=s(o);i.has(r)||i.set(r,[]),i.get(r).push(o)}),i}formatHelp(e,n){let s=n.padWidth(e,n),i=n.helpWidth??80;function o(p,d){return n.formatItem(p,s,d,n)}let r=[`${n.styleTitle("Usage:")} ${n.styleUsage(n.commandUsage(e))}`,""],a=n.commandDescription(e);a.length>0&&(r=r.concat([n.boxWrap(n.styleCommandDescription(a),i),""]));let c=n.visibleArguments(e).map(p=>o(n.styleArgumentTerm(n.argumentTerm(p)),n.styleArgumentDescription(n.argumentDescription(p))));if(r=r.concat(this.formatItemList("Arguments:",c,n)),this.groupItems(e.options,n.visibleOptions(e),p=>p.helpGroupHeading??"Options:").forEach((p,d)=>{let h=p.map(f=>o(n.styleOptionTerm(n.optionTerm(f)),n.styleOptionDescription(n.optionDescription(f))));r=r.concat(this.formatItemList(d,h,n))}),n.showGlobalOptions){let p=n.visibleGlobalOptions(e).map(d=>o(n.styleOptionTerm(n.optionTerm(d)),n.styleOptionDescription(n.optionDescription(d))));r=r.concat(this.formatItemList("Global Options:",p,n))}return this.groupItems(e.commands,n.visibleCommands(e),p=>p.helpGroup()||"Commands:").forEach((p,d)=>{let h=p.map(f=>o(n.styleSubcommandTerm(n.subcommandTerm(f)),n.styleSubcommandDescription(n.subcommandDescription(f))));r=r.concat(this.formatItemList(d,h,n))}),r.join(`
4
+ `)}displayWidth(e){return(0,Jl.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 r=" ".repeat(2);if(!s)return r+e;let a=e.padEnd(n+e.length-i.displayWidth(e)),c=2,u=(this.helpWidth??80)-n-c-2,p;return u<this.minWidthToWrap||i.preformatted(s)?p=s:p=i.boxWrap(s,u).replace(/\n/g,`
5
+ `+" ".repeat(n+c)),r+a+" ".repeat(c)+p.replace(/\n/g,`
6
+ ${r}`)}boxWrap(e,n){if(n<this.minWidthToWrap)return e;let s=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,o=[];return s.forEach(r=>{let a=r.match(i);if(a===null){o.push("");return}let c=[a.shift()],l=this.displayWidth(c[0]);a.forEach(u=>{let p=this.displayWidth(u);if(l+p<=n){c.push(u),l+=p;return}o.push(c.join(""));let d=u.trimStart();c=[d],l=this.displayWidth(d)}),o.push(c.join(""))}),o.join(`
7
+ `)}};var _n=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=Nb(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 Xt(`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?Zl(this.name().replace(/^no-/,"")):Zl(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}},Qs=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,o=i!==void 0?i:!1;return n.negate===(o===e)}};function Zl(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function Nb(t){let e,n,s=/^-[^-]$/,i=/^--[^-]/,o=t.split(/[ |,]+/).concat("guard");if(s.test(o[0])&&(e=o.shift()),i.test(o[0])&&(n=o.shift()),!e&&s.test(o[0])&&(e=o.shift()),!e&&i.test(o[0])&&(e=n,n=o.shift()),o[0].startsWith("-")){let r=o[0],a=`option creation failed due to '${r}' in option flags '${t}'`;throw/^-[^-][^-]/.test(r)?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
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):s.test(o)?new Error(`${a}
11
- - too many short flags`):i.test(o)?new Error(`${a}
10
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):s.test(r)?new Error(`${a}
11
+ - too many short flags`):i.test(r)?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 xy(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 dr(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=xy(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 Mb(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 o;t[i-1]===e[s-1]?o=0:o=1,n[i][s]=Math.min(n[i-1][s]+1,n[i][s-1]+1,n[i-1][s-1]+o),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 Lo(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(r=>r.slice(2)));let s=[],i=3,o=.4;return e.forEach(r=>{if(r.length<=1)return;let a=Mb(t,r),c=Math.max(t.length,r.length);(c-a)/c>o&&(a<i?(i=a,s=[r]):a===i&&s.push(r))}),s.sort((r,a)=>r.localeCompare(a)),n&&(s=s.map(r=>`--${r}`)),s.length>1?`
14
14
  (Did you mean one of ${s.join(", ")}?)`:s.length===1?`
15
- (Did you mean ${s[0]}?)`:""}var cn=class t extends wl.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=>W.default.stdout.write(n),writeErr:n=>W.default.stderr.write(n),outputError:(n,s)=>s(n),getOutHelpWidth:()=>W.default.stdout.isTTY?W.default.stdout.columns:void 0,getErrHelpWidth:()=>W.default.stderr.isTTY?W.default.stderr.columns:void 0,getOutHasColors:()=>bl()??(W.default.stdout.isTTY&&W.default.stdout.hasColors?.()),getErrHasColors:()=>bl()??(W.default.stderr.isTTY&&W.default.stderr.hasColors?.()),stripColor:n=>(0,vl.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 Nn,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
- - 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 Ln(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 wt(e,n,s)),W.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 an(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 an)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){W.default.versions?.electron&&(n.from="electron");let i=W.default.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(n.from="eval")}e===void 0&&(e=W.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":W.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
- - 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(jn.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
15
+ (Did you mean ${s[0]}?)`:""}var xn=class t extends tu.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=>X.default.stdout.write(n),writeErr:n=>X.default.stderr.write(n),outputError:(n,s)=>s(n),getOutHelpWidth:()=>X.default.stdout.isTTY?X.default.stdout.columns:void 0,getErrHelpWidth:()=>X.default.stderr.isTTY?X.default.stderr.columns:void 0,getOutHasColors:()=>eu()??(X.default.stdout.isTTY&&X.default.stdout.hasColors?.()),getErrHasColors:()=>eu()??(X.default.stderr.isTTY&&X.default.stderr.hasColors?.()),stripColor:n=>(0,nu.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,o=s;typeof i=="object"&&i!==null&&(o=i,i=null),o=o||{};let[,r,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(r);return i&&(c.description(i),c._executableHandler=!0),o.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(o.noHelp||o.hidden),c._executableFile=o.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 Zn,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
+ - 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 o=this.createArgument(e,n);return typeof s=="function"?o.default(i).argParser(s):o.default(s),this.addArgument(o),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,o]=s.match(/([^ ]+) *(.*)/),r=n??"display help for command",a=this.createCommand(i);return a.helpOption(!1),o&&a.arguments(o),r&&a.description(r),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 Pt(e,n,s)),X.default.exit(e)}action(e){let n=s=>{let i=this.registeredArguments.length,o=s.slice(0,i);return this._storeOptionsAsProperties?o[i]=this:o[i]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=n,this}createOption(e,n){return new _n(e,n)}_callParseArg(e,n,s,i){try{return e.parseArg(n,s)}catch(o){if(o.code==="commander.invalidArgument"){let r=`${i} ${o.message}`;this.error(r,{exitCode:o.exitCode,code:o.code})}throw o}}_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("|"),o=n(e).join("|");throw new Error(`cannot add command '${o}' 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=(o,r,a)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let c=this.getOptionValue(s);o!==null&&e.parseArg?o=this._callParseArg(e,o,c,r):o!==null&&e.variadic&&(o=e._collectValue(o,c)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(s,o,a)};return this.on("option:"+n,o=>{let r=`error: option '${e.flags}' argument '${o}' is invalid.`;i(o,r,"cli")}),e.envVar&&this.on("optionEnv:"+n,o=>{let r=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;i(o,r,"env")}),this}_optionEx(e,n,s,i,o){if(typeof n=="object"&&n instanceof _n)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(n,s);if(r.makeOptionMandatory(!!e.mandatory),typeof i=="function")r.default(o).argParser(i);else if(i instanceof RegExp){let a=i;i=(c,l)=>{let u=a.exec(c);return u?u[0]:l},r.default(o).argParser(i)}else r.default(i);return this.addOption(r)}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){X.default.versions?.electron&&(n.from="electron");let i=X.default.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(n.from="eval")}e===void 0&&(e=X.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":X.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
+ - 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(Qn.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",o=`'${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=Qe.default.resolve(u,f);if(jn.default.existsSync(d))return d;if(s.includes(Qe.default.extname(f)))return;let p=s.find(h=>jn.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=jn.default.realpathSync(this._scriptPath)}catch{u=this._scriptPath}o=Qe.default.resolve(Qe.default.dirname(u),o)}if(o){let u=i(o,r);if(!u&&!e._executableFile&&this._scriptPath){let f=Qe.default.basename(this._scriptPath,Qe.default.extname(this._scriptPath));f!==this._name&&(u=i(o,`${f}-${e._name}`))}r=u||r}let a=s.includes(Qe.default.extname(r)),c;W.default.platform!=="win32"?a?(n.unshift(r),n=yl(W.default.execArgv).concat(n),c=Ms.default.spawn(W.default.argv[0],n,{stdio:"inherit"})):c=Ms.default.spawn(r,n,{stdio:"inherit"}):(this._checkForMissingExecutable(r,o,e._name),n.unshift(r),n=yl(W.default.execArgv).concat(n),c=Ms.default.spawn(W.default.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{W.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 wt(u,"commander.executeSubCommandAsync","(close)")):W.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)W.default.exit(1);else{let f=new wt(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(o)}_executeSubCommand(e,n){n=n.slice();let s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,p){let d=ut.default.resolve(u,p);if(Qn.default.existsSync(d))return d;if(s.includes(ut.default.extname(p)))return;let h=s.find(f=>Qn.default.existsSync(`${d}${f}`));if(h)return`${d}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,r=this._executableDir||"";if(this._scriptPath){let u;try{u=Qn.default.realpathSync(this._scriptPath)}catch{u=this._scriptPath}r=ut.default.resolve(ut.default.dirname(u),r)}if(r){let u=i(r,o);if(!u&&!e._executableFile&&this._scriptPath){let p=ut.default.basename(this._scriptPath,ut.default.extname(this._scriptPath));p!==this._name&&(u=i(r,`${p}-${e._name}`))}o=u||o}let a=s.includes(ut.default.extname(o)),c;X.default.platform!=="win32"?a?(n.unshift(o),n=Ql(X.default.execArgv).concat(n),c=ei.default.spawn(X.default.argv[0],n,{stdio:"inherit"})):c=ei.default.spawn(o,n,{stdio:"inherit"}):(this._checkForMissingExecutable(o,r,e._name),n.unshift(o),n=Ql(X.default.execArgv).concat(n),c=ei.default.spawn(X.default.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{X.default.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new Pt(u,"commander.executeSubCommandAsync","(close)")):X.default.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT")this._checkForMissingExecutable(o,r,e._name);else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)X.default.exit(1);else{let p=new Pt(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,l(p)}}),this.runningCommand=c}_dispatchSubcommand(e,n,s){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,i,"preSubcommand"),o=this._chainOrCall(o,()=>{if(i._executableHandler)this._executeSubCommand(i,n.concat(s));else return i._parseCommand(n,s)}),o}_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,o)=>{let r=i;if(i!==null&&s.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${s.name()}'.`;r=this._callParseArg(s,i,o,a)}return r};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((s,i)=>{let o=s.defaultValue;s.variadic?i<this.args.length?(o=this.args.slice(i),s.parseArg&&(o=o.reduce((r,a)=>e(s,a,r),s.defaultValue))):o===void 0&&(o=[]):i<this.args.length&&(o=this.args[i],s.parseArg&&(o=e(s,o,s.defaultValue))),n[i]=o}),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(o=>o._lifeCycleHooks[n]!==void 0).forEach(o=>{o._lifeCycleHooks[n].forEach(r=>{i.push({hookedCommand:o,callback:r})})}),n==="postAction"&&i.reverse(),i.forEach(o=>{s=this._chainOrCall(s,()=>o.callback(o.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,n,s){let i=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(o=>{i=this._chainOrCall(i,()=>o(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])},o=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let r;return r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent&&(r=this._chainOrCall(r,()=>{this.parent.emit(o,e,n)})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent?.listenerCount(o))i(),this._processArguments(),this.parent.emit(o,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(o=>s.conflictsWith.includes(o.attributeName()));i&&this._conflictingOption(s,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let n=[],s=[],i=n;function o(u){return u.length>1&&u[0]==="-"}let r=u=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(u)?!this._getCommandAndAncestors().some(p=>p.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&&(!o(u)||r(u))){this.emit(`option:${a.name()}`,u);continue}if(a=null,o(u)){let p=this._findOption(u);if(p){if(p.required){let d=e[l++];d===void 0&&this.optionMissingArgument(p),this.emit(`option:${p.name()}`,d)}else if(p.optional){let d=null;l<e.length&&(!o(e[l])||r(e[l]))&&(d=e[l++]),this.emit(`option:${p.name()}`,d)}else this.emit(`option:${p.name()}`);a=p.variadic?p:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let p=this._findOption(`-${u[1]}`);if(p){p.required||p.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${p.name()}`,u.slice(2)):(this.emit(`option:${p.name()}`),c=`-${u.slice(2)}`);continue}}if(/^--[^=]+=/.test(u)){let p=u.indexOf("="),d=this._findOption(u.slice(0,p));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,u.slice(p+1));continue}}if(i===n&&o(u)&&!(this.commands.length===0&&r(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 W.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()}`,W.default.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new js(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=dr(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=dr(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=>Ns(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=Qe.default.basename(e,Qe.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(W.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
- 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 yl(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 bl(){if(W.default.env.NO_COLOR||W.default.env.FORCE_COLOR==="0"||W.default.env.FORCE_COLOR==="false")return!1;if(W.default.env.FORCE_COLOR||W.default.env.CLICOLOR_FORCE!==void 0)return!0}var vT=new cn;var at=R(require("node:fs/promises"),1),Ge=R(require("node:path"),1);var he=new Set(["claude","agents","cursor","windsurf","copilot","gemini","cline","persona","prompt"]),_y=new Set(["skill","agent"]);function xl(t){return _y.has(t)}var Ds=["auto","typescript","nextjs","unity","dotnet","python","go","rust","unknown"];var Ad=R(Gn(),1),Kn=R(require("node:fs"),1),$d=R(require("node:fs/promises"),1),De=R(require("node:path"),1);var L0=/^ {0,3}([`~]{3,})\s*([^\s`]*)/,N0=/^ {0,3}([`~]{3,})\s*$/,pd=/(`+)([^`]+)\1/g;function Se(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=L0.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=N0.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 Un(t){let e=[],n=null;for(let s of Se(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 qe(t,e={}){let n=Se(t).filter(s=>!s.inFence).map(s=>s.text).join(`
30
- `);return e.stripInlineCode?n.replace(/`[^`\n]+`/g,""):n}function hd(t){return Se(t).map(e=>e.inFence?"":e.text).join(`
31
- `)}function md(t,e={}){let n=e.closedOnly??!0;return Un(t).filter(s=>n?s.closed:!0).map(s=>s.lines.join(`
25
+ `),this.outputHelp({error:!0}));let s=n||{},i=s.exitCode||1,o=s.code||"commander.error";this._exit(i,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in X.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()}`,X.default.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Qs(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=r=>{let a=r.attributeName(),c=this.getOptionValue(a),l=this.options.find(p=>p.negate&&a===p.attributeName()),u=this.options.find(p=>!p.negate&&a===p.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||r},i=r=>{let a=s(r),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${i(e)} cannot be used with ${i(n)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],o=this;do{let r=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);i=i.concat(r),o=o.parent}while(o&&!o._enablePositionalOptions);n=Lo(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,o=this.parent?` for '${this.name()}'`:"",r=e.join(", "),a=`error: too many arguments${o}. Expected ${n} argument${s} but got ${i}: ${r}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(o=>{i.push(o.name()),o.alias()&&i.push(o.alias())}),n=Lo(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=>Zs(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=ut.default.basename(e,ut.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,o;return n?(s=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(s=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:n,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),s(a)),hasColors:i,helpWidth:o}}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(r=>r.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let o=this.helpInformation({error:s.error});if(n&&(o=n(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(r=>r.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(X.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
+ Expecting one of '${s.join("', '")}'`);let i=`${e}Help`;return this.on(i,o=>{let r;typeof n=="function"?r=n({error:o.error,command:o.command}):r=n,r&&o.write(`${r}
28
+ `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(i=>n.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ql(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,s="127.0.0.1",i="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?n=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=o[1],/^\d+$/.test(o[3])?i=o[3]:s=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=o[1],s=o[3],i=o[4]),n&&i!=="0"?`${n}=${s}:${parseInt(i)+1}`:e})}function eu(){if(X.default.env.NO_COLOR||X.default.env.FORCE_COLOR==="0"||X.default.env.FORCE_COLOR==="false")return!1;if(X.default.env.FORCE_COLOR||X.default.env.CLICOLOR_FORCE!==void 0)return!0}var yL=new xn;var bt=R(require("node:fs/promises"),1),Qe=R(require("node:path"),1);var Ae=new Set(["claude","agents","cursor","windsurf","copilot","gemini","cline","persona","prompt"]),jb=new Set(["skill","agent"]);function su(t){return jb.has(t)}var ti=["auto","typescript","nextjs","unity","dotnet","python","go","rust","unknown"];var uf=R(rs(),1),us=R(require("node:fs"),1),df=R(require("node:fs/promises"),1),Ye=R(require("node:path"),1);var YS=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/,XS=/^ {0,3}(`{3,}|~{3,})\s*$/,Kp=/(`+)([^`]+)\1/g;function we(t){let e=t.split(`
29
+ `),n=[],s=!1,i=null,o=0,r="",a=-1;for(let c=0;c<e.length;c++){let l=e[c]??"",u=c+1;if(!s){let d=YS.exec(l);if(d){s=!0,i=d[1][0]??null,o=d[1].length,r=(d[2]??"").toLowerCase(),a=n.length,n.push({text:l,lineNumber:u,kind:"open",inFence:!0,lang:r,closed:!0});continue}n.push({text:l,lineNumber:u,kind:"text",inFence:!1,lang:"",closed:!0});continue}let p=XS.exec(l);if(p&&p[1][0]===i&&p[1].length>=o){n.push({text:l,lineNumber:u,kind:"close",inFence:!0,lang:r,closed:!0}),s=!1,i=null,o=0,r="",a=-1;continue}n.push({text:l,lineNumber:u,kind:"content",inFence:!0,lang:r,closed:!0})}if(s&&a>=0)for(let c=a;c<n.length;c++)n[c].closed=!1;return n}function en(t){let e=[],n=null;for(let s of we(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 st(t,e={}){let n=we(t).filter(s=>!s.inFence).map(s=>s.text).join(`
30
+ `);return e.stripInlineCode?n.replace(/`[^`\n]+`/g,""):n}function Yp(t){return we(t).map(e=>e.inFence?"":e.text).join(`
31
+ `)}function Xp(t,e={}){let n=e.closedOnly??!0;return en(t).filter(s=>n?s.closed:!0).map(s=>s.lines.join(`
32
32
  `)).join(`
33
- `)}function gd(t){let e=new Array(t.length).fill(!1),n=0;for(let s of Se(t)){if(s.inFence)e.fill(!0,n,n+s.text.length);else{let i,r=new RegExp(pd.source,pd.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 pi=R(require("node:fs"),1),le=R(require("node:path"),1);function X(t,e){let n=le.resolve(t),s=le.resolve(e),i=le.relative(n,s);return i===""||i!==".."&&!i.startsWith(`..${le.sep}`)&&!le.isAbsolute(i)}function Bt(t,e){try{let n=le.resolve(t),s=le.isAbsolute(e)?le.resolve(e):le.resolve(n,e);return X(n,s)?s:null}catch{return null}}function Ct(t){try{let e=pi.realpathSync.native(t);return typeof e=="string"?e:null}catch{return null}}function be(t,e){let n=Ct(e);if(n===null)return!0;let s=Ct(t)??le.resolve(t);return X(s,n)}function ie(t,e){let n=Bt(t,e);return n===null?null:be(t,n)?n:null}function gn(t,e){let n=le.resolve(e);if(!X(t,n))return!0;let s=n;for(;;){if(Ct(s)!==null)return be(t,s);try{if(pi.lstatSync(s).isSymbolicLink())return!1}catch{}let i=le.dirname(s);if(i===s)return!0;s=i}}var pt=R(require("node:fs"),1),we=R(require("node:path"),1),j0=1024*1024,M0=128*1024*1024,D0=2e6,F0=24;function H0(t){let e=we.resolve(t);for(let n=0;n<F0;n++){let s=we.join(e,".git");try{let r=pt.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(pt.readFileSync(s,"utf8"))?.[1];if(o){let a=we.resolve(e,o),c=a;try{let l=pt.readFileSync(we.join(a,"commondir"),"utf8").trim();l&&(c=we.resolve(a,l))}catch{}return{workTree:e,gitDir:a,commonDir:c}}}}catch{}let i=we.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>D0)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 yd(t){let e,n=()=>{if(e!==void 0)return e;e=null;let s=H0(t);if(!s)return e;let i=!1;try{let o=we.join(s.commonDir,"config");pt.statSync(o).size<=j0&&(i=B0(pt.readFileSync(o,"utf8")))}catch{}let r;try{let o=we.join(s.gitDir,"index");pt.statSync(o).size<=M0&&(r=W0(pt.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=we.relative(i.git.workTree,we.resolve(t,s)).split(we.sep).join("/");return i.links.has(r)}return i.configFalse}}}var At=R(require("node:fs"),1),G=R(require("node:path"),1);function bd(t){if(t==="")return"";if(/^[/\\]/.test(t)||/^[A-Za-z]:/.test(t))return null;let e=[];for(let n of t.split(/[/\\]+/))if(!(n===""||n===".")){if(n==="..")return null;e.push(n)}return e.join("/")}function G0(t){let e=[""],n=t.split("/");for(let s=1;s<n.length;s++)e.push(n.slice(0,s).join("/"));return e}var Zo=class{complete;files=new Set;tree=new Map;constructor(e,n=!1){this.complete=n;let s=new Set,i=new Set;for(let a of e){let c=bd(a);c===null||c===""||(/[/\\]\s*$/.test(a)?i.add(c):s.add(c))}let r=new Set(["",...i]);for(let a of[...s,...i])for(let c of G0(a))r.add(c);for(let a of s)r.has(a)||this.files.add(a);let o=(a,c)=>{let l=a.lastIndexOf("/"),u=l===-1?"":a.slice(0,l),f=l===-1?a:a.slice(l+1),d=this.tree.get(u);d===void 0&&(d=new Map,this.tree.set(u,d)),(c==="dir"||!d.has(f))&&d.set(f,c)};for(let a of this.files)o(a,"file");for(let a of r)a!==""&&(o(a,"dir"),this.tree.has(a)||this.tree.set(a,new Map));this.tree.has("")||this.tree.set("",new Map)}classify(e){return e===""||this.tree.has(e)?"dir":this.files.has(e)?"file":this.complete?"absent":"unknown"}children(e){return this.tree.get(e)}listedFiles(){return[...this.files].sort()}};function wd(t,e){if(t!==void 0)return new Zo(t,e===!0)}function zn(t){return G.posix.isAbsolute(t)||G.win32.isAbsolute(t)||/^[A-Za-z]:/.test(t)}function U0(t,e){return{name:t,isFile:()=>e==="file",isDirectory:()=>e==="dir",isSymbolicLink:()=>!1}}function Vn(t){let e=t?.code;return typeof e=="string"?e:void 0}var V0=40,Ee=class{root;realRoot;listings=new Map;inventory;unreadable=new Map;constructor(e,n={}){this.root=G.resolve(e);let s=Ct(this.root);this.realRoot=s!==null&&s!==this.root?s:void 0,this.inventory=wd(n.knownPaths,n.knownPathsComplete)}relative(e){return G.relative(this.root,e).split(G.sep).join("/")||"."}relativePosix(e){let n=this.relative(e);return n==="."?"":n}noteUnreadable(e,n,s="dir"){let i=G.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)}listFs(e,n){try{return new Map(At.readdirSync(e,{withFileTypes:!0}).map(s=>[s.name,s]))}catch(s){let i=Vn(s);return i==="ENOENT"||i==="ENOTDIR"?"missing":(n&&this.noteUnreadable(e,i??"error"),"unreadable")}}list(e){let n=this.listings.get(e);if(n!==void 0)return n;let s=this.inventory?.children(this.relativePosix(e)),i=s===void 0?void 0:new Map([...s].map(([r,o])=>[r,U0(r,o)]));if(this.inventory!==void 0&&this.inventory.complete)n=i??"missing";else{let r=this.listFs(e,i===void 0);if(i===void 0)n=r;else if(typeof r=="string")n=i;else{let o=new Map([...r,...i]);for(let[a,c]of r)c.isSymbolicLink()&&o.set(a,c);n=o}}return this.listings.set(e,n),n}fromRealRoot(e){return this.realRoot===void 0||X(this.root,e)||!X(this.realRoot,e)?e:G.join(this.root,G.relative(this.realRoot,e))}linkTargetWithinRoot(e,n){if((/^[A-Za-z]:/.test(n)||n.startsWith("\\\\"))&&!G.isAbsolute(n))return null;if(G.isAbsolute(n)){let r=this.fromRealRoot(G.resolve(n));return X(this.root,r)?r:null}let i=G.relative(this.root,e).split(G.sep).filter(Boolean);if(i.includes("..")||G.isAbsolute(i.join(G.sep)))return null;for(let r of n.split(/[\\/]/))if(!(r===""||r===".")){if(r!=="..")i.push(r);else if(i.pop()===void 0)return null}return G.join(this.root,...i)}lookup(e){let n=G.resolve(this.root,e),s="";for(let i=0;i<=V0;i++){if(!X(this.root,n))return{state:"outside"};let r=G.relative(this.root,n).split(G.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=G.join(o,f);if(d.isSymbolicLink()){let h;try{h=At.readlinkSync(p)}catch(g){return this.noteUnreadable(p,Vn(g)??"unreadable link","link"),{state:"unreadable"}}s=p;let m=this.linkTargetWithinRoot(o,h);if(m===null)return{state:"outside"};c=G.join(m,...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}exists(e){return this.lookup(e).state==="found"}isFile(e){let n=this.lookup(e);return n.state==="found"&&!n.isDir}readText(e,n={}){let s=this.lookup(e);if(s.state!=="found")return{state:s.state};if(s.isDir)return{state:"missing"};if(!be(this.root,s.path))return{state:"outside"};try{if(n.maxBytes!==void 0){let i=At.statSync(s.path);if(!i.isFile())return{state:"missing"};if(i.size>n.maxBytes)return{state:"too-large"}}return{state:"found",content:At.readFileSync(s.path,"utf8")}}catch(i){let r=Vn(i);return r==="ENOENT"||r==="ENOTDIR"?{state:this.inventory!==void 0?"unfetched":"missing"}:(this.noteUnreadable(s.path,r??"error","link"),{state:"unreadable"})}}hasStemSibling(e){let n=this.lookup(G.dirname(e));if(n.state!=="found"||!n.isDir)return!1;let s=this.list(n.path);if(typeof s=="string")return!1;let i=`${G.basename(e)}.`;for(let r of s.keys())if(r.startsWith(i))return!0;return!1}entries(e){let n=this.lookup(e);return n.state!=="found"?n.state:n.isDir?this.list(n.path):"missing"}walkFs(e){return{readdirSync:(s,i)=>{let r=this.list(s);if(r==="missing")throw Object.assign(new Error(`ENOENT: no such file or directory, scandir '${s}'`),{code:"ENOENT"});if(r==="unreadable")throw e(),Object.assign(new Error(`EACCES: permission denied, scandir '${s}'`),{code:"EACCES"});let o=[...r.values()];return i?o:o.map(a=>a.name)}}}};function V(t){return t.tree??new Ee(t.repoRoot)}var Qo=10;function hi(t,e,n){let s=(c,l)=>c.length>Qo?[...c.slice(0,Qo),`\u2026and ${c.length-Qo} more ${l}`]:c,i=[...t.unreadable].sort(([c],[l])=>c.localeCompare(l)),r=i.map(([c,l])=>`Could not read: ${c} (${l})`),o=[...new Set(e.flatMap(c=>[...c.filePaths]))],a=new Map;for(let c of e)for(let[l,u]of c.fileLines){let f=a.get(l);(f===void 0||u<f)&&a.set(l,u)}return{id:n.id,severity:"warning",category:n.category,title:n.title,summary:`${e.length} ${n.unit}(s) were not checked because part of the repository could not be read (${i.length} location${i.length===1?"":"s"}). ${n.unknown}; no ${n.finding} finding was reported for them.`,filePaths:o,locations:o.map(c=>{let l=a.get(c);return l!==void 0?{filePath:c,startLine:l}:{filePath:c}}),evidence:[...s(r,"locations"),...s(e.map(c=>c.evidence),`${n.unit}s`)],recommendation:`Make the listed locations readable by the user running the scan (or fix the symlink), then scan again to check these ${n.unit}s.`,confidence:.8}}var z0=R(ft(),1),ce=500*1024,yn=512,vd=["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"],q0=new Set([".clinerules/**/*.md","!.clinerules/workflows/**"]);function xd(t){return t?vd:vd.filter(e=>!q0.has(e))}var ea=[".git","node_modules","Library","Temp","bin","obj","dist","build","worktrees",".worktrees"],ta=[".claude/**/SKILL.md",".agents/skills/**/SKILL.md","skills/*/SKILL.md","plugins/*/skills/*/SKILL.md"];var na=["node_modules",".git","dist","build","worktrees",".worktrees"],K0=new Set([".",".claude",".agents",".claude/skills",".agents/skills",".claude/plugins","skills","plugins"]);function qn(t){return K0.has(t)}var _d=new Set(["node_modules",".git","worktrees",".worktrees"]),mi=200;var sa=100,Y0=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 gi(t){return Y0.test(t)}function Sd(t,e,n,s,i=sa){let r=[],o=a=>{let c=`${a}/package.json`;r.length<i&&n(c)&&r.push(c)};for(let a of[...t].sort()){if(r.length>=i)break;if(!a.startsWith("."))if(a.startsWith("@"))for(let c of[...e(a)].sort())o(`${s}/${a}/${c}`);else o(`${s}/${a}`)}return r}var Ed=["action.yml","action.yaml",".github/actions/**/action.yml",".github/actions/**/action.yaml"];var YI=ea.map(t=>`**/${t}/**`),JI=na.map(t=>`**/${t}/**`);var J0=ea;var X0=new Set(["/SOUL.md","/USER.md","/TOOLS.md"]);function Z0(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 Q0(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}function Pd(t){let e=t.split(`
33
+ `)}function Jp(t){let e=new Array(t.length).fill(!1),n=0;for(let s of we(t)){if(s.inFence)e.fill(!0,n,n+s.text.length);else{let i,o=new RegExp(Kp.source,Kp.flags);for(;(i=o.exec(s.text))!==null;)e.fill(!0,n+i.index,n+i.index+i[0].length)}n+=s.text.length+1}return e}var Pi=R(require("node:fs"),1),ve=R(require("node:path"),1);function ue(t,e){let n=ve.resolve(t),s=ve.resolve(e),i=ve.relative(n,s);return i===""||i!==".."&&!i.startsWith(`..${ve.sep}`)&&!ve.isAbsolute(i)}function tn(t,e){try{let n=ve.resolve(t),s=ve.isAbsolute(e)?ve.resolve(e):ve.resolve(n,e);return ue(n,s)?s:null}catch{return null}}function Dt(t){try{let e=Pi.realpathSync.native(t);return typeof e=="string"?e:null}catch{return null}}function Pe(t,e){let n=Dt(e);if(n===null)return!0;let s=Dt(t)??ve.resolve(t);return ue(s,n)}function he(t,e){let n=tn(t,e);return n===null?null:Pe(t,n)?n:null}function $n(t,e){let n=ve.resolve(e);if(!ue(t,n))return!0;let s=n;for(;;){if(Dt(s)!==null)return Pe(t,s);try{if(Pi.lstatSync(s).isSymbolicLink())return!1}catch{}let i=ve.dirname(s);if(i===s)return!0;s=i}}var kt=R(require("node:fs"),1),$e=R(require("node:path"),1),JS=1024*1024,ZS=128*1024*1024,QS=2e6,e_=24;function t_(t){let e=$e.resolve(t);for(let n=0;n<e_;n++){let s=$e.join(e,".git");try{let o=kt.statSync(s);if(o.isDirectory())return{workTree:e,gitDir:s,commonDir:s};if(o.isFile()&&o.size<4096){let r=/^gitdir:\s*(.+?)\s*$/m.exec(kt.readFileSync(s,"utf8"))?.[1];if(r){let a=$e.resolve(e,r),c=a;try{let l=kt.readFileSync($e.join(a,"commondir"),"utf8").trim();l&&(c=$e.resolve(a,l))}catch{}return{workTree:e,gitDir:a,commonDir:c}}}}catch{}let i=$e.dirname(e);if(i===e)break;e=i}}function n_(t){let e=!1,n;for(let s of t.split(/\r?\n/)){let i=s.trim(),o=/^\[\s*([A-Za-z0-9.-]+)(?:\s+"[^"]*")?\s*\]/.exec(i);if(o){e=o[1].toLowerCase()==="core"&&!i.includes('"');continue}if(!e)continue;let r=/^symlinks\s*(?:=\s*(.*?))?\s*(?:[;#].*)?$/i.exec(i);r&&(n=r[1]===void 0?"true":r[1].replace(/^"|"$/g,"").trim())}return n!==void 0&&/^(?:false|no|off|0)$/i.test(n)}function s_(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>QS)return;let s=new Set,i=12;for(let o=0;o<n;o++){if(i+62>t.length)return;let r=t.readUInt32BE(i+24),a=t.readUInt16BE(i+60),l=e===3&&(a&16384)!==0?64:62,u=a&4095;if(u===4095){let p=t.indexOf(0,i+l);if(p<0)return;u=p-(i+l)}if(i+l+u>t.length)return;(r&61440)===40960&&s.add(t.toString("utf8",i+l,i+l+u)),i+=Math.ceil((l+u+1)/8)*8}return s}function Zp(t){let e,n=()=>{if(e!==void 0)return e;e=null;let s=t_(t);if(!s)return e;let i=!1;try{let r=$e.join(s.commonDir,"config");kt.statSync(r).size<=JS&&(i=n_(kt.readFileSync(r,"utf8")))}catch{}let o;try{let r=$e.join(s.gitDir,"index");kt.statSync(r).size<=ZS&&(o=s_(kt.readFileSync(r)))}catch{}return e={git:s,links:o,configFalse:i},e};return{isSymlink(s){let i=n();if(!i)return!1;if(i.links){let o=$e.relative(i.git.workTree,$e.resolve(t,s)).split($e.sep).join("/");return i.links.has(o)}return i.configFalse}}}var Ft=R(require("node:fs"),1),J=R(require("node:path"),1);function Qp(t){if(t==="")return"";if(/^[/\\]/.test(t)||/^[A-Za-z]:/.test(t))return null;let e=[];for(let n of t.split(/[/\\]+/))if(!(n===""||n===".")){if(n==="..")return null;e.push(n)}return e.join("/")}function i_(t){let e=[""],n=t.split("/");for(let s=1;s<n.length;s++)e.push(n.slice(0,s).join("/"));return e}var wa=class{complete;files=new Set;tree=new Map;constructor(e,n=!1){this.complete=n;let s=new Set,i=new Set;for(let a of e){let c=Qp(a);c===null||c===""||(/[/\\]\s*$/.test(a)?i.add(c):s.add(c))}let o=new Set(["",...i]);for(let a of[...s,...i])for(let c of i_(a))o.add(c);for(let a of s)o.has(a)||this.files.add(a);let r=(a,c)=>{let l=a.lastIndexOf("/"),u=l===-1?"":a.slice(0,l),p=l===-1?a:a.slice(l+1),d=this.tree.get(u);d===void 0&&(d=new Map,this.tree.set(u,d)),(c==="dir"||!d.has(p))&&d.set(p,c)};for(let a of this.files)r(a,"file");for(let a of o)a!==""&&(r(a,"dir"),this.tree.has(a)||this.tree.set(a,new Map));this.tree.has("")||this.tree.set("",new Map)}classify(e){return e===""||this.tree.has(e)?"dir":this.files.has(e)?"file":this.complete?"absent":"unknown"}children(e){return this.tree.get(e)}listedFiles(){return[...this.files].sort()}};function ef(t,e){if(t!==void 0)return new wa(t,e===!0)}function cs(t){return J.posix.isAbsolute(t)||J.win32.isAbsolute(t)||/^[A-Za-z]:/.test(t)}function o_(t,e){return{name:t,isFile:()=>e==="file",isDirectory:()=>e==="dir",isSymbolicLink:()=>!1}}function as(t){let e=t?.code;return typeof e=="string"?e:void 0}var r_=40,Le=class{root;realRoot;listings=new Map;inventory;unreadable=new Map;constructor(e,n={}){this.root=J.resolve(e);let s=Dt(this.root);this.realRoot=s!==null&&s!==this.root?s:void 0,this.inventory=ef(n.knownPaths,n.knownPathsComplete)}relative(e){return J.relative(this.root,e).split(J.sep).join("/")||"."}relativePosix(e){let n=this.relative(e);return n==="."?"":n}noteUnreadable(e,n,s="dir"){let i=J.resolve(this.root,e);if(!ue(this.root,i))return;let o=this.relative(i),r=s==="link"?o:o==="."?"./":`${o}/`;this.unreadable.has(r)||this.unreadable.set(r,n)}listFs(e,n){try{return new Map(Ft.readdirSync(e,{withFileTypes:!0}).map(s=>[s.name,s]))}catch(s){let i=as(s);return i==="ENOENT"||i==="ENOTDIR"?"missing":(n&&this.noteUnreadable(e,i??"error"),"unreadable")}}list(e){let n=this.listings.get(e);if(n!==void 0)return n;let s=this.inventory?.children(this.relativePosix(e)),i=s===void 0?void 0:new Map([...s].map(([o,r])=>[o,o_(o,r)]));if(this.inventory!==void 0&&this.inventory.complete)n=i??"missing";else{let o=this.listFs(e,i===void 0);if(i===void 0)n=o;else if(typeof o=="string")n=i;else{let r=new Map([...o,...i]);for(let[a,c]of o)c.isSymbolicLink()&&r.set(a,c);n=r}}return this.listings.set(e,n),n}fromRealRoot(e){return this.realRoot===void 0||ue(this.root,e)||!ue(this.realRoot,e)?e:J.join(this.root,J.relative(this.realRoot,e))}linkTargetWithinRoot(e,n){if((/^[A-Za-z]:/.test(n)||n.startsWith("\\\\"))&&!J.isAbsolute(n))return null;if(J.isAbsolute(n)){let o=this.fromRealRoot(J.resolve(n));return ue(this.root,o)?o:null}let i=J.relative(this.root,e).split(J.sep).filter(Boolean);if(i.includes("..")||J.isAbsolute(i.join(J.sep)))return null;for(let o of n.split(/[\\/]/))if(!(o===""||o===".")){if(o!=="..")i.push(o);else if(i.pop()===void 0)return null}return J.join(this.root,...i)}lookup(e){let n=J.resolve(this.root,e),s="";for(let i=0;i<=r_;i++){if(!ue(this.root,n))return{state:"outside"};let o=J.relative(this.root,n).split(J.sep).filter(Boolean),r=this.root,a=!0,c;for(let l=0;l<o.length;l++){if(!a)return{state:"missing"};let u=this.list(r);if(u==="missing")return{state:"missing"};if(u==="unreadable")return{state:"unreadable"};let p=o[l],d=u.get(p);if(!d)return{state:"missing"};let h=J.join(r,p);if(d.isSymbolicLink()){let f;try{f=Ft.readlinkSync(h)}catch(g){return this.noteUnreadable(h,as(g)??"unreadable link","link"),{state:"unreadable"}}s=h;let m=this.linkTargetWithinRoot(r,f);if(m===null)return{state:"outside"};c=J.join(m,...o.slice(l+1));break}a=d.isDirectory(),r=h}if(c===void 0)return{state:"found",path:r,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}exists(e){return this.lookup(e).state==="found"}isFile(e){let n=this.lookup(e);return n.state==="found"&&!n.isDir}readText(e,n={}){let s=this.lookup(e);if(s.state!=="found")return{state:s.state};if(s.isDir)return{state:"missing"};if(!Pe(this.root,s.path))return{state:"outside"};try{if(n.maxBytes!==void 0){let i=Ft.statSync(s.path);if(!i.isFile())return{state:"missing"};if(i.size>n.maxBytes)return{state:"too-large"}}return{state:"found",content:Ft.readFileSync(s.path,"utf8")}}catch(i){let o=as(i);return o==="ENOENT"||o==="ENOTDIR"?{state:this.inventory!==void 0?"unfetched":"missing"}:(this.noteUnreadable(s.path,o??"error","link"),{state:"unreadable"})}}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 o of s.keys())if(o.startsWith(i))return!0;return!1}entries(e){let n=this.lookup(e);return n.state!=="found"?n.state:n.isDir?this.list(n.path):"missing"}walkFs(e){return{readdirSync:(s,i)=>{let o=this.list(s);if(o==="missing")throw Object.assign(new Error(`ENOENT: no such file or directory, scandir '${s}'`),{code:"ENOENT"});if(o==="unreadable")throw e(),Object.assign(new Error(`EACCES: permission denied, scandir '${s}'`),{code:"EACCES"});let r=[...o.values()];return i?r:r.map(a=>a.name)}}}};function Z(t){return t.tree??new Le(t.repoRoot)}var va=10;function $i(t,e,n){let s=(c,l)=>c.length>va?[...c.slice(0,va),`\u2026and ${c.length-va} more ${l}`]:c,i=[...t.unreadable].sort(([c],[l])=>c.localeCompare(l)),o=i.map(([c,l])=>`Could not read: ${c} (${l})`),r=[...new Set(e.flatMap(c=>[...c.filePaths]))],a=new Map;for(let c of e)for(let[l,u]of c.fileLines){let p=a.get(l);(p===void 0||u<p)&&a.set(l,u)}return{id:n.id,severity:"warning",category:n.category,title:n.title,summary:`${e.length} ${n.unit}(s) were not checked because part of the repository could not be read (${i.length} location${i.length===1?"":"s"}). ${n.unknown}; no ${n.finding} finding was reported for them.`,filePaths:r,locations:r.map(c=>{let l=a.get(c);return l!==void 0?{filePath:c,startLine:l}:{filePath:c}}),evidence:[...s(o,"locations"),...s(e.map(c=>c.evidence),`${n.unit}s`)],recommendation:`Make the listed locations readable by the user running the scan (or fix the symlink), then scan again to check these ${n.unit}s.`,confidence:.8}}var a_=R(_t(),1),ye=500*1024,In=512,tf=["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"],c_=new Set([".clinerules/**/*.md","!.clinerules/workflows/**"]);function nf(t){return t?tf:tf.filter(e=>!c_.has(e))}var Sa=[".git","node_modules","Library","Temp","bin","obj","dist","build","worktrees",".worktrees"],_a=[".claude/**/SKILL.md",".agents/skills/**/SKILL.md","skills/*/SKILL.md","plugins/*/skills/*/SKILL.md"];var xa=["node_modules",".git","dist","build","worktrees",".worktrees"],l_=new Set([".",".claude",".agents",".claude/skills",".agents/skills",".claude/plugins","skills","plugins"]);function ls(t){return l_.has(t)}var sf=new Set(["node_modules",".git","worktrees",".worktrees"]),Ii=200;var ka=100,u_=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 Oi(t){return u_.test(t)}function of(t,e,n,s,i=ka){let o=[],r=a=>{let c=`${a}/package.json`;o.length<i&&n(c)&&o.push(c)};for(let a of[...t].sort()){if(o.length>=i)break;if(!a.startsWith("."))if(a.startsWith("@"))for(let c of[...e(a)].sort())r(`${s}/${a}/${c}`);else r(`${s}/${a}`)}return o}var rf=["action.yml","action.yaml",".github/actions/**/action.yml",".github/actions/**/action.yaml"];var zN=Sa.map(t=>`**/${t}/**`),qN=xa.map(t=>`**/${t}/**`);var d_=Sa;var p_=new Set(["/SOUL.md","/USER.md","/TOOLS.md"]);function f_(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":p_.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 h_(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}function pf(t){let e=t.split(`
34
34
  `);return t.length>0&&t.endsWith(`
35
- `)&&e.pop(),e}function Wt(t,e,n){let s=Pd(t),i=[],r,o=1,a=[],c=u=>{let f=a.join(`
36
- `),d=r!==void 0?Q0(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=Se(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 Gt(t){let e=Math.min(t.length,yn);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}function ex(t){return[...xd(t.isDir(".clinerules"))]}function Td(t){try{return Kn.realpathSync.native(t)}catch{return null}}async function kd(t,e,n,s){let i=Td(n);if(i===null||!X(e,i))return;let r;try{let o=Kn.constants.O_NOFOLLOW??0;r=await $d.open(i,Kn.constants.O_RDONLY|o);let a=await r.stat();if(!a.isFile()||a.size>ce)return;let c=await r.readFile();if(Gt(c))return;let l=c.toString("utf-8"),u=De.relative(t,n).replace(/\\/g,"/"),f=Wt(l,n,u),d=Pd(l).length,p=l.length;return{path:n,relativePath:u,fileType:Z0(s),content:l,sections:f,lineCount:d,charCount:p,estimatedTokens:Math.round(p/4)}}catch{return}finally{await r?.close().catch(()=>{})}}var Rd=260,tx=8;function nx(t,e,n){let s=t.relativePath;if(s===void 0||t.charCount>Rd+16)return;let i=t.content.replace(/^\u{FEFF}/u,"").trim();if(i===""||i.length>Rd||/[\r\n]/.test(i)||i.startsWith("/")||/^[A-Za-z]:/.test(i)||i.includes("\\"))return;let r=De.posix.normalize(De.posix.join(De.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:Wt(e.content,t.path,t.relativePath),aliasOf:e.relativePath}}function sx(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=nx(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<tx;)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 yi(t,e){let n=De.resolve(t.repoPath),s=Td(n)??n,i=e??new Ee(n,{...t.knownPaths!==void 0?{knownPaths:t.knownPaths}:{},...t.knownPathsComplete!==void 0?{knownPathsComplete:t.knownPathsComplete}:{}}),r=t.include&&t.include.length>0?t.include:ex(i),o=[...J0.map(m=>`**/${m}/**`),...t.exclude??[]],a;try{a=await(0,Ad.default)(r,{cwd:n,ignore:o,dot:!0,absolute:!1,onlyFiles:!1,objectMode:!0,followSymbolicLinks:!1,suppressErrors:!0})}catch{return{files:[],aliases:[]}}let c=[],l=[];for(let m of a)m.dirent.isSymbolicLink()?l.push(m.path):m.dirent.isFile()&&c.push(m.path);l.sort();let u=[],f=[],d=new Map,p=[];for(let m of c){let g=De.resolve(n,m);if(!X(n,g)||!be(n,g))continue;let y=Ct(g);p.push({relPath:m,absPath:g,real:y,direct:y!==null&&y===De.join(s,m)})}p.sort((m,g)=>Number(g.direct)-Number(m.direct)||m.relPath.localeCompare(g.relPath));for(let{relPath:m,absPath:g,real:y}of p){let b=await kd(n,s,g,m);if(!b)continue;let v=y!==null?d.get(y):void 0;if(v){f.push({...b,aliasOf:v.relativePath});continue}u.push(b),y!==null&&d.set(y,b)}for(let m of l){let g=De.resolve(n,m);if(!X(n,g)||!be(n,g))continue;let y=await kd(n,s,g,m);if(!y)continue;let b=Ct(g),v=b!==null?d.get(b):void 0;if(v){f.push({...y,aliasOf:v.relativePath});continue}u.push(y),b!==null&&d.set(b,y)}let h=sx(u,f,yd(n));return h.files.sort((m,g)=>m.path.localeCompare(g.path)),h.aliases.sort((m,g)=>m.path.localeCompare(g.path)),h}async function ia(t){return(await yi(t)).files}var Yn=R(require("node:path"),1);function ix(t){let e=t.entries(t.root);if(typeof e=="string")return new Set;let n=new Set;for(let s of e.values())s.isDirectory()||n.add(s.name);return n}async function Jn(t,e=new Ee(t)){let n=Yn.resolve(t),s=(...y)=>e.exists(Yn.join(n,...y)),i=(...y)=>e.isDir(Yn.join(n,...y)),r=ix(e);if([...r].some(y=>y.startsWith("next.config.")))return"nextjs";let o=s("package.json");if(o&&(i("app")||i("pages")))return"nextjs";let a=i("Assets"),c=s("ProjectSettings","ProjectVersion.txt");if(a&&c)return"unity";if([...r].some(y=>y.endsWith(".sln")||y.endsWith(".csproj")))return"dotnet";let l=s("tsconfig.json");if(o||l)return"typescript";let u=s("pyproject.toml"),f=s("requirements.txt"),d=s("Pipfile"),p=s("environment.yml"),h=s("setup.py");return u||f||d||p||h?"python":s("go.mod")?"go":s("Cargo.toml")?"rust":"unknown"}function ra(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 Nd=R(require("node:crypto"),1);var rx=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}]/u;function bi(t){return`<U+${t.toString(16).toUpperCase().padStart(4,"0")}>`}function ox(t,e=t.codePointAt(0)){return e===9||e>=32&&e<127?!1:rx.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 wi(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):bi(r);continue}s(),e+=ox(i,r)?bi(r):i}return s(),e}function Z(t,e=120){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e)}\u2026`}function ax(t,e,n=120){let i=new RegExp(e.source,e.flags.replace("g","")).exec(t);return i?Z(i[0],n):void 0}function bn(t,e,n,s=120){let i=ax(t,e,s);return i?`${n}: "${i}"`:n}function Id(t){return t.replace(/\\/g,"/").replace(/^(?:\.\/)+/,"")}function N(t){return Id(t.relativePath??t.path)}function Fe(t){return Id(t.relativePath??t.filePath)}var vi=150,cx=80,lx=10,ux=.8,fx=.6,dx=.6,Od=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 jd(t){return t.toLowerCase().replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+\.\s+/gm,"").replace(/\s+/g," ").trim()}function oa(t){let e=t.match(/\b\w+\b/g)??[];return new Set(e)}function px(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 aa(t){if(!t)return!1;let e=t.toLowerCase().trim();if(Od.has(e))return!0;for(let n of Od)if(e.startsWith(n))return!0;return!1}function Ld(t){return t?.toLowerCase().replace(/\s+/g," ").trim()??""}function hx(t,e){let n=Ld(t.heading),s=Ld(e.heading);return n.length>0&&n===s}function Xn(t,e){if(!t.has(e))return e;let n=Xn(t,t.get(e));return t.set(e,n),n}function mx(t,e,n){let s=Xn(t,e),i=Xn(t,n);s!==i&&t.set(s,i)}function ca(t){let e=[...t].sort().join("|");return`duplicate-${Nd.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function la(t){let e=[];for(let u of t)for(let f of u.sections){let d=jd(f.text);d.length<cx||oa(d).size<lx||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=`${Fe(d)}:${d.startLine}`,m=`${Fe(p)}:${p.startLine}`,g=d.normalizedText,y=p.normalizedText,b=null,v=0;if(aa(d.heading)||aa(p.heading))continue;let x=d.filePath===p.filePath;if(g===y){if(!x&&(g.length<vi||y.length<vi)&&!hx(d,p))continue;b="high",v=.95}else{if(!x&&(g.length<vi||y.length<vi))continue;let w=x?dx:ux,_=px(oa(g),oa(y));_>=w?(b="warning",v=x?.8:.75):!x&&_>=fx&&(b="info",v=.5)}b!==null&&(s.set(h,d),s.set(m,p),mx(n,h,m),i.push({keyA:h,keyB:m,severity:b,confidence:v}))}let r=new Map;for(let u of s.keys()){let f=Xn(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=Xn(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(_=>s.get(_)),p=a.get(u)??"warning",h=c.get(u)??.75,m=[...new Set(d.map(_=>_.filePath))],g=[...new Set(d.map(_=>_.heading??"(untitled)"))],y=g.length===1?g[0]:g.slice(0,2).join(" / "),b=m.length,v=b>2?`Possible duplicate: ${y} (${b} files)`:`Possible duplicate: ${y}`,x=d.slice(1).reduce((_,A)=>_+Math.round(A.text.length/4),0),w=b>2?`This section appears highly similar in ${b} files. Consider consolidating into one canonical location.`:"These sections appear highly similar. Consider consolidating them into one canonical location.";l.push({id:ca(f),severity:p,category:"duplicate",title:v,summary:w,filePaths:m,locations:d.map(_=>({filePath:_.filePath,startLine:_.startLine,endLine:_.endLine})),evidence:[Z(d[0].normalizedText,200),`Duplicated size: ~${x} tokens`],recommendation:`Consolidate these sections into one canonical location (e.g. AGENTS.md) and use forwarding pointers to save ~${x} tokens per session. If both are intentional, add a comment clarifying the distinction.`,autoApplySafe:b>=2,confidence:h})}return l}function ua(t){let e=[];for(let n of t){let s=new Map;for(let o of n.sections){if(!o.heading||aa(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=>`${N(n)}:${f.startLine}`),l=ca(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),y=[...m,...g].sort((v,x)=>v.startLine-x.startLine),b=y.map(v=>`${N(n)}:${v.startLine}`);e.push({id:ca(b),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:y.map(v=>({filePath:n.path,startLine:v.startLine,endLine:v.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 _i=R(require("node:crypto"),1),fa=R(require("node:path"),1);var gx=1,Vd=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"]),yx=new Set(["for","when","if","unless","except"]),bx=new Set(["it","them","they","we","code","sure","careful","good","clean","simple","easy","proper","consistent","clear","correct","possible","necessary","appropriate"]),zd=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 Md(t,e,n=3,s=!1){let i=t.slice(e).replace(/^\s+/,"");if(s){let a=/^([a-zA-Z]+)\s+/.exec(i);a&&zd.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&&(Vd.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 Zn=[{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 wx(t,e,n,s){let i=t.slice(e).replace(/^\s+/,"");if(s){let l=/^([a-zA-Z]+)\s+/.exec(i);l&&zd.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 yx.has(c)}function xi(t){return t.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim()}function Dd(t){if(!t||t.length<2)return!0;let e=t.split(" ").filter(Boolean);return e.length===0?!0:e.every(n=>bx.has(n))}function vx(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 Fd(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&&!Vd.has(c)&&(o.unshift(c),o.length>=n))break}return o.join(" ")}function xx(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 Hd(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 _x(t){let e=[],n=xx({...t,text:qe(t.text)});for(let s=0;s<Zn.length;s++){let i=Zn[s];for(let r of n){let o=i.skipLeadingVerb??!1,a=i.extractSubjectBefore??!1,c=Hd(i.negativePattern,r),l=r;for(let f of c){let d=f.index+f.text.length,p=a,h=xi(p?Fd(r,f.index,4):Md(r,d,3,o));if(h.length>=2&&!Dd(h)){let m=!p&&wx(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=Hd(i.positivePattern,l);for(let f of u){let d=a||(i.extractPositiveSubjectBefore??!1),p=xi(d?Fd(r,f.index,4):Md(r,f.index+f.text.length,3,o));p.length>=2&&!Dd(p)&&e.push({section:t,pairIndex:s,polarity:"positive",subject:p,matchedLine:r})}}}return e}function Bd(t,e,n,s,i,r){let o=[`${t}:${e}`,`${n}:${s}`].sort(),a=`${o[0]}|${o[1]}|${i}|${r}`;return`conflict-${_i.createHash("sha1").update(a).digest("hex").slice(0,12)}`}function da(t){let e=[];for(let a of t)for(let c of a.sections)c.text.trim().length>=gx&&e.push(c);let n=[];for(let a of e)n.push(..._x(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:vx(f.subject,d.subject),h;if(f.subject===d.subject){let w=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)),_=Zn[l.pairIndex];h=d.hasQualifier&&/\balways\b/i.test(f.matchedLine)&&_.label.includes("always")?.5:d.hasQualifier?.35:w?.5:.8}else if(p>=.5){let x=Zn[l.pairIndex],w=f.subject.split(" ").filter(Boolean),_=d.subject.split(" ").filter(Boolean);if(w.length<2||_.length<2){if(!x.allowSingleTokenMatch)continue;let A=w.length<=_.length?w[0]:_[0];if(!(w.length>_.length?f.subject:d.subject).startsWith(A))continue}h=d.hasQualifier?.3:.5}else continue;if(h<.4)continue;let m=Bd(Fe(f.section),f.section.startLine,Fe(d.section),d.section.startLine,l.pairIndex,f.subject);if(i.has(m))continue;i.add(m);let g=h>=.7?"high":"warning",y=Zn[l.pairIndex],b=f.subject.length<=d.subject.length?f.subject:d.subject,v=Array.from(new Set([f.section.filePath,d.section.filePath]));s.push({id:m,severity:g,category:"conflict",title:`Possible conflicting instruction: ${b}`,summary:`Possible conflict \u2014 review these together. A "${y.label}" directive pattern was found pointing in opposite directions for the subject "${b}".`,filePaths:v,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=Bd(Fe(u.section),u.section.startLine,Fe(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 Sx=[{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 Ex(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 kx(t){let e=new Map;for(let{re:n,name:s,normalize:i}of Sx){let r=new RegExp(n.source,n.flags),o;for(;(o=r.exec(t))!==null;){if(Ex(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 Rx(t,e){let n=`version-conflict:${t}:${[...e].sort().join("|")}`;return`version-conflict-${_i.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function pa(t){if(t.length<2)return[];let e=t.map(r=>({file:r,versions:kx(qe(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=Rx(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 Cx(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ax={"kebab-case":["kebab-case","kebab case","kebabcase"],camelcase:["camelcase","camel case","camel-case"],pascalcase:["pascalcase","pascal case","pascal-case"]};function Wd(t){let e=Ax[t.toLowerCase()]??[t];return new RegExp(`\\b(?:${e.map(Cx).join("|")})\\b`,"i")}var $x=[{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"}],Gd=/\b(?:use|prefer|always|must|should|follow|rely\s+on|stick\s+to|require)\b/i;function Ud(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)&&Gd.test(i))return!0;let r=n[s+1];if(i&&r){let o=`${i} ${r}`;if(e.test(o)&&Gd.test(o))return!0}}return!1}function ha(t){if(t.length<2)return[];let e=[],n=new Set,s=new Map(t.map(r=>[r.path,qe(r.content)])),i=r=>s.get(r.path)??r.content;for(let r of $x){let o=Wd(r.termA),a=Wd(r.termB),c=t.filter(b=>o.test(i(b))),l=t.filter(b=>a.test(i(b)));if(c.length===0||l.length===0)continue;let u=new Set(c.map(b=>b.path)),f=new Set(l.map(b=>b.path));if([...u].every(b=>f.has(b))&&[...f].every(b=>u.has(b)))continue;let p=c.some(b=>Ud(i(b),o)),h=l.some(b=>Ud(i(b),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(b=>b.path))],y=`competing-tech-${_i.createHash("sha1").update(m).digest("hex").slice(0,12)}`;e.push({id:y,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(b=>({filePath:b})),evidence:[`"${r.termA}" referenced in: ${c.map(b=>fa.basename(b.path)).join(", ")}`,`"${r.termB}" referenced in: ${l.map(b=>fa.basename(b.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 z=R(require("node:path"),1),ip=R(require("node:crypto"),1),ya=R(Gn(),1);function qd(t){return/[\\^$.*+?()[\]{}|/]/.test(t)?`\\${t}`:t}function Px(t){let e="",n=0;for(;n<t.length;){let s=t[n];if(s==="\\")n+1<t.length&&(e+=qd(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+=qd(s),n++}return e}function Tx(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(`^${Px(s)}$`)})}catch{}}return e}function Ix(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===void 0){let r=t.readText(s===""?".gitignore":`${s}/.gitignore`);i=r.state==="found"?Tx(r.content):r.state==="unfetched"?"unfetched":r.state==="unreadable"||r.state==="too-large"?"unreadable":[],e.set(s,i)}return i};return s=>{let i=s.replace(/\\/g,"/").replace(/^\.\//,"").split("/").filter(Boolean),r;for(let o=1;o<=i.length;o++){let a=o<i.length,c;for(let l=0;l<o;l++){let u=i.slice(l,o).join("/"),f=n(i.slice(0,l).join("/"));if(typeof f=="string"){(f==="unreadable"||r===void 0)&&(r=f);continue}for(let d of f)Ix(d,u,a)&&(c=!d.negate)}if(c===!0)return!0}return r??!1}}var Kd=/\[(?:[^\]]*)\]\(([^)]+)\)/g,Yd=/\[(?:[^\]]|\]\([^)]*\))*\]\(([^)]+)\)/g,Jd=/^[ \t]{0,3}\[[^\]]+\]:\s*(\S+)/gm,Xd=/(?<!\w)@((?:\.{1,2}\/)?[\w./\\-]+\.(?:md|ts|js|mjs|cjs|tsx|jsx|json|yml|yaml|toml|txt|sh|py|cs|go|rs))/g,Zd=/`([^\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,Qd=/`((?:\.\/)?[\w@.()[\]-]+(?:\/[\w@.()[\]-]+)+\/?)`/g,Ox=/\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"]),rp=new Set(["dist","build","out",".next","coverage","target","bin","obj","node_modules",".turbo"]),ep=/^[ \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,tp="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",Nx=new RegExp(`^(?:#{1,4}\\s+.*\\b(?:${tp})\\b|\\*\\*[^*\\n]*\\b(?:${tp})\\b[^*\\n]*\\*\\*\\s*)`,"im"),jx=/\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 np(t){return it(t).replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase()}var Mx=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 Ei(t){return/^https?:\/\/|^mailto:|^#|^data:/.test(t.trimStart())}function ma(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 Dx=/^(foo|bar|baz|qux|quux|example|sample|placeholder|stub|demo|test|your[-_]?file|my[-_]?file|filename|file[-_]?name)(\.\w+)?$/i,Fx=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"]),Hx=/^(ComponentName|MyComponent|YourComponent|WidgetName|FeatureName|ModuleName|ServiceName|ModelName|EntityName|ResourceName|DomainName|ControllerName|ScreenName|PageName)(?:\.\w+)*$/i;function Bx(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=z.basename(it(t)),n=z.dirname(it(t)),s=n!=="."&&n!==""&&n!==".\\"&&n!=="./";return!!(!s&&Dx.test(e)||Hx.test(e)||!s&&Fx.has(e.toLowerCase())||/camelCase|CamelCase|PascalCase|pascalCase|kebab[-_]?[Cc]ase|snake_?[Cc]ase/.test(e))}var Wx=[/(?:^|[/\\])\.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 Gx(t){let e=t.replace(/\\/g,"/");return Wx.some(n=>n.test(e))}var Ux=/^(?:~(?:[/\\]|$)|\$\{?(?:HOME|USERPROFILE|XDG_CONFIG_HOME|XDG_DATA_HOME)\}?(?:[/\\]|$)|\$env:(?:HOME|USERPROFILE|APPDATA|LOCALAPPDATA)(?:[/\\]|$)|%(?:USERPROFILE|HOMEPATH|APPDATA|LOCALAPPDATA)%(?:[/\\]|$))/i;function ba(t){return Ux.test(t.trim())}function Vx(t){let e=z.extname(t.split("#")[0]??"").toLowerCase();return Mx.has(e)}function zx(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("/")||z.extname(e)===""}function it(t){return t.split("#")[0].split("?")[0].trim()}var qx=new Set([".go",".cs",".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".sh",".java",".kt",".swift"]),Kx=new Set([".go",".rs",".cs",".java",".kt",".swift",".ts",".tsx"]),Yx=/(?:^|[/\\])(?:legacy|old|deprecated|archive|archived)(?:[/\\]|[-_.])/i,Jx=new Set(["readme","claude","agents","cursor","windsurf","copilot","gemini","cline","persona","docs","prompt","unknown"]),Xx=2,Zx=.45;function sp(t){let e=`dead-ref:${t}`;return`dead-ref-${ip.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function Qx(t){let e=[0];for(let n=0;n<t.length;n++)t[n]===`
40
- `&&e.push(n+1);return e}function $t(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 e_=/\.(?:md|png|jpg|jpeg|gif|svg|webp|pdf)$/i;function t_(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 op(t,e,n){let s=[],i=[],r=n;for(let o of t){let a=r;r+=o.length+1;let c=t_(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(!e_.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:$t(e,a)})}return s}function n_(t,e){let n=[];for(let s of Un(t)){if(!s.closed)continue;let i=e[s.contentStartLine-1]??t.length;n.push(...op(s.lines,e,i))}return n}function s_(t,e){return op(t.split(`
41
- `),e,0)}function i_(t,e={}){let n=[],s=Qx(t),i=Se(t),r=m=>{let g=$t(s,m);return i[g-1]?.inFence?!0:(t.slice(s[g-1]??0,m).match(/`/g)?.length??0)%2===1},o=(m,g,y,b)=>{if(!m||Ei(m))return;let v=$t(s,y),x=i[v-1]?.inFence===!0||r(y);Vx(m)?n.push({ref:m,evidence:g,line:v,kind:"file",linkRaw:b,inCodeContext:x}):zx(m)&&!r(y)&&n.push({ref:m,evidence:g,line:v,kind:"linkPath",linkRaw:b,inCodeContext:x})},a,c=new RegExp(Kd.source,Kd.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(it(ma(m)),`[...](${m})`,a.index,m)}let l=new RegExp(Yd.source,Yd.flags);for(;(a=l.exec(t))!==null;){if(!a[0].slice(0,a[0].lastIndexOf("](")).includes("]("))continue;let g=a[1]??"";o(it(ma(g)),`[...](${g})`,a.index,g)}let u=new RegExp(Jd.source,Jd.flags);for(;(a=u.exec(t))!==null;){let m=a[1]??"";/^[ \t]*\[\^/.test(a[0])||o(it(m),a[0].trim(),a.index)}let f=new RegExp(Xd.source,Xd.flags);for(;(a=f.exec(t))!==null;){let m=a[1]??"";m&&!Ei(m)&&n.push({ref:m,evidence:`@${m}`,line:$t(s,a.index),kind:"file"})}let d=new RegExp(Zd.source,Zd.flags);for(;(a=d.exec(t))!==null;){let m=a[1]??"";if(m&&!Ei(m)&&!m.includes("*")&&!m.includes("?")){let g=z.extname(m).toLowerCase(),y=e.skipSourceBackticks&&Kx.has(g)&&!Yx.test(m);n.push({ref:m,evidence:`\`${m}\``,line:$t(s,a.index),kind:y?"rootedSource":"file",codeSpan:!0})}}let p=new RegExp(Qd.source,Qd.flags);for(;(a=p.exec(t))!==null;){let m=a[1]??"",g=m.replace(/\/+$/,"").split("/").pop()??"";if(!m.endsWith("/")&&z.extname(g)!=="")continue;let y=$t(s,a.index),b=t.slice(s[y-1]??0,s[y]??t.length);Ox.test(b)||n.push({ref:m,evidence:`\`${m}\``,line:$t(s,a.index),kind:"rootedPath"})}if(Nx.test(t)){let m=new RegExp(ep.source,ep.flags);for(;(a=m.exec(t))!==null;){let g=a[1]??"";g&&!Ei(g)&&n.push({ref:g,evidence:a[0].trim(),line:$t(s,a.index),kind:"file"})}for(let g of s_(t,s))n.push({...g,kind:"file"});for(let g of n_(t,s))n.push({...g,kind:"file"})}let h=t.split(`
42
- `);return n.filter(({ref:m,line:g})=>{let y=h[g-1]??"",b=jx.exec(y);if(!b)return!0;let v=np(b[1]??"");if(!v)return!0;let x=np(m);return!(x===v||x.endsWith(`/${v}`)||v.endsWith(`/${x}`))})}function ga(t){return it(t).replace(/\\/g,"/").split("/").filter(e=>e!==""&&e!==".")}function r_(t){return ga(t).some(e=>rp.has(e.toLowerCase()))}var o_=[...[...rp,".git","worktrees",".worktrees","Library","Temp","Logs","vendor",".venv","venv","__pycache__","Pods",".gradle",".cache",".idea"].map(t=>`**/${t}/**`)];function ap(t,e,n){let s=!0,i=[];try{i=ya.default.sync(e,{cwd:t.root,dot:!0,onlyFiles:n,followSymbolicLinks:!1,suppressErrors:!0,ignore:o_,fs:t.walkFs(()=>{s=!1})})}catch(r){t.noteUnreadable(".",Vn(r)??"walk failed"),s=!1}return{entries:i,complete:s}}function a_(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=ya.default.escapePath(i),c=[`**/${a}`];n&&c.push(`**/${a}.*`);let{entries:l,complete:u}=ap(t,c,!1),f=l.length>0?!0:u?!1:"unknown";return s.set(r,f),f}function c_(t){let e=new Map,{entries:n,complete:s}=ap(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 l_="__promptci_dir_probe__",Qn="unjudged";function u_(t,e,n,s,i){let{tree:r,isIgnored:o}=i;if(ga(t)[0]===".git"||e!=="file"&&r_(t))return null;let a=e==="rootedPath"||e==="linkPath",c=a?it(t):t;if(zn(c))return null;let l=[];for(let m of new Set([z.resolve(s,c),z.resolve(r.root,c)])){if(!X(r.root,m))continue;let g=r.lookup(m);g.state!=="outside"&&l.push({abs:m,found:g})}if(l.length===0)return null;let u=!1;for(let{abs:m}of l){let g=z.relative(r.root,m).replace(/\\/g,"/");if(g)for(let y of[o(g),...a?[o(`${g}/${l_}`)]:[]]){if(y===!0||y==="unfetched")return null;y==="unreadable"&&(u=!0)}}if(u)return Qn;let f=a&&!c.endsWith("/");if(l.some(({abs:m,found:g})=>g.state==="found"||f&&r.hasStemSibling(m)))return null;if(l.some(({found:m})=>m.state==="unreadable"))return Qn;if(e==="file"){if(n&&!/[/\\]/.test(c)){let b=i.nameIndex();if(b.paths.get(c)?.some(v=>o(v)!==!0))return null;if(!b.complete)return Qn}let m=z.extname(t.split("#")[0]??"").toLowerCase(),g=qx.has(m),y=l.some(({abs:b})=>r.isDir(z.dirname(b)));return g&&y?.5:.85}if(e==="linkPath")return .8;let d=ga(t);if(d.length<2||d.includes(".."))return null;let p=[s,r.root].filter(m=>r.isDir(z.join(m,d[0])));if(p.length===0||d.length-1>Xx&&!p.some(m=>r.isDir(z.join(m,d[0],d[1])))||e==="rootedPath"&&(Lx.has(d[0].toLowerCase())&&!c.endsWith("/")||d.length===2&&p.some(m=>r.lookup(z.join(m,d[1])).state==="found")))return null;let h=a_(r,d,f,i.suffixCache);return h===!0?null:h==="unknown"?Qn:.6}function f_(t,e,n,s,i,r){if(i!=="file"||s.endsWith("/")||s!==s.trim()||s.startsWith("<")||ma(s)!==s||/[()[\]\s`]/.test(s))return;let o=s.indexOf("#"),a=o===-1?s:s.slice(0,o),c=o===-1?"":s.slice(o),l=z.basename(a.replace(/\\/g,"/").replace(/\/+$/,""));if(!l)return;let u=r.nameIndex();if(!u.complete)return;let f=(u.paths.get(l)??[]).filter(y=>r.isIgnored(y)!==!0);if(f.length!==1)return;let d=z.resolve(r.tree.root,f[0]);if(d===z.resolve(t))return;let p=z.relative(z.dirname(t),d).split(z.sep).join("/");if(!p||/[()[\]\s`#%<>?]/.test(p))return;let h=`${p.startsWith(".")?p:`./${p}`}${c}`;if(h===s)return;let m=`](${s})`,g=0;for(let y=n.indexOf(m);y!==-1;y=n.indexOf(m,y+m.length))g++;if(g===1)return{filePath:t,line:e,find:m,replace:`](${h})`}}function wa(t,e,n){let s=new Map,i=n??new Ee(e),r,o,a=()=>o??=c_(i),c=new Map;for(let f of t){let d=z.dirname(f.path),p=i_(f.content,{skipSourceBackticks:Jx.has(f.fileType)}),h=f.content.split(/\r?\n/);for(let{ref:m,evidence:g,line:y,kind:b,codeSpan:v,linkRaw:x,inCodeContext:w}of p){if(Bx(m)||Gx(m)||ba(m))continue;r??={tree:i,isIgnored:Si(i),suffixCache:new Map,nameIndex:a};let _=u_(m,b,v??!1,d,r);if(_===null)continue;if(_===Qn){let H=`Not checked: ${g}`,ne=c.get(H)??{filePaths:new Set,fileLines:new Map,evidence:H};ne.filePaths.add(f.path);let S=ne.fileLines.get(f.path);(S===void 0||y<S)&&ne.fileLines.set(f.path,y),c.set(H,ne);continue}let A=m.toLowerCase().replace(/\\/g,"/"),C=b==="rootedPath"||b==="linkPath"?A.replace(/^\.\//,"").replace(/\/+$/,""):A,O=`Reference: ${g}`;s.has(C)||s.set(C,{displayRef:m,kind:b,filePaths:new Set,fileLines:new Map,evidenceLines:[],minConfidence:_,edits:[],allRewritable:!0});let M=s.get(C),E=x===void 0||w===!0?void 0:f_(f.path,y,h[y-1]??"",x,b,r);E===void 0?M.allRewritable=!1:M.edits.some(H=>H.filePath===E.filePath&&H.line===E.line&&H.find===E.find)||M.edits.push(E),M.filePaths.add(f.path);let U=M.fileLines.get(f.path);(U===void 0||y<U)&&M.fileLines.set(f.path,y),M.evidenceLines.includes(O)||M.evidenceLines.push(O),M.minConfidence=Math.min(M.minConfidence,_)}}let l=[],u=Zx;for(let[f,{displayRef:d,kind:p,filePaths:h,fileLines:m,evidenceLines:g,minConfidence:y,edits:b,allRewritable:v}]of s){if(y<u)continue;let x=[...h],w=p==="rootedPath"||p==="linkPath",_=w&&it(d).endsWith("/"),A=_?"directory":w?"path":"file",C=z.basename(it(d).replace(/\/+$/,""));l.push({id:sp(f),severity:"warning",category:"structure",title:`Broken ${A} reference: ${C}${_?"/":""}`,summary:`This instruction file references "${d}" which does not appear to exist. The ${A} may have been renamed, moved, or deleted.`,filePaths:x,locations:x.map(O=>{let M=m.get(O);return M!==void 0?{filePath:O,startLine:M}:{filePath:O}}),evidence:g,recommendation:"Verify the path is correct relative to the instruction file location, or remove the reference if the file no longer exists.",...v&&b.length>0?{fixRecipe:`Re-point the link${b.length>1?"s":""} at the one file of that name in the repository: ${[...new Set(b.map(O=>`\`${O.find}\` -> \`${O.replace}\``))].join(", ")}.`,autoApplySafe:!0,fixEdits:b}:{},confidence:y})}return c.size>0&&l.push(hi(i,[...c.values()],{id:sp("(dead-reference check incomplete)"),category:"structure",title:"Dead-reference check incomplete: part of the repository could not be read",unit:"reference",unknown:"They may or may not exist",finding:"broken-reference"})),l}var Pt=R(require("node:crypto"),1),Le=R(require("node:path"),1);function Ut(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 es(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 cp(t,e,n){let s=es(Ut(t,e??[],n)).map(i=>i[0]);return s.length===0?t:[...t,...s]}var wn=[{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."}],d_=/\bdo\s+not\s+(edit|modify|change)\b/im,p_=/<!--\s*auto[- ]?generated|auto[- ]?generated|<!--\s*generated\s*(?:by\s+\w+)?|this\s+file\s+is\s+generated|generated\s+by\s+\w+/i,h_=/<\/?claude:[\w-]+|<instructions-for-claude[\s>]/i,lp=/(?:follow|use|see|refer\s+to|canonical\s+(?:source|instructions?)|pointer\s+to)\s+[`'"*]*(?:\.?\/)?(?:\.github\/)?(?:AGENTS|CLAUDE)\.md\b/i,m_=/\b(AGENTS|CLAUDE)\.md\b[^\n]{0,60}?\b(?:single\s+source\s+of\s+truth|canonical)\b/i;function g_(t){return`agent-practice-${Pt.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function y_(t){return`do-not-edit-${Pt.createHash("sha1").update(`do-not-edit:${t}`).digest("hex").slice(0,12)}`}function b_(t){return`per-file-behavior-${Pt.createHash("sha1").update(`per-file-behavior:${t}`).digest("hex").slice(0,12)}`}function ts(t,e){return e.some(n=>n.test(t))}function w_(t,e){let n=1;for(let s=0;s<e&&s<t.length;s++)t[s]===`
43
- `&&n++;return n}function ki(t){return t.split(`
35
+ `)&&e.pop(),e}function nn(t,e,n){let s=pf(t),i=[],o,r=1,a=[],c=u=>{let p=a.join(`
36
+ `),d=o!==void 0?h_(o):`${e}:0`;i.push({id:d,filePath:e,...n!==void 0?{relativePath:n}:{},heading:o,startLine:r,endLine:u,text:p,normalizedText:p.toLowerCase().trim()})},l=we(t);for(let u=0;u<s.length;u++){let p=u+1,d=s[u]??"";if(l[u]?.inFence){a.push(d);continue}let h=/^ {0,3}(#{1,3})\s+(.+)/.exec(d);h?((a.length>0||o!==void 0)&&c(p-1),o=h[2].trim(),r=p,a=[d]):a.push(d)}return(a.length>0||o!==void 0)&&c(s.length),i}function sn(t){let e=Math.min(t.length,In);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}function m_(t){return[...nf(t.isDir(".clinerules"))]}function ff(t){try{return us.realpathSync.native(t)}catch{return null}}async function af(t,e,n,s){let i=ff(n);if(i===null||!ue(e,i))return;let o;try{let r=us.constants.O_NOFOLLOW??0;o=await df.open(i,us.constants.O_RDONLY|r);let a=await o.stat();if(!a.isFile()||a.size>ye)return;let c=await o.readFile();if(sn(c))return;let l=c.toString("utf-8"),u=Ye.relative(t,n).replace(/\\/g,"/"),p=nn(l,n,u),d=pf(l).length,h=l.length;return{path:n,relativePath:u,fileType:f_(s),content:l,sections:p,lineCount:d,charCount:h,estimatedTokens:Math.round(h/4)}}catch{return}finally{await o?.close().catch(()=>{})}}var cf=260,g_=8;function y_(t,e,n){let s=t.relativePath;if(s===void 0||t.charCount>cf+16)return;let i=t.content.replace(/^\u{FEFF}/u,"").trim();if(i===""||i.length>cf||/[\r\n]/.test(i)||i.startsWith("/")||/^[A-Za-z]:/.test(i)||i.includes("\\"))return;let o=Ye.posix.normalize(Ye.posix.join(Ye.posix.dirname(s),i));if(!(o===".."||o.startsWith("../")||o===s||!e.has(o)))return n.isSymlink(s)?o:void 0}function lf(t,e){return{...e,path:t.path,relativePath:t.relativePath,fileType:t.fileType,sections:nn(e.content,t.path,t.relativePath),aliasOf:e.relativePath}}function b_(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=y_(c,s,n);l!==void 0&&i.set(c.relativePath,l)}if(i.size===0)return{files:t,aliases:e};let o=new Map;for(let c of i.keys()){let l=i.get(c),u=1;for(;i.has(l)&&u<g_;)l=i.get(l),u++;i.has(l)||o.set(c,s.get(l))}if(o.size===0)return{files:t,aliases:e};let r=t.filter(c=>c.relativePath===void 0||!o.has(c.relativePath)),a=e.map(c=>{let l=c.aliasOf===void 0?void 0:o.get(c.aliasOf);return l===void 0?c:lf(c,l)});for(let[c,l]of o)a.push(lf(s.get(c),l));return{files:r,aliases:a}}async function Li(t,e){let n=Ye.resolve(t.repoPath),s=ff(n)??n,i=e??new Le(n,{...t.knownPaths!==void 0?{knownPaths:t.knownPaths}:{},...t.knownPathsComplete!==void 0?{knownPathsComplete:t.knownPathsComplete}:{}}),o=t.include&&t.include.length>0?t.include:m_(i),r=[...d_.map(m=>`**/${m}/**`),...t.exclude??[]],a;try{a=await(0,uf.default)(o,{cwd:n,ignore:r,dot:!0,absolute:!1,onlyFiles:!1,objectMode:!0,followSymbolicLinks:!1,suppressErrors:!0})}catch{return{files:[],aliases:[]}}let c=[],l=[];for(let m of a)m.dirent.isSymbolicLink()?l.push(m.path):m.dirent.isFile()&&c.push(m.path);l.sort();let u=[],p=[],d=new Map,h=[];for(let m of c){let g=Ye.resolve(n,m);if(!ue(n,g)||!Pe(n,g))continue;let y=Dt(g);h.push({relPath:m,absPath:g,real:y,direct:y!==null&&y===Ye.join(s,m)})}h.sort((m,g)=>Number(g.direct)-Number(m.direct)||m.relPath.localeCompare(g.relPath));for(let{relPath:m,absPath:g,real:y}of h){let b=await af(n,s,g,m);if(!b)continue;let w=y!==null?d.get(y):void 0;if(w){p.push({...b,aliasOf:w.relativePath});continue}u.push(b),y!==null&&d.set(y,b)}for(let m of l){let g=Ye.resolve(n,m);if(!ue(n,g)||!Pe(n,g))continue;let y=await af(n,s,g,m);if(!y)continue;let b=Dt(g),w=b!==null?d.get(b):void 0;if(w){p.push({...y,aliasOf:w.relativePath});continue}u.push(y),b!==null&&d.set(b,y)}let f=b_(u,p,Zp(n));return f.files.sort((m,g)=>m.path.localeCompare(g.path)),f.aliases.sort((m,g)=>m.path.localeCompare(g.path)),f}async function Ea(t){return(await Li(t)).files}var ds=R(require("node:path"),1);function w_(t){let e=t.entries(t.root);if(typeof e=="string")return new Set;let n=new Set;for(let s of e.values())s.isDirectory()||n.add(s.name);return n}async function ps(t,e=new Le(t)){let n=ds.resolve(t),s=(...y)=>e.exists(ds.join(n,...y)),i=(...y)=>e.isDir(ds.join(n,...y)),o=w_(e);if([...o].some(y=>y.startsWith("next.config.")))return"nextjs";let r=s("package.json");if(r&&(i("app")||i("pages")))return"nextjs";let a=i("Assets"),c=s("ProjectSettings","ProjectVersion.txt");if(a&&c)return"unity";if([...o].some(y=>y.endsWith(".sln")||y.endsWith(".csproj")))return"dotnet";let l=s("tsconfig.json");if(r||l)return"typescript";let u=s("pyproject.toml"),p=s("requirements.txt"),d=s("Pipfile"),h=s("environment.yml"),f=s("setup.py");return u||p||d||h||f?"python":s("go.mod")?"go":s("Cargo.toml")?"rust":"unknown"}function Aa(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 $a=R(require("node:crypto"),1),fs=R(require("node:path"),1);var v_=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}]/u;function Ni(t){return`<U+${t.toString(16).toUpperCase().padStart(4,"0")}>`}function S_(t,e=t.codePointAt(0)){return e===9||e>=32&&e<127?!1:v_.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 Mi(t){let e="",n="",s=()=>{n&&(e+=`<TAGS:"${n}">`),n=""};for(let i of t){let o=i.codePointAt(0);if(o>=917504&&o<=917631){n+=o>=917536&&o<=917630?String.fromCharCode(o-917504):Ni(o);continue}s(),e+=S_(i,o)?Ni(o):i}return s(),e}function se(t,e=120){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e)}\u2026`}function __(t,e,n=120){let i=new RegExp(e.source,e.flags.replace("g","")).exec(t);return i?se(i[0],n):void 0}function On(t,e,n,s=120){let i=__(t,e,s);return i?`${n}: "${i}"`:n}function hf(t){return t.replace(/\\/g,"/").replace(/^(?:\.\/)+/,"")}function G(t){return hf(t.relativePath??t.path)}function He(t){return hf(t.relativePath??t.filePath)}var ji=150,x_=80,k_=10,E_=.8,A_=.6,C_=.6,mf=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 Ia(t){return t.toLowerCase().replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+\.\s+/gm,"").replace(/\s+/g," ").trim()}function Ca(t){let e=t.match(/\b\w+\b/g)??[];return new Set(e)}function R_(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 Ra(t){if(!t)return!1;let e=t.toLowerCase().trim();if(mf.has(e))return!0;for(let n of mf)if(e.startsWith(n))return!0;return!1}function T_(t){let e=t.text.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
38
+ `).split(`
39
+ `).map(n=>n.replace(/[ \t\f\v]+$/,""));for(;e.length>0&&e[0]==="";)e.shift();for(;e.length>0&&e[e.length-1]==="";)e.pop();return e.join(`
40
+ `)}function bf(t){return new Set(t.map(T_)).size===1}function gf(t){return t?.toLowerCase().replace(/\s+/g," ").trim()??""}function P_(t,e){let n=gf(t.heading),s=gf(e.heading);return n.length>0&&n===s}function Ln(t,e){if(!t.has(e))return e;let n=Ln(t,t.get(e));return t.set(e,n),n}function wf(t,e,n){let s=Ln(t,e),i=Ln(t,n);s!==i&&t.set(s,i)}function Ta(t){let e=[...t].sort().join("|");return`duplicate-${$a.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function Oa(t){let e=[];for(let h of t)for(let f of h.sections){let m=Ia(f.text);m.length<x_||Ca(m).size<k_||e.push({...f,normalizedText:m})}let n=new Map,s=new Map,i=[];for(let h=0;h<e.length;h++)for(let f=h+1;f<e.length;f++){let m=e[h],g=e[f];if(m.filePath===g.filePath&&m.startLine===g.startLine)continue;let y=`${He(m)}:${m.startLine}`,b=`${He(g)}:${g.startLine}`,w=m.normalizedText,S=g.normalizedText,C=null,v=0;if(Ra(m.heading)||Ra(g.heading))continue;let _=m.filePath===g.filePath;if(w===S){if(!_&&(w.length<ji||S.length<ji)&&!P_(m,g))continue;C="high",v=.95}else{if(!_&&(w.length<ji||S.length<ji))continue;let A=_?C_:E_,O=R_(Ca(w),Ca(S));O>=A?(C="warning",v=_?.8:.75):!_&&O>=A_&&(C="info",v=.5)}C!==null&&(s.set(y,m),s.set(b,g),wf(n,y,b),i.push({keyA:y,keyB:b,severity:C,confidence:v}))}let o=new Map;for(let h of s.keys()){let f=Ln(n,h);o.has(f)||o.set(f,[]),o.get(f).push(h)}let r={info:0,warning:1,high:2,critical:3},a=new Map,c=new Map;for(let h of i){let f=Ln(n,h.keyA),m=a.get(f);(!m||r[h.severity]>r[m])&&(a.set(f,h.severity),c.set(f,h.confidence))}let l=N_(t,i,s),u=new Map;for(let[,h]of o){if(h.length<2)continue;let f=D_(h.map(g=>s.get(g).filePath),l);if(f===void 0)continue;let m=u.get(f)??[];m.push(h),u.set(f,m)}let p=new Set([...u.values()].flat(2)),d=[];for(let[h,f]of o){if(f.length<2||p.has(f[0]))continue;let m=f.map(j=>s.get(j)),g=a.get(h)??"warning",y=c.get(h)??.75,b=[...new Set(m.map(j=>j.filePath))],w=[...new Set(m.map(j=>j.heading??"(untitled)"))],S=w.length===1?w[0]:w.slice(0,2).join(" / "),C=b.length,v=C>2?`Possible duplicate: ${S} (${C} files)`:`Possible duplicate: ${S}`,_=m.slice(1).reduce((j,x)=>j+Math.round(x.text.length/4),0),A=bf(m),O=(C>2?`This section appears highly similar in ${C} files. Consider consolidating into one canonical location.`:"These sections appear highly similar. Consider consolidating them into one canonical location.")+(A?"":" The copies are not identical: they differ in places, so compare them before consolidating.");d.push({id:Ta(f),severity:g,category:"duplicate",title:v,summary:O,filePaths:b,locations:m.map(j=>({filePath:j.filePath,startLine:j.startLine,endLine:j.endLine})),evidence:[se(m[0].normalizedText,200),`Duplicated size: ~${_} tokens`],recommendation:(A?"":"The copies differ: decide which text is right before consolidating, since a pointer would discard the other. Then ")+`${A?"Consolidate":"consolidate"} these sections into one canonical location (e.g. AGENTS.md) and use forwarding pointers to save ~${_} tokens per session. If both are intentional, add a comment clarifying the distinction.`,autoApplySafe:C>=2&&A,confidence:y})}for(let[h,f]of[...u].sort((m,g)=>m[0]-g[0]))d.push(F_(l.groups[h],f,s,l));return d}var $_=.5,I_=.8,O_=2;function L_(t){return`duplicate-${$a.createHash("sha1").update(`mirror:${t.join("|")}`).digest("hex").slice(0,12)}`}function Pa(t){let e=[...t].sort(),n=e.find(s=>fs.basename(s).toLowerCase()==="agents.md");return n?[n,...e.filter(s=>s!==n)]:e}function N_(t,e,n){let s=new Map;for(let m of t)for(let g of m.sections){if(!j_(g))continue;let y=s.get(g.filePath)??new Set;y.add(`${He(g)}:${g.startLine}`),s.set(g.filePath,y)}let i=new Map,o=new Set,r=(m,g,y)=>{let b=i.get(m)??new Map,w=b.get(g)??new Set;w.add(y),b.set(g,w),i.set(m,b)};for(let m of e){if(m.severity!=="high"&&m.severity!=="warning")continue;let g=n.get(m.keyA).filePath,y=n.get(m.keyB).filePath;g!==y&&(r(g,y,m.keyA),r(y,g,m.keyB),m.severity==="high"&&o.add([g,y].sort().join("\0")))}let a=(m,g)=>new Set([...s.get(m)??[],...g]).size,c=new Map,l=new Set,u=new Set;for(let[m,g]of i)for(let[y,b]of g){if(m>=y)continue;let w=i.get(y)?.get(m)??new Set,S=b.size/a(m,b),C=w.size/a(y,w),v=S===1&&C===1&&o.has([m,y].sort().join("\0"));Math.min(b.size,w.size)<O_&&!v||Math.min(S,C)<$_&&Math.max(S,C)<I_||(wf(c,m,y),l.add(m),l.add(y),u.add(yf(m,y)))}let p=new Map;for(let m of l){let g=Ln(c,m);p.set(g,[...p.get(g)??[],m])}let d=[...p.values()].flatMap(m=>M_(m,(g,y)=>u.has(yf(g,y)))).map(Pa).sort((m,g)=>m[0].localeCompare(g[0])),h=new Map,f=new Map;return d.forEach((m,g)=>{for(let y of m)f.set(y,g),h.set(y,s.get(y)?.size??0)}),{groups:d,groupOfFile:f,comparable:h}}var yf=(t,e)=>t<e?`${t}\0${e}`:`${e}\0${t}`;function M_(t,e){let n=[],s=Pa(t);for(;s.length>1;){let i=[s[0]];for(let o of s.slice(1))i.every(r=>e(r,o))&&i.push(o);i.length>1&&n.push(i),s=Pa(s.filter(o=>!i.includes(o)))}return n}function j_(t){let e=t.text.replace(/^\s*#{1,6}\s+[^\n]*\n?/,"");return Ia(e).length>0}function D_(t,e){let n=[...new Set(t)];if(n.length<2)return;let s=e.groupOfFile.get(n[0]);if(s!==void 0)return n.every(i=>e.groupOfFile.get(i)===s)?s:void 0}function F_(t,e,n,s){let i=t[0],o=w=>w.map(S=>n.get(S)),r=e.flatMap(o),a=new Map,c=new Map;for(let w of r)a.set(w.filePath,w.relativePath??fs.basename(w.filePath)),c.set(w.filePath,He(w));let l=t.map(w=>a.get(w)??fs.basename(w)),u=l[0],p=0;for(let w of e){let S=o(w),C=S.find(v=>v.filePath===i)??S[0];p+=S.filter(v=>v!==C).reduce((v,_)=>v+Math.round(_.text.length/4),0)}let d=w=>new Set(r.filter(S=>S.filePath===w).map(S=>S.startLine)).size,h=new Map(t.map((w,S)=>[w,S])),f=[...r].sort((w,S)=>h.get(w.filePath)-h.get(S.filePath)||w.startLine-S.startLine).map(w=>({filePath:w.filePath,startLine:w.startLine,endLine:w.endLine})),m=w=>o(w)[0].heading??"(untitled)",g=[...new Set(e.map(m))],y=e.filter(w=>!bf(o(w))).map(m),b=t.map((w,S)=>`${l[S]} ${d(w)} of ${Math.max(d(w),s.comparable.get(w)??0)}`).join(", ");return{id:L_(t.map(w=>c.get(w)??w)),severity:"warning",category:"duplicate",title:`Possible mirrored instruction files: ${l.join(", ")}`,summary:`These ${t.length} instruction files appear to be copies of one another: ${e.length} section(s) have the same or nearly the same text in more than one of them, covering most of at least one file (shared sections per file: ${b}). That is common when copies are kept in step for tools that read different files, or generated. Reported once for the group rather than once per section. Every tool that loads more than one of them pays about ${p} extra tokens per session, and copies tend to drift apart.`+(y.length>0?` The copies already differ in ${y.length} section(s): ${se(y.join(", "),200)}.`:""),filePaths:t,locations:f,evidence:[...l.map(w=>`Mirrored file: ${w}`),`Shared sections: ${se(g.join(", "),200)}`],recommendation:(y.length>0?`Reconcile the sections that differ (${se(y.join(", "),120)}) first: decide which text is right, since a pointer would discard the other. Then consider `:"Consider ")+`keeping one canonical file (here ${u}) and replacing the others with a short pointer such as "Follow ${fs.basename(u)}", or a symlink where the tool follows one. If a generator writes these files, configure it to write the pointer instead. Keep only genuinely tool-specific guidance in the other files.`,autoApplySafe:y.length===0,fingerprintKey:`duplicate-mirror:${c.get(i)??i}`,confidence:.8}}function La(t){let e=[];for(let n of t){let s=new Map;for(let r of n.sections){if(!r.heading||Ra(r.heading))continue;let a=r.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(r))}for(let[,r]of s){if(r.length<2||new Set(r.map(p=>{let d=/^(#{1,6})\s/.exec(p.text);return d?d[1].length:0})).size>1)continue;let c=r.map(p=>`${G(n)}:${p.startLine}`),l=Ta(c),u=r[0].heading??"(untitled)";e.push({id:l,severity:"warning",category:"duplicate",title:`Duplicate section heading in one file: "${u}"`,summary:`The heading "${u}" appears ${r.length} times in this file. This is likely an accidental duplicate \u2014 consider consolidating into one section.`,filePaths:[n.path],locations:r.map(p=>({filePath:n.path,startLine:p.startLine,endLine:p.endLine})),evidence:[`Heading "${u}" found at lines: ${r.map(p=>p.startLine).join(", ")}`],recommendation:"Merge the duplicate sections into one, or rename one if the distinction is intentional.",confidence:.85})}let i=[...s.keys()],o=new Set;for(let r=0;r<i.length;r++)for(let a=r+1;a<i.length;a++){let c=i[r],l=i[a],u=c.length<=l.length?c:l,p=c.length<=l.length?l:c;if(u.length<4||!p.startsWith(u))continue;let d=p.slice(u.length);if(!/^\s/.test(d)||!d.trimStart())continue;let f=[c,l].sort().join("|");if(o.has(f))continue;o.add(f);let m=s.get(c),g=s.get(l),y=[...m,...g].sort((w,S)=>w.startLine-S.startLine),b=y.map(w=>`${G(n)}:${w.startLine}`);e.push({id:Ta(b),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:y.map(w=>({filePath:n.path,startLine:w.startLine,endLine:w.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 Fi=R(require("node:crypto"),1),Na=R(require("node:path"),1);var H_=1,Rf=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"]),B_=new Set(["for","when","if","unless","except"]),G_=new Set(["it","them","they","we","code","sure","careful","good","clean","simple","easy","proper","consistent","clear","correct","possible","necessary","appropriate"]),Tf=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 vf(t,e,n=3,s=!1){let i=t.slice(e).replace(/^\s+/,"");if(s){let a=/^([a-zA-Z]+)\s+/.exec(i);a&&Tf.has(a[1].toLowerCase())&&(i=i.slice(a[0].length))}let o=[],r=i.replace(/[—–].*$/,"").replace(/\s*\(.*$/,"").replace(/[,;:.].*$/,"").trim();for(let a of r.split(/\s+/)){let c=a.replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g,"").toLowerCase();if(c&&(Rf.has(c)||!/^[a-z]/i.test(c)&&!/^[0-9]+[a-z]/i.test(c)||(o.push(c),o.length>=n)))break}return o.join(" ")}var hs=[{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 W_(t,e,n,s){let i=t.slice(e).replace(/^\s+/,"");if(s){let l=/^([a-zA-Z]+)\s+/.exec(i);l&&Tf.has(l[1].toLowerCase())&&(i=i.slice(l[0].length))}let o=i.replace(/[—–].*$/,"").replace(/\s*\(.*$/,"").replace(/[,;:.].*$/,"").trim(),r=n.split(" ").filter(Boolean),a=o;for(let l of r){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 B_.has(c)}function Di(t){return t.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim()}function Sf(t){if(!t||t.length<2)return!0;let e=t.split(" ").filter(Boolean);return e.length===0?!0:e.every(n=>G_.has(n))}function V_(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 r of n)s.has(r)&&i++;let o=n.size+s.size-i;return i/o}function _f(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 o=s.slice(i).trim(),r=[];for(let a of o.split(/\s+/).reverse()){let c=a.replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g,"").toLowerCase();if(c&&!Rf.has(c)&&(r.unshift(c),r.length>=n))break}return r.join(" ")}function U_(t){let e=t.text.split(`
41
+ `).map(i=>i.trim()),n=[],s="";for(let i of e){let o=/^ {0,3}#{1,6}\s/.test(i),r=/^(?:[-*+]\s+|\d+[.)]\s+)/.test(i);if(!i||i.startsWith("|")||o){s&&(n.push(s),s=""),o&&n.push(i);continue}r&&s&&(n.push(s),s=""),s=s?`${s} ${i}`:i,/[.!?:;]$/.test(i)&&(n.push(s),s="")}return s&&n.push(s),n}function xf(t,e){let n=t.flags.includes("g")?t.flags:`${t.flags}g`,s=new RegExp(t.source,n),i=[],o;for(;(o=s.exec(e))!==null;)i.push({index:o.index,text:o[0]}),o[0].length===0&&s.lastIndex++;return i}function z_(t){let e=[],n=U_({...t,text:st(t.text)});for(let s=0;s<hs.length;s++){let i=hs[s];for(let o of n){let r=i.skipLeadingVerb??!1,a=i.extractSubjectBefore??!1,c=xf(i.negativePattern,o),l=o;for(let p of c){let d=p.index+p.text.length,h=a,f=Di(h?_f(o,p.index,4):vf(o,d,3,r));if(f.length>=2&&!Sf(f)){let m=!h&&W_(o,d,f,r);e.push({section:t,pairIndex:s,polarity:"negative",subject:f,matchedLine:o,hasQualifier:m})}l=l.slice(0,p.index)+" ".repeat(p.text.length)+l.slice(d)}let u=xf(i.positivePattern,l);for(let p of u){let d=a||(i.extractPositiveSubjectBefore??!1),h=Di(d?_f(o,p.index,4):vf(o,p.index+p.text.length,3,r));h.length>=2&&!Sf(h)&&e.push({section:t,pairIndex:s,polarity:"positive",subject:h,matchedLine:o})}}}return e}function kf(t,e,n,s,i,o){let r=[`${t}:${e}`,`${n}:${s}`].sort(),a=`${r[0]}|${r[1]}|${i}|${o}`;return`conflict-${Fi.createHash("sha1").update(a).digest("hex").slice(0,12)}`}function Ma(t){let e=[];for(let a of t)for(let c of a.sections)c.text.trim().length>=H_&&e.push(c);let n=[];for(let a of e)n.push(...z_(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 p=l.polarity==="positive"?l:u,d=l.polarity==="negative"?l:u,h=p.subject===d.subject?1:V_(p.subject,d.subject),f;if(p.subject===d.subject){let C=p.subject.split(" ").filter(Boolean).length===1&&(new RegExp(`\`${p.subject}\\.[a-z]`,"i").test(p.matchedLine)||new RegExp(`\`${d.subject}\\.[a-z]`,"i").test(d.matchedLine)),v=hs[l.pairIndex];f=d.hasQualifier&&/\balways\b/i.test(p.matchedLine)&&v.label.includes("always")?.5:d.hasQualifier?.35:C?.5:.8}else if(h>=.5){let S=hs[l.pairIndex],C=p.subject.split(" ").filter(Boolean),v=d.subject.split(" ").filter(Boolean);if(C.length<2||v.length<2){if(!S.allowSingleTokenMatch)continue;let _=C.length<=v.length?C[0]:v[0];if(!(C.length>v.length?p.subject:d.subject).startsWith(_))continue}f=d.hasQualifier?.3:.5}else continue;if(f<.4)continue;let m=kf(He(p.section),p.section.startLine,He(d.section),d.section.startLine,l.pairIndex,p.subject);if(i.has(m))continue;i.add(m);let g=f>=.7?"high":"warning",y=hs[l.pairIndex],b=p.subject.length<=d.subject.length?p.subject:d.subject,w=Array.from(new Set([p.section.filePath,d.section.filePath]));s.push({id:m,severity:g,category:"conflict",title:`Possible conflicting instruction: ${b}`,summary:`Possible conflict \u2014 review these together. A "${y.label}" directive pattern was found pointing in opposite directions for the subject "${b}".`,filePaths:w,locations:[{filePath:p.section.filePath,startLine:p.section.startLine,endLine:p.section.endLine},{filePath:d.section.filePath,startLine:d.section.startLine,endLine:d.section.endLine}],evidence:[p.matchedLine,d.matchedLine],recommendation:"Review these instructions together and consolidate into one clear directive.",confidence:f})}let o=new Map,r=new Map;for(let a of n)a.polarity==="positive"?(o.has(a.subject)||o.set(a.subject,[]),o.get(a.subject).push(a)):(r.has(a.subject)||r.set(a.subject,[]),r.get(a.subject).push(a));for(let[a,c]of o){let l=r.get(a);if(l)for(let u of c)for(let p of l){if(u.pairIndex===p.pairIndex||u.section.filePath===p.section.filePath&&u.section.startLine===p.section.startLine)continue;{let f=u.subject.split(" ").filter(Boolean).length,m=p.subject.split(" ").filter(Boolean).length;if(f<2||m<2)continue}if(p.hasQualifier)continue;let d=kf(He(u.section),u.section.startLine,He(p.section),p.section.startLine,-1,a);if(i.has(d))continue;i.add(d);let h=Array.from(new Set([u.section.filePath,p.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:h,locations:[{filePath:u.section.filePath,startLine:u.section.startLine,endLine:u.section.endLine},{filePath:p.section.filePath,startLine:p.section.startLine,endLine:p.section.endLine}],evidence:[u.matchedLine,p.matchedLine],recommendation:"Review these instructions together and consolidate into one clear directive.",confidence:.5})}}return s}var q_=[{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 K_(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 Y_(t){let e=new Map;for(let{re:n,name:s,normalize:i}of q_){let o=new RegExp(n.source,n.flags),r;for(;(r=o.exec(t))!==null;){if(K_(t,r.index))continue;let a=i(r[1]);e.has(s)||e.set(s,new Set),e.get(s).add(a)}}return e}function X_(t,e){let n=`version-conflict:${t}:${[...e].sort().join("|")}`;return`version-conflict-${Fi.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function ja(t){if(t.length<2)return[];let e=t.map(o=>({file:o,versions:Y_(st(o.content))})),n=new Map;for(let{file:o,versions:r}of e)for(let[a,c]of r){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(o.path)}let s=[],i=o=>o.split(/[\\/]/).pop()??o;for(let[o,r]of n){if(r.size<=1)continue;let a=[...r.keys()],c=[...new Set([...r.values()].flat())];if(a.map(h=>r.get(h)).every(h=>h.every(f=>f===c[0])))continue;let p=X_(o,a),d=a.map(h=>`${o} ${h} referenced in: ${r.get(h).map(i).join(", ")}`);s.push({id:p,severity:"high",category:"conflict",title:`Version conflict: ${o} (${a.join(" vs ")})`,summary:`Possible conflict \u2014 review these together. Different instruction files specify different versions of ${o}: ${a.join(" vs ")}.`,filePaths:c,locations:c.map(h=>({filePath:h})),evidence:d,recommendation:`Ensure all instruction files agree on which version of ${o} this project targets. Remove or update whichever reference is out of date.`,confidence:.75})}return s}function J_(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Z_={"kebab-case":["kebab-case","kebab case","kebabcase"],camelcase:["camelcase","camel case","camel-case"],pascalcase:["pascalcase","pascal case","pascal-case"]};function Ef(t){let e=Z_[t.toLowerCase()]??[t];return new RegExp(`\\b(?:${e.map(J_).join("|")})\\b`,"i")}var Q_=[{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"}],Af=/\b(?:use|prefer|always|must|should|follow|rely\s+on|stick\s+to|require)\b/i;function Cf(t,e){let n=t.split(`
42
+ `).map(s=>s.trim());for(let s=0;s<n.length;s++){let i=n[s];if(e.test(i)&&Af.test(i))return!0;let o=n[s+1];if(i&&o){let r=`${i} ${o}`;if(e.test(r)&&Af.test(r))return!0}}return!1}function Da(t){if(t.length<2)return[];let e=[],n=new Set,s=new Map(t.map(o=>[o.path,st(o.content)])),i=o=>s.get(o.path)??o.content;for(let o of Q_){let r=Ef(o.termA),a=Ef(o.termB),c=t.filter(b=>r.test(i(b))),l=t.filter(b=>a.test(i(b)));if(c.length===0||l.length===0)continue;let u=new Set(c.map(b=>b.path)),p=new Set(l.map(b=>b.path));if([...u].every(b=>p.has(b))&&[...p].every(b=>u.has(b)))continue;let h=c.some(b=>Cf(i(b),r)),f=l.some(b=>Cf(i(b),a));if(!h&&!f)continue;let m=[o.termA.toLowerCase(),o.termB.toLowerCase()].sort().join("|");if(n.has(m))continue;n.add(m);let g=[...new Set([...c,...l].map(b=>b.path))],y=`competing-tech-${Fi.createHash("sha1").update(m).digest("hex").slice(0,12)}`;e.push({id:y,severity:"warning",category:"conflict",title:`Possible ${o.dimension} conflict: "${o.termA}" vs "${o.termB}"`,summary:`Possible conflict \u2014 review these together. Different instruction files reference competing ${o.dimension} choices: "${o.termA}" and "${o.termB}".`,filePaths:g,locations:g.map(b=>({filePath:b})),evidence:[`"${o.termA}" referenced in: ${c.map(b=>Na.basename(b.path)).join(", ")}`,`"${o.termB}" referenced in: ${l.map(b=>Na.basename(b.path)).join(", ")}`],recommendation:`Review both instruction files and decide which ${o.dimension} is canonical. Remove or update whichever reference contradicts the team's actual choice.`,confidence:.6})}return e}var Q=R(require("node:path"),1),Vf=R(require("node:crypto"),1),Ba=R(rs(),1);function Pf(t){return/[\\^$.*+?()[\]{}|/]/.test(t)?`\\${t}`:t}function ex(t){let e="",n=0;for(;n<t.length;){let s=t[n];if(s==="\\")n+1<t.length&&(e+=Pf(t[n+1])),n+=2;else if(s==="*")if(t[n+1]==="*"){let i=n===0||t[n-1]==="/",o=n+2;for(;t[o]==="*";)o++;i&&t[o]==="/"?(e+="(?:.*/)?",n=o+1):i&&o===t.length?(e+=".*",n=o):(e+="[^/]*",n=o)}else e+="[^/]*",n++;else if(s==="?")e+="[^/]",n++;else if(s==="["){let i=t.indexOf("]",n+2);if(i===-1)e+="\\[",n++;else{let o=t.slice(n+1,i),r=!1;(o.startsWith("!")||o.startsWith("^"))&&(r=!0,o=o.slice(1)),o=o.replace(/[\\^\]]/g,a=>`\\${a}`),e+=`[${r?"^":""}${o}]`,n=i+1}}else e+=Pf(s),n++}return e}function tx(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 o=!1;s.endsWith("/")&&(o=!0,s=s.slice(0,-1));let r=s.includes("/");if(s=s.replace(/^\//,""),s!=="")try{e.push({negate:i,dirOnly:o,anchored:r,regex:new RegExp(`^${ex(s)}$`)})}catch{}}return e}function nx(t,e,n){if(t.dirOnly&&!n)return!1;let s=t.anchored?e:e.split("/").pop();return t.regex.test(s)}function Hi(t){let e=new Map,n=s=>{let i=e.get(s);if(i===void 0){let o=t.readText(s===""?".gitignore":`${s}/.gitignore`);i=o.state==="found"?tx(o.content):o.state==="unfetched"?"unfetched":o.state==="unreadable"||o.state==="too-large"?"unreadable":[],e.set(s,i)}return i};return s=>{let i=s.replace(/\\/g,"/").replace(/^\.\//,"").split("/").filter(Boolean),o;for(let r=1;r<=i.length;r++){let a=r<i.length,c;for(let l=0;l<r;l++){let u=i.slice(l,r).join("/"),p=n(i.slice(0,l).join("/"));if(typeof p=="string"){(p==="unreadable"||o===void 0)&&(o=p);continue}for(let d of p)nx(d,u,a)&&(c=!d.negate)}if(c===!0)return!0}return o??!1}}function Fa(t){let e=we(t),n=[],s=0,i=0;return t.split(`
43
+ `).forEach((o,r)=>{if(e[r]?.inFence!==!0)for(let a=o.indexOf("<!--");a!==-1;a=o.indexOf("<!--",a+4)){let c=s+a;if(c<i||(o.slice(0,a).match(/`/g)?.length??0)%2===1)continue;let l=t.indexOf("-->",c+4);i=l===-1?t.length:l+3,n.push([c,i])}s+=o.length+1}),n}function $f(t,e){return t.some(([n,s])=>e>=n&&e<s)}function If(t){return t.split(`
44
+ `).map(e=>/^(?: {4,}|\t)\S/.test(e))}function Of(t){let e=Fa(t),n=[],s=0;for(let i of t.split(`
45
+ `)){let o=s+i.length;n.push(e.some(([r,a])=>r<o+1&&a>s)),s=o+1}return n}var Lf=/\[(?:[^\]]*)\]\(([^)]+)\)/g,Nf=/\[(?:[^\]]|\]\([^)]*\))*\]\(([^)]+)\)/g,Mf=/^[ \t]{0,3}\[[^\]]+\]:\s*(\S+)/gm,jf=/(?<!\w)@((?:\.{1,2}\/)?[\w./\\-]+\.(?:md|ts|js|mjs|cjs|tsx|jsx|json|yml|yaml|toml|txt|sh|py|cs|go|rs))/g,Df=/`([^\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,Ff=/`((?:\.\/)?[\w@.()[\]-]+(?:\/[\w@.()[\]-]+)+\/?)`/g,sx=/\b(?:branch(?:es)?|checkout|rebase|merge|cherry-pick|route[sd]?|routing|endpoints?|urls?|uris?|http\s+(?:get|post|put|patch|delete))\b/i,ix=new Set(["feat","feature","features","fix","bugfix","hotfix","chore","docs","doc","refactor","test","tests","ci","perf","build","release","releases","style","wip","dependabot"]),Uf=new Set(["dist","build","out",".next","coverage","target","bin","obj","node_modules",".turbo"]),Hf=/^[ \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,Bf="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",ox=new RegExp(`^(?:#{1,4}\\s+.*\\b(?:${Bf})\\b|\\*\\*[^*\\n]*\\b(?:${Bf})\\b[^*\\n]*\\*\\*\\s*)`,"im"),rx=/\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 Gf(t){return mt(t).replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase()}var ax=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 Bi(t){return/^https?:\/\/|^mailto:|^#|^data:/.test(t.trimStart())}function Ha(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 cx=/^(foo|bar|baz|qux|quux|example|sample|placeholder|stub|demo|test|your[-_]?file|my[-_]?file|filename|file[-_]?name)(\.\w+)?$/i,lx=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"]),ux=/^(ComponentName|MyComponent|YourComponent|WidgetName|FeatureName|ModuleName|ServiceName|ModelName|EntityName|ResourceName|DomainName|ControllerName|ScreenName|PageName)(?:\.\w+)*$/i;function dx(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=Q.basename(mt(t)),n=Q.dirname(mt(t)),s=n!=="."&&n!==""&&n!==".\\"&&n!=="./";return!!(!s&&cx.test(e)||ux.test(e)||!s&&lx.has(e.toLowerCase())||/camelCase|CamelCase|PascalCase|pascalCase|kebab[-_]?[Cc]ase|snake_?[Cc]ase/.test(e))}var px=[/(?:^|[/\\])\.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 fx(t){let e=t.replace(/\\/g,"/");return px.some(n=>n.test(e))}var hx=/^(?:~(?:[/\\]|$)|\$\{?(?:HOME|USERPROFILE|XDG_CONFIG_HOME|XDG_DATA_HOME)\}?(?:[/\\]|$)|\$env:(?:HOME|USERPROFILE|APPDATA|LOCALAPPDATA)(?:[/\\]|$)|%(?:USERPROFILE|HOMEPATH|APPDATA|LOCALAPPDATA)%(?:[/\\]|$))/i;function Ga(t){return hx.test(t.trim())}function mx(t){let e=Q.extname(t.split("#")[0]??"").toLowerCase();return ax.has(e)}function gx(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("/")||Q.extname(e)===""}function mt(t){return t.split("#")[0].split("?")[0].trim()}var yx=new Set([".go",".cs",".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".sh",".java",".kt",".swift"]),bx=new Set([".go",".rs",".cs",".java",".kt",".swift",".ts",".tsx"]),wx=/(?:^|[/\\])(?:legacy|old|deprecated|archive|archived)(?:[/\\]|[-_.])/i,vx=new Set(["readme","claude","agents","cursor","windsurf","copilot","gemini","cline","persona","docs","prompt","unknown"]),Sx=2,_x=.45;function Wf(t){let e=`dead-ref:${t}`;return`dead-ref-${Vf.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function xx(t){let e=[0];for(let n=0;n<t.length;n++)t[n]===`
46
+ `&&e.push(n+1);return e}function Ht(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 kx=/\.(?:md|png|jpg|jpeg|gif|svg|webp|pdf)$/i;function Ex(t){let e=t.replace(/\s*#.*$/,""),s=(e.match(/^[ \t│|]*/)?.[0]??"").replace(/[│|]/g," ").length,i=e.trim();if(!i)return null;let o=/^(?:[│|]\s*)*(?:[├└][-─\s]+|[|+`][-─]+\s*)(.+)$/.exec(i),r=(o?o[1]:i)?.trim()??"";return!r||!o&&/\s/.test(r)?null:{entry:r,indent:s,hasConnector:!!o}}function zf(t,e,n){let s=[],i=[],o=n;for(let r of t){let a=o;o+=r.length+1;let c=Ex(r);if(!c)continue;let l=c.entry;if(/\/$/.test(l)){let f=`${[...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:f,plain:!c.hasConnector});continue}if(!kx.test(l))continue;let p=[...i].reverse().find(h=>h.indent<c.indent||h.indent===c.indent&&h.plain),d=/[/\\]/.test(l)?l:`${p?.path??""}${l}`;s.push({ref:d,evidence:r.trim(),line:Ht(e,a)})}return s}function Ax(t,e){let n=[];for(let s of en(t)){if(!s.closed)continue;let i=e[s.contentStartLine-1]??t.length;n.push(...zf(s.lines,e,i))}return n}function Cx(t,e){return zf(t.split(`
47
+ `),e,0)}function Rx(t,e={}){let n=[],s=xx(t),i=we(t),o=If(t),r=Fa(t),a=y=>{let b=Ht(s,y);return i[b-1]?.inFence?!0:(t.slice(s[b-1]??0,y).match(/`/g)?.length??0)%2===1},c=(y,b,w,S)=>{if(!y||Bi(y))return;let C=Ht(s,w),v=i[C-1]?.inFence===!0||a(w)||o[C-1]===!0||$f(r,w);mx(y)?n.push({ref:y,evidence:b,line:C,kind:"file",linkRaw:S,inCodeContext:v}):gx(y)&&!a(w)&&n.push({ref:y,evidence:b,line:C,kind:"linkPath",linkRaw:S,inCodeContext:v})},l,u=new RegExp(Lf.source,Lf.flags);for(;(l=u.exec(t))!==null;){if(l.index>=2&&t[l.index-2]==="["&&t[l.index-1]==="!")continue;let y=l[1]??"";c(mt(Ha(y)),`[...](${y})`,l.index,y)}let p=new RegExp(Nf.source,Nf.flags);for(;(l=p.exec(t))!==null;){if(!l[0].slice(0,l[0].lastIndexOf("](")).includes("]("))continue;let b=l[1]??"";c(mt(Ha(b)),`[...](${b})`,l.index+l[0].lastIndexOf("]("),b)}let d=new RegExp(Mf.source,Mf.flags);for(;(l=d.exec(t))!==null;){let y=l[1]??"";/^[ \t]*\[\^/.test(l[0])||c(mt(y),l[0].trim(),l.index)}let h=new RegExp(jf.source,jf.flags);for(;(l=h.exec(t))!==null;){let y=l[1]??"";y&&!Bi(y)&&n.push({ref:y,evidence:`@${y}`,line:Ht(s,l.index),kind:"file"})}let f=new RegExp(Df.source,Df.flags);for(;(l=f.exec(t))!==null;){let y=l[1]??"";if(y&&!Bi(y)&&!y.includes("*")&&!y.includes("?")){let b=Q.extname(y).toLowerCase(),w=e.skipSourceBackticks&&bx.has(b)&&!wx.test(y);n.push({ref:y,evidence:`\`${y}\``,line:Ht(s,l.index),kind:w?"rootedSource":"file",codeSpan:!0})}}let m=new RegExp(Ff.source,Ff.flags);for(;(l=m.exec(t))!==null;){let y=l[1]??"",b=y.replace(/\/+$/,"").split("/").pop()??"";if(!y.endsWith("/")&&Q.extname(b)!=="")continue;let w=Ht(s,l.index),S=t.slice(s[w-1]??0,s[w]??t.length);sx.test(S)||n.push({ref:y,evidence:`\`${y}\``,line:Ht(s,l.index),kind:"rootedPath"})}if(ox.test(t)){let y=new RegExp(Hf.source,Hf.flags);for(;(l=y.exec(t))!==null;){let b=l[1]??"";b&&!Bi(b)&&n.push({ref:b,evidence:l[0].trim(),line:Ht(s,l.index),kind:"file"})}for(let b of Cx(t,s))n.push({...b,kind:"file"});for(let b of Ax(t,s))n.push({...b,kind:"file"})}let g=t.split(`
48
+ `);return n.filter(({ref:y,line:b})=>{let w=g[b-1]??"",S=rx.exec(w);if(!S)return!0;let C=Gf(S[1]??"");if(!C)return!0;let v=Gf(y);return!(v===C||v.endsWith(`/${C}`)||C.endsWith(`/${v}`))})}function gs(t){return mt(t).replace(/\\/g,"/").split("/").filter(e=>e!==""&&e!==".")}function Tx(t){return gs(t).some(e=>Uf.has(e.toLowerCase()))}var Px=[...[...Uf,".git","worktrees",".worktrees","Library","Temp","Logs","vendor",".venv","venv","__pycache__","Pods",".gradle",".cache",".idea"].map(t=>`**/${t}/**`)];function qf(t,e,n){let s=!0,i=[];try{i=Ba.default.sync(e,{cwd:t.root,dot:!0,onlyFiles:n,followSymbolicLinks:!1,suppressErrors:!0,ignore:Px,fs:t.walkFs(()=>{s=!1})})}catch(o){t.noteUnreadable(".",as(o)??"walk failed"),s=!1}return{entries:i,complete:s}}function $x(t,e,n,s){let i=e.join("/"),o=`${n?"m":"x"}:${i}`,r=s.get(o);if(r!==void 0)return r;let a=Ba.default.escapePath(i),c=[`**/${a}`];n&&c.push(`**/${a}.*`);let{entries:l,complete:u}=qf(t,c,!1),p=l.length>0?!0:u?!1:"unknown";return s.set(o,p),p}function Ix(t){let e=new Map,{entries:n,complete:s}=qf(t,["**"],!0);for(let i of n){let o=i.slice(i.lastIndexOf("/")+1),r=e.get(o);r?r.push(i):e.set(o,[i])}return{paths:e,complete:s}}var Kf="__promptci_dir_probe__";function Ox(t){let e=new Set;for(let s of t.paths.values())for(let i of s)for(let o=i.indexOf("/");o!==-1;o=i.indexOf("/",o+1))e.add(i.slice(0,o));let n=new Map;for(let s of[...e].sort()){let i=s.slice(s.lastIndexOf("/")+1),o=n.get(i);o?o.push(s):n.set(i,[s])}return n}var ms="unjudged";function Lx(t,e,n,s,i){let{tree:o,isIgnored:r}=i;if(gs(t)[0]===".git"||e!=="file"&&Tx(t))return null;let a=e==="rootedPath"||e==="linkPath",c=a?mt(t):t;if(cs(c))return null;let l=[];for(let m of new Set([Q.resolve(s,c),Q.resolve(o.root,c)])){if(!ue(o.root,m))continue;let g=o.lookup(m);g.state!=="outside"&&l.push({abs:m,found:g})}if(l.length===0)return null;let u=!1;for(let{abs:m}of l){let g=Q.relative(o.root,m).replace(/\\/g,"/");if(g)for(let y of[r(g),...a?[r(`${g}/${Kf}`)]:[]]){if(y===!0||y==="unfetched")return null;y==="unreadable"&&(u=!0)}}if(u)return ms;let p=a&&!c.endsWith("/");if(l.some(({abs:m,found:g})=>g.state==="found"||p&&o.hasStemSibling(m)))return null;if(l.some(({found:m})=>m.state==="unreadable"))return ms;if(e==="file"){if(n&&!/[/\\]/.test(c)){let b=i.nameIndex();if(b.paths.get(c)?.some(w=>r(w)!==!0))return null;if(!b.complete)return ms}let m=Q.extname(t.split("#")[0]??"").toLowerCase(),g=yx.has(m),y=l.some(({abs:b})=>o.isDir(Q.dirname(b)));return g&&y?.5:.85}if(e==="linkPath")return .8;let d=gs(t);if(d.length<2||d.includes(".."))return null;let h=[s,o.root].filter(m=>o.isDir(Q.join(m,d[0])));if(h.length===0||d.length-1>Sx&&!h.some(m=>o.isDir(Q.join(m,d[0],d[1])))||e==="rootedPath"&&(ix.has(d[0].toLowerCase())&&!c.endsWith("/")||d.length===2&&h.some(m=>o.lookup(Q.join(m,d[1])).state==="found")))return null;let f=$x(o,d,p,i.suffixCache);return f===!0?null:f==="unknown"?ms:.6}function Nx(t,e,n,s,i,o){if(i!=="file"||s.endsWith("/")||s!==s.trim()||s.startsWith("<")||Ha(s)!==s||/[()[\]\s`]/.test(s))return;let r=s.indexOf("#"),a=r===-1?s:s.slice(0,r),c=r===-1?"":s.slice(r),l=Q.basename(a.replace(/\\/g,"/").replace(/\/+$/,""));if(!l)return;let u=o.nameIndex();if(!u.complete)return;let p=(u.paths.get(l)??[]).filter(y=>Yf(y,a,o,!1));if(p.length!==1)return;let d=Q.resolve(o.tree.root,p[0]);if(d===Q.resolve(t))return;let h=Q.relative(Q.dirname(t),d).split(Q.sep).join("/");if(!h||/[()[\]\s`#%<>?]/.test(h))return;let f=`${h.startsWith(".")?h:`./${h}`}${c}`;if(f===s)return;let m=`](${s})`,g=0;for(let y=n.indexOf(m);y!==-1;y=n.indexOf(m,y+m.length))g++;if(g===1)return{filePath:t,line:e,find:m,replace:`](${f})`}}var Mx=new Set(["test","tests","__tests__","fixtures","fixture","__fixtures__","testdata","example","examples","sample","samples","vendor","vendors","third_party","third-party","external"]);function Yf(t,e,n,s){let i=new Set(gs(e).map(r=>r.toLowerCase()));return t.split("/").slice(0,s?void 0:-1).some(r=>Mx.has(r.toLowerCase())&&!i.has(r.toLowerCase()))?!1:n.isIgnored(s?`${t}/${Kf}`:t)===!1}function jx(t,e,n){let s=n.nameIndex();if(!s.complete)return;let i=gs(t),o=i[i.length-1];if(!o||i.includes(".."))return;let r=i.join("/"),a=e==="rootedPath"||e==="linkPath",c=(a?n.dirIndex().get(o)??[]:s.paths.get(o)??[]).filter(l=>Yf(l,t,n,a));return c.length===1&&c[0]!==r?c[0]:void 0}function Wa(t,e,n){let s=new Map,i=n??new Le(e),o,r,a=()=>r??=Ix(i),c,l=new Map;for(let d of t){let h=Q.dirname(d.path),f=Rx(d.content,{skipSourceBackticks:vx.has(d.fileType)}),m=d.content.split(/\r?\n/);for(let{ref:g,evidence:y,line:b,kind:w,codeSpan:S,linkRaw:C,inCodeContext:v}of f){if(dx(g)||fx(g)||Ga(g))continue;o??={tree:i,isIgnored:Hi(i),suffixCache:new Map,nameIndex:a,dirIndex:()=>c??=Ox(a())};let _=Lx(g,w,S??!1,h,o);if(_===null)continue;if(_===ms){let te=`Not checked: ${y}`,k=l.get(te)??{filePaths:new Set,fileLines:new Map,evidence:te};k.filePaths.add(d.path);let E=k.fileLines.get(d.path);(E===void 0||b<E)&&k.fileLines.set(d.path,b),l.set(te,k);continue}let A=g.toLowerCase().replace(/\\/g,"/"),O=w==="rootedPath"||w==="linkPath"?A.replace(/^\.\//,"").replace(/\/+$/,""):A,j=`Reference: ${y}`;s.has(O)||s.set(O,{displayRef:g,kind:w,filePaths:new Set,fileLines:new Map,evidenceLines:[],minConfidence:_,edits:[],allRewritable:!0});let x=s.get(O),D=C===void 0||v===!0?void 0:Nx(d.path,b,m[b-1]??"",C,w,o);D===void 0?x.allRewritable=!1:x.edits.some(te=>te.filePath===D.filePath&&te.line===D.line&&te.find===D.find)||x.edits.push(D),x.filePaths.add(d.path);let U=x.fileLines.get(d.path);(U===void 0||b<U)&&x.fileLines.set(d.path,b),x.evidenceLines.includes(j)||x.evidenceLines.push(j),x.minConfidence=Math.min(x.minConfidence,_)}}let u=[],p=_x;for(let[d,{displayRef:h,kind:f,filePaths:m,fileLines:g,evidenceLines:y,minConfidence:b,edits:w,allRewritable:S}]of s){if(b<p)continue;let C=[...m],v=f==="rootedPath"||f==="linkPath",_=v&&mt(h).endsWith("/"),A=_?"directory":v?"path":"file",O=Q.basename(mt(h).replace(/\/+$/,"")),j=o?jx(h,f,o):void 0,x=j?` The only ${A==="directory"?"directory":"file"} named "${O}" in the repository is "${j}${_?"/":""}"; it may be what was meant.`:"";u.push({id:Wf(d),severity:"warning",category:"structure",title:`Broken ${A} reference: ${O}${_?"/":""}`,summary:`This instruction file references "${h}" which does not appear to exist. The ${A} may have been renamed, moved, or deleted.`+x,filePaths:C,locations:C.map(D=>{let U=g.get(D);return U!==void 0?{filePath:D,startLine:U}:{filePath:D}}),evidence:y,recommendation:"Verify the path is correct relative to the instruction file location, or remove the reference if the file no longer exists."+x,...S&&w.length>0?{fixRecipe:`Re-point the link${w.length>1?"s":""} at the one file of that name in the repository: ${[...new Set(w.map(D=>`\`${D.find}\` -> \`${D.replace}\``))].join(", ")}.`,autoApplySafe:!0,fixEdits:w}:{},confidence:b})}return l.size>0&&u.push($i(i,[...l.values()],{id:Wf("(dead-reference check incomplete)"),category:"structure",title:"Dead-reference check incomplete: part of the repository could not be read",unit:"reference",unknown:"They may or may not exist",finding:"broken-reference"})),u}var Bt=R(require("node:crypto"),1),Ue=R(require("node:path"),1);function on(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 o=i.aliasOf===void 0?void 0:s.get(i.aliasOf);return o===void 0||!n(o.fileType)})}function ys(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 Xf(t,e,n){let s=ys(on(t,e??[],n)).map(i=>i[0]);return s.length===0?t:[...t,...s]}var Va={critical:18,high:10,warning:4,info:1},Dx={structure:30,stale_instruction:15,duplicate:20,vague_guidance:10,ai_config:25},Fx={"supply-chain":8,"skill-supply-chain":15},Nn="unscored";function Gi(t){return!(t.tags??[]).includes(Nn)}function Hx(t){for(let n of t.tags??[]){let s=Fx[n];if(s!==void 0)return{key:`tag:${n}`,cap:s}}let e=Dx[t.category];return e!==void 0?{key:t.category,cap:e}:void 0}function Ua(t){let e=100,n=new Map;for(let s of t){if(!Gi(s))continue;let i=(Va[s.severity]??0)*s.confidence,o=Hx(s);if(o!==void 0){let r=n.get(o.key)??0,a=Math.max(0,o.cap-r),c=Math.min(i,a);n.set(o.key,r+c),e-=c}else e-=i}return Math.round(Math.max(0,Math.min(100,e)))}var Jf={high:3,medium:2,low:1};function Zf(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 za(t){let e=[...t].sort((i,o)=>{let r=Number(Gi(o))-Number(Gi(i));if(r!==0)return r;let a=(Va[o.severity]??0)-(Va[i.severity]??0);if(a!==0)return a;let c=o.confidence-i.confidence;if(c!==0)return c;let l=Jf[Zf(o)]-Jf[Zf(i)];if(l!==0)return l;let u=o.filePaths.length-i.filePaths.length;if(u!==0)return u;let p=i.category.localeCompare(o.category);return p!==0?p:i.id.localeCompare(o.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 rn=[{id:"no-verification-loop",title:"No verification loop instruction",label:"verification loop",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."',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',label:"report failures honestly",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."',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',label:"ask when unsure",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."',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',label:"read before edit",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."',confidence:.75,fixRecipe:"Read a file before editing it. Preserve unrelated user changes."},{id:"no-scope-control",title:"No scope-control instruction",label:"scope control",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."',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",label:"code preservation",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."',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',label:"plan before implementing",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."',confidence:.65,fixRecipe:"For complex or multi-file tasks, outline the approach and get confirmation before writing code."}],Bx=/\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,Wx=/<\/?claude:[\w-]+|<instructions-for-claude[\s>]/i,Qf=/(?: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,nh=`agent-practice-${Bt.createHash("sha1").update("missing-practices").digest("hex").slice(0,12)}`;function Ux(t,e,n){let s=t.map(i=>i.label);return{id:nh,severity:"info",category:"agent_practices",title:"Some common agent-practice guidance was not found",summary:`No instruction found for ${t.length} of the ${rn.length} agent practices PromptCI looks for (${s.join(", ")}). These are suggestions that often help agents, not defects, so this finding does not count toward the health score.`,filePaths:n,locations:[],evidence:[`Searched ${e} instruction file(s).`,...s.map(i=>`Not found: ${i}`)],recommendation:"Consider adding the rules that fit how you want agents to work, for example: "+t.map(i=>i.recommendation.replace(/^Add (?:an explicit |a )?rule such as: /,"")).join(" "),fixRecipe:t.map(i=>i.fixRecipe).filter(Boolean).join(`
49
+ `),confidence:Math.min(...t.map(i=>i.confidence)),fingerprintKey:"agent-practice:missing-practices",tags:[Nn]}}function zx(t){return`do-not-edit-${Bt.createHash("sha1").update(`do-not-edit:${t}`).digest("hex").slice(0,12)}`}function qx(t){return`per-file-behavior-${Bt.createHash("sha1").update(`per-file-behavior:${t}`).digest("hex").slice(0,12)}`}function bs(t,e){return e.some(n=>n.test(t))}function Kx(t,e){let n=1;for(let s=0;s<e&&s<t.length;s++)t[s]===`
50
+ `&&n++;return n}function Wi(t){return t.split(`
44
51
  `).filter(e=>!/^\s*(?:[-*+]|\d+\.)\s+/.test(e)||!/\[[ x?]\]/.test(e)).join(`
45
- `)}function Ri(t){return t.fileType==="copilot"||Le.basename(t.path).toLowerCase()==="copilot-instructions.md"}function v_(t){return t.fileType==="cursor"||Le.basename(t.path).toLowerCase()===".cursorrules"}function x_(t){return t.fileType==="windsurf"||Le.basename(t.path).toLowerCase()===".windsurfrules"}function __(t){return t.fileType==="claude"||Le.basename(t.path).toLowerCase()==="claude.md"}function Ci(t){if(v_(t))return{label:"Cursor rules file",agent:"Cursor agents"};if(x_(t))return{label:".windsurfrules",agent:"Windsurf agents"};if(__(t))return{label:"CLAUDE.md",agent:"Claude"};if(Ri(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"&&Le.basename(t.path)===".clinerules")return{label:".clinerules",agent:"Cline"}}function up(t){let e=t.content.split(/\r?\n/).slice(0,12).join(`
46
- `);if(lp.test(e))return!0;let n=m_.exec(e);return n&&`${n[1].toLowerCase()}.md`!==Le.basename(t.path).toLowerCase()?!0:t.lineCount<20&&lp.test(t.content)}function S_(t,e){return e.filter(n=>{let s=Ci(n);if(!s)return!1;let i=t.find(r=>r.relativePath===n.aliasOf);return i===void 0||Ci(i)?.label!==s.label})}function dp(t){return t!=="claude"&&t!=="readme"}function fp(t){let e=t[0];if(!dp(e.fileType))return;let n=qe(e.content).replace(/`[^`\n]+`/g,"");if(!h_.test(n))return;let s=Pt.createHash("sha1").update(`claude-xml-tag:${N(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 va(t,e=[]){if(t.length===0)return[];let n=[...t,...S_(t,e)],s=[],i=t.map(p=>p.content).join(`
47
- `),r=ki(i),o=t.map(p=>p.path);for(let p of wn){let h=p.id==="no-verification-loop"?r:i;ts(h,p.patterns)||s.push({id:g_(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=[...wn.find(p=>p.id==="no-verification-loop").patterns,...wn.find(p=>p.id==="no-honesty-policy").patterns,...wn.find(p=>p.id==="no-scope-control").patterns,...wn.find(p=>p.id==="no-read-before-edit").patterns],c=p=>ts(ki(p.content),a),l=new Set;for(let p of n){let h=Ci(p);if(!h||c(p)||up(p))continue;let m=t.find(g=>g!==p&&c(g));m&&(l.add(p.path),s.push({id:b_(N(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 ${Le.basename(p.path)}.`,`Some behavioral guidance appears in ${Le.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 wn){let h=t.find(m=>ts(ki(m.content),p.patterns));if(h)for(let m of n){if(m===h)continue;let g=Ci(m);if(!g||up(m)||l.has(m.path))continue;if(!ts(ki(m.content),p.patterns)){let b=p.title.toLowerCase().replace("no ","").replace(" instruction",""),v=Pt.createHash("sha1").update(`behavior-gap:${N(m)}:${p.id}`).digest("hex").slice(0,12);s.push({id:`per-file-behavioral-gap-${v}`,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 "${b}" which is defined in ${Le.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 ${Le.basename(m.path)}.`,`Guidance defined in ${Le.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 ${Le.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-${Pt.createHash("sha1").update(`copilot-agent-behavior:${p}`).digest("hex").slice(0,12)}`;if((()=>{let p=t.filter(Ri);return p.length===0||!p.some(c)?!1:!t.filter(g=>!Ri(g)&&g.fileType!=="readme"&&g.fileType!=="docs").some(c)})()){let p=t.find(Ri);s.push({id:f(N(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)&&ts(p.content,a)&&(s.some(h=>h.id===f(N(p)))||s.push({id:f(N(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=d_.exec(h),g=!!m,y=p_.test(h),b=m?w_(p.content,m.index):1;if(g&&!y)s.push({id:y_(N(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:b,endLine:b}],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&&y&&p.lineCount>5){let x=w=>`auto-gen-header-${Pt.createHash("sha1").update(`auto-gen-header:${w}`).digest("hex").slice(0,12)}`;s.push({id:x(N(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:b,endLine:b}],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 v=fp([p]);v&&s.push(v)}for(let p of es(Ut(t,e,dp))){let h=fp(p);h&&s.push(h)}return s}var wp=R(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"],pp=new Set([...E_,"all"]),hp=/<!--\s*promptci-ignore:\s*(\S+)([\s\S]*?)-->/g,mp=/<!--\s*promptci-ignore-start:\s*(\S+)([\s\S]*?)-->/g,gp=/<!--\s*promptci-ignore-end\s*-->/g;function ns(t,e){return t.slice(0,e).split(`
48
- `).length}function k_(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 yp(t){let e=/reason:\s*(.+?)(?:\r?\n|$)/i.exec(t);return e?e[1].trim():null}function bp(t,e){return pp.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: ${[...pp].join(", ")}.`}}function R_(t,e,n){let s=`suppression-invalid:${t}:${e}:${n}`;return`suppression-invalid-${wp.createHash("sha1").update(s).digest("hex").slice(0,12)}`}function C_(t){let{content:e,path:n,sections:s,lineCount:i}=t,r=[],o=hd(e),a=new RegExp(hp.source,hp.flags),c;for(;(c=a.exec(o))!==null;){let m=c[1]?.trim()??"",g=c[2]??"",y=yp(g),b=ns(o,c.index),v=ns(o,c.index+c[0].length),x=k_(b,v,s,i,e),{valid:w,message:_}=bp(m,y);r.push({filePath:n,category:w?m:"all",reason:y??"",startLine:b,endLine:x,valid:w,validationMessage:_})}let l=[],u=new RegExp(mp.source,mp.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:yp(c[2]??"")});let f=new RegExp(gp.source,gp.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:ns(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=ns(o,p.offset),y=ns(o,m.endOffset),{valid:b,message:v}=bp(p.category??"",p.reason??null);r.push({filePath:n,category:b?p.category:"all",reason:p.reason??"",startLine:g,endLine:y,valid:b,validationMessage:v}),p=null}p&&d(p);let{relativePath:h}=t;return h===void 0?r:r.map(m=>({...m,relativePath:h}))}function xa(t){return t.flatMap(C_)}function _a(t){return t.filter(e=>!e.valid).map(e=>({id:R_(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
49
- reason: This section documents examples. -->`,confidence:1}))}function Ai(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 Sa={critical:18,high:10,warning:4,info:1},A_={structure:30,stale_instruction:15,duplicate:20,vague_guidance:10,ai_config:25},$_={"supply-chain":8,"skill-supply-chain":15};function P_(t){for(let n of t.tags??[]){let s=$_[n];if(s!==void 0)return{key:`tag:${n}`,cap:s}}let e=A_[t.category];return e!==void 0?{key:t.category,cap:e}:void 0}function Ea(t){let e=100,n=new Map;for(let s of t){let i=(Sa[s.severity]??0)*s.confidence,r=P_(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 vp={high:3,medium:2,low:1};function xp(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 ka(t){let e=[...t].sort((i,r)=>{let o=(Sa[r.severity]??0)-(Sa[i.severity]??0);if(o!==0)return o;let a=r.confidence-i.confidence;if(a!==0)return a;let c=vp[xp(r)]-vp[xp(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 ae=R(require("node:fs/promises"),1),ue=R(require("node:path"),1);var Sp=R(require("node:crypto"),1),zt=R(require("node:path"),1),T_={info:0,warning:1,high:2,critical:3};function _p(t){return T_[t]??-1}function Vt(t){return t.replace(/\\/g,"/")}function Ep(t,e){if(!e)return t;try{let i=zt.relative(e,t);if(i&&!i.startsWith("..")&&!zt.isAbsolute(i))return Vt(i)}catch{}let n=Vt(t),s=[Vt(e).replace(/\/+$/,""),Vt(zt.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 I_(t,e){if(!e)return t;let n=Vt(t);return[Vt(e).replace(/\/+$/,""),Vt(zt.resolve(e)).replace(/\/+$/,"")].reduce((i,r)=>i.replaceAll(r,"<repo>"),n)}function qt(t,e){let n=t.filePaths.map(r=>Ep(r,e)).sort(),s=t.evidence.map(r=>I_(r,e)).sort(),i=[t.category,t.title,...n,...s].join("|");return Sp.createHash("sha256").update(i).digest("hex")}function vn(t,e){return t.map(n=>({id:n.id,category:n.category,title:n.title,filePaths:n.filePaths.map(s=>Ep(s,e)).sort(),severity:n.severity,fingerprint:qt(n,e)})).sort((n,s)=>n.fingerprint.localeCompare(s.fingerprint))}function Ra(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 xn(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=qt(o,n),c=s.get(a);c===void 0||_p(o.severity)>_p(c)?i.push(o):r.push(o)}return{newIssues:i,baselinedIssues:r}}var O_={critical:"CRITICAL",high:"HIGH",warning:"WARNING",info:"INFO"},Aa={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},kp={critical:0,high:1,warning:2,info:3},L_={critical:"Critical",high:"High",warning:"Warning",info:"Info"},N_="ai-setup",j_={critical:"issues-critical",high:"issues-high",warning:"issues-warning",info:"issues-info"},M_=50;function D_(t){let e=[],n=Cp(t.filter(r=>r.category==="ai_config"));n.length>0&&e.push({anchor:N_,heading:`\u{1F916} AI Setup (${n.length})`,issues:n});let s=t.filter(r=>r.category!=="ai_config"),i=$p(s);for(let r of["critical","high","warning","info"]){let o=Cp(i.get(r));o.length!==0&&e.push({anchor:j_[r],heading:`${Aa[r]} ${L_[r]} (${o.length})`,issues:o})}return e}function Ap(t,e){let n=ue.relative(e,t);return!n||n.startsWith("..")?t:n}function F_(t,e){return qt({category:t.category??"",title:t.title??"",filePaths:t.filePaths??[],evidence:t.evidence??[]},e)}function Rp(t,e){return t.map(n=>F_(n,e))}function H_(t){let e=Math.round(t/10),n=10-e;return"\u2588".repeat(e)+"\u2591".repeat(n)}function _n(t){return t>=90?"Healthy":t>=70?"Fair":t>=50?"Needs attention":"Critical issues found"}function $p(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 Cp(t){return[...t].sort((e,n)=>{let s=kp[e.severity]-kp[n.severity];if(s!==0)return s;let i=n.confidence-e.confidence;return i!==0?i:e.id.localeCompare(n.id)})}function Ca(t){let e=wi(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 B_(t,e,n){let s=Aa[t.severity],i=O_[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:** ${Ca(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:** ${Ca(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?Ca(Z(c,160)):Z(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(`
50
- `)}function Pp(t){let e=[],{healthScore:n,topFixes:s,issues:i,projectType:r,repoPath:o,generatedAt:a,filesScanned:c}=t,l=d=>Ap(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.estimatedAddressableTokens!==void 0&&e.push(`**In flagged sections:** up to ${t.metrics.estimatedAddressableTokens} tokens (always-loaded, overlaps counted once)`),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(`${H_(n)} ${n}/100 ${_n(n)}`),e.push("```"),e.push("");let u=$p(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(`${Aa[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],y=g>0?`+${g}`:`${g}`;e.push(` - ${m}: ${y}`)}}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=D_(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(B_(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,M_);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(`
51
- `)}function $i(t,e=!0){let n=i=>Ap(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 $a(t){return ue.join(t,".promptci","history","index.json")}async function Pa(t){let e=$a(t);try{let n=await ae.readFile(e,"utf8"),s=JSON.parse(n);if(Array.isArray(s))return s}catch{}return[]}async function Tp(t,e,n){let s;try{s=await ae.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 ae.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 ae.copyFile(e,u)}catch{await ae.writeFile(u,s,"utf8")}await ae.copyFile(n,f);let d=Array.isArray(i.issues)?i.issues:[],p={critical:0,high:0,warning:0,info:0};for(let b of d){let v=b.severity;v in p&&p[v]++}let h={generatedAt:r,healthScore:typeof i.healthScore=="number"?i.healthScore:0,issueCount:p,archiveMdPath:c,archiveJsonPath:l},m=await Pa(t);m.push(h);let g=$a(t);await ae.mkdir(ue.dirname(g),{recursive:!0});let y=`${g}.tmp`;return await ae.writeFile(y,JSON.stringify(m,null,2),"utf8"),await ae.rename(y,g),h}async function Pi(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(!gn(t.repoPath,d))throw new Error(`Refusing to write the report: ${d} resolves outside the repository through a symlink.`);await ae.mkdir(ue.dirname(s),{recursive:!0}),await ae.mkdir(ue.dirname(i),{recursive:!0});let r=await W_(i),o=await Pa(t.repoPath),a=await G_(t,r,o);a&&(t.trend=a);let l=e.archive!==!1&&!e.mdPath&&!e.jsonPath?await Tp(t.repoPath,s,i):null,u=Pp(t),f=$i(t);return await Promise.all([ae.writeFile(s,u,"utf8"),ae.writeFile(i,f,"utf8")]),{mdPath:s,jsonPath:i,archivedEntry:l}}async function W_(t){try{let e=await ae.readFile(t,"utf8");return JSON.parse(e)}catch{return null}}async function G_(t,e,n){if(!e)return null;try{let s=t.issues||[],i=Array.isArray(e.issues)?e.issues:[],r=new Set(Rp(s,t.repoPath)),o=new Set(Rp(i,t.repoPath)),a=[...r].filter(y=>!o.has(y)),c=[...o].filter(y=>!r.has(y)),l=new Set([...s.map(y=>y.category),...i.map(y=>y.category)].filter(y=>typeof y=="string")),u={};for(let y of l){if(!y)continue;let b=s.filter(x=>x.category===y).length,v=i.filter(x=>x.category===y).length;u[y]=b-v}let f=["critical","high","warning","info"],d={};for(let y of f){let b=s.filter(x=>x.severity===y).length,v=i.filter(x=>x.severity===y).length;d[y]=b-v}let p=s.filter(y=>y.severity==="high"||y.severity==="critical").length,h=0;if(p===0&&(h=1,i.filter(b=>b.severity==="high"||b.severity==="critical").length===0)){h++;for(let b=n.length-1;b>=0;b--){let v=n[b];if(v&&(v.issueCount.high??0)===0&&(v.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 Sn=R(require("node:path"),1);var Lp="https://github.com/SeriousGeese/PromptCI",U_=`${Lp}#what-gets-detected`,V_="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/sarif-2.1/schema/sarif-schema-2.1.0.json",z_={critical:"error",high:"error",warning:"warning",info:"note"},q_={duplicate:{name:"Duplicate instruction content",shortDescription:"Repeated or near-identical guidance across sections or files.",defaultLevel:"warning"},conflict:{name:"Conflicting directives",shortDescription:"Contradictory instructions, versions, or competing framework/tech choices.",defaultLevel:"error"},context_bloat:{name:"Context bloat",shortDescription:"Instruction files exceeding size or token-budget thresholds.",defaultLevel:"warning"},missing_context:{name:"Missing setup context",shortDescription:"Missing setup, validation, or project-specific guidance.",defaultLevel:"warning"},stale_instruction:{name:"Stale instructions",shortDescription:"Old years, dated TODOs, deprecated wording, or outdated versions.",defaultLevel:"warning"},vague_guidance:{name:"Vague guidance",shortDescription:"Guidance too vague for an agent or contributor to act on.",defaultLevel:"note"},structure:{name:"Structural issue",shortDescription:"Malformed suppression annotations or other structural problems.",defaultLevel:"warning"},command_validity:{name:"Invalid command reference",shortDescription:"Documented commands, scripts, or make targets that no longer exist.",defaultLevel:"warning"},agent_practices:{name:"Agent practice gap",shortDescription:"Gaps in agent-facing operational guidance.",defaultLevel:"note"},ai_config:{name:"AI setup config rot",shortDescription:"Agent Skills, subagents, hooks/settings, MCP servers, or editor rule files drifted from filesystem reality.",defaultLevel:"warning"},security:{name:"Security or privacy gap",shortDescription:"Security or privacy gaps in instruction guidance.",defaultLevel:"error"},custom:{name:"Custom rule finding",shortDescription:"A finding from the repository's own .promptci/custom-rules.json rules.",defaultLevel:"warning"}},K_="Suppressed via an inline `promptci-ignore` annotation in the scanned repository.";function Ia(t){return/^[a-zA-Z]:[\\/]/.test(t)||t.includes("\\")}function Np(t){return(Ia(t)?Sn.win32:Sn.posix).basename(t)}function Y_(t,e){let n=Ia(e)||Ia(t)?Sn.win32:Sn.posix,s=n.relative(e,t);return s===".."||s.startsWith(`..${n.sep}`)||n.isAbsolute(s)?null:s.split(n.sep).join("/").split("/").map(r=>encodeURIComponent(r)).join("/")}function Ta(t,e,n,s){let i=e(t);if(i===null)return null;let r=n!==void 0&&n>=1?{startLine:n,...s!==void 0&&s>=n?{endLine:s}:{}}:void 0;return{physicalLocation:{artifactLocation:{uri:i,uriBaseId:"%SRCROOT%"},...r?{region:r}:{}}}}function J_(t,e,n){let s=t.locations.map(r=>Ta(r.filePath,e,r.startLine,r.endLine)).filter(r=>r!==null);if(s.length>0)return{locations:s,usedFallback:!1};let i=t.filePaths.map(r=>Ta(r,e,void 0,void 0)).filter(r=>r!==null);if(i.length>0)return{locations:i,usedFallback:!1};if(n){let r=Ta(n,e,void 0,void 0);if(r)return{locations:[r],usedFallback:!0}}return{locations:[],usedFallback:!1}}function X_(t,e){let n=t.summary.trim()||t.title.trim(),s=t.recommendation.trim(),i=s?`${n} Recommendation: ${s}`:n;return e?`${i} ${e}`:i}function Ip(t,e){let n=t.locations.find(r=>r.startLine!==void 0&&e(r.filePath)!==null)??t.locations.find(r=>e(r.filePath)!==null),s=n?e(n.filePath):t.filePaths.map(e).find(r=>r!==null)??"",i=n?.startLine??0;return[s,String(i).padStart(10,"0"),t.category,t.id].join("\0")}function Op(t,e){return t<e?-1:t>e?1:0}function Z_(t,e,n,s,i,r){let{locations:o,usedFallback:a}=J_(t,e,r),c=a&&r?`(No specific location was recorded for this finding; pointing at ${Np(r)} as the repository's primary instruction file.)`:void 0,l={ruleId:t.category,ruleIndex:s,level:z_[t.severity],message:{text:X_(t,c)},locations:o,partialFingerprints:{"promptci/v1":n}};return i&&(l.suppressions=[{kind:"external",justification:K_}]),l}function Q_(t){let e=q_[t];return{id:t,name:e.name,shortDescription:{text:e.shortDescription},helpUri:U_,defaultConfiguration:{level:e.defaultLevel}}}function eS(t){let e=t.filesScanned.filter(s=>s.aliasOf===void 0&&he.has(s.fileType));return(e.find(s=>{let i=Np(s.path).toLowerCase();return i==="agents.md"||i==="claude.md"})??e[0])?.path}function Oa(t,e,n=!0){let s=d=>Y_(d,t.repoPath),i=eS(t),r=[...t.issues.map(d=>({issue:d,suppressed:!1})),...(t.suppressedIssues??[]).map(d=>({issue:d,suppressed:!0}))];r.sort((d,p)=>Op(Ip(d.issue,s),Ip(p.issue,s)));let o=[...new Set(r.map(({issue:d})=>d.category))].sort(Op),a=o.map(d=>Q_(d)),c=new Map(o.map((d,p)=>[d,p])),l=new Map,u=r.map(({issue:d,suppressed:p})=>{let h=qt(d,t.repoPath),m=l.get(h)??0;return l.set(h,m+1),Z_(d,s,`${h}:${m}`,c.get(d.category),p,i)}),f={$schema:V_,version:"2.1.0",runs:[{tool:{driver:{name:"PromptCI",version:e,informationUri:Lp,rules:a}},results:u}]};return n?JSON.stringify(f,null,2):JSON.stringify(f)}var oh=R(require("node:crypto"),1);var Q=R(require("node:path"),1),nh=R(require("node:crypto"),1);var is=R(require("node:fs/promises"),1),zp=R(require("node:path"),1),Ma=R(ft(),1);var Pe=R(require("node:fs"),1),Ti=R(require("node:path"),1),Mp=R(require("node:crypto"),1),Dp=R(Gn(),1),Ii=R(ft(),1);function Yt(t){return t.replace(/\\/g,"/")}function rt(t,e){if(typeof t!="string")return t.isFile(e);let n=ie(t,e);if(!n)return!1;try{return Pe.statSync(n).isFile()}catch{return!1}}function ve(t,e){let n=ie(t,e);if(n)try{return Pe.readFileSync(n,"utf8")}catch{return}}var Fp=na.map(t=>`**/${t}/**`);function ot(t,e,n=Fp){let s;try{s=Dp.default.sync(e,{cwd:t,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,ignore:n})}catch{return[]}return s.map(Yt).sort()}var Kt={skills:ta,allSkills:ta,agents:[".claude/agents/**/*.md"],settings:[".claude/settings.json",".claude/settings.local.json"],mcp:[".mcp.json"],cursorRules:[".cursor/rules/**/*.mdc"],copilotInstructions:[".github/instructions/**/*.md"]};var tS=2e4,La=1e3;function nS(t,e){let n=r=>{let o=ie(t,r);if(!o)return[];try{return Pe.readdirSync(o,{withFileTypes:!0})}catch{return[]}},s=n(e).filter(r=>r.isDirectory()).map(r=>r.name);return Sd(s,r=>n(`${e}/${r}`).filter(o=>o.isDirectory()).map(o=>o.name),r=>rt(t,r),e)}function sS(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=>Ii.default.isMatch(i,e,{dot:!0}))}function iS(t,e,n){let s=[...new Set(e.map(c=>Ti.posix.dirname(c)).filter(c=>!qn(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(),y=ie(t,g);if(!y)continue;let b;try{b=Pe.readdirSync(y,{withFileTypes:!0})}catch{continue}b.sort((v,x)=>v.name<x.name?1:v.name>x.name?-1:0);for(let v of b){if(++d>tS){p=!0;break}let x=`${g}/${v.name}`;if(!v.isSymbolicLink()&&!sS(x,n.exclude)){if(v.isDirectory()){if(i.has(x))continue;if(_d.has(v.name)){a.push({path:x,kind:"dependency-dir"}),v.name==="node_modules"&&u.push(...nS(t,x));continue}h.push(x)}else if(v.isFile()&&v.name!=="SKILL.md"){if(n.include&&!Ii.default.isMatch(x,n.include,{dot:!0})){f++;continue}l.push(x)}}}if(p)break}l.sort((g,y)=>Number(gi(y))-Number(gi(g))||(g<y?-1:g>y?1:0)),r.push(...l.slice(0,mi)),r.push(...u.sort().slice(0,sa));let m=l.slice(mi);o.push(...m.slice(0,La)),(m.length>La||p)&&a.push({path:c,kind:"listing-limit",count:Math.max(0,m.length-La)}),f>0&&a.push({path:c,kind:"include",count:f})}return{files:r.sort(),overCap:o.sort(),skips:a}}function rS(t,e){let n=ie(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,yn)),o=Pe.readSync(i,r,0,r.length,0);return!Gt(r.subarray(0,o))}finally{Pe.closeSync(i)}}catch{return!1}}function Na(t,e={}){let n=[...Fp,...e.exclude??[]],s=e.include&&e.include.length>0?e.include:void 0,i=c=>{let l=ot(t,[...c],n);return s?(0,Ii.default)(l,s,{dot:!0}).sort():l},r=c=>i(c).filter(l=>rS(t,l)),o=i(Kt.allSkills),a=iS(t,o,{include:s,exclude:e.exclude??[]});return{skills:r(Kt.skills),allSkills:o,skillFiles:a.files,skillFilesOverCap:a.overCap,skillBundleSkips:a.skips,agents:r(Kt.agents),settings:r(Kt.settings),mcp:r(Kt.mcp),cursorRules:r(Kt.cursorRules),copilotInstructions:r(Kt.copilotInstructions)}}function fe(t){return Mp.createHash("sha1").update(t).digest("hex").slice(0,12)}function Te(t,e){let n=s=>Ti.resolve(t,s);return e.map(s=>({...s,filePaths:s.filePaths.map(n),locations:s.locations.map(i=>({...i,filePath:n(i.filePath)}))}))}var ss=/\.(sh|bash|zsh|js|mjs|cjs|ts|py|rb|ps1)$/i;function Ke(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 oS(t){return t.charCodeAt(0)===65279?t.slice(1):t}var jp=/^(?:---|\.\.\.)[ \t]*$/;function Hp(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 Bp(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=>ja(r.trim())).filter(r=>r!=="")}function ja(t){return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function aS(t){let e=Hp(t).trim();if(e==="")return null;let n=ja(e);if(n!==e)return n;if(e.startsWith("[")&&e.endsWith("]")){let s=e.slice(1,-1).trim();return s===""?[]:Bp(s)}return e==="true"?!0:e==="false"?!1:e==="null"||e==="~"?null:/^-?\d+(\.\d+)?$/.test(e)?Number(e):e}function ht(t){let n=oS(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(`
52
- `);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(jp.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(jp.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 b=s.data[i],v=ja(Hp(d[2]).trim());v!==""&&(Array.isArray(b)?b.push(v):s.data[i]=[v]);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 y=g.trim();if(y==="|"||y==="|-"||y==="|+"||y===">"||y===">-"||y===">+"){r=m,o=y.startsWith(">"),a=[],i=null;continue}if(y===""){s.data[m]=null,i=m;continue}s.data[m]=aS(g),i=null}return r!==null&&c(),s.closed||(s.bodyStartLine=n.length+1),s}function En(t){return t==null?[]:Array.isArray(t)?t.map(e=>String(e).trim()).filter(Boolean):typeof t=="string"?t.split(`
53
- `).flatMap(e=>Bp(e)):[String(t)]}function B(t){return{severity:"warning",category:"ai_config",confidence:.8,...t}}function Tt(t,e,n,s){let i=(o,a)=>`ai-config-${s.idPrefix}-${o}-${fe(a)}`;if(!n.present)return[B({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(B({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(B({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}var Wp=200,cS=["apps/*","packages/*","libs/*"],lS=["dependencies","devDependencies","peerDependencies","optionalDependencies"],uS={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 fS(t){return typeof t!="object"||t===null||Array.isArray(t)?[]:Object.keys(t)}function Gp(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 dS(t){let{bin:e,name:n}=t;return typeof e=="string"&&typeof n=="string"?[n.split("/").pop()]:fS(e)}function rs(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 lS){let a=Gp(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:Gp(s.scripts),dependencies:[...i].sort(),versions:r,bins:dS(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 Up(t){let e=t.trim(),n=/^(?:"([^"]*)"|'([^']*)')/.exec(e);return n?n[1]??n[2]??"":e.replace(/\s+#.*$/,"")}function hS(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=Up(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=Up(c[1]);l&&n.push(l);continue}if(!(a.trim()===""||/^\s*#/.test(a)||/^\s/.test(a)))break}break}return n}function Vp(t){let e=t.replace(/\\/g,"/");return e.startsWith("/")||/^[a-zA-Z]:/.test(e)?!1:!e.split("/").includes("..")}function mS(t){return`${t.replace(/^\.\//,"").replace(/\/+$/,"")}/package.json`}async function qp(t,e,n=()=>!1){let s;try{let p=ie(t,"pnpm-workspace.yaml");s=p?await is.readFile(p,"utf-8"):void 0}catch{s=void 0}let i=[...pS(e),...hS(s)],r=i.filter(p=>!p.startsWith("!")&&Vp(p)),o=i.filter(p=>p.startsWith("!")).map(p=>p.slice(1)),a=r.length>0?r:cS,c=["**/node_modules/**","**/.git/**",...o.filter(Vp).map(p=>`${p.replace(/\/+$/,"")}/**`)],l=ot(t,a.map(mS),c).filter(p=>Bt(t,p)!==null&&!n(p)),u=l.length>Wp,f=[],d=e?rs(".",e):void 0;d&&f.push(d);for(let p of l.slice(0,Wp))if(p!=="package.json")try{let h=ie(t,p);if(!h)continue;let m=await is.stat(h);if(!m.isFile()||m.size>ce)continue;let g=rs(zp.posix.dirname(p),await is.readFile(h,"utf-8"));g&&f.push(g)}catch{}return{manifests:f,truncated:u}}function gS(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 kn(t,e){if((t.workspaces??[]).some(i=>i.bins.includes(e)))return!0;let n=gS(t);if(n.has(e))return!0;let s=uS[e];return s?t.workspaces===void 0||t.workspacesTruncated?!0:s.some(i=>n.has(i)):!1}function Oi(t,e){return t.packageJson.scripts[e]?!0:(t.workspaces??[]).some(n=>!!n.scripts[e])}function Da(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&&Ma.default.isMatch(r.name,e,i)||Ma.default.isMatch(r.dir,s,i)))}var yS=["GNUmakefile","makefile","Makefile"],Kp=/^[A-Za-z0-9_.%/+-]+$/;function bS(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 wS(t,e="Makefile"){let n=new Set,s=new Set,i=!1,r=!1;for(let o of bS(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("$")&&Kp.test(p)?n.add(p):p.includes("$")&&(i=!0);continue}for(let p of d.split(/\s+/))!p||!Kp.test(p)||(p.includes("%")?s.add(p):n.add(p))}}return{file:e,targets:[...n].sort(),patterns:[...s].sort(),unverifiable:i}}function Yp(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 Li(t,e,n=new Ee(t)){for(let s of yS){let i=e==="."||e===""?s:`${e}/${s}`,r=n.readText(i,{maxBytes:ce});switch(r.state){case"found":return wS(r.content,i);case"too-large":case"unreadable":case"unfetched":return{file:i,targets:[],patterns:[],unverifiable:!0};default:continue}}}function Ni(t){return t.toLowerCase().replace(/[-_:./\s]/g,"")}var Jp=8,Xp=5;function vS(t,e){if(t.length!==e.length)return!1;let n=[];for(let s=0;s<t.length;s++)t[s]!==e[s]&&n.push(s);return n.length===2&&n[1]===n[0]+1&&t[n[0]]===e[n[1]]&&t[n[1]]===e[n[0]]}function xS(t,e){if(t.length!==e.length)return!1;let n=!1;for(let s=0;s<t.length;s++)if(t[s]!==e[s]){if(!/^\d$/.test(t[s])||!/^\d$/.test(e[s]))return!1;n=!0}return n}function Fa(t,e){if(!t||!e||t===e)return!1;if(Ni(t)===Ni(e))return!0;let n=t.split(":"),s=e.split(":");if(n.length!==s.length)return!1;let i=n.map((l,u)=>l===s[u]?-1:u).filter(l=>l!==-1);if(i.length!==1)return!1;let r=n[i[0]],o=s[i[0]],a=Ha(r,o);if(a<1||a>2||a===2&&t.length<Jp)return!1;let c=l=>l.replace(/\d+$/,"");return c(r)===c(o)?!1:Math.max(r.length,o.length)<Xp?vS(r,o)||xS(r,o):!0}function Ha(t,e){if(t===e)return 0;if(t.length===0)return e.length;if(e.length===0)return t.length;let n=[],s=Array.from({length:e.length+1},(r,o)=>o),i=new Array(e.length+1);for(let r=1;r<=t.length;r++){i[0]=r;for(let o=1;o<=e.length;o++){let a=t[r-1]===e[o-1]?0:1,c=Math.min(s[o]+1,i[o-1]+1,s[o-1]+a);r>1&&o>1&&t[r-1]===e[o-2]&&t[r-2]===e[o-1]&&(c=Math.min(c,n[o-2]+1)),i[o]=c}n=s,s=i,i=new Array(e.length+1)}return s[e.length]}function Ba(t,e){let n=[...new Set(e)].filter(c=>c!==t&&c.length>0);if(n.length===0||t.length===0)return;let s=Ni(t),i=n.filter(c=>Ni(c)===s);if(i.length===1)return i[0];if(i.length>1||t.length<4)return;let r=3,o,a=!1;for(let c of n){let l=Ha(t,c);l>2||(l<r?(r=l,o=c,a=!1):l===r&&(a=!0))}return a?void 0:o}function _S(t,e){if(!e)return 0;let n=0;for(let s=t.indexOf(e);s!==-1;s=t.indexOf(e,s+e.length))n++;return n}function Zp(t,e){return`cmd-validity-${nh.createHash("sha1").update(`${t}|${e}`).digest("hex").slice(0,12)}`}var cs=Symbol("unjudged"),SS=Q.sep==="\\"?/[\\/]/:/\//;function sh(t,e,n){if(zn(n)||/^~|[$`%]/.test(n))return null;let s=Q.relative(t.root,e).split(Q.sep).filter(Boolean);if(s.includes("..")||Q.isAbsolute(s.join(Q.sep)))return null;for(let i of n.split(SS))if(!(i===""||i===".")){if(i!=="..")s.push(i);else if(s.pop()===void 0)return null}return Q.join(t.root,...s)}function os(t,e,n){let s=sh(t,e,n);return s===null?{state:"outside"}:t.lookup(s)}function as(t,e){return t.state==="missing"?e:t.state==="unreadable"?cs:null}function ih(t,e){let n=t.lookup(e);if(n.state==="unreadable")return"unreadable";if(n.state!=="found"||n.isDir)return null;let s=t.readText(e);if(s.state==="unreadable"||s.state==="too-large")return"unreadable";if(s.state==="unfetched")return"unfetched";if(s.state!=="found")return null;try{let i=s.content,r=JSON.parse(i);if(typeof r!="object"||r===null||Array.isArray(r))return null;let o=typeof r.scripts=="object"&&r.scripts!==null&&!Array.isArray(r.scripts)?Object.fromEntries(Object.entries(r.scripts).filter(a=>typeof a[1]=="string")):{};return{name:typeof r.name=="string"?r.name:void 0,scripts:o}}catch{return null}}function ES(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 kS(t){if(t)return t.replace(/^['"]|['"]$/g,"").replace(/^\.\.\./,"").replace(/\.\.\.$/,"").replace(/^!/,"").trim()}function RS(t,e){let n=new Set,s=!0,i=e.replace(/\\/g,"/");if(i.startsWith(".")||i.includes("/")){let r=sh(t,t.root,i);r!==null&&n.add(Q.join(r,"package.json"))}for(let r of["apps","packages","libs"]){let o=Q.join(t.root,r),a=t.entries(o);if(a==="unreadable"&&(s=!1),typeof a!="string")for(let c of a.values())c.isDirectory()&&n.add(Q.join(o,c.name,"package.json"))}return{candidates:[...n],complete:s}}function CS(t,e,n,s){let i=kS(n);if(!i)return!1;if(t.workspaces)return Da(t,i).some(l=>!!l.scripts[s]);let{candidates:r,complete:o}=RS(e,i),a=!o,c=!1;for(let l of r){let u=ih(e,l);if(u==="unreadable"&&(a=!0),u==="unfetched"&&(c=!0),!u||u==="unreadable"||u==="unfetched")continue;let f=Q.dirname(l).replace(/\\/g,"/"),d=Q.relative(t.repoRoot,f).replace(/\\/g,"/");if((u.name===i||d===i||d.endsWith(`/${i}`))&&u.scripts[s])return!0}return a?"unknown":c?"silent":!1}function ls(t){return!t||t.startsWith("-")?!1:t.includes("/")||t.includes("\\")||/\.[a-z]{1,5}$/i.test(t)}var AS=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"]),$S=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"]),PS=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"]),Ga=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"]),Qp=new Set(["run","run-script"]);function ji(t,e){if(t===null)return null;let n=e.replace(/^['"]|['"]$/g,"").trim();if(!n||zn(n)||n.startsWith("~")||/^-|[$`%<>{}*?]/.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 eh(t){return t.split(/&&|\|\||;|\n/).map(e=>e.trim()).filter(Boolean)}function TS(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 IS=new Set(["bash","sh","shell","powershell","pwsh","zsh","command-line","cmd"]);function OS(t){let e=[];for(let n of Un(t)){let s=/^[a-zA-Z0-9_-]*/.exec(n.lang)[0];if(!(!(s===""||IS.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 eh(a)){let u=/^cd\s+(.+)$/.exec(l);u&&(c=ji(c,u[1].trim())),e.push({text:l,line:n.contentStartLine+r,cwd:c,fenced:!0})}}}for(let n of Se(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 eh(o)){let l=/^cd\s+(.+)$/.exec(c);l&&(a=ji(a,l[1].trim())),TS(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 LS=/[<{]|\.{3,}|your-file|your-script|example|placeholder/i,NS=new Set(["--filter","-F","--cwd","-C","--dir","--loader","--require","-r","--workspace","--prefix"]);function jS(t,e){return t==="pnpm"&&e==="-r"?!1:e==="-w"?t==="npm":NS.has(e)}function Wa(t,e=1){let n=e,s=t[0]??"";for(;n<t.length;){let i=t[n];if(!i.startsWith("-"))break;n++,jS(s,i)&&t[n]&&!t[n].startsWith("-")&&n++}return n}function MS(t,e){let n=ES(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 DS(t,e){return t==="pnpm"?e.some(n=>n==="-r"||n==="--recursive"):t==="npm"?e.some(n=>n==="--workspaces"||n==="-ws"):!1}function FS(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 HS(t,e,n,s,i,r,o,a,c,l){let u=i.includes("/")?i.split("/").map(w=>w.trim()).filter(Boolean):[i];for(let w of u)c?.(w);if(n===null)return null;let f=FS(s);if(f!==void 0){let w=ji(n,f);if(w===null)return null;n=w}let d=a.workspaceName??MS(o,s),p=DS(o,s),h=w=>p?Oi(t,w):CS(t,e,d,w),m=d&&t.workspaces&&!p?Da(t,d.replace(/^['"]|['"]$/g,"").replace(/^\.\.\./,"").replace(/\.\.\.$/,"").trim()):void 0,g=(w,_)=>{if(!l||u.length!==1)return;let A=Ba(w,_);A!==void 0&&l({missing:w,candidate:A,mechanical:Fa(w,A)})},y=d!==void 0||p,b=n!=="."&&n!=="",v=b?ih(e,Q.join(e.root,n,"package.json")):null;if(v==="unfetched")return null;if(v==="unreadable")return cs;if(b&&!v)return null;let x=Object.keys(t.packageJson.scripts).length>0;if(!v&&!x)return null;for(let w of u){if(r.has(w)||a.allowBinary&&kn(t,w))continue;if(m){if(m.length===0){if(t.workspacesTruncated)continue;return`no workspace matches "${d}" for ${o} script "${w}"`}if(m.some(O=>!!O.scripts[w]))continue;let A=m.length===1?`${m[0].name??m[0].dir} (${m[0].dir}/package.json)`:`the ${m.length} workspaces selected by "${d}"`,C=m.map(O=>Object.keys(O.scripts));return g(w,C.slice(1).reduce((O,M)=>O.filter(E=>M.includes(E)),C[0]??[])),`${o} script "${w}" does not appear in ${A} scripts`}if(v){if(v.scripts[w])continue;let A=h(w);if(A===!0||A==="silent")continue;return A==="unknown"?cs:(y||g(w,Object.keys(v.scripts)),`${o} script "${w}" does not appear in ${n}/package.json scripts`)}let _=h(w);if(!(_===!0||_==="silent")&&!t.packageJson.scripts[w])return _==="unknown"?cs:(y||g(w,Object.keys(t.packageJson.scripts)),`${o} script "${w}" does not appear in package.json scripts`)}return null}var BS={pnpm:AS,npm:$S,yarn:PS,bun:new Set};function WS(t,e,n,s,i,r,o,a){let c=Wa(e),l=e[c];if(!l)return null;let u=!1,f=c,d;if(Qp.has(l))u=!0,f=Wa(e,c+1);else{if(t==="npm")return null;t==="yarn"&&l==="workspace"&&(d=e[c+1],f=c+2,Qp.has(e[f]??"")&&(u=!0,f++))}let p=e[f];if(!p||p.startsWith("-"))return null;if(t==="bun"){if(!u&&Ga.has(p))return null;if(ls(p))return r&&/\.[cm]?[jt]sx?$/.test(p)?as(os(s,r,p),`File "${p}" referenced by "bun" does not appear to exist in the repository`):null}let h=e.slice(0,f).join(" "),m=a?({missing:g,candidate:y,mechanical:b})=>a({find:h?`${h} ${g}`:g,replace:h?`${h} ${y}`:y,missing:g,candidate:y,mechanical:b}):void 0;return HS(n,s,i,e,p,BS[t],t,{allowBinary:!(u&&(t==="npm"||t==="pnpm")),workspaceName:d},o,m)}var GS=new Set(["-C","-f","-o","-W","-I","-E","--directory","--file","--makefile","--old-file","--what-if","--include-dir","--new-file","--assume-old","--assume-new","--eval"]),US=new Set(["sure","it","this","that","them","these","those","certain","sense","changes","room","use","way"]),VS=new Set(["-j","-l","--jobs","--load-average","--max-load"]);function zS(t,e,n,s){let i=n,r=[];for(let c=1;c<t.length;c++){let l=t[c];if(/^(?:[|&<>#]|\d*>)/.test(l))break;if(l.startsWith("-")){let u=l.indexOf("="),f=u===-1?l:l.slice(0,u);if(f==="-f"||f==="--file"||f==="--makefile"||/^-f./.test(l))return null;let d;GS.has(f)?d=u!==-1?l.slice(u+1):t[++c]:/^-C./.test(l)?d=l.slice(2):VS.has(l)&&/^\d+(?:\.\d+)?$/.test(t[c+1]??"")&&c++,(f==="-C"||f==="--directory"||/^-C./.test(l))&&d!==void 0&&(i=ji(i,d));continue}l.includes("=")||r.push(l)}if(i===null||r.length===0)return null;let o=s(i);if(!o||o.unverifiable)return null;let a;for(let c of r){let l=c.replace(/^['"]|['"]$/g,"");if(!(!l||ls(l)||!/^[A-Za-z0-9_.+-]+$/.test(l))&&!Yp(o,l)){if(a===void 0){let u=e.entries(i);if(typeof u=="string")return null;a=[...u.keys()]}if(!a.some(u=>u===l||u.startsWith(`${l}.`)))return`make target "${l}" does not appear in ${o.file}`}}return null}function qS(t,e,n=".",s,i={}){if(LS.test(t))return null;let r=t.trim().split(/\s+/);if(r.length===0)return null;let o=r[0],a=i.tree??V(e),c=n===null?null:n!=="."&&n!==""?Q.join(a.root,n):a.root;if(o==="pnpm"||o==="npm"||o==="yarn"||o==="bun")return WS(o,r,e,a,n,c,s,i.suggestScript);if(c&&["node","tsx","ts-node","bash","sh","python","python3"].includes(o)&&r[1]){let u=r[Wa(r)];if(u&&ls(u)){let f=as(os(a,c,u),`File "${u}" referenced by "${o}" does not appear to exist in the repository`);if(f!==null)return f}}if(o==="make"&&n!==null&&i.makefileFor){let u=i.fileDir??".",f=n==="."&&u!=="."&&i.makefileFor(u)?u:n;return!i.fenced&&r.length===2&&US.has(r[1].toLowerCase())?null:zS(r,a,f,i.makefileFor)}if(c&&(o.startsWith("./")||o.startsWith("../"))){let u=os(a,c,o);if(r.length===1&&Q.extname(o.replace(/\/+$/,""))===""&&(u.state==="found"&&u.isDir||!i.fenced||o.endsWith("/")))return null;let f=as(u,`Script "${o}" does not appear to exist in the repository`);if(f!==null)return f}if(c&&o==="docker"&&r[1]==="compose"&&r.includes("-f")){let u=r.indexOf("-f"),f=r[u+1];if(f&&ls(f)){let d=as(os(a,c,f),`Docker Compose file "${f}" does not appear to exist in the repository`);if(d!==null)return d}}if(c&&o==="dotnet"&&r[1]==="test"&&r[2]){let u=r[2];if(ls(u)){let f=os(a,c,u);if(f.state==="outside")return null;let d=as(f,`dotnet test target "${u}" does not appear to exist`);if(d!==null)return d;if(!/\.(sln|csproj|fsproj)$/.test(u))return`dotnet test target "${u}" should be a .sln, .csproj, or .fsproj file`}}return null}function rh(t){return Ua(t).issues.map(e=>({...e}))}var th=new WeakMap;function Ua(t){let e=th.get(t);return e||(e=KS(t),th.set(t,e)),e}function KS(t){let e=[],n=new Map,s=new Set,i=V(t),r=new Map,o=new Map,a=c=>c==="."||c===""?t.makefile:(o.has(c)||o.set(c,Li(t.repoRoot,c,i)),o.get(c));for(let c of t.files){let l=OS(c.content),u=c.content.split(/\r?\n/),f=new Set,d=Q.relative(t.repoRoot,Q.dirname(c.path)).replace(/\\/g,"/")||".";n.set(c.path,f);for(let p of l){let h=p.cwd===void 0?".":p.cwd,m,g=qS(p.text,t,h,x=>f.add(`${p.line}:${x}`),{fenced:p.fenced===!0,makefileFor:a,fileDir:d.startsWith("..")?".":d,tree:i,suggestScript:x=>{m=x}});if(!g)continue;if(g===cs){let x=`Not checked: \`${p.text}\``,w=r.get(x)??{filePaths:new Set,fileLines:new Map,evidence:x};w.filePaths.add(c.path);let _=w.fileLines.get(c.path);(_===void 0||p.line<_)&&w.fileLines.set(c.path,p.line),r.set(x,w);continue}let y=`${c.path}|${p.text}`;if(s.has(y))continue;s.add(y);let b=m?.mechanical&&_S(u[p.line-1]??"",m.find)===1?m:void 0,v=m&&!b?` The manifest defines "${m.candidate}", which is close to "${m.missing}"; it may be what was meant, but it is near enough to be a different script, so check before changing it.`:"";e.push({id:Zp(N(c),p.text),severity:"warning",category:"command_validity",title:`Possible reference to missing command or file: \`${p.text.split(/\s+/).slice(0,3).join(" ")}\``,summary:b?`${g}. The closest script name the manifest defines is "${b.candidate}".`:g,filePaths:[c.path],locations:[{filePath:c.path,startLine:p.line,endLine:p.line}],evidence:[`Command: \`${p.text}\``,`In file: ${c.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."+v,...b?{fixRecipe:`Rename the script in this command: \`${b.find}\` -> \`${b.replace}\`.`,autoApplySafe:!0,fixEdits:[{filePath:c.path,line:p.line,find:b.find,replace:b.replace}]}:{},confidence:.8})}}return r.size>0&&e.push(hi(i,[...r.values()],{id:Zp("","(command check incomplete)"),category:"command_validity",title:"Command check incomplete: part of the repository could not be read",unit:"command",unknown:"The files they name may or may not exist",finding:"missing-command"})),{issues:e,evaluatedScripts:n}}function Mi(t){return`manifest-${oh.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function YS(t,e,n){if(!(/\[tool\.poetry\]/.test(e)||/build-backend\s*=\s*["'][^"']*poetry[^"']*["']/i.test(e))||n.exists("requirements.txt"))return null;let i=/pip\s+install\s+-r\s+requirements\.txt/i,r=t.filter(o=>i.test(o.content));return r.length===0?null:{id:Mi("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:r.map(o=>o.path),locations:r.map(o=>({filePath:o.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 JS(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(qa(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:Mi(`python-version:${N(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 XS=["pandas","numpy","sqlalchemy","fastapi","django","flask","pydantic"];function ZS(t){return t==="sqlalchemy"?"SQLAlchemy":t==="fastapi"?"FastAPI":t[0].toUpperCase()+t.slice(1)}function za(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Va(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 QS(t){let e=new Map;for(let n of XS){let s=za(n),r=new RegExp(`^\\s*${s}\\s*=\\s*["']([^"']+)["']`,"im").exec(t);if(r){let c=Va(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=Va(a[1]);if(c!==null){e.set(n,c);break}}}return e}function eE(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 tE(t,e){let n=QS(e);if(n.size===0)return[];let s=[],i=new Set;for(let[r,o]of n){let a=ZS(r),c=new RegExp(`\\b${za(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(!eE(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:Mi(`library-version:${N(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 nE=["react","next","typescript","vite","vitest","jest"],sE={react:"React",next:"Next.js",typescript:"TypeScript",vite:"Vite",vitest:"Vitest",jest:"Jest"};function iE(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 nE){let c=o[a];if(typeof c!="string")continue;let l=Va(c);l!==null&&s.set(a,l)}}return s}function rE(t,e){let n=iE(e);if(n.size===0)return[];let s=[],i=new Set;for(let[r,o]of n){let a=sE[r],c=new RegExp(`\\b${za(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(!oE(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:Mi(`js-library-version:${N(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 oE(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 qa(t,e){let n=t.lastIndexOf(`
52
+ `)}function Vi(t){return t.fileType==="copilot"||Ue.basename(t.path).toLowerCase()==="copilot-instructions.md"}function Yx(t){return t.fileType==="cursor"||Ue.basename(t.path).toLowerCase()===".cursorrules"}function Xx(t){return t.fileType==="windsurf"||Ue.basename(t.path).toLowerCase()===".windsurfrules"}function Jx(t){return t.fileType==="claude"||Ue.basename(t.path).toLowerCase()==="claude.md"}function Ui(t){if(Yx(t))return{label:"Cursor rules file",agent:"Cursor agents"};if(Xx(t))return{label:".windsurfrules",agent:"Windsurf agents"};if(Jx(t))return{label:"CLAUDE.md",agent:"Claude"};if(Vi(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"&&Ue.basename(t.path)===".clinerules")return{label:".clinerules",agent:"Cline"}}function eh(t){let e=t.content.split(/\r?\n/).slice(0,12).join(`
53
+ `);if(Qf.test(e))return!0;let n=Vx.exec(e);return n&&`${n[1].toLowerCase()}.md`!==Ue.basename(t.path).toLowerCase()?!0:t.lineCount<20&&Qf.test(t.content)}function Zx(t,e){return e.filter(n=>{let s=Ui(n);if(!s)return!1;let i=t.find(o=>o.relativePath===n.aliasOf);return i===void 0||Ui(i)?.label!==s.label})}function sh(t){return t!=="claude"&&t!=="readme"}function th(t){let e=t[0];if(!sh(e.fileType))return;let n=st(e.content).replace(/`[^`\n]+`/g,"");if(!Wx.test(n))return;let s=Bt.createHash("sha1").update(`claude-xml-tag:${G(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(o=>o.path),locations:t.map(o=>({filePath:o.path})),evidence:[`Found: ${i} in ${[...new Set(t.map(o=>o.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 qa(t,e=[]){if(t.length===0)return[];let n=[...t,...Zx(t,e)],s=[],i=t.map(f=>f.content).join(`
54
+ `),o=Wi(i),r=t.map(f=>f.path),a=rn.filter(f=>{let m=f.id==="no-verification-loop"?o:i;return!bs(m,f.patterns)});a.length>0&&s.push(Ux(a,t.length,r));let c=[...rn.find(f=>f.id==="no-verification-loop").patterns,...rn.find(f=>f.id==="no-honesty-policy").patterns,...rn.find(f=>f.id==="no-scope-control").patterns,...rn.find(f=>f.id==="no-read-before-edit").patterns],l=f=>bs(Wi(f.content),c),u=new Set;for(let f of n){let m=Ui(f);if(!m||l(f)||eh(f))continue;let g=t.find(y=>y!==f&&l(y));g&&(u.add(f.path),s.push({id:qx(G(f)),severity:"warning",category:"agent_practices",title:`No behavioral guidance in ${m.label}`,summary:`The ${m.label} contains no agent behavioral rules (verification loop, honesty policy, scope control, read-before-edit). ${m.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:[f.path],locations:[{filePath:f.path}],evidence:[`No behavioral patterns found in ${Ue.basename(f.path)}.`,`Some behavioral guidance appears in ${Ue.basename(g.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 ${m.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 f of rn){let m=t.find(g=>bs(Wi(g.content),f.patterns));if(m)for(let g of n){if(g===m)continue;let y=Ui(g);if(!y||eh(g)||u.has(g.path))continue;if(!bs(Wi(g.content),f.patterns)){let w=f.title.toLowerCase().replace("no ","").replace(" instruction",""),S=Bt.createHash("sha1").update(`behavior-gap:${G(g)}:${f.id}`).digest("hex").slice(0,12);s.push({id:`per-file-behavioral-gap-${S}`,severity:"warning",category:"agent_practices",title:`Missing critical guidance "${f.title.replace("No ","").replace(" instruction","")}" in ${y.label}`,summary:`The ${y.label} lacks the critical behavioral guidance regarding "${w}" which is defined in ${Ue.basename(m.path)}. Since ${y.agent} reads ${y.label}, they will miss this rule.`,filePaths:[g.path,m.path],locations:[{filePath:g.path}],evidence:[`Guidance pattern not found in ${Ue.basename(g.path)}.`,`Guidance defined in ${Ue.basename(m.path)}.`],recommendation:`Add the missing guidance to ${y.label} (e.g., "${f.recommendation.replace("Add a rule such as: ","").replace(/"/g,"")}") or use a forwarding pointer (e.g., "Follow ${Ue.basename(m.path)}").`,fixRecipe:f.fixRecipe,confidence:.8})}}}let p=/^#{1,4}\s+(?:agent\s+behavior|ai\s+behavior|agent\s+rules|behavior\s+rules|agent\s+instructions)\b/im,d=f=>`copilot-agent-behavior-${Bt.createHash("sha1").update(`copilot-agent-behavior:${f}`).digest("hex").slice(0,12)}`;if((()=>{let f=t.filter(Vi);return f.length===0||!f.some(l)?!1:!t.filter(y=>!Vi(y)&&y.fileType!=="readme"&&y.fileType!=="docs").some(l)})()){let f=t.find(Vi);s.push({id:d(G(f)),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:[f.path],locations:[{filePath:f.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 f of t)f.fileType==="copilot"&&p.test(f.content)&&bs(f.content,c)&&(s.some(m=>m.id===d(G(f)))||s.push({id:d(G(f)),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:[f.path],locations:[{filePath:f.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 f of t){let m=f.content.slice(0,500),g=Bx.exec(m),y=!!g,b=Gx.test(m),w=g?Kx(f.content,g.index):1;if(y&&!b)s.push({id:zx(G(f)),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:[f.path],locations:[{filePath:f.path,startLine:w,endLine:w}],evidence:[g[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(y&&b&&f.lineCount>5){let C=v=>`auto-gen-header-${Bt.createHash("sha1").update(`auto-gen-header:${v}`).digest("hex").slice(0,12)}`;s.push({id:C(G(f)),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 ${f.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:[f.path],locations:[{filePath:f.path,startLine:w,endLine:w}],evidence:[g[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 S=th([f]);S&&s.push(S)}for(let f of ys(on(t,e,sh))){let m=th(f);m&&s.push(m)}return s}var uh=R(require("node:crypto"),1);var Qx=["duplicate","conflict","context_bloat","missing_context","stale_instruction","vague_guidance","structure","command_validity","agent_practices","ai_config","security","custom"],ih=new Set([...Qx,"all"]),oh=/<!--\s*promptci-ignore:\s*(\S+)([\s\S]*?)-->/g,rh=/<!--\s*promptci-ignore-start:\s*(\S+)([\s\S]*?)-->/g,ah=/<!--\s*promptci-ignore-end\s*-->/g;function ws(t,e){return t.slice(0,e).split(`
55
+ `).length}function ek(t,e,n,s,i){let o=i.split(/\r?\n/);for(let r=0;r<n.length;r++){let a=n[r];if(a.startLine<=t&&a.endLine>=t){let c=n[r+1],u=o.slice(e,Math.max(e,c?.startLine?c.startLine-1:e)).every(p=>p.trim()==="");return c&&c.startLine>e&&u?c.endLine:a.endLine}}for(let r of n)if(r.startLine>t)return r.endLine;return s}function ch(t){let e=/reason:\s*(.+?)(?:\r?\n|$)/i.exec(t);return e?e[1].trim():null}function lh(t,e){return ih.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: ${[...ih].join(", ")}.`}}function tk(t,e,n){let s=`suppression-invalid:${t}:${e}:${n}`;return`suppression-invalid-${uh.createHash("sha1").update(s).digest("hex").slice(0,12)}`}function nk(t){let{content:e,path:n,sections:s,lineCount:i}=t,o=[],r=Yp(e),a=new RegExp(oh.source,oh.flags),c;for(;(c=a.exec(r))!==null;){let m=c[1]?.trim()??"",g=c[2]??"",y=ch(g),b=ws(r,c.index),w=ws(r,c.index+c[0].length),S=ek(b,w,s,i,e),{valid:C,message:v}=lh(m,y);o.push({filePath:n,category:C?m:"all",reason:y??"",startLine:b,endLine:S,valid:C,validationMessage:v})}let l=[],u=new RegExp(rh.source,rh.flags);for(;(c=u.exec(r))!==null;)l.push({kind:"start",offset:c.index,endOffset:c.index+c[0].length,category:c[1]?.trim()??"",reason:ch(c[2]??"")});let p=new RegExp(ah.source,ah.flags);for(;(c=p.exec(r))!==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=>{o.push({filePath:n,category:"all",reason:"",startLine:ws(r,m.offset),endLine:i,valid:!1,validationMessage:"promptci-ignore-start has no matching promptci-ignore-end marker."})},h=null;for(let m of l){if(m.kind==="start"){h&&d(h),h=m;continue}if(!h)continue;let g=ws(r,h.offset),y=ws(r,m.endOffset),{valid:b,message:w}=lh(h.category??"",h.reason??null);o.push({filePath:n,category:b?h.category:"all",reason:h.reason??"",startLine:g,endLine:y,valid:b,validationMessage:w}),h=null}h&&d(h);let{relativePath:f}=t;return f===void 0?o:o.map(m=>({...m,relativePath:f}))}function Ka(t){return t.flatMap(nk)}function Ya(t){return t.filter(e=>!e.valid).map(e=>({id:tk(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
56
+ reason: This section documents examples. -->`,confidence:1}))}function zi(t,e){let n=e.filter(o=>o.valid),s=[],i=[];for(let o of t)n.some(a=>{if(a.category!=="all"&&a.category!==o.category)return!1;if(o.locations.length>0){if(o.locations.some(p=>{if(p.filePath!==a.filePath)return!1;if(p.startLine===void 0)return!0;let d=p.endLine??p.startLine;return p.startLine<=a.endLine&&d>=a.startLine}))return!0;let l=new Set(o.filePaths);return!!(!o.locations.some(p=>l.has(p.filePath))&&o.filePaths.includes(a.filePath))}return o.filePaths.includes(a.filePath)})?i.push(o):s.push(o);return{active:s,suppressed:i}}var ge=R(require("node:fs/promises"),1),Se=R(require("node:path"),1);var Xa=R(require("node:crypto"),1),cn=R(require("node:path"),1),sk={info:0,warning:1,high:2,critical:3};function dh(t){return sk[t]??-1}function an(t){return t.replace(/\\/g,"/")}function ph(t,e){if(!e)return t;try{let i=cn.relative(e,t);if(i&&!i.startsWith("..")&&!cn.isAbsolute(i))return an(i)}catch{}let n=an(t),s=[an(e).replace(/\/+$/,""),an(cn.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 ik(t,e){if(!e)return t;let n=an(t);return[an(e).replace(/\/+$/,""),an(cn.resolve(e)).replace(/\/+$/,"")].reduce((i,o)=>i.replaceAll(o,"<repo>"),n)}function ln(t,e){if(t.fingerprintKey!==void 0)return Xa.createHash("sha256").update(["promptci-fingerprint-key/v1",t.category,t.fingerprintKey].join("\0")).digest("hex");let n=t.filePaths.map(o=>ph(o,e)).sort(),s=t.evidence.map(o=>ik(o,e)).sort(),i=[t.category,t.title,...n,...s].join("|");return Xa.createHash("sha256").update(i).digest("hex")}function Mn(t,e){return t.map(n=>({id:n.id,category:n.category,title:n.title,filePaths:n.filePaths.map(s=>ph(s,e)).sort(),severity:n.severity,fingerprint:ln(n,e)})).sort((n,s)=>n.fingerprint.localeCompare(s.fingerprint))}function Ja(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 jn(t,e,n){let s=new Map;for(let r of e)s.set(r.fingerprint,r.severity??"info");let i=[],o=[];for(let r of t){let a=ln(r,n),c=s.get(a);c===void 0||dh(r.severity)>dh(c)?i.push(r):o.push(r)}return{newIssues:i,baselinedIssues:o}}var ok={critical:"CRITICAL",high:"HIGH",warning:"WARNING",info:"INFO"},Qa={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},fh={critical:0,high:1,warning:2,info:3},rk={critical:"Critical",high:"High",warning:"Warning",info:"Info"},ak="ai-setup",ck={critical:"issues-critical",high:"issues-high",warning:"issues-warning",info:"issues-info"},lk=50;function uk(t){let e=[],n=mh(t.filter(o=>o.category==="ai_config"));n.length>0&&e.push({anchor:ak,heading:`\u{1F916} AI Setup (${n.length})`,issues:n});let s=t.filter(o=>o.category!=="ai_config"),i=yh(s);for(let o of["critical","high","warning","info"]){let r=mh(i.get(o));r.length!==0&&e.push({anchor:ck[o],heading:`${Qa[o]} ${rk[o]} (${r.length})`,issues:r})}return e}function gh(t,e){let n=Se.relative(e,t);return!n||n.startsWith("..")?t:n}function dk(t,e){return ln({category:t.category??"",title:t.title??"",filePaths:t.filePaths??[],evidence:t.evidence??[],...typeof t.fingerprintKey=="string"?{fingerprintKey:t.fingerprintKey}:{}},e)}function hh(t,e){return t.map(n=>dk(n,e))}function pk(t){let e=Math.round(t/10),n=10-e;return"\u2588".repeat(e)+"\u2591".repeat(n)}function Dn(t){return t>=90?"Healthy":t>=70?"Fair":t>=50?"Needs attention":"Critical issues found"}function yh(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 mh(t){return[...t].sort((e,n)=>{let s=fh[e.severity]-fh[n.severity];if(s!==0)return s;let i=n.confidence-e.confidence;return i!==0?i:e.id.localeCompare(n.id)})}function Za(t){let e=Mi(t),n=Math.max(0,...(e.match(/`+/g)??[]).map(o=>o.length)),s="`".repeat(n+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${s}${i}${e}${i}${s}`}function fk(t,e,n){let s=Qa[t.severity],i=ok[t.severity],o=[];if(o.push(`#### ${e}. ${s} [${i}] ${t.title}`),o.push(""),o.push(`**ID:** \`${t.id}\``),o.push(""),o.push(`${t.summary}`),o.push(""),t.filePaths.length>0){for(let a of t.filePaths)o.push(`**File:** ${Za(n(a))}`);o.push("")}let r=t.locations.filter(a=>a.startLine!==void 0);if(r.length>0){for(let a of r){let c=a.endLine!==void 0?`L${a.startLine}\u2013L${a.endLine}`:`L${a.startLine}`;o.push(`**Location:** ${Za(n(a.filePath))} ${c}`)}o.push("")}if(t.evidence.length>0){o.push("**Evidence:**");let a=t.tags?.[0]==="skill-supply-chain";for(let c of t.evidence)o.push(`- ${a?Za(se(c,160)):se(c,100)}`);o.push("")}return o.push(`> **Recommendation:** ${t.recommendation}`),t.fixRecipe&&(o.push(""),o.push("**Suggested text to add:**"),o.push("```markdown"),o.push(t.fixRecipe),o.push("```")),o.join(`
57
+ `)}function bh(t){let e=[],{healthScore:n,topFixes:s,issues:i,projectType:o,repoPath:r,generatedAt:a,filesScanned:c}=t,l=d=>gh(d,r);e.push("# PromptCI Health Report"),e.push(""),e.push(`**Generated:** ${a}`),e.push(`**Repo:** \`${r}\``),e.push(`**Project type:** ${o}`),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.estimatedAddressableTokens!==void 0&&e.push(`**In flagged sections:** up to ${t.metrics.estimatedAddressableTokens} tokens (always-loaded, overlaps counted once)`),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(`${pk(n)} ${n}/100 ${Dn(n)}`),e.push("```"),e.push("");let u=yh(i);if(i.length>0){let d=[];for(let h of["critical","high","warning","info"]){let f=u.get(h).length;f>0&&d.push(`${Qa[h]} ${f} ${h}`)}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 h=d.scoreDelta>0?`+${d.scoreDelta}`:`${d.scoreDelta}`;e.push(`- **Score change:** ${h}`),e.push(`- **New issues:** ${d.newIssuesCount}`),e.push(`- **Resolved issues:** ${d.resolvedIssuesCount}`);let f=Object.keys(d.categoryDeltas);if(f.length>0){e.push("- **Category changes:**");for(let m of f){let g=d.categoryDeltas[m],y=g>0?`+${g}`:`${g}`;e.push(` - ${m}: ${y}`)}}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,h)=>{e.push(`**${h+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=uk(i);e.push(`**Jump to:** ${d.map(h=>`[${h.heading}](#${h.anchor})`).join(" \xB7 ")}`),e.push("");for(let h of d)e.push(`<a id="${h.anchor}"></a>`),e.push(""),e.push(`### ${h.heading}`),e.push(""),h.issues.forEach((f,m)=>{e.push(fk(f,m+1,l)),e.push(""),e.push("---"),e.push("")})}let p=t.suppressedIssues;if(p&&p.length>0){e.push(`## Suppressed (${p.length})`),e.push(""),e.push(`The following ${p.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 p){let h=d.filePaths[0]?l(d.filePaths[0]):"(unknown)",f=d.locations.find(g=>g.startLine!==void 0),m=f?` L${f.startLine}${f.endLine?`\u2013${f.endLine}`:""}`:"";e.push(`- **${d.category}** in \`${h}\`${m}`)}e.push("")}if(c.length>0){e.push("## Files Scanned"),e.push("");let d=c.slice(0,lk);for(let f of d)e.push(f.aliasOf!==void 0?`- \`${l(f.path)}\` (symlink to \`${f.aliasOf}\`)`:`- \`${l(f.path)}\` (${f.fileType}, ${f.lineCount} lines, ~${f.estimatedTokens} tokens)`);let h=c.length-d.length;h>0&&e.push(`- \u2026and ${h} 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(`
58
+ `)}function qi(t,e=!0){let n=i=>gh(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(o=>({...o,filePath:n(o.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(o=>({...o,filePath:n(o.filePath)}))}))}:{}};return e?JSON.stringify(s,null,2):JSON.stringify(s)}function ec(t){return Se.join(t,".promptci","history","index.json")}async function tc(t){let e=ec(t);try{let n=await ge.readFile(e,"utf8"),s=JSON.parse(n);if(Array.isArray(s))return s}catch{}return[]}async function wh(t,e,n){let s;try{s=await ge.readFile(n,"utf8")}catch{return null}let i;try{i=JSON.parse(s)}catch{return null}let o=typeof i.generatedAt=="string"?i.generatedAt:new Date().toISOString(),r=o.replace(/[:.]/g,"-").replace(/Z$/,"Z"),a=Se.join(t,".promptci","history",r);await ge.mkdir(a,{recursive:!0});let c=Se.join(".promptci","history",r,"report.md"),l=Se.join(".promptci","history",r,"report.json"),u=Se.join(t,c),p=Se.join(t,l);try{await ge.copyFile(e,u)}catch{await ge.writeFile(u,s,"utf8")}await ge.copyFile(n,p);let d=Array.isArray(i.issues)?i.issues:[],h={critical:0,high:0,warning:0,info:0};for(let b of d){let w=b.severity;w in h&&h[w]++}let f={generatedAt:o,healthScore:typeof i.healthScore=="number"?i.healthScore:0,issueCount:h,archiveMdPath:c,archiveJsonPath:l},m=await tc(t);m.push(f);let g=ec(t);await ge.mkdir(Se.dirname(g),{recursive:!0});let y=`${g}.tmp`;return await ge.writeFile(y,JSON.stringify(m,null,2),"utf8"),await ge.rename(y,g),f}async function Ki(t,e={}){let n=Se.join(t.repoPath,".promptci"),s=e.mdPath??Se.join(n,"latest.md"),i=e.jsonPath??Se.join(n,"report.json");for(let d of[n,s,i,Se.join(n,"history")])if(!$n(t.repoPath,d))throw new Error(`Refusing to write the report: ${d} resolves outside the repository through a symlink.`);await ge.mkdir(Se.dirname(s),{recursive:!0}),await ge.mkdir(Se.dirname(i),{recursive:!0});let o=await hk(i),r=await tc(t.repoPath),a=await mk(t,o,r);a&&(t.trend=a);let l=e.archive!==!1&&!e.mdPath&&!e.jsonPath?await wh(t.repoPath,s,i):null,u=bh(t),p=qi(t);return await Promise.all([ge.writeFile(s,u,"utf8"),ge.writeFile(i,p,"utf8")]),{mdPath:s,jsonPath:i,archivedEntry:l}}async function hk(t){try{let e=await ge.readFile(t,"utf8");return JSON.parse(e)}catch{return null}}async function mk(t,e,n){if(!e)return null;try{let s=t.issues||[],i=Array.isArray(e.issues)?e.issues:[],o=new Set(hh(s,t.repoPath)),r=new Set(hh(i,t.repoPath)),a=[...o].filter(y=>!r.has(y)),c=[...r].filter(y=>!o.has(y)),l=new Set([...s.map(y=>y.category),...i.map(y=>y.category)].filter(y=>typeof y=="string")),u={};for(let y of l){if(!y)continue;let b=s.filter(S=>S.category===y).length,w=i.filter(S=>S.category===y).length;u[y]=b-w}let p=["critical","high","warning","info"],d={};for(let y of p){let b=s.filter(S=>S.severity===y).length,w=i.filter(S=>S.severity===y).length;d[y]=b-w}let h=s.filter(y=>y.severity==="high"||y.severity==="critical").length,f=0;if(h===0&&(f=1,i.filter(b=>b.severity==="high"||b.severity==="critical").length===0)){f++;for(let b=n.length-1;b>=0;b--){let w=n[b];if(w&&(w.issueCount.high??0)===0&&(w.issueCount.critical??0)===0)f++;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:f}}catch{return null}}var Fn=R(require("node:path"),1);var _h="https://github.com/SeriousGeese/PromptCI",gk=`${_h}#what-gets-detected`,yk="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/sarif-2.1/schema/sarif-schema-2.1.0.json",bk={critical:"error",high:"error",warning:"warning",info:"note"},wk={duplicate:{name:"Duplicate instruction content",shortDescription:"Repeated or near-identical guidance across sections or files.",defaultLevel:"warning"},conflict:{name:"Conflicting directives",shortDescription:"Contradictory instructions, versions, or competing framework/tech choices.",defaultLevel:"error"},context_bloat:{name:"Context bloat",shortDescription:"Instruction files exceeding size or token-budget thresholds.",defaultLevel:"warning"},missing_context:{name:"Missing setup context",shortDescription:"Missing setup, validation, or project-specific guidance.",defaultLevel:"warning"},stale_instruction:{name:"Stale instructions",shortDescription:"Old years, dated TODOs, deprecated wording, or outdated versions.",defaultLevel:"warning"},vague_guidance:{name:"Vague guidance",shortDescription:"Guidance too vague for an agent or contributor to act on.",defaultLevel:"note"},structure:{name:"Structural issue",shortDescription:"Malformed suppression annotations or other structural problems.",defaultLevel:"warning"},command_validity:{name:"Invalid command reference",shortDescription:"Documented commands, scripts, or make targets that no longer exist.",defaultLevel:"warning"},agent_practices:{name:"Agent practice gap",shortDescription:"Gaps in agent-facing operational guidance.",defaultLevel:"note"},ai_config:{name:"AI setup config rot",shortDescription:"Agent Skills, subagents, hooks/settings, MCP servers, or editor rule files drifted from filesystem reality.",defaultLevel:"warning"},security:{name:"Security or privacy gap",shortDescription:"Security or privacy gaps in instruction guidance.",defaultLevel:"error"},custom:{name:"Custom rule finding",shortDescription:"A finding from the repository's own .promptci/custom-rules.json rules.",defaultLevel:"warning"}},vk="Suppressed via an inline `promptci-ignore` annotation in the scanned repository.";function sc(t){return/^[a-zA-Z]:[\\/]/.test(t)||t.includes("\\")}function xh(t){return(sc(t)?Fn.win32:Fn.posix).basename(t)}function Sk(t,e){let n=sc(e)||sc(t)?Fn.win32:Fn.posix,s=n.relative(e,t);return s===".."||s.startsWith(`..${n.sep}`)||n.isAbsolute(s)?null:s.split(n.sep).join("/").split("/").map(o=>encodeURIComponent(o)).join("/")}function nc(t,e,n,s){let i=e(t);if(i===null)return null;let o=n!==void 0&&n>=1?{startLine:n,...s!==void 0&&s>=n?{endLine:s}:{}}:void 0;return{physicalLocation:{artifactLocation:{uri:i,uriBaseId:"%SRCROOT%"},...o?{region:o}:{}}}}function _k(t,e,n){let s=t.locations.map(o=>nc(o.filePath,e,o.startLine,o.endLine)).filter(o=>o!==null);if(s.length>0)return{locations:s,usedFallback:!1};let i=t.filePaths.map(o=>nc(o,e,void 0,void 0)).filter(o=>o!==null);if(i.length>0)return{locations:i,usedFallback:!1};if(n){let o=nc(n,e,void 0,void 0);if(o)return{locations:[o],usedFallback:!0}}return{locations:[],usedFallback:!1}}function xk(t,e){let n=t.summary.trim()||t.title.trim(),s=t.recommendation.trim(),i=s?`${n} Recommendation: ${s}`:n;return e?`${i} ${e}`:i}function vh(t,e){let n=t.locations.find(o=>o.startLine!==void 0&&e(o.filePath)!==null)??t.locations.find(o=>e(o.filePath)!==null),s=n?e(n.filePath):t.filePaths.map(e).find(o=>o!==null)??"",i=n?.startLine??0;return[s,String(i).padStart(10,"0"),t.category,t.id].join("\0")}function Sh(t,e){return t<e?-1:t>e?1:0}function kk(t,e,n,s,i,o){let{locations:r,usedFallback:a}=_k(t,e,o),c=a&&o?`(No specific location was recorded for this finding; pointing at ${xh(o)} as the repository's primary instruction file.)`:void 0,l={ruleId:t.category,ruleIndex:s,level:bk[t.severity],message:{text:xk(t,c)},locations:r,partialFingerprints:{"promptci/v1":n}};return i&&(l.suppressions=[{kind:"external",justification:vk}]),l}function Ek(t){let e=wk[t];return{id:t,name:e.name,shortDescription:{text:e.shortDescription},helpUri:gk,defaultConfiguration:{level:e.defaultLevel}}}function Ak(t){let e=t.filesScanned.filter(s=>s.aliasOf===void 0&&Ae.has(s.fileType));return(e.find(s=>{let i=xh(s.path).toLowerCase();return i==="agents.md"||i==="claude.md"})??e[0])?.path}function ic(t,e,n=!0){let s=d=>Sk(d,t.repoPath),i=Ak(t),o=[...t.issues.map(d=>({issue:d,suppressed:!1})),...(t.suppressedIssues??[]).map(d=>({issue:d,suppressed:!0}))];o.sort((d,h)=>Sh(vh(d.issue,s),vh(h.issue,s)));let r=[...new Set(o.map(({issue:d})=>d.category))].sort(Sh),a=r.map(d=>Ek(d)),c=new Map(r.map((d,h)=>[d,h])),l=new Map,u=o.map(({issue:d,suppressed:h})=>{let f=ln(d,t.repoPath),m=l.get(f)??0;return l.set(f,m+1),kk(d,s,`${f}:${m}`,c.get(d.category),h,i)}),p={$schema:yk,version:"2.1.0",runs:[{tool:{driver:{name:"PromptCI",version:e,informationUri:_h,rules:a}},results:u}]};return n?JSON.stringify(p,null,2):JSON.stringify(p)}var om=R(require("node:crypto"),1);var Y=R(require("node:path"),1),Jh=R(require("node:crypto"),1);var Ss=R(require("node:fs/promises"),1),Lh=R(require("node:path"),1),cc=R(_t(),1);var Be=R(require("node:fs"),1),Yi=R(require("node:path"),1),Eh=R(require("node:crypto"),1),Ah=R(rs(),1),Xi=R(_t(),1);function dn(t){return t.replace(/\\/g,"/")}function gt(t,e){if(typeof t!="string")return t.isFile(e);let n=he(t,e);if(!n)return!1;try{return Be.statSync(n).isFile()}catch{return!1}}function Ie(t,e){let n=he(t,e);if(n)try{return Be.readFileSync(n,"utf8")}catch{return}}var Ch=xa.map(t=>`**/${t}/**`);function yt(t,e,n=Ch){let s;try{s=Ah.default.sync(e,{cwd:t,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,ignore:n})}catch{return[]}return s.map(dn).sort()}var un={skills:_a,allSkills:_a,agents:[".claude/agents/**/*.md"],settings:[".claude/settings.json",".claude/settings.local.json"],mcp:[".mcp.json"],cursorRules:[".cursor/rules/**/*.mdc"],copilotInstructions:[".github/instructions/**/*.md"]};var Ck=2e4,oc=1e3;function Rk(t,e){let n=o=>{let r=he(t,o);if(!r)return[];try{return Be.readdirSync(r,{withFileTypes:!0})}catch{return[]}},s=n(e).filter(o=>o.isDirectory()).map(o=>o.name);return of(s,o=>n(`${e}/${o}`).filter(r=>r.isDirectory()).map(r=>r.name),o=>gt(t,o),e)}function Tk(t,e){if(e.length===0)return!1;let n=t.split("/"),s=[t];for(let i=1;i<n.length;i++){let o=n.slice(0,i).join("/");s.push(o,`${o}/`)}return s.some(i=>Xi.default.isMatch(i,e,{dot:!0}))}function Pk(t,e,n){let s=[...new Set(e.map(c=>Yi.posix.dirname(c)).filter(c=>!ls(c)))].sort(),i=new Set(s),o=[],r=[],a=[];for(let c of s){let l=[],u=[],p=0,d=0,h=!1,f=[c];for(;f.length>0;){let g=f.pop(),y=he(t,g);if(!y)continue;let b;try{b=Be.readdirSync(y,{withFileTypes:!0})}catch{continue}b.sort((w,S)=>w.name<S.name?1:w.name>S.name?-1:0);for(let w of b){if(++d>Ck){h=!0;break}let S=`${g}/${w.name}`;if(!w.isSymbolicLink()&&!Tk(S,n.exclude)){if(w.isDirectory()){if(i.has(S))continue;if(sf.has(w.name)){a.push({path:S,kind:"dependency-dir"}),w.name==="node_modules"&&u.push(...Rk(t,S));continue}f.push(S)}else if(w.isFile()&&w.name!=="SKILL.md"){if(n.include&&!Xi.default.isMatch(S,n.include,{dot:!0})){p++;continue}l.push(S)}}}if(h)break}l.sort((g,y)=>Number(Oi(y))-Number(Oi(g))||(g<y?-1:g>y?1:0)),o.push(...l.slice(0,Ii)),o.push(...u.sort().slice(0,ka));let m=l.slice(Ii);r.push(...m.slice(0,oc)),(m.length>oc||h)&&a.push({path:c,kind:"listing-limit",count:Math.max(0,m.length-oc)}),p>0&&a.push({path:c,kind:"include",count:p})}return{files:o.sort(),overCap:r.sort(),skips:a}}function $k(t,e){let n=he(t,e);if(!n)return!1;try{let s=Be.statSync(n);if(!s.isFile()||s.size>ye)return!1;let i=Be.openSync(n,"r");try{let o=Buffer.alloc(Math.min(s.size,In)),r=Be.readSync(i,o,0,o.length,0);return!sn(o.subarray(0,r))}finally{Be.closeSync(i)}}catch{return!1}}function rc(t,e={}){let n=[...Ch,...e.exclude??[]],s=e.include&&e.include.length>0?e.include:void 0,i=c=>{let l=yt(t,[...c],n);return s?(0,Xi.default)(l,s,{dot:!0}).sort():l},o=c=>i(c).filter(l=>$k(t,l)),r=i(un.allSkills),a=Pk(t,r,{include:s,exclude:e.exclude??[]});return{skills:o(un.skills),allSkills:r,skillFiles:a.files,skillFilesOverCap:a.overCap,skillBundleSkips:a.skips,agents:o(un.agents),settings:o(un.settings),mcp:o(un.mcp),cursorRules:o(un.cursorRules),copilotInstructions:o(un.copilotInstructions)}}function _e(t){return Eh.createHash("sha1").update(t).digest("hex").slice(0,12)}function Ge(t,e){let n=s=>Yi.resolve(t,s);return e.map(s=>({...s,filePaths:s.filePaths.map(n),locations:s.locations.map(i=>({...i,filePath:n(i.filePath)}))}))}var vs=/\.(sh|bash|zsh|js|mjs|cjs|ts|py|rb|ps1)$/i;function it(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 Ik(t){return t.charCodeAt(0)===65279?t.slice(1):t}var kh=/^(?:---|\.\.\.)[ \t]*$/;function Rh(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 Th(t){let e=[],n="",s=0,i="";for(let o of t){if(i){n+=o,o===i&&(i="");continue}if((o==='"'||o==="'")&&n.trim()===""){i=o,n+=o;continue}if(o==="["||o==="{"||o==="("){s++,n+=o;continue}if(o==="]"||o==="}"||o===")"){s>0&&s--,n+=o;continue}if(o===","&&s===0){e.push(n),n="";continue}n+=o}return e.push(n),e.map(o=>ac(o.trim())).filter(o=>o!=="")}function ac(t){return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function Ok(t){let e=Rh(t).trim();if(e==="")return null;let n=ac(e);if(n!==e)return n;if(e.startsWith("[")&&e.endsWith("]")){let s=e.slice(1,-1).trim();return s===""?[]:Th(s)}return e==="true"?!0:e==="false"?!1:e==="null"||e==="~"?null:/^-?\d+(\.\d+)?$/.test(e)?Number(e):e}function Et(t){let n=Ik(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,o=null,r=!1,a=[],c=()=>{if(o===null)return;let u=r?a.join(" "):a.join(`
59
+ `);s.data[o]=u.trim(),o=null,a=[]},l=1;for(;l<n.length;l++){let u=n[l],p=u.trim();if(o!==null){if(kh.test(u)){c(),s.closed=!0,s.fenceEndLine=l+1,s.bodyStartLine=l+2;break}if(p===""||/^\s/.test(u)){a.push(p);continue}c()}if(kh.test(u)){s.closed=!0,s.fenceEndLine=l+1,s.bodyStartLine=l+2;break}if(p===""||p.startsWith("#"))continue;let d=/^(\s*)-\s+(.*)$/.exec(u);if(d&&i){let b=s.data[i],w=ac(Rh(d[2]).trim());w!==""&&(Array.isArray(b)?b.push(w):s.data[i]=[w]);continue}let h=/^(\s*)([^:\s][^:]*):\s?(.*)$/.exec(u);if(!h){s.errors.push(`Unparseable frontmatter line ${l+1}: ${p.slice(0,60)}`);continue}let f=h[1].length,m=h[2].trim(),g=h[3];if(f>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 y=g.trim();if(y==="|"||y==="|-"||y==="|+"||y===">"||y===">-"||y===">+"){o=m,r=y.startsWith(">"),a=[],i=null;continue}if(y===""){s.data[m]=null,i=m;continue}s.data[m]=Ok(g),i=null}return o!==null&&c(),s.closed||(s.bodyStartLine=n.length+1),s}function Hn(t){return t==null?[]:Array.isArray(t)?t.map(e=>String(e).trim()).filter(Boolean):typeof t=="string"?t.split(`
60
+ `).flatMap(e=>Th(e)):[String(t)]}function K(t){return{severity:"warning",category:"ai_config",confidence:.8,...t}}function Gt(t,e,n,s){let i=(r,a)=>`ai-config-${s.idPrefix}-${r}-${_e(a)}`;if(!n.present)return[K({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 o=[];n.closed||o.push(K({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 r of n.errors){let a=/"([^"]+)"/.exec(r)?.[1],c=Number(/\bline (\d+)\b/.exec(r)?.[1]),l=Number.isInteger(c)&&c>0?c:n.fenceEndLine>0?n.fenceEndLine:1;o.push(K({id:i("fm-error",`${t}|${r}`),title:a?`${s.noun} frontmatter has an unsupported key "${a}"`:`${s.noun} frontmatter has a structural problem`,summary:`${t}: ${r}.`,filePaths:[t],locations:[{filePath:t,startLine:l,endLine:l}],evidence:[r],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 o}var Ph=200,Lk=["apps/*","packages/*","libs/*"],Nk=["dependencies","devDependencies","peerDependencies","optionalDependencies"],Mk={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 jk(t){return typeof t!="object"||t===null||Array.isArray(t)?[]:Object.keys(t)}function $h(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"))}function Dk(t){let{bin:e,name:n}=t;return typeof e=="string"&&typeof n=="string"?[n.split("/").pop()]:jk(e)}function _s(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,o={};for(let r of Nk){let a=$h(s[r]);for(let c of Object.keys(a))a[c].startsWith("workspace:")||(i.add(c),c in o||(o[c]=a[c]))}return{dir:t,name:typeof s.name=="string"?s.name:void 0,scripts:$h(s.scripts),dependencies:[...i].sort(),versions:o,bins:Dk(s)}}function Fk(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 Ih(t){let e=t.trim(),n=/^(?:"([^"]*)"|'([^']*)')/.exec(e);return n?n[1]??n[2]??"":e.replace(/\s+#.*$/,"")}function Hk(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 o=i[1].trim();if(o.startsWith("[")){let r=o;for(let c=s+1;!r.includes("]")&&c<e.length;c++)r+=` ${e[c].trim()}`;let a=r.slice(1,r.includes("]")?r.indexOf("]"):void 0);for(let c of a.split(",")){let l=Ih(c);l&&n.push(l)}break}for(let r=s+1;r<e.length;r++){let a=e[r],c=/^\s*-\s+(.*)$/.exec(a);if(c){let l=Ih(c[1]);l&&n.push(l);continue}if(!(a.trim()===""||/^\s*#/.test(a)||/^\s/.test(a)))break}break}return n}function Oh(t){let e=t.replace(/\\/g,"/");return e.startsWith("/")||/^[a-zA-Z]:/.test(e)?!1:!e.split("/").includes("..")}function Bk(t){return`${t.replace(/^\.\//,"").replace(/\/+$/,"")}/package.json`}async function Nh(t,e,n=()=>!1){let s;try{let h=he(t,"pnpm-workspace.yaml");s=h?await Ss.readFile(h,"utf-8"):void 0}catch{s=void 0}let i=[...Fk(e),...Hk(s)],o=i.filter(h=>!h.startsWith("!")&&Oh(h)),r=i.filter(h=>h.startsWith("!")).map(h=>h.slice(1)),a=o.length>0?o:Lk,c=["**/node_modules/**","**/.git/**",...r.filter(Oh).map(h=>`${h.replace(/\/+$/,"")}/**`)],l=yt(t,a.map(Bk),c).filter(h=>tn(t,h)!==null&&!n(h)),u=l.length>Ph,p=[],d=e?_s(".",e):void 0;d&&p.push(d);for(let h of l.slice(0,Ph))if(h!=="package.json")try{let f=he(t,h);if(!f)continue;let m=await Ss.stat(f);if(!m.isFile()||m.size>ye)continue;let g=_s(Lh.posix.dirname(h),await Ss.readFile(f,"utf-8"));g&&p.push(g)}catch{}return{manifests:p,truncated:u}}function Gk(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:o,peerDependencies:r}=t.packageJson;for(let a of[i,o,r])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 Bn(t,e){if((t.workspaces??[]).some(i=>i.bins.includes(e)))return!0;let n=Gk(t);if(n.has(e))return!0;let s=Mk[e];return s?t.workspaces===void 0||t.workspacesTruncated?!0:s.some(i=>n.has(i)):!1}function ot(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Ji(t,e){return ot(t.packageJson.scripts,e)?!0:(t.workspaces??[]).some(n=>ot(n.scripts,e))}function lc(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(o=>o.name===e||o.dir===s||o.dir.endsWith(`/${s}`)||/[*?[{]/.test(e)&&(o.name!==void 0&&cc.default.isMatch(o.name,e,i)||cc.default.isMatch(o.dir,s,i)))}var Wk=["GNUmakefile","makefile","Makefile"],Mh=/^[A-Za-z0-9_.%/+-]+$/;function Vk(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 Uk(t,e="Makefile"){let n=new Set,s=new Set,i=!1,o=!1;for(let r of Vk(t)){if(r.startsWith(" "))continue;let c=r.replace(/(?<!\\)#.*$/,"").trimEnd().trim();if(!c)continue;if(/^define\b/.test(c)||/^(?:override\s+)?define\s/.test(c)){o=!0;continue}if(o){/^endef\b/.test(c)&&(o=!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 p=c.slice(l+1);if(/^:?=/.test(p)||/^::=/.test(p))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 h of p.replace(/^:/,"").trim().split(/\s+/))h&&!h.includes("$")&&Mh.test(h)?n.add(h):h.includes("$")&&(i=!0);continue}for(let h of d.split(/\s+/))!h||!Mh.test(h)||(h.includes("%")?s.add(h):n.add(h))}}return{file:e,targets:[...n].sort(),patterns:[...s].sort(),unverifiable:i}}function jh(t,e){return t.targets.includes(e)?!0:t.patterns.some(n=>{let s=n.indexOf("%"),i=n.slice(0,s),o=n.slice(s+1);return e.length>i.length+o.length&&e.startsWith(i)&&e.endsWith(o)})}function Zi(t,e,n=new Le(t)){for(let s of Wk){let i=e==="."||e===""?s:`${e}/${s}`,o=n.readText(i,{maxBytes:ye});switch(o.state){case"found":return Uk(o.content,i);case"too-large":case"unreadable":case"unfetched":return{file:i,targets:[],patterns:[],unverifiable:!0};default:continue}}}function Qi(t){return t.toLowerCase().replace(/[-_:./\s]/g,"")}var Dh=8,Fh=5;function zk(t,e){if(t.length!==e.length)return!1;let n=[];for(let s=0;s<t.length;s++)t[s]!==e[s]&&n.push(s);return n.length===2&&n[1]===n[0]+1&&t[n[0]]===e[n[1]]&&t[n[1]]===e[n[0]]}function qk(t,e){if(t.length!==e.length)return!1;let n=!1;for(let s=0;s<t.length;s++)if(t[s]!==e[s]){if(!/^\d$/.test(t[s])||!/^\d$/.test(e[s]))return!1;n=!0}return n}function uc(t,e){if(!t||!e||t===e)return!1;if(Qi(t)===Qi(e))return!0;let n=t.split(":"),s=e.split(":");if(n.length!==s.length)return!1;let i=n.map((l,u)=>l===s[u]?-1:u).filter(l=>l!==-1);if(i.length!==1)return!1;let o=n[i[0]],r=s[i[0]],a=dc(o,r);if(a<1||a>2||a===2&&t.length<Dh)return!1;let c=l=>l.replace(/\d+$/,"");return c(o)===c(r)?!1:Math.max(o.length,r.length)<Fh?zk(o,r)||qk(o,r):!0}function dc(t,e){if(t===e)return 0;if(t.length===0)return e.length;if(e.length===0)return t.length;let n=[],s=Array.from({length:e.length+1},(o,r)=>r),i=new Array(e.length+1);for(let o=1;o<=t.length;o++){i[0]=o;for(let r=1;r<=e.length;r++){let a=t[o-1]===e[r-1]?0:1,c=Math.min(s[r]+1,i[r-1]+1,s[r-1]+a);o>1&&r>1&&t[o-1]===e[r-2]&&t[o-2]===e[r-1]&&(c=Math.min(c,n[r-2]+1)),i[r]=c}n=s,s=i,i=new Array(e.length+1)}return s[e.length]}function pc(t,e){let n=[...new Set(e)].filter(c=>c!==t&&c.length>0);if(n.length===0||t.length===0)return;let s=Qi(t),i=n.filter(c=>Qi(c)===s);if(i.length===1)return i[0];if(i.length>1||t.length<4)return;let o=3,r,a=!1;for(let c of n){let l=dc(t,c);l>2||(l<o?(o=l,r=c,a=!1):l===o&&(a=!0))}return a?void 0:r}function Wh(t){let e=t.split(/\r?\n/),n=new Array(e.length).fill(!1),s=new Map;for(let i of en(t)){let o=i.closed?i.contentStartLine+i.lines.length:e.length;for(let r=i.openLine;r<=o&&r<=e.length;r++)n[r-1]=!0;for(let r=i.contentStartLine;r<i.contentStartLine+i.lines.length;r++)s.set(r,i.openLine)}return{lines:e,inFence:n,opener:s}}var Kk=/^ {0,3}(#{1,6})(?:\s|$)/,Yk=/^ {0,3}(=+|-{2,})\s*$/,to=/^\s*(?:[-*+]|\d+[.)])\s/;function Vh(t,e){if(e<1||e>t.lines.length||t.inFence[e-1])return;let n=t.lines[e-1],s=Kk.exec(n);if(s)return s[1].length;if(n.trim()===""||to.test(n)||/^\s*>/.test(n))return;let i=t.lines[e];if(i===void 0||t.inFence[e])return;let o=Yk.exec(i);return o?o[1].startsWith("=")?1:2:void 0}function Wt(t,e){return Vh(t,e)!==void 0}function Xk(t,e){let n=[],s=7;for(let i=Math.min(e,t.lines.length);i>=1&&s>1;i--){let o=Vh(t,i);o!==void 0&&o<s&&(n.push(i),s=o)}return n}function Hh(t){return t.replace(/[‘’ʼ′]/g,"'").replace(/[“”]/g,'"')}var Jk=/\b(?:at|in|from|on|under)\s+(?:the\s+)?(?:(?:repo(?:sitory)?|project|workspace|monorepo)\s+)?root\b|\b(?:repo(?:sitory)?|project|workspace|monorepo)\s+root\b|\broot\s+(?:directory|folder|of\s+(?:the\s+)?(?:repo(?:sitory)?|project|monorepo))\b/i,Zk=/\b(?:not|never|without|instead\s+of|rather\s+than|other\s+than|except|unlike)\b|n't\b/i,Qk=/\b(?:don'?t|do\s+not|doesn'?t|never|avoid|wrong|bad|incorrect|invalid|broken|deprecated|outdated|obsolete|legacy|old|removed|renamed|anti-?pattern|typo|mistakes?|warning|should\s+not|shouldn'?t|must\s+not|can'?t|cannot|fails?|failing|instead\s+of|no\s+longer|gone|previously|dropped|not\s+(?:this|that|like\s+this|recommended|to))\b|[❌✗✘✖⚠\u{1f6ab}⛔]|~~|<\/?(?:del|s|strike)>|\bbefore\s*:/iu;function eo(t,e,n){let s=[];for(let i=e;i>=1&&s.length<n&&!(t.inFence[i-1]||Wt(t,i)||t.lines[i-1].trim()==="");i--)s.unshift(t.lines[i-1]);return s}function eE(t,e){for(let n=e-1;n>=1&&e-n<=40;n--){if(t.inFence[n-1]||Wt(t,n))return[];let s=t.lines[n-1];if(!(s.trim()===""||to.test(s)||/^\s{2,}\S/.test(s)))return eo(t,n,3)}return[]}function fc(t){return/^\s*/.exec(t)[0].replace(/\t/g," ").length}function tE(t,e){let n=[],s=fc(t.lines[e-1]??"");for(let i=e-1;i>=1&&e-i<=200&&s>0;i--){if(t.inFence[i-1]||Wt(t,i))continue;let o=t.lines[i-1];to.test(o)&&fc(o)<s&&(n.push(o),s=fc(o))}return n}function hc(t,e,n){let s=e;for(;s>1&&e-s<60&&n(t.lines[s-2]);)s--;let i=e;for(;i<t.lines.length&&i-e<60&&n(t.lines[i]);)i++;return t.lines.slice(s-1,i)}function nE(t,e){let n=0;for(let s=e-1;s>=1&&e-s<=300;s--){let i=t.lines[s-1];if(/<\/details>/i.test(i)&&n++,/<details\b/i.test(i)){if(n>0){n--;continue}let o=t.lines.slice(s-1,Math.min(t.lines.length,s+6)).join(`
61
+ `);return/<summary[\s\S]*?<\/summary>/i.exec(o)?.slice(0,1)??[i]}}return[]}function Bh(t){return(t.match(/[^.!?;:]+(?:[.!?;:]+(?=\s|$)|$)/g)??[t]).map(e=>e.trim()).filter(Boolean)}function Gh(t,e){let n=t.indexOf(e);if(n===-1)return t;let s=0;for(let i of t.match(/[^.!?;:]+(?:[.!?;:]+(?=\s|$)|$)/g)??[t]){let o=s+i.length;if(n<o)return i.trim();s=o}return t}function Uh(t,e,n,s){let i=t.lines[e-1]??"",o=[i],r=t.opener.get(e),a=[],c=e,l=[];if(r!==void 0){c=r;for(let b=e-1;b>r;b--){let w=t.lines[b-1].trim();if(!w.startsWith("#"))break;o.push(w)}let y=r-1;for(;y>=1&&t.lines[y-1].trim()==="";)y--;l=eo(t,y,4),a.push(i)}else to.test(i)?(l=eE(t,e),a.push(Gh(i,n))):Wt(t,e)||(l=eo(t,e-1,3),a.push(Gh(i,n)));o.push(...l);let u=[...tE(t,c),...nE(t,c)];if(i.includes("|")&&r===void 0){let y=hc(t,e,b=>b.includes("|"));u.push(...y.slice(0,2))}o.push(...u);let p=Bh(l.join(" ")).pop();p&&a.push(p);let d=Xk(t,c),h=d[0];if(h!==void 0&&(o.push(t.lines[h-1]),a.push(t.lines[h-1])),Wt(t,e)){let y=!1;for(let b=e+1;b<=t.lines.length&&b<=e+8&&!(t.inFence[b-1]||Wt(t,b));b++){let w=t.lines[b-1];if(w.trim()===""){if(y)break;continue}y=!0,o.push(w);let S=Bh(w)[0];S&&a.push(S)}}let f=[...o,...d.map(y=>t.lines[y-1])];if(r!==void 0){f.push(t.lines[r-1]);let y=r+1;for(;y<=t.lines.length&&t.opener.get(y)===r;)f.push(t.lines[y++-1]);y<=t.lines.length&&t.inFence[y-1]&&f.push(t.lines[y-1])}else if(!Wt(t,e)){f.push(...eo(t,e,30));for(let y=e+1;y<=t.lines.length&&y<=e+30&&!(t.inFence[y-1]||Wt(t,y)||t.lines[y-1].trim()==="");y++)f.push(t.lines[y-1])}/^\s*>/.test(i)&&f.push(...hc(t,e,y=>/^\s*>/.test(y))),i.includes("|")&&r===void 0&&f.push(...hc(t,e,y=>y.includes("|")));let m=Qk.test(Hh(f.join(`
62
+ `))),g=a.some(y=>{let b=Hh(y);return Jk.test(b)&&!Zk.test(b)&&!s(y)});return{text:o,cautionary:m,explicitRoot:g}}var sE=/`([^`\s]+)`|(?<![\w./@-])((?:\.{1,2}\/)?[\w@.-]+(?:\/[\w@.-]+)*\/)(?![\w@.*?[{-])|\bcd\s+(?:\.\/)?([\w@.-]+(?:\/[\w@.-]+)*)|\b(?:from|in|inside|under|within|into)\s+(?:the\s+)?([\w@.-]+(?:\/[\w@.-]+)*)/gi,iE=/[*?<>{}[\]$~%\\]/,oE=24;function mc(t){let e=new Set;for(let n of t)for(let s of n.matchAll(sE)){let i=(s[1]??s[2]??s[3]??s[4]??"").replace(/^\.\//,"").replace(/\/+$/,"");if(!(!i||i==="."||iE.test(i))&&(e.add(i),e.size>=oE))return[...e]}return[...e]}function rE(t,e,n,s,i,o,r){if(n)return"this command is inside an HTML comment";if(!t.fenced&&/^(?: {4}|\t)/.test(e[t.line-1]??""))return"this command is in an indented block";if(typeof t.cwd=="string"&&t.cwd!=="."&&t.cwd!==""||/\s(?:--cwd|--dir|--prefix)(?:\s|=)|\s-C/.test(t.text))return"this command runs from another directory";if(i)return"an earlier line of its block changes directory";if(s.cautionary)return"the text around this command reads as an example not to follow, or as a warning";if(!o)return"this repository has more than one package, which makes the manifest the command runs against uncertain";if(!r)return"the closest name is not in the root manifest"}function aE(t,e){if(!e)return 0;let n=0;for(let s=t.indexOf(e);s!==-1;s=t.indexOf(e,s+e.length))n++;return n}function no(t,e){return`cmd-validity-${Jh.createHash("sha1").update(`${t}|${e}`).digest("hex").slice(0,12)}`}var Gn=Symbol("unjudged"),cE=Y.sep==="\\"?/[\\/]/:/\//;function vc(t,e,n){if(cs(n)||/^~|[$`%]/.test(n))return null;let s=Y.relative(t.root,e).split(Y.sep).filter(Boolean);if(s.includes("..")||Y.isAbsolute(s.join(Y.sep)))return null;for(let i of n.split(cE))if(!(i===""||i===".")){if(i!=="..")s.push(i);else if(s.pop()===void 0)return null}return Y.join(t.root,...s)}function xs(t,e,n){let s=vc(t,e,n);return s===null?{state:"outside"}:t.lookup(s)}function ks(t,e){return t.state==="missing"?e:t.state==="unreadable"?Gn:null}var Zh=512*1024;function so(t,e){let n=t.lookup(e);if(n.state==="unreadable")return"unreadable";if(n.state!=="found"||n.isDir)return null;let s=t.readText(e,{maxBytes:Zh});if(s.state==="unreadable")return"unreadable";if(s.state==="unfetched"||s.state==="too-large")return"unfetched";if(s.state!=="found")return null;try{let i=s.content,o=JSON.parse(i);if(typeof o!="object"||o===null||Array.isArray(o))return"corrupt";let r=typeof o.scripts=="object"&&o.scripts!==null&&!Array.isArray(o.scripts)?Object.fromEntries(Object.entries(o.scripts).filter(a=>typeof a[1]=="string")):{};return{name:typeof o.name=="string"?o.name:void 0,scripts:r}}catch{return"corrupt"}}var lE=/[*?<>{}[\]$`]|%\w+%/,uE=2e3,dE=12,yc=new WeakMap;function zh(t,e){let n=yc.get(t);n||yc.set(t,n=new Set),n.add(e)}var qh=new WeakMap;function Qh(t){let e=qh.get(t);if(e)return e;let n={scripts:new Map,unfetched:[],incomplete:!1,foreign:!1},s=[{dir:"",depth:0}];for(let i=0;i<s.length;i++){if(i>=uE){n.incomplete=!0;break}let{dir:o,depth:r}=s[i],a=o?Y.join(t.root,o):t.root,c=t.entries(a);if(c==="unreadable"&&(n.incomplete=!0),typeof c=="string")continue;let l=[...c.keys()].sort();if(l.includes("package.json")){let u=so(t,Y.join(a,"package.json"));u==="unfetched"?n.unfetched.push(o||"."):u==="unreadable"||u==="corrupt"?n.incomplete=!0:u&&n.scripts.set(o||".",u.scripts)}l.some(u=>hE.has(u))&&(n.foreign=!0);for(let u of["deno.json","deno.jsonc"]){if(!l.includes(u))continue;let p=t.readText(Y.join(a,u),{maxBytes:Zh});(p.state!=="found"||/"tasks"\s*:/.test(p.content))&&(n.foreign=!0)}for(let u of l){let p=c.get(u);if(p.isSymbolicLink()){let d=t.lookup(Y.join(a,u)).state;d==="outside"?n.foreign=!0:d==="unreadable"&&(n.incomplete=!0);continue}if(p.isDirectory()&&!(u==="node_modules"||u===".git")){if(r>=dE){n.incomplete=!0;continue}s.push({dir:o?`${o}/${u}`:u,depth:r+1})}}}return qh.set(t,n),n}function pE(t,e,n){let s=new Set;for(let i of t.workspaces??[])i.dir!=="."&&ot(i.scripts,n)&&s.add(i.dir);for(let[i,o]of Qh(e).scripts)i!=="."&&!i.split("/").some(r=>r.startsWith("."))&&ot(o,n)&&s.add(i);return[...s].sort()}var fE=["pnpm-workspace.yaml","lerna.json","nx.json","turbo.json","rush.json",".gitmodules"],hE=new Set(["package.yaml","package.json5","rush.json"]),Kh=new WeakMap;function mE(t,e){let n=Kh.get(e);if(n!==void 0)return n;let s=Qh(e),i=!s.incomplete&&!s.foreign&&s.unfetched.length===0&&s.scripts.size===1&&s.scripts.has(".")&&(e.inventory===void 0||e.inventory.complete);if(i&&/"workspaces"\s*:/.test(t.packageJson.raw??"")&&(i=!1),i)for(let o of fE)e.lookup(Y.join(e.root,o)).state!=="missing"&&(i=!1);return Kh.set(e,i),i}function gc(t,e,n){let s=[],i=new Set;for(let o of t)for(let r of e==="."?["."]:[".",e]){let a=vc(n,n.root,r==="."?o:`${r}/${o}`);if(a===null)continue;let c=Y.relative(n.root,a).split(Y.sep).join("/");if(!c||i.has(c))continue;let l=n.lookup(a);l.state!=="found"||!l.isDir||(i.add(c),s.push(c))}return s}function gE(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 yE(t){if(t)return t.replace(/^['"]|['"]$/g,"").replace(/^\.\.\./,"").replace(/\.\.\.$/,"").replace(/^!/,"").trim()}function bE(t,e){let n=new Set,s=!0,i=e.replace(/\\/g,"/");if(i.startsWith(".")||i.includes("/")){let o=vc(t,t.root,i);o!==null&&n.add(Y.join(o,"package.json"))}for(let o of["apps","packages","libs"]){let r=Y.join(t.root,o),a=t.entries(r);if(a==="unreadable"&&(s=!1),typeof a!="string")for(let c of a.values())c.isDirectory()&&n.add(Y.join(r,c.name,"package.json"))}return{candidates:[...n],complete:s}}function wE(t,e,n,s){let i=yE(n);if(!i)return!1;if(t.workspaces)return lc(t,i).some(l=>ot(l.scripts,s));let{candidates:o,complete:r}=bE(e,i),a=!r,c=!1;for(let l of o){let u=so(e,l);if(u==="unreadable"&&(a=!0),(u==="unfetched"||u==="corrupt")&&(c=!0),!u||u==="unreadable"||u==="unfetched"||u==="corrupt")continue;let p=Y.dirname(l).replace(/\\/g,"/"),d=Y.relative(t.repoRoot,p).replace(/\\/g,"/");if((u.name===i||d===i||d.endsWith(`/${i}`))&&ot(u.scripts,s))return!0}return a?"unknown":c?"silent":!1}function Es(t){return!t||t.startsWith("-")?!1:t.includes("/")||t.includes("\\")||/\.[a-z]{1,5}$/i.test(t)}var vE=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"]),SE=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"]),_E=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"]),Sc=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"]),Yh=new Set(["run","run-script"]);function As(t,e){if(t===null)return null;let n=e.replace(/^['"]|['"]$/g,"").trim();if(!n||cs(n)||n.startsWith("~")||/^-|[$`%<>{}*?]/.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 xE(t,e){let n=t.opener.get(e),s=".",i=!1;if(n===void 0)return{any:i,dir:s};for(let o=n+1;o<e;o++){let r=(t.lines[o-1]??"").trim().replace(/^\$\s*/,"");if(!(!r||r.startsWith("#")))for(let a of bc(r)){let c=/^(?:cd|pushd)\s+(.+)$/.exec(a);c?(i=!0,s=As(s,c[1].trim())):(/^(?:cd|pushd|popd)$/.test(a)||a.startsWith("popd "))&&(i=!0,s=null)}}return{any:i,dir:s}}function bc(t){return t.split(/&&|\|\||;|\n/).map(e=>kE(e.trim())).filter(Boolean)}function kE(t){let e=t;for(;e.startsWith("(");)e=e.slice(1).trim();for(;e.endsWith(")")&&(e.match(/\)/g)?.length??0)>(e.match(/\(/g)?.length??0);)e=e.slice(0,-1).trim();return e}function EE(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 AE=new Set(["bash","sh","shell","powershell","pwsh","zsh","command-line","cmd"]);function CE(t){let e=[];for(let n of en(t)){let s=/^[a-zA-Z0-9_-]*/.exec(n.lang)[0];if(!(!(s===""||AE.has(s))||!n.closed))for(let o=0;o<n.lines.length;o++){let r=n.lines[o].trim();if(r.startsWith("#"))continue;let a=r.replace(/^\$\s*/,"");if(!a)continue;let c=".";for(let l of bc(a)){let u=/^cd\s+(.+)$/.exec(l);u&&(c=As(c,u[1].trim())),e.push({text:l,line:n.contentStartLine+o,cwd:c,fenced:!0})}}}for(let n of we(t)){if(n.inFence)continue;let s=n.lineNumber-1,i=n.text.replace(/\r$/,"");for(let o of i.matchAll(/`([^`]+)`/g)){let r=o[1].trim(),a=".";for(let c of bc(r)){let l=/^cd\s+(.+)$/.exec(c);l&&(a=As(a,l[1].trim())),EE(c)&&e.push({text:c,line:s+1,cwd:a})}}for(let o of i.matchAll(/\brun\s+(pnpm|npm|yarn|bun|node|tsx|ts-node|bash|python|dotnet|docker)\s+(.+?)(?=[.!?](?:\s|$)|[,;!]|$)/gi)){let r=(o[2]??"").trim().replace(/[.!?]+$/,""),a=`${o[1]} ${r}`.trim();e.push({text:a,line:s+1})}}return e.sort((n,s)=>n.line-s.line)}var RE=/[<{]|\.{3,}|your-file|your-script|example|placeholder/i,TE=new Set(["--filter","-F","--cwd","-C","--dir","--loader","--require","-r","--workspace","--prefix"]);function PE(t,e){return t==="pnpm"&&e==="-r"?!1:e==="-w"?t==="npm":TE.has(e)}function wc(t,e=1){let n=e,s=t[0]??"";for(;n<t.length;){let i=t[n];if(!i.startsWith("-"))break;n++,PE(s,i)&&t[n]&&!t[n].startsWith("-")&&n++}return n}function $E(t,e){let n=gE(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 IE(t,e){return t==="pnpm"?e.some(n=>n==="-r"||n==="--recursive"):t==="npm"?e.some(n=>n==="--workspaces"||n==="-ws"):!1}function OE(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 LE(t,e,n,s,i,o,r,a,c,l,u){let p=i.includes("/")?i.split("/").map(_=>_.trim()).filter(Boolean):[i];for(let _ of p)c?.(_);if(n===null)return null;let d=OE(s);if(d!==void 0){let _=As(n,d);if(_===null)return null;n=_}let h=a.workspaceName??$E(r,s),f=IE(r,s),m=_=>f?Ji(t,_):wE(t,e,h,_),g=h&&t.workspaces&&!f?lc(t,h.replace(/^['"]|['"]$/g,"").replace(/^\.\.\./,"").replace(/\.\.\.$/,"").trim()):void 0,y=(_,A,O=!1)=>{if(!l||p.length!==1)return;let j=pc(_,A);j!==void 0&&l({missing:_,candidate:j,mechanical:uc(_,j),viaRoot:O})},b=h!==void 0||f,w=n!=="."&&n!=="",S=w?so(e,Y.join(e.root,n,"package.json")):null;if(S==="unfetched")return null;if(S==="corrupt")return zh(e,Y.join(e.root,n,"package.json")),null;if(S==="unreadable")return Gn;if(w&&!S)return null;let C=Object.keys(t.packageJson.scripts).length>0;if(!S&&!C)return null;let v;for(let _ of p){if(o.has(_)||a.allowBinary&&Bn(t,_))continue;if(g){if(g.length===0){if(t.workspacesTruncated)continue;return`no workspace matches "${h}" for ${r} script "${_}"`}if(g.some(x=>ot(x.scripts,_)))continue;let O=g.length===1?`${g[0].name??g[0].dir} (${g[0].dir}/package.json)`:`the ${g.length} workspaces selected by "${h}"`,j=g.map(x=>Object.keys(x.scripts));return y(_,j.slice(1).reduce((x,D)=>x.filter(U=>D.includes(U)),j[0]??[])),`${r} script "${_}" does not appear in ${O} scripts`}if(S){if(ot(S.scripts,_))continue;let O=m(_);if(O===!0||O==="silent")continue;return O==="unknown"?Gn:(b||y(_,Object.keys(S.scripts)),`${r} script "${_}" does not appear in ${n}/package.json scripts`)}let A=m(_);if(!(A===!0||A==="silent")&&!ot(t.packageJson.scripts,_)){if(A==="unknown")return Gn;if(!b){let O=!1;if(!u?.explicitRoot){for(let x of u?.hintDirs?.()??[]){let D=so(e,Y.join(e.root,x,"package.json"));if(D==="unfetched")O=!0;else if(D==="corrupt")zh(e,Y.join(e.root,x,"package.json")),O=!0;else{if(D==="unreadable")return Gn;D&&ot(D.scripts,_)&&(O=!0)}}if(O)continue;let j=pE(t,e,_);if(j.length>0){v??={name:_,dirs:j};continue}}y(_,Object.keys(t.packageJson.scripts),!0)}return`${r} script "${_}" does not appear in package.json scripts`}}return v?(u?.elsewhere?.(v.name,v.dirs),`${r} script "${v.name}" does not appear in package.json scripts`):null}var NE={pnpm:vE,npm:SE,yarn:_E,bun:new Set};function ME(t,e,n,s,i,o,r,a,c){let l=wc(e),u=e[l];if(!u)return null;let p=!1,d=l,h;if(Yh.has(u))p=!0,d=wc(e,l+1);else{if(t==="npm")return null;t==="yarn"&&u==="workspace"&&(h=e[l+1],d=l+2,Yh.has(e[d]??"")&&(p=!0,d++))}let f=e[d];if(!f||f.startsWith("-"))return null;if(lE.test(f))return r?.(f),null;if(t==="bun"){if(!p&&Sc.has(f))return null;if(Es(f))return o&&/\.[cm]?[jt]sx?$/.test(f)?ks(xs(s,o,f),`File "${f}" referenced by "bun" does not appear to exist in the repository`):null}let m=e.slice(0,d).join(" "),g=a?({missing:y,candidate:b,mechanical:w,viaRoot:S})=>a({find:m?`${m} ${y}`:y,replace:m?`${m} ${b}`:b,missing:y,candidate:b,mechanical:w,viaRoot:S}):void 0;return LE(n,s,i,e,f,NE[t],t,{allowBinary:!(p&&(t==="npm"||t==="pnpm")),workspaceName:h},r,g,c)}var jE=new Set(["-C","-f","-o","-W","-I","-E","--directory","--file","--makefile","--old-file","--what-if","--include-dir","--new-file","--assume-old","--assume-new","--eval"]),DE=new Set(["sure","it","this","that","them","these","those","certain","sense","changes","room","use","way"]),FE=new Set(["-j","-l","--jobs","--load-average","--max-load"]);function HE(t,e,n,s){let i=n,o=[];for(let c=1;c<t.length;c++){let l=t[c];if(/^(?:[|&<>#]|\d*>)/.test(l))break;if(l.startsWith("-")){let u=l.indexOf("="),p=u===-1?l:l.slice(0,u);if(p==="-f"||p==="--file"||p==="--makefile"||/^-f./.test(l))return null;let d;jE.has(p)?d=u!==-1?l.slice(u+1):t[++c]:/^-C./.test(l)?d=l.slice(2):FE.has(l)&&/^\d+(?:\.\d+)?$/.test(t[c+1]??"")&&c++,(p==="-C"||p==="--directory"||/^-C./.test(l))&&d!==void 0&&(i=As(i,d));continue}l.includes("=")||o.push(l)}if(i===null||o.length===0)return null;let r=s(i);if(!r||r.unverifiable)return null;let a;for(let c of o){let l=c.replace(/^['"]|['"]$/g,"");if(!(!l||Es(l)||!/^[A-Za-z0-9_.+-]+$/.test(l))&&!jh(r,l)){if(a===void 0){let u=e.entries(i);if(typeof u=="string")return null;a=[...u.keys()]}if(!a.some(u=>u===l||u.startsWith(`${l}.`)))return`make target "${l}" does not appear in ${r.file}`}}return null}function BE(t,e,n=".",s,i={}){if(RE.test(t))return null;let o=t.trim().split(/\s+/);if(o.length===0)return null;let r=o[0],a=i.tree??Z(e),c=n===null?null:n!=="."&&n!==""?Y.join(a.root,n):a.root;if(r==="pnpm"||r==="npm"||r==="yarn"||r==="bun")return ME(r,o,e,a,n,c,s,i.suggestScript,i.scope);if(c&&["node","tsx","ts-node","bash","sh","python","python3"].includes(r)&&o[1]){let u=o[wc(o)];if(u&&Es(u)){let p=ks(xs(a,c,u),`File "${u}" referenced by "${r}" does not appear to exist in the repository`);if(p!==null)return p}}if(r==="make"&&n!==null&&i.makefileFor){let u=i.fileDir??".",p=n==="."&&u!=="."&&i.makefileFor(u)?u:n;return!i.fenced&&o.length===2&&DE.has(o[1].toLowerCase())?null:HE(o,a,p,i.makefileFor)}if(c&&(r.startsWith("./")||r.startsWith("../"))){let u=xs(a,c,r);if(o.length===1&&Y.extname(r.replace(/\/+$/,""))===""&&(u.state==="found"&&u.isDir||!i.fenced||r.endsWith("/")))return null;let p=ks(u,`Script "${r}" does not appear to exist in the repository`);if(p!==null)return p}if(c&&r==="docker"&&o[1]==="compose"&&o.includes("-f")){let u=o.indexOf("-f"),p=o[u+1];if(p&&Es(p)){let d=ks(xs(a,c,p),`Docker Compose file "${p}" does not appear to exist in the repository`);if(d!==null)return d}}if(c&&r==="dotnet"&&o[1]==="test"&&o[2]){let u=o[2];if(Es(u)){let p=xs(a,c,u);if(p.state==="outside")return null;let d=ks(p,`dotnet test target "${u}" does not appear to exist`);if(d!==null)return d;if(!/\.(sln|csproj|fsproj)$/.test(u))return`dotnet test target "${u}" should be a .sln, .csproj, or .fsproj file`}}return null}function em(t){return _c(t).issues.map(e=>({...e}))}var Xh=new WeakMap;function _c(t){let e=Xh.get(t);return e||(e=GE(t),Xh.set(t,e)),e}function GE(t){let e=[],n=new Map,s=new Set,i=Z(t),o=new Map,r=new Map,a=c=>c==="."||c===""?t.makefile:(r.has(c)||r.set(c,Zi(t.repoRoot,c,i)),r.get(c));for(let c of t.files){let l=CE(c.content),u=c.content.split(/\r?\n/),p=Of(c.content),d=Wh(c.content),h=new Set,f=Y.relative(t.repoRoot,Y.dirname(c.path)).replace(/\\/g,"/")||".",m=f.startsWith("..")?".":f;n.set(c.path,h);for(let g of l){let y=g.cwd===void 0?".":g.cwd,b,w,S=M=>gc(mc([M]),m,i).length>0,C,v=()=>C??=Uh(d,g.line,g.text,S),_=xE(d,g.line),A=()=>_.dir!==null&&_.dir!=="."?gc([_.dir],m,i):[],O,j=()=>O??=y==="."?[...new Set([...A(),...gc(mc(v().text),m,i)])]:[],x=BE(g.text,t,y,M=>h.add(`${g.line}:${M}`),{fenced:g.fenced===!0,makefileFor:a,fileDir:m,tree:i,suggestScript:M=>{b=M},scope:{hintDirs:j,get explicitRoot(){return y==="."&&v().explicitRoot},elsewhere:(M,T)=>{w={script:M,dirs:T}}}});if(!x||p[g.line-1]===!0)continue;if(x===Gn){let M=`Not checked: \`${g.text}\``,T=o.get(M)??{filePaths:new Set,fileLines:new Map,evidence:M};T.filePaths.add(c.path);let ne=T.fileLines.get(c.path);(ne===void 0||g.line<ne)&&T.fileLines.set(c.path,g.line),o.set(M,T);continue}let D=`${c.path}|${g.text}`;if(s.has(D))continue;s.add(D);let U=b?.mechanical===!0&&aE(u[g.line-1]??"",b.find)===1,te=U?rE(g,u,p[g.line-1]===!0,v(),_.any,mE(t,i),b?.viaRoot===!0):void 0,k=U&&te===void 0?b:void 0,E=b&&!k?` The manifest defines "${b.candidate}", which is close to "${b.missing}"; `+(te?`it may be what was meant, but ${te}, so it was left unedited; check before changing it.`:"it may be what was meant, but it is near enough to be a different script, so check before changing it."):"";if(w){let M=w.dirs.slice(0,3).map(be=>`${be}/package.json`),T=w.dirs.length-M.length,ne=`${M.join(", ")}${T>0?` and ${T} more`:""}`,de=w.dirs[0];e.push({id:no(G(c),g.text),severity:"info",category:"command_validity",title:`Command may need a working directory: \`${g.text.split(/\s+/).slice(0,3).join(" ")}\``,summary:`${x}, but ${ne} defines "${w.script}". Nothing near the command names that directory, so it may be meant to run from there.`,filePaths:[c.path],locations:[{filePath:c.path,startLine:g.line,endLine:g.line}],evidence:[`Command: \`${g.text}\``,`In file: ${c.path}`,`Defined in: ${ne}`],recommendation:`If the command runs from \`${de}/\`, say so next to it (for example "from \`${de}/\`", or \`cd ${de} && ${g.text}\`) so a reader or an agent runs it in the right place. If the script was renamed or removed, update the instruction file.`,confidence:.6});continue}e.push({id:no(G(c),g.text),severity:"warning",category:"command_validity",title:`Possible reference to missing command or file: \`${g.text.split(/\s+/).slice(0,3).join(" ")}\``,summary:k?`${x}. The closest script name the manifest defines is "${k.candidate}".`:x,filePaths:[c.path],locations:[{filePath:c.path,startLine:g.line,endLine:g.line}],evidence:[`Command: \`${g.text}\``,`In file: ${c.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."+E,...k?{fixRecipe:`Rename the script in this command: \`${k.find}\` -> \`${k.replace}\`.`,autoApplySafe:!0,fixEdits:[{filePath:c.path,line:g.line,find:k.find,replace:k.replace}]}:{},confidence:.8})}}for(let c of[...yc.get(i)??[]].sort()){let l=Y.relative(i.root,c).split(Y.sep).join("/");e.push({id:no("",`(unparsable ${l})`),severity:"info",category:"command_validity",title:`Could not parse ${l}`,summary:`${l} is not a valid JSON object, so the commands that depend on its scripts were not checked.`,filePaths:[c],locations:[{filePath:c}],evidence:[`File: ${l}`],recommendation:`Fix the syntax of ${l}; commands documented to run there are checked once it parses.`,confidence:.9})}return o.size>0&&e.push($i(i,[...o.values()],{id:no("","(command check incomplete)"),category:"command_validity",title:"Command check incomplete: part of the repository could not be read",unit:"command",unknown:"The files they name may or may not exist",finding:"missing-command"})),{issues:e,evaluatedScripts:n}}var tm=R(require("node:crypto"),1);function xc(t){return`ci-align-${tm.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function kc(t){return t.split(/&&|\n/).map(e=>e.trim()).filter(Boolean)}function WE(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 VE(t){let e=[];for(let n of kc(t)){let s=WE(n);s&&!e.includes(s)&&e.push(s)}return e}var UE={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 zE(t,e){let n=UE[t];return e.some(s=>n.test(s.content))}function qE(t){let e=/\b(pnpm|npm|yarn|bun)\b/.exec(t.toLowerCase());return e?e[1]:null}function Ec(t){let e=new Set;for(let n of t)for(let s of kc(n.command)){let i=qE(s);i&&e.add(i)}return e}var nm=new Set(["install","i","add","remove","uninstall","init","help","test","start","stop","restart","exec","dlx","run","workspace","workspaces"]),sm=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 KE(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 nm.has(n)||sm.has(n)?null:n}function YE(t){let{workflows:e,files:n}=t;if(e.files.length===0)return[];let s=new Map;for(let o of e.commands)for(let r of VE(o.command))s.has(r)||s.set(r,[]),s.get(r).push(o);let i=[];for(let[o,r]of s.entries()){if(zE(o,n))continue;let a=[...new Set(r.map(c=>c.filePath))];i.push({id:xc(`missing-ci-task:${o}`),severity:"warning",category:"missing_context",title:`CI runs \`${o}\` but no instruction file appears to include it`,summary:`The GitHub workflow${a.length>1?"s":""} (${a.join(", ")}) run \`${o}\`, but no instruction file appears to direct the agent to run this step locally. Agents that follow only the instruction files may skip \`${o}\` and miss failures before declaring work complete.`,filePaths:n.map(c=>c.path),locations:r.map(c=>({filePath:c.filePath,startLine:c.line})),evidence:r.map(c=>`CI command: \`${c.command}\` in ${c.filePath} (line ${c.line})`),recommendation:`Consider adding \`${o}\` 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 XE(t){let{workflows:e,files:n,packageJson:s}=t;if(e.files.length===0)return[];if(s.packageManagerName!=="unknown")return[];let i=Ec(e.commands);if(i.size===0)return[];let o=s.packageManagerName!=="unknown"?s.packageManagerName:Array.from(i)[0];if(!i.has(o))return[];let r=[];for(let a of n)for(let c of["npm","pnpm","yarn","bun"]){if(c===o)continue;let l=new RegExp(`\\b${c}\\s+(?:install|add|run|exec|dlx|i)\\b`,"gi"),u,p=!1;for(;(u=l.exec(a.content))!==null;){let d=a.content.lastIndexOf(`
63
+ `,u.index-1)+1,h=a.content.indexOf(`
64
+ `,u.index),f=a.content.slice(d,h===-1?void 0:h);if(!/\b(?:do\s+not|don'?t|avoid|never|not\s+use|refrain)\b/i.test(f)){p=!0;break}}p&&r.push({id:xc(`pm-mismatch-ci:${G(a)}:${c}`),severity:"warning",category:"conflict",title:`Possible package manager mismatch: instructions use \`${c}\` but CI uses \`${o}\``,summary:`The instruction file appears to direct the agent to use \`${c}\`, but the CI workflows use \`${o}\`. 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 \`${o}\` commands to align with CI.`,confidence:.85})}return r}function JE(t){let{workflows:e,files:n,packageJson:s,manifests:i}=t;if(e.files.length===0)return[];if(i.packageJson)return[];let o=new Set(Object.keys(s.scripts)),r=new Set;for(let l of e.commands)for(let u of kc(l.command)){let p=KE(u);p&&r.add(p)}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,p;for(;(p=u.exec(l.content))!==null;){let d=p[1].toLowerCase();if(!(nm.has(d)||sm.has(d))&&!o.has(d)&&!r.has(d)){let h=`${l.path}:${d}`;if(a.has(h))continue;a.add(h),c.push({id:xc(`orphan-script:${G(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 im(t){return t.workflows.files.length===0?[]:[...YE(t),...XE(t),...JE(t)]}function io(t){return`manifest-${om.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function ZE(t,e,n){if(!(/\[tool\.poetry\]/.test(e)||/build-backend\s*=\s*["'][^"']*poetry[^"']*["']/i.test(e))||n.exists("requirements.txt"))return null;let i=/pip\s+install\s+-r\s+requirements\.txt/i,o=t.filter(r=>i.test(r.content));return o.length===0?null:{id:io("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(r=>r.path),locations:o.map(r=>({filePath:r.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 QE(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),o=[],r=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 p=parseInt(l[1],10),d=parseInt(l[2],10);if(Rc(c.content,l.index)||!(p<s||p===s&&d<i))continue;let f=`${p}.${d}`,m=`${s}.${i}`,g=`${c.path}:${f}`;r.has(g)||(r.add(g),o.push({id:io(`python-version:${G(c)}:${f}`),severity:"high",category:"stale_instruction",title:`Python version mismatch: instruction says ${f}, pyproject.toml requires \u2265${m}`,summary:`An instruction file refers to Python ${f}, 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 ${f}"; 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 o}var eA=["pandas","numpy","sqlalchemy","fastapi","django","flask","pydantic"];function tA(t){return t==="sqlalchemy"?"SQLAlchemy":t==="fastapi"?"FastAPI":t[0].toUpperCase()+t.slice(1)}function Cc(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ac(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 nA(t){let e=new Map;for(let n of eA){let s=Cc(n),o=new RegExp(`^\\s*${s}\\s*=\\s*["']([^"']+)["']`,"im").exec(t);if(o){let c=Ac(o[1]);if(c!==null){e.set(n,c);continue}}let r=new RegExp(`["']${s}(?:\\[[^\\]]+\\])?\\s*([~^=<>!]{1,2}\\s*\\d+(?:\\.\\d+)?)`,"gim"),a;for(;(a=r.exec(t))!==null;){let c=Ac(a[1]);if(c!==null){e.set(n,c);break}}}return e}function sA(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 iA(t,e){let n=nA(e);if(n.size===0)return[];let s=[],i=new Set;for(let[o,r]of n){let a=tA(o),c=new RegExp(`\\b${Cc(a)}\\s+(?:v(?:ersion)?\\s*)?(\\d+)(?:\\.(\\d+|x))?\\b`,"gi");for(let l of t){let u,p=new RegExp(c.source,c.flags);for(;(u=p.exec(l.content))!==null;){if(!sA(l.content,u.index))continue;let d=parseInt(u[1],10);if(d>=r)continue;let h=u[2]?`${d}.${u[2]}`:`${d}.x`,f=`${l.path}:${o}:${h}`;i.has(f)||(i.add(f),s.push({id:io(`library-version:${G(l)}:${o}:${h}`),severity:"high",category:"stale_instruction",title:`${a} version mismatch: instruction says ${h}, pyproject.toml uses ${r}.x`,summary:`An instruction file refers to ${a} ${h}, but pyproject.toml declares ${o} ${r}.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} ${h}"; pyproject.toml uses ${o} ${r}.x`],recommendation:`Update the instruction file to match ${a} ${r}.x, or remove the version-specific guidance and rely on pyproject.toml as the authoritative source.`,confidence:.85}))}}}return s}var oA=["react","next","typescript","vite","vitest","jest"],rA={react:"React",next:"Next.js",typescript:"TypeScript",vite:"Vite",vitest:"Vitest",jest:"Jest"};function aA(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 o of i){if(typeof o!="object"||o===null||Array.isArray(o))continue;let r=o;for(let a of oA){let c=r[a];if(typeof c!="string")continue;let l=Ac(c);l!==null&&s.set(a,l)}}return s}function cA(t,e){let n=aA(e);if(n.size===0)return[];let s=[],i=new Set;for(let[o,r]of n){let a=rA[o],c=new RegExp(`\\b${Cc(a)}\\s+(?:v(?:ersion)?\\s*)?(\\d+)(?:\\.(\\d+|x))?\\b`,"gi");for(let l of t){let u,p=new RegExp(c.source,c.flags);for(;(u=p.exec(l.content))!==null;){if(!lA(l.content,u.index))continue;let d=parseInt(u[1],10);if(d>=r)continue;let h=u[2]?`${d}.${u[2]}`:`${d}.x`,f=`${l.path}:${o}:${h}`;i.has(f)||(i.add(f),s.push({id:io(`js-library-version:${G(l)}:${o}:${h}`),severity:"high",category:"stale_instruction",title:`${a} version mismatch: instruction says ${h}, package.json uses ${r}.x`,summary:`An instruction file refers to ${a} ${h}, but package.json declares ${o} ${r}.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} ${h}"; package.json uses ${o} ${r}.x`],recommendation:`Update the instruction file to match ${a} ${r}.x, or remove the version-specific guidance and rely on package.json as the authoritative source.`,confidence:.85}))}}}return s}function lA(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 Rc(t,e){let n=t.lastIndexOf(`
54
65
  `,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 aE(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
- `,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))&&!qa(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 cE(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
- `,h-1)+1;if(o.test(p.slice(g,h)))return!0;let y=p.indexOf(`
59
- `,m),b=p.slice(m,y===-1?void 0:y);return a.test(b.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=Ua(t);for(let p of n){let h=gd(p.content),m=d.evaluatedScripts.get(p.path),g,y=new RegExp(r.source,r.flags);for(;(g=y.exec(p.content))!==null;){let b=g[1].toLowerCase(),v=g[2]!==void 0,x=g[3];if(!x.startsWith("-")&&!/^[0-9]/.test(x)&&!(!v&&!h[g.index])&&!u.has(x)&&!f.has(x.toLowerCase())&&!(b==="bun"&&!v&&Ga.has(x))&&!s.has(x)){if(m?.size){let A=p.content.slice(0,g.index).split(`
60
- `).length;if(m.has(`${A}:${x}`))continue}if(Oi(t,x)||!(v&&(b==="npm"||b==="pnpm"))&&kn(t,x)||c(p.content,g.index,g.index+g[0].length))continue;let _=`${p.path}:${x}`;if(l.has(_))continue;l.add(_),i.push({id:`manifest-missing-script:${N(p)}:${x}`,severity:"warning",category:"stale_instruction",title:`Reference to missing script: "${x}"`,summary:`Instructions tell the agent to run \`${x}\`, 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 \`${x}\` in ${p.path}`],recommendation:"Verify if the script name is correct or add the missing script to package.json.",confidence:.7})}}}return i}function lE(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(!qa(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:${N(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 uE(t,e,n){let s=t.lastIndexOf(`
66
+ `,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 uA(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(a=>a.name!==s),o=[];for(let a of n)for(let c of i){let l=new RegExp(`\\b${c.name}\\s+(?:install|add|run|exec|dlx|i)\\b`,"gi"),u,p=!1;for(;(u=l.exec(a.content))!==null;){let d=a.content.lastIndexOf(`
67
+ `,u.index-1)+1,h=a.content.indexOf(`
68
+ `,u.index),f=a.content.slice(d,h===-1?void 0:h);if(!(s==="pnpm"&&/\bnpm\s+(?:install|i)\s+-g\s+pnpm\b/i.test(f))&&!Rc(a.content,u.index)){p=!0;break}}if(p){o.push(a);break}}if(o.length===0)return null;let r=t.workflows.files.length>0&&Ec(t.workflows.commands).has(s);return{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"}). `+(r?`The CI workflows use ${s} too. `:"")+"Mixing package managers can lead to inconsistent lockfiles and installation errors.",filePaths:o.map(a=>a.path),locations:o.map(a=>({filePath:a.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 dA(t){let{packageJson:e,files:n}=t,s=new Set(Object.keys(e.scripts));if(s.size===0)return[];let i=[],o=/\b(npm|yarn|pnpm|bun)\s+(run(?:-script)?\s+)?([a-z0-9][a-z0-9:_-]*)\b/gi,r=/\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=(h,f,m)=>{let g=h.lastIndexOf(`
69
+ `,f-1)+1;if(r.test(h.slice(g,f)))return!0;let y=h.indexOf(`
70
+ `,m),b=h.slice(m,y===-1?void 0:y);return a.test(b.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"]),p=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=_c(t);for(let h of n){let f=Jp(h.content),m=d.evaluatedScripts.get(h.path),g,y=new RegExp(o.source,o.flags);for(;(g=y.exec(h.content))!==null;){let b=g[1].toLowerCase(),w=g[2]!==void 0,S=g[3];if(!S.startsWith("-")&&!/^[0-9]/.test(S)&&!(!w&&!f[g.index])&&!u.has(S)&&!p.has(S.toLowerCase())&&!(b==="bun"&&!w&&Sc.has(S))&&!s.has(S)){if(m?.size){let _=h.content.slice(0,g.index).split(`
71
+ `).length;if(m.has(`${_}:${S}`))continue}if(Ji(t,S)||!(w&&(b==="npm"||b==="pnpm"))&&Bn(t,S)||c(h.content,g.index,g.index+g[0].length))continue;let v=`${h.path}:${S}`;if(l.has(v))continue;l.add(v),i.push({id:`manifest-missing-script:${G(h)}:${S}`,severity:"warning",category:"stale_instruction",title:`Reference to missing script: "${S}"`,summary:`Instructions tell the agent to run \`${S}\`, but this script is not defined in package.json. The agent might attempt to run a command that fails.`,filePaths:[h.path],locations:[{filePath:h.path}],evidence:[`Found reference to \`${S}\` in ${h.path}`],recommendation:"Verify if the script name is correct or add the missing script to package.json.",confidence:.7})}}}return i}function pA(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),o=[],r=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 p=parseInt(l[1],10);if(!Rc(c.content,l.index)&&p<i){let d=`${c.path}:${p}`;if(r.has(d))continue;r.add(d),o.push({id:`manifest-node-version-mismatch:${G(c)}:${p}`,severity:"warning",category:"stale_instruction",title:`Node.js version mismatch: instruction says ${p}, project requires \u2265${i}`,summary:`Instructions mention Node.js ${p}, but package.json specifies a minimum version of ${i} in \`engines.node\`.`,filePaths:[c.path],locations:[{filePath:c.path}],evidence:[`Instruction says Node ${p}; engines.node says ${e.enginesNode}`],recommendation:`Update instructions to reflect the minimum supported Node.js version (${i}).`,confidence:.8})}}}return o}function fA(t,e,n){let s=t.lastIndexOf(`
61
72
  `,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 fE(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(!uE(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 Ka(t){let{files:e,manifests:n}=t,s=[];n.packageJson&&(s.push(...rE(e,n.packageJson)),s.push(...cE(t)),s.push(...lE(t)),s.push(...fE(t)));let i=aE(t);if(i&&s.push(i),n.pyproject){let r=YS(e,n.pyproject,V(t));r&&s.push(r),s.push(...JS(e,n.pyproject)),s.push(...tE(e,n.pyproject))}return s}var Ah=R(require("node:crypto"),1),Wi=R(require("node:fs"),1),gt=R(require("node:path"),1),lc=R(Gn(),1);var It=R(require("node:fs/promises"),1),mt=R(require("node:path"),1);var wh=R(ft(),1);var Ya={"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},us=Object.keys(Ya),ah={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"},dE=4,pE=.03,hE=.35;function ch(t){return Math.round(t/1e3)*1e3}function Rn(t){let e=t.trim().toLowerCase();if(Object.prototype.hasOwnProperty.call(Ya,e))return e;if(Object.prototype.hasOwnProperty.call(ah,e))return ah[e]}function lh(t){let e=Ya[t],n=ch(e*pE*dE),s=ch(n*hE);return{contextWindowTokens:e,contextBudget:n,fileContextBudget:s}}function Ja(t){let e=Rn(t);return e?lh(e):void 0}var dh=R(require("node:crypto"),1),ph=R(require("node:fs/promises"),1),Jt=R(require("node:path"),1),hh=R(ft(),1);var Za=Jt.join(".promptci","custom-rules.json"),Xa=["forbiddenPattern","absentPattern","requiredSection","crossFileConflict"],uh=["info","warning","high","critical"],mE=/^[gimsuy]*$/,ke=class extends Error{constructor(e){super(`Invalid ${Za}: ${e}`),this.name="CustomRulesError"}};function fs(t,e,n){let s=t[e];if(typeof s!="string"||s.trim()==="")throw new ke(`${n} is missing a non-empty string "${e}".`);return s}function gE(t,e,n){if(!Array.isArray(t)||!t.every(s=>typeof s=="string"))throw new ke(`${n}: "${e}" must be an array of strings.`);return t}function yE(t,e,n){if(e!==void 0&&!mE.test(e))throw new ke(`${n}: "flags" may only contain regex flags (gimsuy).`);try{new RegExp(t,e)}catch(s){throw new ke(`${n}: "pattern" is not a valid regular expression: ${s instanceof Error?s.message:String(s)}`)}}function mh(t){let e;if(Array.isArray(t))e=t;else if(t&&typeof t=="object"&&"rules"in t)e=t.rules;else throw new ke('top level must be an object with a "rules" array (or a bare array of rules).');if(!Array.isArray(e))throw new ke('"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 ke(`${o} must be an object.`);let a=r,c=fs(a,"id",o),l=`rule "${c}"`;if(s.has(c))throw new ke(`${l}: duplicate rule id (ids must be unique).`);s.add(c);let u=fs(a,"type",l);if(!Xa.includes(u))throw new ke(`${l}: "type" must be one of ${Xa.join(", ")} (got "${u}").`);let f=fs(a,"message",l),d="warning";if("severity"in a){if(typeof a.severity!="string"||!uh.includes(a.severity))throw new ke(`${l}: "severity" must be one of ${uh.join(", ")}.`);d=a.severity}let p={id:c,type:u,message:f,severity:d};if("files"in a&&(p.files=gE(a.files,"files",l)),"flags"in a){if(typeof a.flags!="string")throw new ke(`${l}: "flags" must be a string.`);p.flags=a.flags}u==="requiredSection"?p.heading=fs(a,"heading",l):(p.pattern=fs(a,"pattern",l),yE(p.pattern,p.flags,l)),n.push(p)}return n}async function Qa(t){let e=Jt.join(t,Za);if(!be(t,e))return[];let n;try{n=await ph.readFile(e,"utf-8")}catch(i){if(i.code==="ENOENT")return[];throw i}let s;try{s=JSON.parse(n)}catch{throw new ke("file is not valid JSON.")}return mh(s)}function bE(t){return dh.createHash("sha1").update(t).digest("hex").slice(0,12)}function gh(t,e){let n=1;for(let s=0;s<e&&s<t.length;s++)t[s]===`
63
- `&&n++;return n}function wE(t,e,n){return!e.files||e.files.length===0?t:t.filter(s=>{let i=Jt.relative(n,s.path).replace(/\\/g,"/");return hh.default.isMatch(i,e.files,{dot:!0})})}function ec(t){return new RegExp(t.pattern,t.flags)}function Di(t){return{severity:t.severity,category:"custom",confidence:1,tags:["custom-rule"]}}function vE(t,e){let n=[];for(let s of t){let i=ec(e).exec(s.content);if(!i)continue;let r=gh(s.content,i.index);n.push({id:`custom:${e.id}:${bE(N(s))}`,...Di(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: "${Z(i[0],120)}" (line ${r})`],recommendation:`Remove or revise the flagged content to satisfy custom rule "${e.id}".`})}return n}function xE(t,e){return t.some(s=>ec(e).test(s.content))?[]:[{id:`custom:${e.id}`,...Di(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 fh(t){return t.toLowerCase().replace(/^#+\s*/,"").replace(/\s+/g," ").trim()}function _E(t,e){let n=fh(e.heading);return t.some(i=>i.sections.some(r=>r.heading!==void 0&&fh(r.heading).includes(n)))?[]:[{id:`custom:${e.id}`,...Di(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 SE(t,e){let n=new Map;for(let o of t){let a=ec(e).exec(o.content);if(!a)continue;let c=(a[1]??a[0]).trim(),l=gh(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])=>`"${Z(o,60)}" in ${a.map(c=>Jt.basename(c.filePath)).join(", ")}`);return[{id:`custom:${e.id}`,...Di(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 tc(t,e,n){let s=[];for(let i of e){let r=wE(t,i,n);switch(i.type){case"forbiddenPattern":s.push(...vE(r,i));break;case"absentPattern":s.push(...xE(r,i));break;case"requiredSection":s.push(..._E(r,i));break;case"crossFileConflict":s.push(...SE(r,i));break}}return s}var EE=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","bun.lock"];function kE(){return{packageManagerName:"unknown",scripts:{},dependencies:{},devDependencies:{},peerDependencies:{},lockfiles:[]}}function sc(t,e){let n=ie(t,e);if(n===null)throw new Error(`Path escapes repo root: ${e}`);return n}async function nc(t,e){try{return await It.readFile(sc(t,e),"utf-8")}catch{return}}function RE(t,e){return e.filter(n=>t.isFile(n))}function yh(t){return t?t.startsWith("pnpm@")?"pnpm":t.startsWith("npm@")?"npm":t.startsWith("yarn@")?"yarn":t.startsWith("bun@")?"bun":"unknown":"unknown"}function Fi(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 Hi(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 vh(t,e){let n=kE();if(n.raw=t,n.lockfiles=e,!t)return n.packageManagerName=Fi(e),n;let s;try{s=JSON.parse(t)}catch{return n.packageManagerName=Fi(e),n}if(typeof s!="object"||s===null||Array.isArray(s))return n.packageManagerName=Fi(e),n;let i=s;if(n.packageManager=typeof i.packageManager=="string"?i.packageManager:void 0,n.packageManagerName=yh(n.packageManager)!=="unknown"?yh(n.packageManager):Fi(e),n.scripts=Hi(i.scripts),n.dependencies=Hi(i.dependencies),n.devDependencies=Hi(i.devDependencies),n.peerDependencies=Hi(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 CE(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 AE(t,e,n=[]){let s=mt.join(t,".github","workflows"),i=e.entries(s);if(typeof i=="string")return{files:[],commands:[],sources:await bh(t,n)};let r=[...i.values()].filter(c=>c.isFile()&&/\.(ya?ml)$/i.test(c.name)).map(c=>mt.join(s,c.name)).sort(),o=[],a=[];for(let c of r){let l=mt.relative(t,c);if(!be(t,c))continue;let u;try{u=await It.readFile(c,"utf-8")}catch{continue}o.push(...CE(l,u));let f=l.replace(/\\/g,"/");u.length<=ce&&!ds(f,n)&&a.push({filePath:f,content:u})}return a.push(...await bh(t,n)),{files:r.map(c=>mt.relative(t,c)),commands:o,sources:a}}async function bh(t,e){let n=[];for(let s of ot(t,[...Ed])){if(ds(s,e))continue;let i=ie(t,s);if(i)try{let r=await It.stat(i);if(!r.isFile()||r.size>ce)continue;n.push({filePath:s,content:await It.readFile(i,"utf-8")})}catch{}}return n}function ds(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=>wh.default.isMatch(i,e,{dot:!0}))}async function $E(t,e,n){let s;try{let o=await It.stat(sc(t,e));if(!o.isFile()||o.size>ce)return;s=await It.readFile(sc(t,e))}catch{return}if(Gt(s))return;let i=s.toString("utf-8"),r=i.split(`
73
+ `,e),o=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(o.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(o))}function hA(t){let{packageJson:e,files:n}=t,s={...e.dependencies,...e.devDependencies},i=[],o=[{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 r of o)if(!s[r.package]){let a=r.alternatives.find(c=>s[c]);if(a){let c=new RegExp(`\\b${r.name}\\b`,"gi"),l=n.filter(u=>{let p,d=new RegExp(c.source,c.flags);for(;(p=d.exec(u.content))!==null;)if(!fA(u.content,p.index,r.name))return!0;return!1});l.length>0&&i.push({id:`manifest-js-tooling-mismatch:${r.package}`,severity:"warning",category:"conflict",title:`Possible tooling mismatch: instructions mention ${r.name} but project uses ${a}`,summary:`Instructions appear to reference ${r.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 ${r.name}`,`${a} found in dependencies`,`${r.package} not found in dependencies`],recommendation:`Update instructions to reference ${a} instead of ${r.name}, or confirm migration is complete.`,confidence:.75})}}return i}function Tc(t){let{files:e,manifests:n}=t,s=[];n.packageJson&&(s.push(...cA(e,n.packageJson)),s.push(...dA(t)),s.push(...pA(t)),s.push(...hA(t)));let i=uA(t);if(i&&s.push(i),n.pyproject){let o=ZE(e,n.pyproject,Z(t));o&&s.push(o),s.push(...QE(e,n.pyproject)),s.push(...iA(e,n.pyproject))}return s}var Cm=R(require("node:crypto"),1),lo=R(require("node:fs"),1),Ct=R(require("node:path"),1),Vc=R(rs(),1);var Vt=R(require("node:fs/promises"),1),At=R(require("node:path"),1);var bm=R(_t(),1);var Pc={"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},Cs=Object.keys(Pc),rm={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"},mA=4,gA=.03,yA=.35;function am(t){return Math.round(t/1e3)*1e3}function Wn(t){let e=t.trim().toLowerCase();if(Object.prototype.hasOwnProperty.call(Pc,e))return e;if(Object.prototype.hasOwnProperty.call(rm,e))return rm[e]}function cm(t){let e=Pc[t],n=am(e*gA*mA),s=am(n*yA);return{contextWindowTokens:e,contextBudget:n,fileContextBudget:s}}function $c(t){let e=Wn(t);return e?cm(e):void 0}var dm=R(require("node:crypto"),1),pm=R(require("node:fs/promises"),1),pn=R(require("node:path"),1),fm=R(_t(),1);var Oc=pn.join(".promptci","custom-rules.json"),Ic=["forbiddenPattern","absentPattern","requiredSection","crossFileConflict"],lm=["info","warning","high","critical"],bA=/^[gimsuy]*$/,Ne=class extends Error{constructor(e){super(`Invalid ${Oc}: ${e}`),this.name="CustomRulesError"}};function Rs(t,e,n){let s=t[e];if(typeof s!="string"||s.trim()==="")throw new Ne(`${n} is missing a non-empty string "${e}".`);return s}function wA(t,e,n){if(!Array.isArray(t)||!t.every(s=>typeof s=="string"))throw new Ne(`${n}: "${e}" must be an array of strings.`);return t}function vA(t,e,n){if(e!==void 0&&!bA.test(e))throw new Ne(`${n}: "flags" may only contain regex flags (gimsuy).`);try{new RegExp(t,e)}catch(s){throw new Ne(`${n}: "pattern" is not a valid regular expression: ${s instanceof Error?s.message:String(s)}`)}}function hm(t){let e;if(Array.isArray(t))e=t;else if(t&&typeof t=="object"&&"rules"in t)e=t.rules;else throw new Ne('top level must be an object with a "rules" array (or a bare array of rules).');if(!Array.isArray(e))throw new Ne('"rules" must be an array.');let n=[],s=new Set;for(let i=0;i<e.length;i++){let o=e[i],r=`rule at index ${i}`;if(typeof o!="object"||o===null||Array.isArray(o))throw new Ne(`${r} must be an object.`);let a=o,c=Rs(a,"id",r),l=`rule "${c}"`;if(s.has(c))throw new Ne(`${l}: duplicate rule id (ids must be unique).`);s.add(c);let u=Rs(a,"type",l);if(!Ic.includes(u))throw new Ne(`${l}: "type" must be one of ${Ic.join(", ")} (got "${u}").`);let p=Rs(a,"message",l),d="warning";if("severity"in a){if(typeof a.severity!="string"||!lm.includes(a.severity))throw new Ne(`${l}: "severity" must be one of ${lm.join(", ")}.`);d=a.severity}let h={id:c,type:u,message:p,severity:d};if("files"in a&&(h.files=wA(a.files,"files",l)),"flags"in a){if(typeof a.flags!="string")throw new Ne(`${l}: "flags" must be a string.`);h.flags=a.flags}u==="requiredSection"?h.heading=Rs(a,"heading",l):(h.pattern=Rs(a,"pattern",l),vA(h.pattern,h.flags,l)),n.push(h)}return n}async function Lc(t){let e=pn.join(t,Oc);if(!Pe(t,e))return[];let n;try{n=await pm.readFile(e,"utf-8")}catch(i){if(i.code==="ENOENT")return[];throw i}let s;try{s=JSON.parse(n)}catch{throw new Ne("file is not valid JSON.")}return hm(s)}function SA(t){return dm.createHash("sha1").update(t).digest("hex").slice(0,12)}function mm(t,e){let n=1;for(let s=0;s<e&&s<t.length;s++)t[s]===`
74
+ `&&n++;return n}function _A(t,e,n){return!e.files||e.files.length===0?t:t.filter(s=>{let i=pn.relative(n,s.path).replace(/\\/g,"/");return fm.default.isMatch(i,e.files,{dot:!0})})}function Nc(t){return new RegExp(t.pattern,t.flags)}function oo(t){return{severity:t.severity,category:"custom",confidence:1,tags:["custom-rule"]}}function xA(t,e){let n=[];for(let s of t){let i=Nc(e).exec(s.content);if(!i)continue;let o=mm(s.content,i.index);n.push({id:`custom:${e.id}:${SA(G(s))}`,...oo(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:o,endLine:o}],evidence:[`Matched text: "${se(i[0],120)}" (line ${o})`],recommendation:`Remove or revise the flagged content to satisfy custom rule "${e.id}".`})}return n}function kA(t,e){return t.some(s=>Nc(e).test(s.content))?[]:[{id:`custom:${e.id}`,...oo(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 um(t){return t.toLowerCase().replace(/^#+\s*/,"").replace(/\s+/g," ").trim()}function EA(t,e){let n=um(e.heading);return t.some(i=>i.sections.some(o=>o.heading!==void 0&&um(o.heading).includes(n)))?[]:[{id:`custom:${e.id}`,...oo(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 AA(t,e){let n=new Map;for(let r of t){let a=Nc(e).exec(r.content);if(!a)continue;let c=(a[1]??a[0]).trim(),l=mm(r.content,a.index),u=n.get(c)??[];u.push({filePath:r.path,line:l}),n.set(c,u)}if(n.size<2)return[];let s=[...new Set([...n.values()].flat().map(r=>r.filePath))],i=[...n.values()].flat().map(r=>({filePath:r.filePath,startLine:r.line,endLine:r.line})),o=[...n.entries()].map(([r,a])=>`"${se(r,60)}" in ${a.map(c=>pn.basename(c.filePath)).join(", ")}`);return[{id:`custom:${e.id}`,...oo(e),title:e.message,summary:`Custom rule "${e.id}": the tracked value differs across files (${n.size} distinct values).`,filePaths:s,locations:i,evidence:o,recommendation:`Reconcile the conflicting values so custom rule "${e.id}" sees a single consistent value.`}]}function Mc(t,e,n){let s=[];for(let i of e){let o=_A(t,i,n);switch(i.type){case"forbiddenPattern":s.push(...xA(o,i));break;case"absentPattern":s.push(...kA(o,i));break;case"requiredSection":s.push(...EA(o,i));break;case"crossFileConflict":s.push(...AA(o,i));break}}return s}var CA=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","bun.lock"];function RA(){return{packageManagerName:"unknown",scripts:{},dependencies:{},devDependencies:{},peerDependencies:{},lockfiles:[]}}function Dc(t,e){let n=he(t,e);if(n===null)throw new Error(`Path escapes repo root: ${e}`);return n}async function jc(t,e){try{return await Vt.readFile(Dc(t,e),"utf-8")}catch{return}}function TA(t,e){return e.filter(n=>t.isFile(n))}function gm(t){return t?t.startsWith("pnpm@")?"pnpm":t.startsWith("npm@")?"npm":t.startsWith("yarn@")?"yarn":t.startsWith("bun@")?"bun":"unknown":"unknown"}function ro(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 ao(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"))}function wm(t,e){let n=RA();if(n.raw=t,n.lockfiles=e,!t)return n.packageManagerName=ro(e),n;let s;try{s=JSON.parse(t)}catch{return n.packageManagerName=ro(e),n}if(typeof s!="object"||s===null||Array.isArray(s))return n.packageManagerName=ro(e),n;let i=s;if(n.packageManager=typeof i.packageManager=="string"?i.packageManager:void 0,n.packageManagerName=gm(n.packageManager)!=="unknown"?gm(n.packageManager):ro(e),n.scripts=ao(i.scripts),n.dependencies=ao(i.dependencies),n.devDependencies=ao(i.devDependencies),n.peerDependencies=ao(i.peerDependencies),typeof i.engines=="object"&&i.engines!==null&&!Array.isArray(i.engines)){let o=i.engines;n.enginesNode=typeof o.node=="string"?o.node:void 0}return n}function PA(t,e){let n=e.split(/\r?\n/),s=[];for(let i=0;i<n.length;i++){let o=n[i],r=/^(\s*)(?:-\s*)?run:\s*(.*)$/.exec(o);if(!r)continue;let a=r[1].length,c=r[2].trim();if(c&&!/^[|>][+-]?$/.test(c)){s.push({filePath:t,command:c,line:i+1});continue}let l=[];for(let p=i+1;p<n.length;p++){let d=n[p];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(`
75
+ `).trim();u&&s.push({filePath:t,command:u,line:i+1})}return s}async function $A(t,e,n=[]){let s=At.join(t,".github","workflows"),i=e.entries(s);if(typeof i=="string")return{files:[],commands:[],sources:await ym(t,n)};let o=[...i.values()].filter(c=>c.isFile()&&/\.(ya?ml)$/i.test(c.name)).map(c=>At.join(s,c.name)).sort(),r=[],a=[];for(let c of o){let l=At.relative(t,c);if(!Pe(t,c))continue;let u;try{u=await Vt.readFile(c,"utf-8")}catch{continue}r.push(...PA(l,u));let p=l.replace(/\\/g,"/");u.length<=ye&&!Ts(p,n)&&a.push({filePath:p,content:u})}return a.push(...await ym(t,n)),{files:o.map(c=>At.relative(t,c)),commands:r,sources:a}}async function ym(t,e){let n=[];for(let s of yt(t,[...rf])){if(Ts(s,e))continue;let i=he(t,s);if(i)try{let o=await Vt.stat(i);if(!o.isFile()||o.size>ye)continue;n.push({filePath:s,content:await Vt.readFile(i,"utf-8")})}catch{}}return n}function Ts(t,e){if(e.length===0)return!1;let n=[t],s=t.split("/");for(let i=1;i<s.length;i++){let o=s.slice(0,i).join("/");n.push(o,`${o}/`)}return n.some(i=>bm.default.isMatch(i,e,{dot:!0}))}async function IA(t,e,n){let s;try{let r=await Vt.stat(Dc(t,e));if(!r.isFile()||r.size>ye)return;s=await Vt.readFile(Dc(t,e))}catch{return}if(sn(s))return;let i=s.toString("utf-8"),o=i.split(`
65
76
  `);return i.endsWith(`
66
- `)&&r.pop(),{path:n,relativePath:e,fileType:"skill",content:i,sections:Wt(i,n,e),lineCount:r.length,charCount:i.length,estimatedTokens:Math.round(i.length/4)}}function PE(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 ps(t){let e=mt.resolve(t.repoPath),n=new Ee(e,{...t.knownPaths!==void 0?{knownPaths:t.knownPaths}:{},...t.knownPathsComplete!==void 0?{knownPathsComplete:t.knownPathsComplete}:{}}),{files:s,aliases:i}=await yi({...t,repoPath:e},n),r=[],o=[];for(let x of s)(xl(x.fileType)?o:r).push(x);let a=Na(e,t),c=new Set(s.map(x=>x.path));for(let x of a.allSkills??[]){let w=mt.resolve(e,x);if(c.has(w))continue;let _=await $E(e,x,w);_&&o.push(_)}o.sort((x,w)=>x.path.localeCompare(w.path));let l=t.projectType&&t.projectType!=="auto"?t.projectType:await Jn(e,n);l==="unknown"&&(l=ra(r));let[u,f,d,p,h,m]=await Promise.all([nc(e,"package.json"),nc(e,"pyproject.toml"),nc(e,"requirements.txt"),Promise.resolve(RE(n,EE)),AE(e,n,t.exclude),Qa(e)]),g=await qp(e,u,x=>ds(x,t.exclude??[])),y=Li(e,".",n),b={};u&&(b.packageJson=u),f&&(b.pyproject=f),d!==void 0&&(b.requirements=d);let v=t.targetModel?Ja(t.targetModel):void 0;return{repoRoot:e,tree:n,files:r,projectType:l,manifests:b,packageJson:vh(u,p),workflows:h,workspaces:g.manifests,workspacesTruncated:g.truncated,...y?{makefile:y}:{},aiConfig:a,...t.exclude&&t.exclude.length>0?{exclude:t.exclude}:{},metrics:PE(r,o),contextBudget:t.contextBudget??v?.contextBudget,fileContextBudget:t.fileContextBudget??v?.fileContextBudget,vagueGuidanceSeverity:t.vagueGuidanceSeverity,onDemandFiles:o,...i.length>0?{aliasFiles:i}:{},customRules:m}}var TE=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"]),IE=new Set(["npm","pnpm","yarn","npx","bun","bunx","deno","node","corepack","nvm","fnm","volta","git"]),OE=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"]),LE=/^(?:your|my|some|example|sample|foo|bar|baz|pkg|package)(?:-|$)/,NE=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"]),jE=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"]),rc=/\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,oc={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}},ME=/(?:^|[\s;&|(])(?:cd|pushd)\s+\S/,DE=new Set(["","sh","bash","shell","zsh","console","shellsession","terminal","powershell","ps1","pwsh","cmd"]),FE=new Set(["","js","jsx","ts","tsx","javascript","typescript","mjs","cjs","mts","cts","vue","svelte","astro"]),xh=/(`+)([^`\n]+)\1/g;function HE(t){let e=[],n=[],s=!1;for(let i of Se(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}),ME.test(r)&&(s=!0);else if(i.kind==="text"){n.push({line:i.lineNumber,text:r});let o=new RegExp(xh.source,xh.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 $h=/^(@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/,Ph=/\.(?: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,BE=/^[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 Th(t){let e=t.replace(/^['"]|['"]$/g,""),n=/^(@[^/@\s]+\/[^/@\s]+|[^/@\s][^@/\s]*)(?:@\S*)?$/.exec(e);if(!n)return;let s=n[1];return $h.test(s)&&!Ph.test(s)?s:void 0}function WE(t){if(/^[./~#$]|^@\/|:|\s|\*|<|\{/.test(t)||BE.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 Ph.test(e[1])?void 0:e[1]}var Ih=new Set(["-C","--cwd","--prefix","--dir"]),_h=new Set(["--filter","-F","--workspace",...Ih]),GE=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"]),UE={npm:new Set(["install","i","add"]),pnpm:new Set(["add","install","i"]),yarn:new Set(["add"]),bun:new Set(["add","install","i"])};function VE(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?UE[r]:void 0;if(!o||i.some(f=>Ih.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(_h.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(GE.has(f)||r==="pnpm"&&f==="-w"||f.includes("="))continue;if(_h.has(f)||r==="npm"&&f==="-w"){a++;continue}u=!0;break}let d=Th(f);if(d===void 0){u=!0;break}l.push(d)}u||n.push(...l)}return n}var Sh=[/\bimport\s+(?:type\s+)?[^'"`;]*?\sfrom\s+['"]([^'"]+)['"]/g,/\bimport\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\(\s*['"]([^'"]+)['"]\s*\)/g,/^\s*\}?\s*from\s+['"]([^'"]+)['"]/g],zE=/\bimport\s+['"]([^'"]+)['"]/g;function qE(t,e){let n=[],s=e?Sh:[...Sh,zE];for(let i of s){let r=new RegExp(i.source,i.flags),o;for(;(o=r.exec(t))!==null;){let a=WE(o[1]);a!==void 0&&n.push(a)}}return n}var KE=[/\b(?:package|library|dependency)\s+`([^`\s]+)`/gi,/`([^`\s]+)`\s+(?:npm\s+)?(?:package|library|dependency)\b/gi];function YE(t){let e=[];for(let n of KE){let s=new RegExp(n.source,n.flags),i;for(;(i=s.exec(t))!==null;){let r=Th(i[1]);r!==void 0&&e.push(r)}}return e}var JE=/(?:^|[\s;&|(])(?:(?:npx|bunx|yarn|pnpm\s+(?:exec|dlx)|npm\s+exec)\s+)?(react-scripts|tslint|node-sass)(?=\s|$)/g;function XE(t){let e=/(?:^|\s)(?:#|\/\/|\/\*|--)\s*(.*)$/.exec(t);return e?e[1]:""}function ZE(t){let e=[],{segments:n,prose:s}=HE(t),i=(r,o,a,c)=>{e.push({pkg:r,kind:o,file:t,line:a,text:c})};for(let r of n){if(rc.test(r.fenced?XE(r.lineText):r.lineText))continue;let o=r.text;if(!r.fenced||DE.has(r.lang)){for(let l of VE(o,r.afterCd))i(l,"install",r.line,r.lineText);let a=new RegExp(JE.source,"g"),c;for(;(c=a.exec(o))!==null;)oc[c[1]]?.command&&i(c[1],"command",r.line,r.lineText)}if(!r.fenced||FE.has(r.lang)){let a=!r.fenced||r.lang==="";for(let c of qE(o,a))i(c,"import",r.line,r.lineText)}!r.fenced&&$h.test(o)&&oc[o]?.distinctive&&i(o,"span",r.line,r.lineText)}for(let{line:r,text:o}of s)if(!rc.test(o))for(let a of YE(o))i(a,"qualified",r,o);return e}var Eh=200,Oh=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/worktrees/**","**/.worktrees/**","**/vendor/**","**/target/**","**/.turbo/**","**/coverage/**","**/Library/**","**/Temp/**"],QE=new Set(["vscode","k6"]),ek={jest:["vitest"],vitest:["jest"],"@playwright/test":["cypress"],cypress:["@playwright/test"]};function ac(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(gt.posix.basename(e.dir)),e.name&&t.localNames.add(e.name.replace(/^@[^/]+\//,""))}function tk(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=rs(".",JSON.stringify({dependencies:i,devDependencies:r,peerDependencies:o}));a&&ac(e,a)}for(let i of t.workspaces??[])ac(e,i);return e}function Bi(t,e){try{let n=ie(t,e);if(!n)return;let s=Wi.statSync(n);return!s.isFile()||s.size>ce?void 0:Wi.readFileSync(n,"utf-8")}catch{return}}function kh(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]!==`
77
+ `)&&o.pop(),{path:n,relativePath:e,fileType:"skill",content:i,sections:nn(i,n,e),lineCount:o.length,charCount:i.length,estimatedTokens:Math.round(i.length/4)}}function OA(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 Ps(t){let e=At.resolve(t.repoPath),n=new Le(e,{...t.knownPaths!==void 0?{knownPaths:t.knownPaths}:{},...t.knownPathsComplete!==void 0?{knownPathsComplete:t.knownPathsComplete}:{}}),{files:s,aliases:i}=await Li({...t,repoPath:e},n),o=[],r=[];for(let S of s)(su(S.fileType)?r:o).push(S);let a=rc(e,t),c=new Set(s.map(S=>S.path));for(let S of a.allSkills??[]){let C=At.resolve(e,S);if(c.has(C))continue;let v=await IA(e,S,C);v&&r.push(v)}r.sort((S,C)=>S.path.localeCompare(C.path));let l=t.projectType&&t.projectType!=="auto"?t.projectType:await ps(e,n);l==="unknown"&&(l=Aa(o));let[u,p,d,h,f,m]=await Promise.all([jc(e,"package.json"),jc(e,"pyproject.toml"),jc(e,"requirements.txt"),Promise.resolve(TA(n,CA)),$A(e,n,t.exclude),Lc(e)]),g=await Nh(e,u,S=>Ts(S,t.exclude??[])),y=Zi(e,".",n),b={};u&&(b.packageJson=u),p&&(b.pyproject=p),d!==void 0&&(b.requirements=d);let w=t.targetModel?$c(t.targetModel):void 0;return{repoRoot:e,tree:n,files:o,projectType:l,manifests:b,packageJson:wm(u,h),workflows:f,workspaces:g.manifests,workspacesTruncated:g.truncated,...y?{makefile:y}:{},aiConfig:a,...t.exclude&&t.exclude.length>0?{exclude:t.exclude}:{},metrics:OA(o,r),contextBudget:t.contextBudget??w?.contextBudget,fileContextBudget:t.fileContextBudget??w?.fileContextBudget,vagueGuidanceSeverity:t.vagueGuidanceSeverity,onDemandFiles:r,...i.length>0?{aliasFiles:i}:{},customRules:m}}var LA=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"]),NA=new Set(["npm","pnpm","yarn","npx","bun","bunx","deno","node","corepack","nvm","fnm","volta","git"]),MA=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"]),jA=/^(?:your|my|some|example|sample|foo|bar|baz|pkg|package)(?:-|$)/,DA=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"]),FA=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"]),Hc=/\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,Bc={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}},HA=/(?:^|[\s;&|(])(?:cd|pushd)\s+\S/,BA=new Set(["","sh","bash","shell","zsh","console","shellsession","terminal","powershell","ps1","pwsh","cmd"]),GA=new Set(["","js","jsx","ts","tsx","javascript","typescript","mjs","cjs","mts","cts","vue","svelte","astro"]),vm=/(`+)([^`\n]+)\1/g;function WA(t){let e=[],n=[],s=!1;for(let i of we(t.content)){let o=i.text.replace(/\r$/,"");if(i.kind==="open"&&(s=!1),i.kind==="content")e.push({text:o,line:i.lineNumber,fenced:!0,lang:i.lang,lineText:o,afterCd:s}),HA.test(o)&&(s=!0);else if(i.kind==="text"){n.push({line:i.lineNumber,text:o});let r=new RegExp(vm.source,vm.flags),a;for(;(a=r.exec(o))!==null;)e.push({text:a[2].trim(),line:i.lineNumber,fenced:!1,lang:"",lineText:o,afterCd:!1})}}return{segments:e,prose:n}}var Rm=/^(@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/,Tm=/\.(?: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,VA=/^[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 Pm(t){let e=t.replace(/^['"]|['"]$/g,""),n=/^(@[^/@\s]+\/[^/@\s]+|[^/@\s][^@/\s]*)(?:@\S*)?$/.exec(e);if(!n)return;let s=n[1];return Rm.test(s)&&!Tm.test(s)?s:void 0}function UA(t){if(/^[./~#$]|^@\/|:|\s|\*|<|\{/.test(t)||VA.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 Tm.test(e[1])?void 0:e[1]}var $m=new Set(["-C","--cwd","--prefix","--dir"]),Sm=new Set(["--filter","-F","--workspace",...$m]),zA=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"]),qA={npm:new Set(["install","i","add"]),pnpm:new Set(["add","install","i"]),yarn:new Set(["add"]),bun:new Set(["add","install","i"])};function KA(t,e){if(e)return[];let n=[];for(let s of t.split(/&&|\|\||[;|]/)){let i=s.replace(/^\s*(?:[$>%]\s+|[({]\s*)+/,"").trim().split(/\s+/),o=i[0];if(o==="cd"||o==="pushd")break;let r=o?qA[o]:void 0;if(!r||i.some(p=>$m.has(p)||/^--(?:prefix|cwd|dir)=/.test(p)))continue;let a=1,c=!1;for(;a<i.length;a++){let p=i[a];if(r.has(p)){c=!0,a++;break}if(Sm.has(p)||o==="npm"&&p==="-w"||o==="yarn"&&p==="workspace"){a++;continue}if(!p.startsWith("-"))break}if(!c)continue;let l=[],u=!1;for(;a<i.length;a++){let p=i[a];if(p.startsWith("#"))break;if(p==="-g"||p==="--global"||p==="--location=global"){u=!0;break}if(p.startsWith("-")){if(zA.has(p)||o==="pnpm"&&p==="-w"||p.includes("="))continue;if(Sm.has(p)||o==="npm"&&p==="-w"){a++;continue}u=!0;break}let d=Pm(p);if(d===void 0){u=!0;break}l.push(d)}u||n.push(...l)}return n}var _m=[/\bimport\s+(?:type\s+)?[^'"`;]*?\sfrom\s+['"]([^'"]+)['"]/g,/\bimport\(\s*['"]([^'"]+)['"]\s*\)/g,/\brequire\(\s*['"]([^'"]+)['"]\s*\)/g,/^\s*\}?\s*from\s+['"]([^'"]+)['"]/g],YA=/\bimport\s+['"]([^'"]+)['"]/g;function XA(t,e){let n=[],s=e?_m:[..._m,YA];for(let i of s){let o=new RegExp(i.source,i.flags),r;for(;(r=o.exec(t))!==null;){let a=UA(r[1]);a!==void 0&&n.push(a)}}return n}var JA=[/\b(?:package|library|dependency)\s+`([^`\s]+)`/gi,/`([^`\s]+)`\s+(?:npm\s+)?(?:package|library|dependency)\b/gi];function ZA(t){let e=[];for(let n of JA){let s=new RegExp(n.source,n.flags),i;for(;(i=s.exec(t))!==null;){let o=Pm(i[1]);o!==void 0&&e.push(o)}}return e}var QA=/(?:^|[\s;&|(])(?:(?:npx|bunx|yarn|pnpm\s+(?:exec|dlx)|npm\s+exec)\s+)?(react-scripts|tslint|node-sass)(?=\s|$)/g;function eC(t){let e=/(?:^|\s)(?:#|\/\/|\/\*|--)\s*(.*)$/.exec(t);return e?e[1]:""}function tC(t){let e=[],{segments:n,prose:s}=WA(t),i=(o,r,a,c)=>{e.push({pkg:o,kind:r,file:t,line:a,text:c})};for(let o of n){if(Hc.test(o.fenced?eC(o.lineText):o.lineText))continue;let r=o.text;if(!o.fenced||BA.has(o.lang)){for(let l of KA(r,o.afterCd))i(l,"install",o.line,o.lineText);let a=new RegExp(QA.source,"g"),c;for(;(c=a.exec(r))!==null;)Bc[c[1]]?.command&&i(c[1],"command",o.line,o.lineText)}if(!o.fenced||GA.has(o.lang)){let a=!o.fenced||o.lang==="";for(let c of XA(r,a))i(c,"import",o.line,o.lineText)}!o.fenced&&Rm.test(r)&&Bc[r]?.distinctive&&i(r,"span",o.line,o.lineText)}for(let{line:o,text:r}of s)if(!Hc.test(r))for(let a of ZA(r))i(a,"qualified",o,r);return e}var xm=200,Im=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/worktrees/**","**/.worktrees/**","**/vendor/**","**/target/**","**/.turbo/**","**/coverage/**","**/Library/**","**/Temp/**"],nC=new Set(["vscode","k6"]),sC={jest:["vitest"],vitest:["jest"],"@playwright/test":["cypress"],cypress:["@playwright/test"]};function Gc(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(Ct.posix.basename(e.dir)),e.name&&t.localNames.add(e.name.replace(/^@[^/]+\//,""))}function iC(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:o,peerDependencies:r}=t.packageJson,a=_s(".",JSON.stringify({dependencies:i,devDependencies:o,peerDependencies:r}));a&&Gc(e,a)}for(let i of t.workspaces??[])Gc(e,i);return e}function co(t,e){try{let n=he(t,e);if(!n)return;let s=lo.statSync(n);return!s.isFile()||s.size>ye?void 0:lo.readFileSync(n,"utf-8")}catch{return}}function km(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
78
  `;)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 nk(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 sk(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=Bi(t.repoRoot,s(i)),o=r===void 0?void 0:kh(r);for(let a of Object.keys(o?.compilerOptions?.paths??{}))nk(e,a)}for(let i of["deno.json","deno.jsonc"]){let r=Bi(t.repoRoot,s(i)),o=r===void 0?void 0:kh(r);for(let a of Object.keys(o?.imports??{}))e.declared.add(a.replace(/\/$/,""))}}}var Rh=/^\s+(['"]?)(@?[^'":\s]+(?:\/[^'":\s]+)?)\1\s*:\s*['"]?([^'"#\s]+)['"]?/;function ik(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=Rh.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=Rh.exec(i);o&&s&&(e.named[s][o[2]]=o[3])}}return e}function rk(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 Gi(t,e){if(e.lazyLoaded)return;e.lazyLoaded=!0;let n=t.exclude??[],s=[];try{s=lc.default.sync(["**/package.json"],{cwd:t.repoRoot,ignore:Oh,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,suppressErrors:!0})}catch{e.truncated=!0}s=s.filter(r=>!ds(r,n)&&!e.dirs.has(gt.posix.dirname(r))).sort(),s.length>Eh&&(e.truncated=!0);for(let r of s.slice(0,Eh)){let o=Bi(t.repoRoot,r),a=o===void 0?void 0:rs(gt.posix.dirname(r),o);a&&ac(e,a)}sk(t,e);let i=Bi(t.repoRoot,"pnpm-workspace.yaml");i!==void 0&&(e.catalogs=ik(i))}function cc(t){return t.startsWith("@")?t.slice(0,t.indexOf("/")):void 0}function ok(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 Lh(t,e){let n=null;for(let s of e)for(let i of t.specs.get(s)??[]){let r=rk(t,s,i),o=r===void 0?null:ok(r);if(r===void 0||o===null)return null;(n===null||o<n.major)&&(n={major:o,spec:r})}return n}function hs(t,e){let n=Ah.createHash("sha1").update(`dep-staleness:${t}:${e}`).digest("hex").slice(0,12);return`dep-staleness-${t}-${n}`}function ms(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 gs(t){return t.map(e=>({filePath:e.file.path,startLine:e.line,endLine:e.line}))}function ys(t){return`${t.file.relativePath??gt.basename(t.file.path)}:${t.line}: "${Z(t.text,100)}"`}function ak(t){let e=cc(t);return e!==void 0?NE.has(e.slice(1)):OE.has(t)||LE.test(t)}function ck(t,...e){return t.exists(gt.posix.join(...e))}function lk(t,e,n){for(let s of new Set([".",...e.dirs]))for(let i of[".","src"])if(ck(t,s,i,n))return!0;return!1}function uk(t){return t.startsWith("@")?`@types/${t.slice(1).replace("/","__")}`:`@types/${t}`}function fk(t,e,n){let s=new Map;for(let o of e)for(let a of ZE(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(uk(c));return a(o)?!0:(Gi(t,n),a(o)||kn(t,o))};for(let[o,a]of[...s].sort(([c],[l])=>c.localeCompare(l))){let c=o.startsWith("@")?o:o.split("/")[0];if(TE.has(c)||IE.has(c)||QE.has(c)||ak(o))continue;let l=oc[o];if(l){let h=r(o),m=h||n.truncated?"info":"warning",g=ms(a);i.push({id:hs("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(y=>y.file.path),locations:gs(g),evidence:[...g.slice(0,3).map(ys),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||ek[o]?.some(h=>r(h)))continue;let f=cc(o),d=u.some(h=>h.kind==="install");if(!d&&(f===void 0&&(jE.has(o)||lk(V(t),n,o))||n.aliasNames.has(o)||f!==void 0&&n.aliasScopes.has(f)||n.localNames.has(o)||f!==void 0&&![...n.declared].some(h=>cc(h)===f)))continue;let p=ms(u);i.push({id:hs("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:gs(p),evidence:[...p.slice(0,3).map(ys),`${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 ic=/\b(?:before|old(?:er)?|previously|legacy|prior|outdated|anti-?patterns?|bad|wrong)\b|❌/i,dk=/^\s{0,3}#{1,6}\s/;function uc(t,e,n,s){let i=[];for(let r of t){let o=Se(r.content),a=[],c=[""],l=[""],u=[],f=0,d=-1;o.forEach((h,m)=>{h.kind==="text"&&dk.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)||rc.test(g)||n.test(g)||s.test(c[a[m]])||ic.test(g)||ic.test(l[a[m]])||ic.test(p(m))||i.push({file:r,line:h.lineNumber,text:g})})}return i}var pk=/\bReactDOM\.render\b/,hk=/\bReact\s*(?:v\.?\s*)?(?:0|1[0-7])\b/i,mk=/\b(?:createRoot|hydrateRoot)\b/;function gk(t,e,n){let s=ms(uc(e,pk,hk,mk));if(s.length===0)return[];Gi(t,n);let i=Lh(n,["react","react-dom"]);if(i===null||i.major<18)return[];let r=i.major>=19;return[{id:hs("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:gs(s),evidence:[...s.slice(0,3).map(ys),`package.json declares react ${i.spec}`],recommendation:"Replace the `ReactDOM.render(...)` guidance with `createRoot(container).render(...)` from `react-dom/client`.",confidence:.8}]}var yk=/\bgetInitialProps\b/,bk=/\bpages\s*(?:router|dir(?:ectory)?)\b|\bpages\//i,wk=/\bServer Components?\b|\broute handlers?\b|\bapp\s+router\b/i,vk=/^(?:layout|page)\.(?:tsx|ts|jsx|js|mdx)$/;function xk(t,e){for(let n of["app","src/app"]){let s=t.entries(gt.posix.join(e,n));if(typeof s!="string"){for(let i of s.keys())if(vk.test(i))return!0}}return!1}function _k(t,e){return["pages","src/pages"].some(n=>t.isDir(gt.posix.join(e,n)))}function Sk(t,e,n){let s=ms(uc(e,yk,bk,wk));if(s.length===0)return[];Gi(t,n);let i=n.nextDirs;if(i.length===0)return[];let r=V(t);return i.some(o=>_k(r,o))?[]:i.some(o=>xk(r,o))?[{id:hs("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(o=>o.file.path),locations:gs(s),evidence:[...s.slice(0,3).map(ys),"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 Ek=/\bNgModules?\b/,Ch=/\bstandalone\b/i;function kk(t){try{return lc.default.sync(["**/*.module.ts"],{cwd:t,ignore:Oh,deep:8,onlyFiles:!0,followSymbolicLinks:!1,suppressErrors:!0}).some(n=>ie(t,n)!==null)}catch{return!0}}function Rk(t,e,n){let s=ms(uc(e,Ek,Ch,Ch));if(s.length===0)return[];Gi(t,n);let i=Lh(n,["@angular/core"]);return i===null||i.major<17?[]:kk(t.repoRoot)?[]:[{id:hs("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:gs(s),evidence:[...s.slice(0,3).map(ys),`package.json declares @angular/core ${i.spec}; no *.module.ts files`],recommendation:"Describe standalone components (`standalone: true`, `bootstrapApplication`) instead of NgModules.",confidence:.6}]}function fc(t){let e=t.files.filter(s=>he.has(s.fileType));if(e.length===0)return[];let n=tk(t);return n.any?[...fk(t,e,n),...gk(t,e,n),...Sk(t,e,n),...Rk(t,e,n)].sort((s,i)=>s.id.localeCompare(i.id)):[]}var jh=R(require("node:crypto"),1),Mh=R(require("node:path"),1),Ck=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i,Ak=/^[\w.-]+\/[\w.-]+(?:\/[\w./-]+)?$/,$k=/^[\w./+-]+$/,Pk=new Set(["actions","github"]),Tk=/^(\s*)(-\s+)?([\w.-]+)\s*:(?:\s+(.*))?$/,Ik=/^\s*-\s+(\{.*)$/,Ok=/^[|>][+-]?\d*\s*(?:#.*)?$/,Lk=new Set(["with","env","secrets","inputs","outputs"]);function Dh(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 Nk(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 Dh(o[1])}}function Fh(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=Ik.exec(r);if(a){let p=Nk(a[1]);p&&n.push({ref:p,line:i+1});continue}let c=Tk.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=Dh(f);p&&n.push({ref:p,line:i+1});continue}if(Ok.test(d)){s=l;continue}(d===""||d.startsWith("#"))&&Lk.has(u)&&(s=l)}return n}function jk(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(Ck.test(i))return;let r=Ak.test(s)&&$k.test(i);return{...t,displayable:r,action:s,version:i,owner:r?s.split("/")[0].toLowerCase():""}}function Nh(t){return jh.createHash("sha1").update(t).digest("hex").slice(0,12)}function bs(t){return t.replace(/`/g,"'")}function Mk(t,e){let{filePath:n,lines:s,use:i}=e,r=Mh.resolve(t.repoRoot,n),o={id:`action-pin-${Nh(`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 ${Nh(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=Pk.has(i.owner),[l,u]=i.action.split("/"),f=bs(i.ref);return{...o,severity:c?"info":"warning",title:`GitHub Action \`${f}\` is not pinned to a commit SHA`,summary:`${n} references \`${bs(i.action)}\` at \`${bs(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: ${bs(i.action)}@<40-char-sha> # ${bs(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 dc(t){let e=t.workflows.sources??[],n=new Map;for(let s of e)for(let i of Fh(s.content)){let r=jk(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=>Mk(t,n.get(s)))}var pc=R(require("node:crypto"),1),Xt=R(require("node:path"),1);var Dk=[/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],Fk=/\b(AGENTS|CLAUDE)\.md\b/gi;function Hk(t){let e=Xt.basename(t.path).toLowerCase();for(let n of Dk)for(let s of t.content.matchAll(new RegExp(n.source,"gi"))){let i=t.content.lastIndexOf(`
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(Fk)].map(l=>`${l[1].toLowerCase()}.md`);if(!(a.length>0&&a.every(l=>l!==e)))return s[0]}}function Hh(t){if(t.length===0)return[];let e=[],n=new Map;for(let a of t){let c=Hk(a);c!==void 0&&n.set(a,c)}let s=[...n.keys()];function i(a){let c=pc.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=>Xt.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=>`${Xt.basename(a.path)}: "${Z(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=>Xt.basename(a.path).toLowerCase()==="agents.md")||s[0];if(o){let a=c=>{let l=c.split(`
79
+ `}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 oC(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 rC(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 o=co(t.repoRoot,s(i)),r=o===void 0?void 0:km(o);for(let a of Object.keys(r?.compilerOptions?.paths??{}))oC(e,a)}for(let i of["deno.json","deno.jsonc"]){let o=co(t.repoRoot,s(i)),r=o===void 0?void 0:km(o);for(let a of Object.keys(r?.imports??{}))e.declared.add(a.replace(/\/$/,""))}}}var Em=/^\s+(['"]?)(@?[^'":\s]+(?:\/[^'":\s]+)?)\1\s*:\s*['"]?([^'"#\s]+)['"]?/;function aC(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 o=Em.exec(i);o&&(e.default[o[2]]=o[3])}else if(n==="catalogs"){let o=/^ {1,3}(['"]?)([^'":\s]+)\1\s*:\s*(?:#.*)?$/.exec(i);if(o){s=o[2],e.named[s]??={};continue}let r=Em.exec(i);r&&s&&(e.named[s][r[2]]=r[3])}}return e}function cC(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 uo(t,e){if(e.lazyLoaded)return;e.lazyLoaded=!0;let n=t.exclude??[],s=[];try{s=Vc.default.sync(["**/package.json"],{cwd:t.repoRoot,ignore:Im,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,suppressErrors:!0})}catch{e.truncated=!0}s=s.filter(o=>!Ts(o,n)&&!e.dirs.has(Ct.posix.dirname(o))).sort(),s.length>xm&&(e.truncated=!0);for(let o of s.slice(0,xm)){let r=co(t.repoRoot,o),a=r===void 0?void 0:_s(Ct.posix.dirname(o),r);a&&Gc(e,a)}rC(t,e);let i=co(t.repoRoot,"pnpm-workspace.yaml");i!==void 0&&(e.catalogs=aC(i))}function Wc(t){return t.startsWith("@")?t.slice(0,t.indexOf("/")):void 0}function lC(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 Om(t,e){let n=null;for(let s of e)for(let i of t.specs.get(s)??[]){let o=cC(t,s,i),r=o===void 0?null:lC(o);if(o===void 0||r===null)return null;(n===null||r<n.major)&&(n={major:r,spec:o})}return n}function $s(t,e){let n=Cm.createHash("sha1").update(`dep-staleness:${t}:${e}`).digest("hex").slice(0,12);return`dep-staleness-${t}-${n}`}function Is(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 Os(t){return t.map(e=>({filePath:e.file.path,startLine:e.line,endLine:e.line}))}function Ls(t){return`${t.file.relativePath??Ct.basename(t.file.path)}:${t.line}: "${se(t.text,100)}"`}function uC(t){let e=Wc(t);return e!==void 0?DA.has(e.slice(1)):MA.has(t)||jA.test(t)}function dC(t,...e){return t.exists(Ct.posix.join(...e))}function pC(t,e,n){for(let s of new Set([".",...e.dirs]))for(let i of[".","src"])if(dC(t,s,i,n))return!0;return!1}function fC(t){return t.startsWith("@")?`@types/${t.slice(1).replace("/","__")}`:`@types/${t}`}function hC(t,e,n){let s=new Map;for(let r of e)for(let a of tC(r))s.set(a.pkg,[...s.get(a.pkg)??[],a]);if(s.size===0)return[];let i=[],o=r=>{let a=c=>n.declared.has(c)||n.declared.has(fC(c));return a(r)?!0:(uo(t,n),a(r)||Bn(t,r))};for(let[r,a]of[...s].sort(([c],[l])=>c.localeCompare(l))){let c=r.startsWith("@")?r:r.split("/")[0];if(LA.has(c)||NA.has(c)||nC.has(c)||uC(r))continue;let l=Bc[r];if(l){let f=o(r),m=f||n.truncated?"info":"warning",g=Is(a);i.push({id:$s("deprecated",r),severity:m,category:"stale_instruction",title:`Instructions point at a deprecated package: ${r}`,summary:`Instruction files mention \`${r}\`, which ${l.status}. `+(f?"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(y=>y.file.path),locations:Os(g),evidence:[...g.slice(0,3).map(Ls),f?`${r} is declared in a package.json`:`${r} is not declared in any package.json`],recommendation:`Update the instructions to recommend ${l.replacement}${f?", and plan the dependency migration":""}; if the repo deliberately keeps ${r}, note why.`,confidence:.7});continue}let u=a.filter(f=>f.kind==="install"||f.kind==="import");if(u.length===0||o(r)||n.truncated||sC[r]?.some(f=>o(f)))continue;let p=Wc(r),d=u.some(f=>f.kind==="install");if(!d&&(p===void 0&&(FA.has(r)||pC(Z(t),n,r))||n.aliasNames.has(r)||p!==void 0&&n.aliasScopes.has(p)||n.localNames.has(r)||p!==void 0&&![...n.declared].some(f=>Wc(f)===p)))continue;let h=Is(u);i.push({id:$s("missing-package",r),severity:d?"warning":"info",category:"stale_instruction",title:`Package named in instructions is not in any package.json: ${r}`,summary:`Instruction files refer to the npm package \`${r}\`, 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:h.map(f=>f.file.path),locations:Os(h),evidence:[...h.slice(0,3).map(Ls),`${r} is not declared in any package.json`],recommendation:`Remove or update the mention of ${r}, or add it to package.json if the repo really depends on it.`,confidence:.5})}return i}var Fc=/\b(?:before|old(?:er)?|previously|legacy|prior|outdated|anti-?patterns?|bad|wrong)\b|❌/i,mC=/^\s{0,3}#{1,6}\s/;function Uc(t,e,n,s){let i=[];for(let o of t){let r=we(o.content),a=[],c=[""],l=[""],u=[],p=0,d=-1;r.forEach((f,m)=>{f.kind==="text"&&mC.test(f.text)&&(p++,c[p]="",l[p]=f.text),f.kind==="open"&&(d=m),u[m]=f.inFence?d:-1,a[m]=p,c[p]+=`${f.text}
80
+ `});let h=f=>{for(let m=(u[f]>=0?u[f]:f)-1;m>=0;m--)if(r[m].text.trim()!=="")return r[m].text;return""};r.forEach((f,m)=>{if(f.kind==="open"||f.kind==="close"||f.inFence&&(f.lang==="diff"||f.lang==="patch"))return;let g=f.text.replace(/\r$/,"");!e.test(g)||Hc.test(g)||n.test(g)||s.test(c[a[m]])||Fc.test(g)||Fc.test(l[a[m]])||Fc.test(h(m))||i.push({file:o,line:f.lineNumber,text:g})})}return i}var gC=/\bReactDOM\.render\b/,yC=/\bReact\s*(?:v\.?\s*)?(?:0|1[0-7])\b/i,bC=/\b(?:createRoot|hydrateRoot)\b/;function wC(t,e,n){let s=Is(Uc(e,gC,yC,bC));if(s.length===0)return[];uo(t,n);let i=Om(n,["react","react-dom"]);if(i===null||i.major<18)return[];let o=i.major>=19;return[{id:$s("react-dom-render","ReactDOM.render"),severity:o?"high":"warning",category:"stale_instruction",title:o?"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}. `+(o?"`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(r=>r.file.path),locations:Os(s),evidence:[...s.slice(0,3).map(Ls),`package.json declares react ${i.spec}`],recommendation:"Replace the `ReactDOM.render(...)` guidance with `createRoot(container).render(...)` from `react-dom/client`.",confidence:.8}]}var vC=/\bgetInitialProps\b/,SC=/\bpages\s*(?:router|dir(?:ectory)?)\b|\bpages\//i,_C=/\bServer Components?\b|\broute handlers?\b|\bapp\s+router\b/i,xC=/^(?:layout|page)\.(?:tsx|ts|jsx|js|mdx)$/;function kC(t,e){for(let n of["app","src/app"]){let s=t.entries(Ct.posix.join(e,n));if(typeof s!="string"){for(let i of s.keys())if(xC.test(i))return!0}}return!1}function EC(t,e){return["pages","src/pages"].some(n=>t.isDir(Ct.posix.join(e,n)))}function AC(t,e,n){let s=Is(Uc(e,vC,SC,_C));if(s.length===0)return[];uo(t,n);let i=n.nextDirs;if(i.length===0)return[];let o=Z(t);return i.some(r=>EC(o,r))?[]:i.some(r=>kC(o,r))?[{id:$s("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:Os(s),evidence:[...s.slice(0,3).map(Ls),"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 CC=/\bNgModules?\b/,Am=/\bstandalone\b/i;function RC(t){try{return Vc.default.sync(["**/*.module.ts"],{cwd:t,ignore:Im,deep:8,onlyFiles:!0,followSymbolicLinks:!1,suppressErrors:!0}).some(n=>he(t,n)!==null)}catch{return!0}}function TC(t,e,n){let s=Is(Uc(e,CC,Am,Am));if(s.length===0)return[];uo(t,n);let i=Om(n,["@angular/core"]);return i===null||i.major<17?[]:RC(t.repoRoot)?[]:[{id:$s("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(o=>o.file.path),locations:Os(s),evidence:[...s.slice(0,3).map(Ls),`package.json declares @angular/core ${i.spec}; no *.module.ts files`],recommendation:"Describe standalone components (`standalone: true`, `bootstrapApplication`) instead of NgModules.",confidence:.6}]}function zc(t){let e=t.files.filter(s=>Ae.has(s.fileType));if(e.length===0)return[];let n=iC(t);return n.any?[...hC(t,e,n),...wC(t,e,n),...AC(t,e,n),...TC(t,e,n)].sort((s,i)=>s.id.localeCompare(i.id)):[]}var Lm=R(require("node:crypto"),1),Nm=R(require("node:path"),1);var PC=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i,$C=/^[\w.-]+\/[\w.-]+(?:\/[\w./-]+)?$/,IC=/^[\w./+-]+$/,OC=new Set(["actions","github"]),LC=/^(\s*)(-\s+)?([\w.-]+)\s*:(?:\s+(.*))?$/,NC=/^\s*-\s+(\{.*)$/,MC=/^[|>][+-]?\d*\s*(?:#.*)?$/,jC=new Set(["with","env","secrets","inputs","outputs"]);function Mm(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 DC(t){let e=[],n=0,s="",i="";for(let o of t){if(s){o===s&&(s=""),n===1&&(i+=o);continue}if(o==='"'||o==="'"){s=o,n===1&&(i+=o);continue}if(o==="{"||o==="["){n++,n>1&&(i+=o);continue}if(o==="}"||o==="]"){if(n--,n===0)break;i+=o;continue}if(o===","&&n===1){e.push(i),i="";continue}n>=1&&(i+=o)}e.push(i);for(let o of e){let r=/^\s*uses\s*:\s*(.*)$/.exec(o);if(r)return Mm(r[1])}}function jm(t){let e=t.split(/\r?\n/),n=[],s=-1;for(let i=0;i<e.length;i++){let o=e[i];if(o.trim()==="")continue;let r=/^\s*/.exec(o)[0].length;if(s>=0){if(r>s)continue;s=-1}if(/^\s*#/.test(o))continue;let a=NC.exec(o);if(a){let h=DC(a[1]);h&&n.push({ref:h,line:i+1});continue}let c=LC.exec(o);if(!c)continue;let l=c[1].length+(c[2]?.length??0),u=c[3],p=c[4]??"",d=p.trim();if(u==="uses"){let h=Mm(p);h&&n.push({ref:h,line:i+1});continue}if(MC.test(d)){s=l;continue}(d===""||d.startsWith("#"))&&jC.has(u)&&(s=l)}return n}function FC(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(PC.test(i))return;let o=$C.test(s)&&IC.test(i);return{...t,displayable:o,action:s,version:i,owner:o?s.split("/")[0].toLowerCase():""}}function Dm(t){return Lm.createHash("sha1").update(t).digest("hex").slice(0,12)}function Ns(t){return t.replace(/`/g,"'")}function HC(t,e){let n=`${t}:${e.lines.join(",")}`;return e.use.displayable?`${n}: uses: ${Ns(e.use.ref)}`:`${n}: unrecognised uses: value (sha1 ${Dm(e.use.ref)})`}var qc=10;function BC(t,e,n){let s=Nm.resolve(t.repoRoot,e),i=[...new Set(n.flatMap(f=>f.lines))].sort((f,m)=>f-m),o=n.filter(f=>f.use.displayable).map(f=>f.use),r=n.length-o.length,a=o.filter(f=>!OC.has(f.owner)),c=a[0]??o[0],l=Ns(e),u=o.slice(0,qc).map(f=>`\`${Ns(f.ref)}\``).join(", ")+(o.length>qc?` and ${o.length-qc} more (see the evidence)`:""),p=r===0?"":` ${o.length>0?"It also has":"They are"} ${r} \`uses:\` value(s) that do not look like a plain \`owner/repo@ref\` and are not shown here; review them by hand.`,d=o.length>0&&a.length===0&&r===0?" All of them are maintained by GitHub, which lowers but does not remove the risk.":"",h="Pin each action to the full commit SHA of a release you trust and keep the version in a trailing comment";if(c){let[f,m]=c.action.split("/");h+=`, e.g. \`uses: ${Ns(c.action)}@<40-char-sha> # ${Ns(c.version)}\`. Resolve the SHA from the action's own repository (\`gh api repos/${f}/${m}/commits/${c.version} --jq .sha\`)`}else h+=", resolving the SHA from the action's own repository";return h+=", and let Dependabot or Renovate update the SHA and comment together. PromptCI reports this but does not rewrite workflow files.",{id:`action-pin-${Dm(`action-pin:${e}`)}`,severity:"info",category:"security",title:`GitHub Actions in \`${l}\` are not pinned to a commit SHA`,summary:`${l} references ${n.length} action(s) by a tag or branch rather than a full commit SHA`+(o.length>0?`: ${u}.`:".")+p+" 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."+d+" This finding does not count toward the health score.",filePaths:[s],locations:i.map(f=>({filePath:s,startLine:f,endLine:f})),evidence:n.map(f=>HC(e,f)),fingerprintKey:`action-pin:${e.replace(/\\/g,"/").replace(/^(?:\.\/)+/,"")}`,recommendation:h,confidence:.8,tags:["supply-chain","github-actions",Nn]}}function Kc(t){let e=t.workflows.sources??[],n=new Map;for(let s of e)for(let i of jm(s.content)){let o=FC(i);if(!o)continue;let r=n.get(s.filePath)??new Map,a=r.get(o.ref)??{lines:[],use:o};a.lines.push(o.line),r.set(o.ref,a),n.set(s.filePath,r)}return[...n.keys()].sort().map(s=>{let i=n.get(s),o=[...i.keys()].sort().map(r=>i.get(r));return BC(t,s,o)})}var Yc=R(require("node:crypto"),1),fn=R(require("node:path"),1);var GC=[/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],WC=/\b(AGENTS|CLAUDE)\.md\b/gi;function VC(t){let e=fn.basename(t.path).toLowerCase();for(let n of GC)for(let s of t.content.matchAll(new RegExp(n.source,"gi"))){let i=t.content.lastIndexOf(`
81
+ `,s.index)+1,o=t.content.indexOf(`
82
+ `,s.index+s[0].length),a=[...t.content.slice(i,o===-1?void 0:o).matchAll(WC)].map(l=>`${l[1].toLowerCase()}.md`);if(!(a.length>0&&a.every(l=>l!==e)))return s[0]}}function Fm(t){if(t.length===0)return[];let e=[],n=new Map;for(let a of t){let c=VC(a);c!==void 0&&n.set(a,c)}let s=[...n.keys()];function i(a){let c=Yc.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=>fn.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=>`${fn.basename(a.path)}: "${se(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 r=t.find(a=>fn.basename(a.path).toLowerCase()==="agents.md")||s[0];if(r){let a=c=>{let l=c.split(`
72
83
  `);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=Xt.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=pc.createHash("sha1").update(`canonical-owner:behavior-duplication:${N(c)}`).digest("hex").slice(0,12),h=Xt.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=R(require("node:crypto"),1);function hc(t){return`ci-align-${Bh.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function mc(t){return t.split(/&&|\n/).map(e=>e.trim()).filter(Boolean)}function Bk(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 Wk(t){let e=[];for(let n of mc(t)){let s=Bk(n);s&&!e.includes(s)&&e.push(s)}return e}var Gk={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 Uk(t,e){let n=Gk[t];return e.some(s=>n.test(s.content))}function Vk(t){let e=/\b(pnpm|npm|yarn|bun)\b/.exec(t.toLowerCase());return e?e[1]:null}function zk(t){let e=new Set;for(let n of t)for(let s of mc(n.command)){let i=Vk(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"]),Gh=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 qk(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)||Gh.has(n)?null:n}function Kk(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 Wk(r.command))s.has(o)||s.set(o,[]),s.get(o).push(r);let i=[];for(let[r,o]of s.entries()){if(Uk(r,n))continue;let a=[...new Set(o.map(c=>c.filePath))];i.push({id:hc(`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 Yk(t){let{workflows:e,files:n,packageJson:s}=t;if(e.files.length===0)return[];let i=zk(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
- `,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:hc(`pm-mismatch-ci:${N(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 Jk(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 mc(l.command)){let f=qk(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)||Gh.has(d))&&!r.has(d)&&!o.has(d)){let p=`${l.path}:${d}`;if(a.has(p))continue;a.add(p),c.push({id:hc(`orphan-script:${N(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 Uh(t){return t.workflows.files.length===0?[]:[...Kk(t),...Yk(t),...Jk(t)]}var qh=R(require("node:crypto"),1);var Xk={fileWarning:8e3,fileHigh:2e4,totalWarning:3e4,totalHigh:6e4,copilotLineWarning:1e3,readmeFileWarning:15e3,readmeFileHigh:3e4,windsurfFileWarning:6e3,windsurfFileHigh:12e3};function Ui(t){return`context-bloat-file-${qh.createHash("sha1").update(t).digest("hex").slice(0,12)}`}var Vh="context-bloat-total",Zk=.5,Qk=1e3,ws=["cost","context"];function eR(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 zh(t,e,n){return Ut(t,e,s=>s===n)}function Kh(t,e,n=[]){let s=eR(Xk,e),i=[];for(let l of[...t,...zh(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",y=`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:Ui(N(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?y:"Consider splitting this file.",confidence:1,tags:ws}):u>=h&&i.push({id:Ui(N(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?y:"Consider trimming this file.",confidence:1,tags:ws})}for(let l of[...t,...zh(t,n,"copilot")])l.fileType==="copilot"&&l.lineCount>s.copilotLineWarning&&i.push({id:Ui(N(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:Vh,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:ws}):r>=s.totalWarning&&i.push({id:Vh,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:ws});let c=t.find(l=>l.fileType==="readme");if(o>0&&c&&c.estimatedTokens>=Qk&&c.estimatedTokens/o>=Zk){let l=Math.round(c.estimatedTokens/o*100);i.push({id:Ui(`${N(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:ws})}return i}var Jh=R(require("node:crypto"),1);var tR={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 Zt(t){return`missing-context-${Jh.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function nR(t,e){let n=e.toLowerCase();return/[^a-z0-9]/.test(n)?t.includes(n):new RegExp(`\\b${n}\\b`).test(t)}var sR=[/(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/],iR=[/`(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],rR=[/\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 oR(t){let e=t.map(i=>i.content).join(`
76
- `),n=md(e);return sR.some(i=>i.test(n))||iR.some(i=>i.test(e))?null:{id:Zt("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 aR=[/\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],cR=[/\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 lR(t){let e=t.map(i=>i.content).join(`
77
- `);return!aR.some(i=>i.test(e))||cR.some(i=>i.test(e))?null:{id:Zt("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 uR(t){let e=t.map(s=>s.content).join(`
78
- `);return rR.some(s=>s.test(e))?null:{id:Zt("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 fR=[/\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],dR=[/\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 pR(t){let e=t.map(i=>i.content).join(`
79
- `);return!fR.some(i=>i.test(e))||dR.some(i=>i.test(e))?null:{id:Zt("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 Yh=/\b([A-Z][A-Z0-9_]{3,})\b/g,hR=[/\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],mR=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 gR(t){let e=t.map(a=>a.content).join(`
80
- `);if(hR.some(a=>a.test(e)))return null;let s=new Set,i,r=new RegExp(Yh.source,Yh.flags);for(;(i=r.exec(e))!==null;){let a=i[1];!mR.has(a)&&a.includes("_")&&s.add(a)}if(s.size<3)return null;let o=[...s].slice(0,4).join(", ");return{id:Zt("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 yR=[{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 bR(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 yR)!o.some(p=>l.some(h=>h.test(p.content)))||r.some(p=>l.some(h=>h.test(p.content)))||a.push({id:Zt(`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 Xh(t,e){let n=[],s=oR(t);s&&n.push(s);let i=uR(t);i&&n.push(i);let r=lR(t);r&&n.push(r);let o=pR(t);o&&n.push(o);let a=gR(t);if(a&&n.push(a),n.push(...bR(t)),e==="auto"||e==="unknown")return n;let c=tR[e];if(!c)return n;let l=t.map(f=>f.content.toLowerCase()).join(`
81
- `);if(c.keywords.filter(f=>nR(l,f)).length<c.minimumPresent){let f=c.keywords.slice(0,3).join(", ");n.push({id:Zt(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 em=R(require("node:crypto"),1);var wR=7;function tm(t=new Date){return t.getFullYear()}var Zh=0,Vi=null;function vR(){let t=tm();if(Vi&&Zh===t)return Vi;let e=[];for(let n=t-wR;n<=t-1;n++)e.push(String(n));return Zh=t,Vi=new RegExp(`(?<![/-])\\b(${e.join("|")})\\b(?![/-])`,"g"),Vi}var xR=/\b(?:history|changelog|change\s*log|release\s+notes?|releases?|versions?|what.?s\s+new|for\s+reference)\b/i,_R=/\b(TODO\s*:?\s*remove|remove\s+later|temporary\s+fix|workaround)\b/gi,Qh=/<!--(?:(?!-->)[\s\S])*?\b(TODO|FIXME|WORKAROUND|HACK|NOTE)\b(?:(?!-->)[\s\S])*?\(\s*(\d{4})[-–\d]/gi,SR=/deprecated[\w\s,.()\\\-:`]{0,60}(v?\d+[\w.]+|react|next\.?js|angular|vue|webpack|babel|unity|jest|mocha)/gi,ER=[{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 kR(t,e){let n=`${Fe(t)}:${t.startLine}:${e}`;return`stale-${em.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function gc(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 RR(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 CR(t){let e=[],n,s=new RegExp(Qh.source,Qh.flags);for(;(n=s.exec(t))!==null;)Number(n[2])<tm()&&e.push(n[0]);return e}function AR(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 nm(t){let e=[],n=new Set;for(let s of t)for(let i of s.sections){if(i.heading&&xR.test(i.heading))continue;let r=i.text,o=qe(r,{stripInlineCode:!0}),a=qe(r),c=[],l=0,u=`${s.path}:${i.startLine}`,f=gc(o,vR());f.length>0&&(c.push(`Year reference(s) that may be outdated: ${[...new Set(f)].join(", ")}`),l=Math.max(l,.6));let d=gc(a,_R);d.length>0&&(c.push(`Cleanup keyword(s): ${[...new Set(d.map(m=>m.trim()))].join(", ")}`),l=Math.max(l,.6));let p=gc(a,SR);p.length>0&&(c.push(`"deprecated" near version/tool: ${Z(p[0]??"",80)}`),l=Math.max(l,.7));for(let{re:m,label:g}of ER){let b=RR(o,m).filter(({index:v})=>!AR(o,v));b.length>0&&(c.push(`Old version reference: ${g} ("${b[0].match}")`),l=Math.max(l,.7))}let h=CR(a);h.length>0&&(c.push(`Dated ${h[0].match(/TODO|FIXME|WORKAROUND|HACK|NOTE/i)?.[0]??"TODO"} marker in HTML comment: ${Z(h[0]??"",80)}`),l=Math.max(l,.65)),c.length!==0&&(n.has(u)||(n.add(u),e.push({id:kR(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: "${Z(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 im=R(require("node:crypto"),1);var $R=["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"],sm=120;function PR(t){let e=new Set;for(let n of t)e.add(n),n.includes("-")&&e.add(n.replace(/-/g," "));return[...e]}var rm=PR($R),TR=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 IR(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var OR=new Map(rm.map(t=>[t,new RegExp(`\\b${IR(t)}\\b`)]));function LR(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<=sm&&s.push(r);let o=n[i+1];if(r&&o){let a=`${r} ${o}`;e.test(a.toLowerCase())&&a.length<=sm&&s.push(a)}}return s}function NR(t){let e=`${Fe(t)}:${t.startLine}:vague`;return`vague-${im.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function om(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=qe(r.text,{stripInlineCode:!0}),c=a.toLowerCase().replace(/\n/g," "),l=[],u=[];for(let g of rm){let y=OR.get(g);if(y.test(c))for(let b of LR(a,y))l.includes(g)||l.push(g),u.includes(b)||u.push(b)}if(l.length===0)continue;s.add(o);let f=l.map(g=>`"${g}"`).join(", "),d=l.some(g=>TR.has(g)),p=d?"warning":"info",h=e.severityOverride??p,m=d?.8:.75;n.push({id:NR(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 Yi=R(require("node:crypto"),1),Cn=R(require("node:path"),1);var vs=["# PromptCI: ignore generated reports, keep the shared baseline, config, and custom rules","**/.promptci/*","!**/.promptci/baseline.json","!**/.promptci/config.json","!**/.promptci/custom-rules.json"],yc=`${vs.join(`
84
+ `).trim():c.trim()};for(let c of t){if(c===r)continue;let l=fn.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 p of c.sections)if(p.endLine-p.startLine>50&&r.sections.some(h=>{let f=a(h.text).toLowerCase().replace(/\s+/g," ").trim(),m=a(p.text).toLowerCase().replace(/\s+/g," ").trim();return f===m||f.length>500&&f.slice(0,500)===m.slice(0,500)})){let h=Yc.createHash("sha1").update(`canonical-owner:behavior-duplication:${G(c)}`).digest("hex").slice(0,12),f=fn.basename(r.path),m=Math.round(p.text.length/4);e.push({id:`behavior-duplication-${h}`,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 ${f}. This can lead to instruction drift.`,filePaths:[c.path,r.path],locations:[{filePath:c.path,startLine:p.startLine,endLine:p.endLine}],evidence:[`Section "${p.heading??"Untitled"}" is near-identical to one in ${f}`,`Duplicate size: ~${m} tokens`],recommendation:`Consider moving shared rules to ${f} and using a forwarding pointer (e.g., "Follow ${f}") to save ~${m} tokens per session.`,confidence:.8});break}}}}return e}var Gm=R(require("node:crypto"),1);var UC={fileWarning:8e3,fileHigh:2e4,totalWarning:3e4,totalHigh:6e4,copilotLineWarning:1e3,readmeFileWarning:15e3,readmeFileHigh:3e4,windsurfFileWarning:6e3,windsurfFileHigh:12e3};function po(t){return`context-bloat-file-${Gm.createHash("sha1").update(t).digest("hex").slice(0,12)}`}var Hm="context-bloat-total",zC=.5,qC=1e3,Ms=["cost","context"];function KC(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 Bm(t,e,n){return on(t,e,s=>s===n)}function Wm(t,e,n=[]){let s=KC(UC,e),i=[];for(let l of[...t,...Bm(t,n,"windsurf")]){let{charCount:u,estimatedTokens:p,path:d,fileType:h}=l,f=s.fileWarning,m=s.fileHigh;h==="readme"?(f=s.readmeFileWarning,m=s.readmeFileHigh):h==="windsurf"&&(f=s.windsurfFileWarning,m=s.windsurfFileHigh);let g=h==="windsurf",y=`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:po(G(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: ~${p.toLocaleString()}`],recommendation:g?y:"Consider splitting this file.",confidence:1,tags:Ms}):u>=f&&i.push({id:po(G(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 (${f.toLocaleString()}).`,filePaths:[d],locations:[{filePath:d}],evidence:[`charCount: ${u.toLocaleString()}`,`estimatedTokens: ~${p.toLocaleString()}`],recommendation:g?y:"Consider trimming this file.",confidence:1,tags:Ms})}for(let l of[...t,...Bm(t,n,"copilot")])l.fileType==="copilot"&&l.lineCount>s.copilotLineWarning&&i.push({id:po(G(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 o=t.reduce((l,u)=>l+u.charCount,0),r=t.reduce((l,u)=>l+u.estimatedTokens,0),a=t.map(l=>l.path);o>=s.totalHigh?i.push({id:Hm,severity:"high",category:"context_bloat",title:"Total instruction context is very large",summary:`Total is ${o.toLocaleString()} chars, above high threshold (${s.totalHigh.toLocaleString()}).`,filePaths:a,locations:a.map(l=>({filePath:l})),evidence:[`totalCharCount: ${o.toLocaleString()}`,`totalEstimatedTokens: ~${r.toLocaleString()}`],recommendation:"Aim to keep total context under 30k characters.",confidence:1,tags:Ms}):o>=s.totalWarning&&i.push({id:Hm,severity:"warning",category:"context_bloat",title:"Total instruction context may be too large",summary:`Total is ${o.toLocaleString()} chars, above warning threshold (${s.totalWarning.toLocaleString()}).`,filePaths:a,locations:a.map(l=>({filePath:l})),evidence:[`totalCharCount: ${o.toLocaleString()}`,`totalEstimatedTokens: ~${r.toLocaleString()}`],recommendation:"Consider trimming instruction files.",confidence:1,tags:Ms});let c=t.find(l=>l.fileType==="readme");if(r>0&&c&&c.estimatedTokens>=qC&&c.estimatedTokens/r>=zC){let l=Math.round(c.estimatedTokens/r*100);i.push({id:po(`${G(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 ~${r} scanned tokens`],recommendation:"Consider keeping AI rules in AGENTS.md and leaving README as project documentation linked only when relevant.",confidence:.65,tags:Ms})}return i}var Um=R(require("node:crypto"),1);var YC={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 hn(t){return`missing-context-${Um.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function XC(t,e){let n=e.toLowerCase();return/[^a-z0-9]/.test(n)?t.includes(n):new RegExp(`\\b${n}\\b`).test(t)}var JC=[/(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/],ZC=[/`(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],QC=[/\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 eR(t){let e=t.map(i=>i.content).join(`
85
+ `),n=Xp(e);return JC.some(i=>i.test(n))||ZC.some(i=>i.test(e))?null:{id:hn("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 tR=[/\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],nR=[/\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 sR(t){let e=t.map(i=>i.content).join(`
86
+ `);return!tR.some(i=>i.test(e))||nR.some(i=>i.test(e))?null:{id:hn("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 iR(t){let e=t.map(s=>s.content).join(`
87
+ `);return QC.some(s=>s.test(e))?null:{id:hn("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 oR=[/\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],rR=[/\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 aR(t){let e=t.map(i=>i.content).join(`
88
+ `);return!oR.some(i=>i.test(e))||rR.some(i=>i.test(e))?null:{id:hn("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 Vm=/\b([A-Z][A-Z0-9_]{3,})\b/g,cR=[/\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],lR=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 uR(t){let e=t.map(a=>a.content).join(`
89
+ `);if(cR.some(a=>a.test(e)))return null;let s=new Set,i,o=new RegExp(Vm.source,Vm.flags);for(;(i=o.exec(e))!==null;){let a=i[1];!lR.has(a)&&a.includes("_")&&s.add(a)}if(s.size<3)return null;let r=[...s].slice(0,4).join(", ");return{id:hn("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. ${r}) 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: ${r}\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 dR=[{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 pR(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 o=t.filter(s),r=t.filter(c=>!o.includes(c));if(r.length===0)return[];let a=[];for(let{label:c,patterns:l,recommendation:u}of dR)!r.some(h=>l.some(f=>f.test(h.content)))||o.some(h=>l.some(f=>f.test(h.content)))||a.push({id:hn(`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 zm(t,e){let n=[],s=eR(t);s&&n.push(s);let i=iR(t);i&&n.push(i);let o=sR(t);o&&n.push(o);let r=aR(t);r&&n.push(r);let a=uR(t);if(a&&n.push(a),n.push(...pR(t)),e==="auto"||e==="unknown")return n;let c=YC[e];if(!c)return n;let l=t.map(p=>p.content.toLowerCase()).join(`
90
+ `);if(c.keywords.filter(p=>XC(l,p)).length<c.minimumPresent){let p=c.keywords.slice(0,3).join(", ");n.push({id:hn(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: ${p}\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 Ym=R(require("node:crypto"),1);var fR=7;function Xm(t=new Date){return t.getFullYear()}var qm=0,fo=null;function hR(){let t=Xm();if(fo&&qm===t)return fo;let e=[];for(let n=t-fR;n<=t-1;n++)e.push(String(n));return qm=t,fo=new RegExp(`(?<![/-])\\b(${e.join("|")})\\b(?![/-])`,"g"),fo}var mR=/\b(?:history|changelog|change\s*log|release\s+notes?|releases?|versions?|what.?s\s+new|for\s+reference)\b/i,gR=/\b(TODO\s*:?\s*remove|remove\s+later|temporary\s+fix|workaround)\b/gi,Km=/<!--(?:(?!-->)[\s\S])*?\b(TODO|FIXME|WORKAROUND|HACK|NOTE)\b(?:(?!-->)[\s\S])*?\(\s*(\d{4})[-–\d]/gi,yR=/deprecated[\w\s,.()\\\-:`]{0,60}(v?\d+[\w.]+|react|next\.?js|angular|vue|webpack|babel|unity|jest|mocha)/gi,bR=[{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 wR(t,e){let n=`${He(t)}:${t.startLine}:${e}`;return`stale-${Ym.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function Xc(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 vR(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 SR(t){let e=[],n,s=new RegExp(Km.source,Km.flags);for(;(n=s.exec(t))!==null;)Number(n[2])<Xm()&&e.push(n[0]);return e}function _R(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 Jm(t){let e=[],n=new Set;for(let s of t)for(let i of s.sections){if(i.heading&&mR.test(i.heading))continue;let o=i.text,r=st(o,{stripInlineCode:!0}),a=st(o),c=[],l=0,u=`${s.path}:${i.startLine}`,p=Xc(r,hR());p.length>0&&(c.push(`Year reference(s) that may be outdated: ${[...new Set(p)].join(", ")}`),l=Math.max(l,.6));let d=Xc(a,gR);d.length>0&&(c.push(`Cleanup keyword(s): ${[...new Set(d.map(m=>m.trim()))].join(", ")}`),l=Math.max(l,.6));let h=Xc(a,yR);h.length>0&&(c.push(`"deprecated" near version/tool: ${se(h[0]??"",80)}`),l=Math.max(l,.7));for(let{re:m,label:g}of bR){let b=vR(r,m).filter(({index:w})=>!_R(r,w));b.length>0&&(c.push(`Old version reference: ${g} ("${b[0].match}")`),l=Math.max(l,.7))}let f=SR(a);f.length>0&&(c.push(`Dated ${f[0].match(/TODO|FIXME|WORKAROUND|HACK|NOTE/i)?.[0]??"TODO"} marker in HTML comment: ${se(f[0]??"",80)}`),l=Math.max(l,.65)),c.length!==0&&(n.has(u)||(n.add(u),e.push({id:wR(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: "${se(o,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 Qm=R(require("node:crypto"),1);var xR=["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"],Zm=120;function kR(t){let e=new Set;for(let n of t)e.add(n),n.includes("-")&&e.add(n.replace(/-/g," "));return[...e]}var eg=kR(xR),ER=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 AR(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var CR=new Map(eg.map(t=>[t,new RegExp(`\\b${AR(t)}\\b`)]));function RR(t,e){let n=t.split(`
91
+ `).map(i=>i.trim()),s=[];for(let i=0;i<n.length;i++){let o=n[i];o&&e.test(o.toLowerCase())&&o.length<=Zm&&s.push(o);let r=n[i+1];if(o&&r){let a=`${o} ${r}`;e.test(a.toLowerCase())&&a.length<=Zm&&s.push(a)}}return s}function TR(t){let e=`${He(t)}:${t.startLine}:vague`;return`vague-${Qm.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function tg(t,e={}){let n=[],s=new Set;for(let i of t)for(let o of i.sections){let r=`${i.path}:${o.startLine}`;if(s.has(r))continue;let a=st(o.text,{stripInlineCode:!0}),c=a.toLowerCase().replace(/\n/g," "),l=[],u=[];for(let g of eg){let y=CR.get(g);if(y.test(c))for(let b of RR(a,y))l.includes(g)||l.push(g),u.includes(b)||u.push(b)}if(l.length===0)continue;s.add(r);let p=l.map(g=>`"${g}"`).join(", "),d=l.some(g=>ER.has(g)),h=d?"warning":"info",f=e.severityOverride??h,m=d?.8:.75;n.push({id:TR(o),severity:f,category:"vague_guidance",title:"Vague guidance detected",summary:`This section contains guidance that may be too vague to be actionable: ${p}.`,filePaths:[i.path],locations:[{filePath:i.path,startLine:o.startLine,endLine:o.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 yo=R(require("node:crypto"),1),Ut=R(require("node:path"),1);var js=["# PromptCI: ignore generated reports, keep the shared baseline, config, and custom rules","**/.promptci/*","!**/.promptci/baseline.json","!**/.promptci/config.json","!**/.promptci/custom-rules.json"],Jc=`${js.join(`
83
92
  `)}
84
- `;function xs(t){return`${vs.join(t)}${t}`}var zi=[{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."}],jR=[{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 qi(t){return`security-pack-${Yi.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function MR(t,e){return`destructive-command-${Yi.createHash("sha1").update(`destructive-command:${t}:${e}`).digest("hex").slice(0,12)}`}function DR(t){return`security-pack-inspect-reports-first-${Yi.createHash("sha1").update(`inspect-reports-first:${t}`).digest("hex").slice(0,12)}`}function _s(t,e){return e.some(n=>n.test(t))}function Ki(t,e){return t.startsWith("!")?!1:t.replace(/^\/+|\/+$/g,"").split("/").includes(e)}function am(t){let{files:e,repoRoot:n}=t;if(e.length===0)return[];let s=V(t),i=[],r=e.map(w=>w.content).join(`
85
- `),o=e.map(w=>w.path);if([".env",".env.example",".env.local",".env.development",".env.production"].some(w=>s.exists(w))||t.files.some(w=>/env\s+vars|environment\s+variables/i.test(w.content))){let w=zi.find(_=>_.id==="no-secret-safeguard");_s(r,w.patterns)||i.push({id:qi(w.id),severity:w.severity,category:"security",title:w.title,summary:w.summary,filePaths:o,locations:[],evidence:["Environment variables detected but no safeguard instruction found."],recommendation:w.recommendation,fixRecipe:w.fixRecipe,confidence:w.confidence})}let l={...t.packageJson.dependencies,...t.packageJson.devDependencies,...t.packageJson.peerDependencies};if(s.exists("supabase/migrations")||Object.keys(l).some(w=>w==="@supabase/supabase-js"||w.startsWith("@supabase/"))){let w=zi.find(_=>_.id==="no-supabase-service-role-rule");_s(r,w.patterns)||i.push({id:qi(w.id),severity:w.severity,category:"security",title:w.title,summary:w.summary,filePaths:o,locations:[],evidence:["Supabase detected but no service role safeguard instruction found."],recommendation:w.recommendation,fixRecipe:w.fixRecipe,confidence:w.confidence})}if(t.files.some(w=>{let _=w.path.replace(/\\/g,"/");return _.includes("/api/upload")||_.includes("/uploads/")||/multer|busboy|formidable/i.test(w.content)})){let w=zi.find(_=>_.id==="no-upload-boundary-docs");_s(r,w.patterns)||i.push({id:qi(w.id),severity:w.severity,category:"security",title:w.title,summary:w.summary,filePaths:o,locations:[],evidence:["Upload features detected but no data boundary documentation found."],recommendation:w.recommendation,fixRecipe:w.fixRecipe,confidence:w.confidence})}if(s.exists(".promptci")){let w=zi.find(_=>_.id==="no-promptci-report-safeguard");_s(r,w.patterns)||i.push({id:qi(w.id),severity:w.severity,category:"security",title:w.title,summary:w.summary,filePaths:o,locations:[],evidence:[".promptci/ folder detected but no report safeguard instruction found."],recommendation:w.recommendation,fixRecipe:w.fixRecipe,confidence:w.confidence})}for(let w of e)for(let _ of jR)if(_.pattern.test(w.content)){let A=[/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];_s(w.content,A)||i.push({id:MR(N(w),_.name),severity:"warning",category:"security",title:`Destructive command "${_.name}" without safety language`,summary:`Instruction file contains a destructive command "${_.name}" but lacks safety language (e.g., "Ask before running").`,filePaths:[w.path],locations:[],evidence:[`Destructive command "${_.name}" found in ${Cn.basename(w.path)} without safety language.`],recommendation:`Add safety language such as "Ask for confirmation before running ${_.name}" to ensure destructive operations are not performed accidentally.`,confidence:.7})}let p=s.readText(".gitignore"),h=p.state==="unreadable"||p.state==="unfetched"||p.state==="too-large",g=(p.state==="found"?p.content:"").split(/\r?\n/).map(w=>w.trim()).filter(w=>w&&!w.startsWith("#"));!g.some(w=>Ki(w,".promptci"))&&!h&&i.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"+vs.map(w=>` ${w}`).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:yc,autoApplySafe:!0,confidence:.9});let v=h?[]:["coverage","dist","build",".next","bin","obj","temp","tmp","logs"].filter(w=>s.isDir(w)?!g.some(_=>Ki(_,w)):!1);v.length>0&&i.push({id:"security-pack-unignored-dirs",severity:"warning",category:"context_bloat",title:"Unignored build, output, or coverage directories",summary:`The repository contains directory/directories (${v.join(", ")}) that are commonly generated but not ignored in .gitignore. AI tools may ingest these, inflating token costs.`,filePaths:[".gitignore"],locations:[],evidence:v.map(w=>`Directory "${w}" exists but is not ignored in .gitignore.`),recommendation:`Add generated directories to .gitignore. For example: "${v.map(w=>`${w}/`).join(", ")}"`,fixRecipe:v.map(w=>`echo "${w}/" >> .gitignore`).join(`
87
- `),autoApplySafe:!0,confidence:.8});let x=!1;try{let w=s.readText(".promptci/config.json");if(w.state==="found"){let _=JSON.parse(w.content);if(Array.isArray(_.include)){let A=["**/*","**/*.md","*","*.*","**"];x=_.include.some(C=>A.includes(C.trim()))}}}catch{}if(x){let w=e.filter(_=>{let A=Cn.relative(n,_.path).replace(/\\/g,"/");return A.includes(".promptci/")||A.includes("coverage/")||A.includes(".next/")});w.length>0&&i.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:w.map(_=>`Scanned generated file: ${Cn.relative(n,_.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 w of e){let _=[{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 A of _)if(A.re.test(w.content)){i.push({id:DR(N(w)),severity:"info",category:"context_bloat",title:"Instruction prioritizing generated reports over source docs",summary:`Instruction file "${Cn.basename(w.path)}" tells the agent to inspect generated reports before source files, which can cause circular or outdated guidance ingestion.`,filePaths:[w.path],locations:[],evidence:[bn(w.content,A.re,A.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 i}function cm(t){let e=[],{packageJson:n,files:s}=t,i=!!(n.dependencies.next||n.devDependencies.next),r=V(t),o=["","apps/web/"].some(u=>["js","mjs","ts"].some(f=>r.isFile(`${u}next.config.${f}`)));if(!i&&!o)return[];let a=u=>["","src/","apps/web/","apps/web/src/"].some(f=>r.isDir(`${f}${u}`)),c=a("app"),l=a("pages");if(c&&(s.some(f=>f.content.toLowerCase().includes("app router")||f.content.toLowerCase().includes("server component")||f.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:s.map(f=>f.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})),c&&!l){let u=s.filter(f=>f.content.toLowerCase().includes("pages router")||f.content.toLowerCase().includes("getstaticprops")||f.content.toLowerCase().includes("getserversideprops"));u.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:u.map(f=>f.path),locations:u.map(f=>({filePath:f.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 Ji=R(require("node:path"),1);function lm(t){let e=[],{manifests:n,repoRoot:s,files:i}=t,r=!!n.pyproject,o=n.requirements!==void 0,a=V(t),c=a.isFile("Pipfile"),l=a.isFile("environment.yml");if(!r&&!o&&!c&&!l)return[];(n.pyproject?.includes("pytest")||n.requirements?.includes("pytest"))&&(i.some(h=>h.content.toLowerCase().includes("pytest")||h.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(h=>h.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 f=[],d=[];return c&&f.push("Pipenv (Pipfile)"),c&&d.push(Ji.join(s,"Pipfile")),l&&f.push("Conda (environment.yml)"),l&&d.push(Ji.join(s,"environment.yml")),r&&n.pyproject?.includes("[tool.poetry]")&&f.push("Poetry (pyproject.toml)"),r&&n.pyproject?.includes("[tool.poetry]")&&d.push(Ji.join(s,"pyproject.toml")),f.length>1&&e.push({id:"python-multiple-env-managers",severity:"warning",category:"conflict",title:"Multiple Python Environment Managers",summary:`Multiple environment managers detected: ${f.join(", ")}. This can lead to conflicting instructions.`,filePaths:d.length>0?d:i.map(p=>p.path),locations:[],evidence:[`Detected: ${f.join(", ")}`],recommendation:"Decide on a single environment manager and remove the others, or clearly document when to use each.",confidence:.9}),e}function um(t){let e=[],{files:n}=t,s=V(t),i=s.isDir("Assets"),r=s.isFile("ProjectSettings/ProjectVersion.txt"),o=n.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=n.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}function fm(t){let e=[],{repoRoot:n,files:s}=t,i=V(t),r=i.entries(i.root),o=typeof r=="string"?[]:[...r.values()].filter(p=>!p.isDirectory()).map(p=>p.name).sort(),a=t.projectType==="dotnet"||o.some(p=>p.endsWith(".sln")||p.endsWith(".csproj")),c=s.map(p=>p.content).join(`
89
- `),l=/\bdotnet\b|\.sln\b|\.csproj\b|\bxunit\b|\bnunit\b|\bmstest\b/i.test(c);if(!a&&!l)return[];let u=s.map(p=>p.path);/dotnet\s+(build|test|restore|run)/i.test(c)||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:u,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 d;try{let p=o.find(h=>h.endsWith(".csproj"));if(p){let h=ve(n,p)??"",m=/<TargetFramework>(.*?)<\/TargetFramework>/.exec(h);m&&(d=m[1]?.trim())}}catch{}if(d){let p=/\b(netcoreapp\d+\.\d+|net5\.0|netcore)\b/i.test(c);/^net(?:[6-9]|[1-9]\d+)\.0/.test(d)&&p&&e.push({id:"dotnet-obsolete-framework-reference",severity:"warning",category:"stale_instruction",title:".NET Obsolete Framework Reference",summary:`The project targets modern .NET (${d}), but instructions still reference obsolete versions like .NET Core 3.1 or .NET 5.0.`,filePaths:u,locations:[],evidence:[`Project targets ${d}; obsolete framework references found in instructions.`],recommendation:`Update instructions to reference the current target framework version (${d}).`,fixRecipe:`Target .NET ${d} as the framework for this project. Do not use legacy .NET Core 3.1 or .NET 5.0 APIs.`,confidence:.8})}return e}function dm(t){let e=[],{files:n}=t,s=V(t).isFile("go.mod"),i=n.map(c=>c.content).join(`
90
- `),r=/\bgo\.mod\b/i.test(i)||/`[^`\n]*\bgo\s+(?:build|test|run|get|mod)\b[^`\n]*`/i.test(i);if(!s&&!r)return[];let o=n.map(c=>c.path);return/\bgo\s+test\b/i.test(i)||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:o,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}function pm(t){let e=[],{repoRoot:n,files:s}=t,i=V(t).isFile("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=ve(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 hm(t){let e=[];return e.push(...cm(t)),e.push(...lm(t)),e.push(...um(t)),e.push(...fm(t)),e.push(...dm(t)),e.push(...pm(t)),e}var gm=R(require("node:path"),1),ym=R(require("node:crypto"),1);function Ss(t,e){let n=ym.createHash("sha1").update(`prompt-cache-${t}:${e}`).digest("hex").slice(0,12);return`prompt-cache-${t}-${n}`}var FR=[{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"}],HR=[{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'}],BR=[{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"}],mm=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i;function bm(t){let e=[],n=t.filter(s=>he.has(s.fileType));for(let s of n){let i=gm.basename(s.path);for(let d of FR)if(d.re.test(s.content)){e.push({id:Ss("volatile-timestamp",N(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:[bn(s.content,d.re,d.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 d of HR)if(d.re.test(s.content)){e.push({id:Ss("pasted-report",N(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:[bn(s.content,d.re,d.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 d of BR)if(d.re.test(s.content)){e.push({id:Ss("volatile-branch-task",N(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:[bn(s.content,d.re,d.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(mm.test(s.content)){let d=s.content.match(mm)?.[0]??"";e.push({id:Ss("local-paths",N(s)),severity:"warning",category:"context_bloat",title:"Local machine paths in instructions",summary:`The instruction file "${i}" contains absolute local machine paths ("${d}"). These paths change per environment, preventing prompt caching and causing instruction drift.`,filePaths:[s.path],locations:[],evidence:[`Found absolute local path: ${d}`],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,c=0,l=0,u=0,f=0;for(let[d,p]of r.entries()){let h=p.trim();if(h.startsWith("|")&&h.endsWith("|")){if(/^\|[-\s:|]+\|$/.test(h))continue;a===0&&(c=d+1),l=d+1,a++}else a>o&&(o=a,u=c,f=l),a=0}a>o&&(o=a,u=c,f=l),o>15&&e.push({id:Ss("large-table",N(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:[{filePath:s.path,startLine:u,endLine:f}],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 bc=R(require("node:path"),1);var wm=12,WR={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 An(t,e,n=""){return`ai-config-skill-${t}-${fe(`${e}|${n}`)}`}function GR(t){return t.toLowerCase().replace(/[`*_~]/g,"").replace(/[^a-z0-9]+/g," ").trim()}function UR(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 wc(t){let e=[],n=new Set,s=(r,o)=>{if(!UR(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 VR(t,e){if(e.startsWith("/")){let r=e.slice(1);return zR.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 zR=new Set(["usr","var","etc","opt","tmp","home","Users","Library","bin","sbin","dev","proc","mnt","private","System"]);function qR(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function KR(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}\`?${qR(e)}`,"i").test(t)}function vc(t){let e=[],n=[],s,i=V(t);for(let r of t.aiConfig.skills){let o=ve(t.repoRoot,r);if(o===void 0)continue;let a=Yt(bc.dirname(r)).split("/").pop()??"",c=ht(o);if(e.push(...Tt(r,o,c,WR)),!c.present)continue;let l=typeof c.data.name=="string"?c.data.name.trim():void 0,u=typeof c.data.description=="string"?c.data.description.trim():void 0;l?l!==a&&a&&e.push(B({id:An("name-dir-mismatch",r),title:"Skill `name` does not match its directory",summary:`${r}: frontmatter \`name: ${l}\` does not match the skill directory \`${a}/\`. Claude resolves skills by directory name.`,filePaths:[r],locations:[{filePath:r,startLine:c.keyLines.name??1,endLine:c.keyLines.name??1}],evidence:[`name: ${l}`,`directory: ${a}`],recommendation:"Rename the directory or the `name` field so they match.",confidence:.6})):e.push(B({id:An("missing-name",r),title:"Skill frontmatter is missing `name`",summary:`${r} has no \`name\` field. Claude uses \`name\` to identify and invoke the skill.`,filePaths:[r],locations:[{filePath:r,startLine:1,endLine:c.fenceEndLine>0?c.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(c.data).join(", ")||"(none)"}`],recommendation:"Add a `name` field to the frontmatter matching the skill directory name.",confidence:.85})),u?u.length<wm&&e.push(B({id:An("empty-description",r),title:"Skill `description` is too short to trigger reliably",summary:`${r}: \`description\` is only ${u.length} characters. Claude matches the description against the user's request to decide when to invoke the skill.`,filePaths:[r],locations:[{filePath:r,startLine:c.keyLines.description??1,endLine:c.keyLines.description??1}],evidence:[`description: ${u}`],recommendation:"Expand the description to describe the task and its trigger conditions.",confidence:.7})):e.push(B({id:An("missing-description",r),title:"Skill frontmatter is missing `description`",summary:`${r} has no \`description\`. The description is the trigger text Claude matches against \u2014 without it the skill rarely activates.`,filePaths:[r],locations:[{filePath:r,startLine:1,endLine:c.fenceEndLine>0?c.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(c.data).join(", ")||"(none)"}`],recommendation:"Add a `description` that says what the skill does and when to use it.",confidence:.85}));let f=Yt(bc.dirname(r)),d=o.split(/\r?\n/);for(let{ref:p,line:h}of wc(o)){if(ba(p)||/^\/?\.git\//.test(p))continue;let m=VR(f,p);if(!m||m.some(y=>rt(i,y))||(s??=Si(i),m.some(y=>s(y)!==!1))||KR(d[h-1]??"",p))continue;let g=p.startsWith("/");e.push(B({id:An("dead-ref",r,p),title:"Skill references a bundled file that does not exist",summary:g?`${r} references \`${p}\`, but no such file exists at that path from the repository root.`:`${r} references \`${p}\`, but no such file exists relative to the skill directory or the repository root.`,filePaths:[r],locations:[{filePath:r,startLine:h,endLine:h}],evidence:[`Reference: ${p}`,`Looked in: ${m.join(", ")}`],recommendation:"Add the referenced file, fix the path, or remove the reference.",confidence:.75}))}u&&n.push({filePath:r,description:u})}return e.push(...YR(n)),Te(t.repoRoot,e)}function YR(t){let e=[],n=new Map;for(let s of t){if(s.description.length<wm)continue;let i=GR(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(B({id:An("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 Ot=R(require("node:fs"),1),Be=R(require("node:path"),1);var Ac="skill-supply-chain",JR=20*1024*1024,XR=2e3,ZR={"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."}},QR=new Set(["md","mdx","markdown","txt"]),eC=new Set(["yml","yaml","json","jsonc","json5","toml","ini","cfg","conf","html","htm","xhtml","xml","svg"]),vm={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"},tC=new Set(["go","rs","java","c","cc","cpp","cxx","h","hpp","cs","swift","kt","kts","groovy","gradle","scala","tf","hcl","sql","service","desktop"]),nC=new Set(["vbs","vba","vbe","hta","applescript","wsf","jse","reg"]),sC=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"]),iC=new Set(["docx","xlsx","pptx","doc","xls","ppt","odt","sqlite","sqlite3","db"]),rC=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"]),oC=new Set([".ds_store","thumbs.db","desktop.ini"]);function Nm(t){let e=Be.posix.basename(t);if(oC.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":QR.has(n)?{kind:"instructions",lang:"other"}:vm[n]?{kind:"script",lang:vm[n]}:n==="mk"||n==="dockerfile"?{kind:"text",lang:"sh"}:eC.has(n)?{kind:"text",lang:"other"}:tC.has(n)?{kind:"text",lang:"other",note:{reason:`.${n} source \u2014 only command and exfiltration patterns were checked`,severity:"info"}}:nC.has(n)?{kind:"script",lang:"other",note:{reason:`.${n} script \u2014 only command and exfiltration patterns were checked`,severity:"warning"}}:sC.has(n)?{report:`binary executable or archive (.${n}) \u2014 cannot be reviewed as text`,severity:"warning"}:iC.has(n)?{report:`.${n} document/database \u2014 not read`,severity:"info"}:rC.has(n)?{skip:"asset"}:"probe"}function xm(t){if(Be.posix.basename(t)==="SKILL.md")return!0;let e=Nm(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 aC(t){let e=/^#!\s{0,5}(\S{1,200})(?:\s{1,5}(\S{1,100}))?/.exec(t);if(!e)return;let n=Be.posix.basename(e[1])==="env"?e[2]??"":Be.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 cC(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 lC(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 Qt=wi;function xc(t){let e=Qt(t),n=Math.max(0,...(e.match(/`+/g)??[]).map(i=>i.length)),s="`".repeat(n+1);return`${s}${e}${s}`}function xe(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=Qt(t.slice(s,i)).replace(/\s+/g," ").trim();return`${s>0?"\u2026":""}${r}${i<t.length?"\u2026":""}`}var Ye=2e3,jm=600;function tr(t,e,n){return Object.assign([t.slice(e,n)],{index:e,input:t,groups:void 0})}function de(t,e,n){if(e.length<=Ye){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+=Ye-jm){let i=e.slice(s,s+Ye),r=n&&!n(i)?null:t.exec(i);if(r)return{index:s+r.index,match:r};if(s+Ye>=e.length)break}}function yt(t,e,n=50){let s=[];if(e.length<=Ye){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+=Ye-jm){for(let o of e.slice(r,r+Ye).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+Ye>=e.length)break}return s}var Mm=20,Dm=4e3,Fm=200,Hm=2e4,uC=/\|\s{0,5}[({]?\s{0,3}(?:while|until)\b/,_m=/\bdo\b/g,Sm=/\bdone\b/g,fC=/\|\s{0,5}rev\s{0,5}\|/,dC=t=>Rs.test(t)||Jm.test(t)||fC.test(t);function pC(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)&&uC.test(d)&&dC(d)){let g=d.match(_m)?.length??0,y=d.match(Sm)?.length??0;(g===0||g>y)&&(m=!0,c=g-y,l=g>0)}if(p||h||a||m){let g=a||m?f.trim():f,y=a||m;if(r<(y?Fm:Mm)&&s.length+g.length<(y?Hm:Dm)){let b=!1;if(a){let w=g.match(_m)?.length??0,_=g.match(Sm)?.length??0;w>0&&(l=!0),c+=w-_,b=l&&c<=0||!l&&_>0}let v=p||h||m&&/(?:\bdo|[;{(])$/.test(g)?" ":"; ",x=a||m?g:d;s+=`${p?x.slice(0,-1):x}${b?"":v}`,r++,m&&(a=!0),b&&(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 hC=/\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,Bm=/[,;:.!?]|\b(?:but|and|then|instead|so)\b/i,mC=2,gC=/^(?:run|pipe|use|execute|invoke|call|send|pass|type|paste)$/i;function Wm(t){return t.match(/[A-Za-z0-9_'-]+/g)??[]}var yC=/\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,bC=/^[`'")\]\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 Gm(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 Um(t,e){return Gm(t.slice(Math.max(0,e-80),e),hC,n=>{if(n.length>30||Bm.test(n))return!1;let s=Wm(n);return s.length===0||s.length===1&&gC.test(s[0])})}function $c(t,e,n){return bC.test(t.slice(e+n,e+n+60))?!0:Gm(t.slice(Math.max(0,e-80),e),yC,s=>s.length<=30&&!Bm.test(s)&&Wm(s).length<=mC)}var wC=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"),Vm=/\b(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod)\b/gi,vC=/^(?:-K|--config|-i|--input-file|-T|--upload-file|--url|--url-query)(?:=|$)|^-K\S/;function xC(t){let e=0;for(let n of t.matchAll(Vm)){if(++e>8)break;if(zm(t,n).some(s=>vC.test(s)||!s.startsWith("-")&&/[/.:@=$~\d[]/.test(s)))return!0}return qm(t)&&(Qi(t,Rs,!1)!==void 0||RC(t))}function zm(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 qm(t,e=4){let n=t.slice(0,600),s=0;for(let i of n.matchAll(Vm)){if(++s>e)break;let r=EC(i[0].toLowerCase(),zm(n,i));if(r!==void 0&&kC(r))return!0}return!1}var _C={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"])},SC=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 EC(t,e){let n=t==="curl"||t==="wget"?t:"iwr",s=_C[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 kC(t){return/^[a-z][a-z0-9_-]{0,62}$/i.test(t)&&!SC.has(t.toLowerCase())}function RC(t){let e=Tc(t,!1).slice(0,50);for(let n=0;n<e.length;n++){if(!Rs.test(e[n].text))continue;let s=Qm(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=Zm.exec(r);if(o&&He(o[1])===s)return!0}}return!1}function Pc(t){let e=t.slice(0,600);return wC.test(e)||xC(e)}function nr(t,e,n,s,i,r=!1){return t.kind!=="instructions"||t.fenced[e]||!Um(n,s)&&!$c(n,s,i)?"none":Pc(n.slice(s,s+Math.max(i,1)+80))?"lowconf":r?Km(n,s,s+i)||CC(n)?"skip":"lowconf":"skip"}function CC(t){return t.trimStart().startsWith("|")}var AC=/\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 $C(t,e,n){if(!Km(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!AC.test(s.slice(0,Math.max(0,i)))}function Km(t,e,n){let s=t.slice(Math.max(0,e-Ye),e),i=t.slice(n,n+Ye);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 PC=/^\s{0,10}\|\s{0,5}`?(?:--[\w-]{2,60}|bypassPermissions)`?\s{0,5}\|/,TC=/`[^`]{0,200}`|\b(?:run|use|execute|launch|invoke|start|pass|add|set|enable|always|call|claude|codex|npx|bash|sh)\b/i;function IC(t){return PC.test(t)?!t.split(/(?<!\\)\|/).slice(2).some(n=>TC.test(n)):!1}function Tc(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 OC=String.raw`(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod|aria2c|downloadstring|downloadfile)`,Rs=new RegExp(String.raw`(?:^|[\s(\x60{>"':=])${OC}\b`,"i"),Ym=/(?:^|[\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,LC=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'"])`,NC=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`${LC}|iex\b|invoke-expression\b|pwsh\b|powershell\b)`,jC=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}`,Ic=String.raw`^\s{0,5}[({]?\s{0,3}(?:${jC}){0,6}`+String.raw`(?:[\w./-]{0,40}\/)?(?:env\s{1,5}(?:-\S{1,20}\s{1,5}){0,3})?`,Em=new RegExp(Ic+NC,"i"),MC=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"),DC=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"),FC=/\beval\s{0,5}\(?\s{0,5}do\s{0,5}\{[^}\n]{0,100}(?:<STDIN>|<>)/i,HC=/(?:^|[;\s{(])\$?([A-Za-z_]\w{0,30})\s{0,3}=\s{0,3}[^;\n=]{0,60}$/,BC=600,WC=150;function GC(t){let e=t.slice(0,BC),n=[];for(let r of e.matchAll(DC))if(n.push(r.index??0),n.length>=16)break;if(n.length===0)return!1;if(FC.test(e))return!0;let s=0,i=0;for(let r of e.matchAll(MC)){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<=WC&&!/[;\n]/.test(e.slice(o,a)))return!0}for(let r of n.slice(0,4)){let o=HC.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 UC=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}["']?`,VC=new RegExp(`${Ic}${UC}`,"i"),zC=new RegExp(`${Ic}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 km(t){let e=VC.exec(t);return e&&GC(t.slice(e.index+e[0].length))?!0:zC.test(t)}var qC=/^\s{0,5}[({]?\s{0,3}(?:sudo\s{1,5}(?:-\S{1,20}\s{1,5}){0,3})?(?:[\w./-]{0,40}\/)?tee\b/i,KC=/^\s{0,5}[({]?\s{0,3}(?:while|until)\b[^;|]{0,150}?\bread\b([^;|]{0,100})/i,YC=/^\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,JC=/^\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,XC=/^\s*do\b/,ZC=/^\s*done\b/,QC=new Set(["-p","-d","-n","-N","-t","-u","-i"]),eA=250;function tA(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(QC.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 nA(t,e,n){let s=n[e];if(s===void 0){let i=t[e],r=i.text.slice(0,400);if(ZC.test(r))s={kind:"done"};else{s={kind:XC.test(r)?"do":"other"};let o=YC.exec(r);o&&(s.runs=o[1]);let a=i.sep==="|"&&e+1<t.length?JC.exec(r):null;a&&(s.echoes=a[1])}n[e]=s}return s}function sA(t,e,n){let s=t[e].text;if(!s.includes("read")||!/while|until/i.test(s))return;let i=KC.exec(s.slice(0,400));if(!i)return;let r=tA(i[1]??""),o=0;for(let a=e+1;a<t.length&&a<=e+eA;a++){let c=nA(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)&&Xm(t[a+1].text))return t[a+1].start+Math.min(t[a+1].text.length,60)}}var iA=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(`${Ym.source}|${iA.source}`,"i"),rA=16;function oA(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 Xm(t){if(!Rm.test(t))return!1;let e=oA(t);if(!Rm.test(e))return!1;if(Em.test(e)||km(e))return!0;if(e.includes(">(")&&qC.test(e)){let n=e.indexOf(">(");for(let s=0;n>=0&&s<4;s++){let i=e.slice(n+2);if(Em.test(i)||km(i))return!0;n=e.indexOf(">(",n+2)}}return!1}function Qi(t,e,n,s=0){if(!t.includes("|"))return;let i=[],r=Tc(t,n,i),o=aA(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:tr(t,a.start+c.index,a.start+c.index+c.match[0].length)}}}var Rm=/sh\b|SHELL|stdin|awk|python|node|perl|ruby|php|deno|bun|iex|invoke-expression|pwsh|powershell/i;function aA(t,e,n){let s=new Array(e.length),i=c=>(s[c]===void 0&&(s[c]=Xm(e[c].text)),s[c]),r=new Array(e.length),o=new Array(e.length),a=c=>(r[c]===void 0&&(r[c]=sA(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<=rA&&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:tr(t,p,h)}}if(f.sep!=="|")break}}}var cA=/^\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,lA=/^\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,Zm=/^\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,uA=/^\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,fA=/^\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 He(t){return Be.posix.basename(t.replace(/^['"]+|['"]+$/g,"").replace(/\\/g,"/"))}function Cm(t){return new Set(t.split(/\s+/).filter(Boolean).map(He))}function Qm(t,e){let n=/(?:^|\s)>{1,2}\s{0,3}(\S{1,300})/.exec(t);if(e==="encoded")return n?He(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?He(i[1]):/\s-[a-zA-Z]{0,10}O\b|\s--remote-name\b/.test(t)&&s?He(s.split(/[?#]/)[0]):n?He(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:He(i[1]):s?He(s.split(/[?#]/)[0]):void 0}return n?He(n[1]):void 0}var dA=/^\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,pA=/^\s{0,5}(?:sudo\s{1,5})?(?:(?:sha(?:1|224|256|384|512)|md5|b2)sum|shasum|openssl\s{1,5}dgst)\b/i,hA=/curl|wget|iwr|irm|invoke-web|base64|xxd|openssl|uudecode|sum\b|gpg|cosign|minisign|slsa/i,ks=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&&!hA.test(e))return;let r=Tc(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=>cA.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=uA.exec(d);if(h){this.fetchedVars.set(h[1],{line:n,feed:i,index:p});continue}let m=Rs.test(d)&&(/https?:\/\//i.test(d)||qm(d,1)),g=Ym.test(d);if(m||g){let A=m?"remote":"encoded",C=Qm(d,A);C&&this.produced.set(C,{kind:A,line:n,feed:i,seg:u,index:p});continue}let y=dA.exec(d);if(y){this.generated.add(He(y[1]));continue}if(a[u]){for(let A of this.verifiedFiles(d,u>0&&r[u-1].sep==="|"?r[u-1].text:void 0))l.set(A,[...l.get(A)??[],u]);continue}let b=fA.exec(d);if(b&&this.fetchedVars.has(b[1])){let A=this.fetchedVars.get(b[1]);return this.hit("remote-exec",e,A.feed===i?A.index:p,f.start+d.length,A.line)}if(/^\s{0,5}(?:chmod|cat|ls|rm|mv|cp|echo|printf|test|\[)\b/i.test(d))continue;let v=Zm.exec(d);if(!v)continue;let x=He(v[1]),w=this.produced.get(x);if(!(!w||w.kind==="remote"&&w.feed===i&&(l.get(x)??[]).some(A=>A>w.seg&&c(w.seg,u))))return this.hit(w.kind==="remote"?"remote-exec":"encoded-exec",e,w.feed===i?w.index:p,f.start+d.length,w.line)}}verifiedFiles(e,n){let s=[...this.produced.keys()];if(/--ignore-missing\b|<<<|<\(/.test(e))return[];let i=lA.exec(e)?.[1];if(i!==void 0){if(i==="-"||i==="/dev/stdin"){if(n===void 0||pA.test(n)||/<\(|\$\(/.test(n))return[];let c=Cm(n);return s.filter(l=>c.has(l))}let o=He(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:tr(n,o,Math.max(o,Math.min(n.length,i)))},fromLine:r}}},mA=[{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}],gA=[{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}],yA=/\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,_c=String.raw`(?:urllib\.request|urllib2|requests|httpx)`,Xi=new RegExp([String.raw`\bfrom\s{1,5}${_c}\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}${_c}\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}${_c}\s{0,3}(?=$|[\s;#)])`].join("|"),"g"),bA=/\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,Rc=["urlopen","get","post","request"],wA=new Set(Rc),Am=/urlopen|urllib|requests|httpx/,$m=new WeakMap;function vA(t,e){let n=[];if(t.length<=Ye){Xi.lastIndex=0;for(let s=Xi.exec(t);s!==null&&n.length<20;s=Xi.exec(t))n.push(s)}else for(let s of yt(Xi,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&&wA.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 Rc)e.add(`${(a??o).trim()}.${c}`)}else if(i.mod!==void 0||i.modassign!==void 0)for(let r of Rc)e.add(`${i.mod??i.modassign}.${r}`);else i.fn!==void 0&&e.add(i.fn)}}function xA(t){let e=$m.get(t);if(e!==void 0)return e;let n=null;if(Am.test(t.content)){let s=ig(t),i=new Map,r=new Set;for(let o of t.active){let a=t.lines[o];if(!a.includes("import")&&!a.includes("=")||!Am.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),vA(a,l)}n={blockOf:s,byBlock:i}}return $m.set(t,n),n}function eg(t,e,n){let s=de(yA,e);if(s)return s;let i=xA(t),r=i?.byBlock.get(i.blockOf(n));if(!(!r||r.size===0||!e.includes("("))){for(let o of yt(bA,e,20))if(r.has(o.match[1]))return o}}var _A={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}[( ]/]},SA={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}\(/]},EA=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"),kA=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"),RA=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"),CA=[/\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],AA=/ignore|disregard|forget|you\s{1,5}are|<\||<<SYS|INST\]|system\s{1,5}prompt|precedence|priority/i,$A=/user|silently/i,PA=/without|disable|turn\s{1,5}off|bypass|circumvent|skip|override|approve/i,TA=[/\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],IA=[/\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],OA=/--dangerously-skip-permissions\b|--dangerously-bypass-approvals-and-sandbox\b|\bbypassPermissions\b|--yolo\b|--allow-all-tools\b/i,LA=[/\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],NA=/\b(?:send|upload|post|transmit|exfiltrate|forward|paste|leak|e-?mail)\b/gi,Pm=/\b(?:send|upload|post|transmit|exfiltrate|forward|paste|leak|e-?mail)\b/i,jA=/\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,MA=/\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,DA=/\b(?:to|into|at|via)\b/i,FA=/webhook|pastebin|paste\.|hastebin|discord|telegram|ngrok|requestbin|pipedream|interactsh|burpcollaborator|\.onion\b|https?:\/\/\d{1,3}(?:\.\d{1,3}){3}/i,HA=/https?:\/\/|\bserver\b|\bendpoint\b|\bremote\b|\bexternal\b|third[-\s]party|\battacker\b|e-?mail\s{1,5}address/i,BA=/\bexternal\b|third[-\s]party|\battacker\b/i,WA=/\b(?:header|authorization|authenticate|bearer\s{1,5}auth)\b|\s-H\s/i,GA=/\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,UA=/\shidden(?:\s|=|\/|$)/i,VA=/^\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,zA=/\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,qA=/\byou\b|\b(?:must|always|never|approve|run|ignore|execute|send|upload|install|delete|disable|download|fetch|read|print|reveal)\b/i,KA=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"),YA=/(?<![A-Za-z0-9+/=])[A-Za-z0-9+/]{200,}={0,2}(?![A-Za-z0-9+/=])/g,JA=/\b(?:pip[0-9.]{0,5}|pipx|uvx|uv|npm|pnpm|yarn|bun|npx|bunx|go|cargo|gem|deno)\b/i,XA=/\bgit\+(?:https?|ssh|git|file):\/\/[^\s'"<>)`]{1,500}|\bgithub:[\w.-]{1,100}\/[\w.-]{1,100}(?:#[^\s'"<>)`]{0,100})?/gi,ZA=/(?<=[\w.-])@(?:latest|master|main|HEAD)(?![\w.-])/gi,QA=/\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,e$=/\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,t$=/\bcargo\s{1,5}install\b[^\n;&|]{0,300}--git\s{1,5}\S/i,n$=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"),s$=/\b(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod|fetch|urlopen|requests\.get|download|downloadstring)\b/i,i$=/(?:\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|ps1|rb|pl)(?:[?#]|$)|install)/i,r$=/(?:\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 Oc(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 Lc(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 tg(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)?!Oc(Lc(e.startsWith("git")||e.includes(":")?e:`github:${e}`)):/^https?:\/\//i.test(e)?!/\d+\.\d+\.\d+|#sha(?:256|512)=/i.test(e):!1}function o$(t){if(/@(?:latest|master|main|head)/i.test(t)){for(let e of yt(ZA,t,10))if(QA.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.\-/])`,c$=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"),l$=new RegExp(String.raw`(?:^|[\s\x60'"(;&|])(\.\/[\w@.\-/]{1,200}\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|rb|pl|ps1))(?![\w.\-/])`,"g"),u$=new Set(["json","jsonc","json5","yaml","yml","toml"]),f$=/\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|mts|rb|pl|ps1)\b/i,Tm={info:0,warning:1,high:2,critical:3},d$=5,$n=25;function Es(t,e){let n=Tm[t.severity]-Tm[e.severity];return n!==0?n>0:t.confidence>e.confidence}var Cc=class{groups=new Map;accepts(e,n,s,i){let r=this.groups.get(`${e}|${n}`);if(!r||r.hits.length<$n)return!0;let o={excerpt:"",severity:s,confidence:i};return r.hits.some(a=>Es(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<$n){r.hits.push(s);return}let o=0;for(let a=1;a<r.hits.length;a++)Es(r.hits[o],r.hits[a])&&(o=a);Es(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})=>p$(e,n,s,i,r))}};function p$(t,e,n,s,i){let r=ZR[e],o=s.map((d,p)=>({h:d,order:p})).sort((d,p)=>Es(d.h,p.h)?-1:Es(p.h,d.h)?1:d.order-p.order),a=o[0].h,c=o.slice(0,d$).sort((d,p)=>(d.h.line??0)-(p.h.line??0)||d.order-p.order).map(d=>d.h),l=Qt(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?xc(t):`${xc(n)} (bundled with ${xc(t)})`;return{id:`skill-supply-chain-${e}-${fe(`${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:[Ac,e]}}var ng=t=>typeof t=="function"?t():t,h$=.4;function er(t,e,n,s,i,r,o){e!=="skip"&&(e==="lowconf"?t(n,s,()=>`(looks like documentation, but names a target) ${ng(i)}`,r,h$):t(n,s,i,r,o))}var m$=/[|&;<$`]|>\(|iex|invoke-expression|atob|decode|FromBase64|powershell|pwsh/i;function sg(t,e){let n=[];if(!m$.test(t))return n;let s=Qi(t,Rs,e);s&&n.push({rule:"remote-exec",found:s});let i=Qi(t,Jm,e);if(i&&n.push({rule:"encoded-exec",found:i}),!n.some(r=>r.rule==="remote-exec"))for(let r of mA){let o=de(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 gA){let o=de(r.pattern,t,r.requires);if(o){n.push({rule:"encoded-exec",found:o});break}}return n}function ig(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 g$(t,e,n,s,i){let r=new Set,o=ig(t),a=new ks(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 ks(i),c=p);let h=sg(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:y,note:b}of h){let v=y.match[0].length,x=nr(t,f,l,y.index,v);er(s,x,g,u,()=>`${b??""}${xe(l,y.index,v)}`,"high",.85),x!=="skip"&&r.add(u)}}if(t.kind==="instructions")for(let{text:l,line:u}of n){if(r.has(u))continue;let f=eg(t,l,u-1);f&&(r.add(u),s("remote-eval",u,xe(l,f.index,f.match[0].length),"high",.85))}return r}function y$(t,e){for(let n of t.active){let s=de(e,t.lines[n]);if(s)return{line:n+1,index:s.index}}}function b$(t,e,n){let s=y$(t,EA),i=[],r=[],o=_A[t.lang]??[],a=SA[t.lang]??[];for(let l of t.active){let u=l+1;if(e.has(u))continue;let f=t.lines[l],d=eg(t,f,l);if(d){n("remote-eval",u,xe(f,d.index,d.match[0].length),"high",.85);continue}if(i.length+r.length>=$n)continue;let p=o.map(m=>de(m,f)).find(Boolean);if(p){i.push({line:u,index:p.index});continue}let h=a.map(m=>de(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: ${xe(t.lines[s.line-1],s.index)}`,"high",.75);for(let l of[...i,...r])n("remote-eval",l.line,xe(t.lines[l.line-1],l.index),"high",.75)}else for(let l of i)n("dynamic-eval",l.line,xe(t.lines[l.line-1],l.index),"warning",.6);if(!s)return;let c=[];for(let l of t.active){if(c.length>=$n)break;let u=t.lines[l],f=de(kA,u)??de(RA,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: ${xe(t.lines[s.line-1],s.index)}`,"high",.7);for(let l of c)n("credential-exfil",l.line,`credential/env read: ${xe(t.lines[l.line-1],l.index)}`,"high",.7)}}function Zi(t,e,n,s,i={}){for(let r of s){let o=de(r,n);if(!o)continue;let a=o.match[0].length;if(i.skipQuoted&&$C(n,o.index,o.index+a))continue;let c;if(i.negatable===!1?c=!t.fenced[e]&&$c(n,o.index,a)?Pc(n.slice(o.index,o.index+a+80))?"lowconf":"skip":"none":c=nr(t,e,n,o.index,a,i.targetless),c!=="skip")return{found:o,verdict:c}}}function w$(t){for(let e of yt(NA,t,20)){let n=Um(t,e.index),s=e.index+e.match[0].length,i=t.slice(s,s+120),r=jA.exec(i),o=r?null:MA.exec(i),a=r??o;if(!a)continue;let c=s+a.index+a[0].length,l=DA.exec(t.slice(c,c+120));if(!l)continue;let u=c+l.index+l[0].length,f=t.slice(u,u+100),d=FA.test(f);if(!d&&WA.test(t))continue;let p=Pc(f),h={index:e.index,strong:d,negated:n,target:p};if(d)return{...h,severity:"high",confidence:.75};if(r&&HA.test(f))return{...h,severity:"warning",confidence:.6};if(o&&BA.test(f))return{...h,severity:"warning",confidence:.6}}}function v$(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 x$(t,e){let n=(s,i,r,o,a,c)=>er(e,o.verdict,s,i,xe(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(AA.test(i)){let o=Zi(t,s,i,CA,{skipQuoted:!0,targetless:!0});o&&n("instruction-override",r,i,o,"high",.8)}if($A.test(i)){let o=Zi(t,s,i,TA,{targetless:!0}),a=o?void 0:Zi(t,s,i,IA,{negatable:!1});o?n("conceal-from-user",r,i,o,"high",.75):a&&n("conceal-from-user",r,i,a,"warning",.6)}if(PA.test(i)){let o=Zi(t,s,i,LA,{targetless:!0});o&&n("permission-bypass",r,i,o,"warning",.6)}if(Pm.test(i))for(let o of v$(i)){if(!Pm.test(o.text))continue;let a=w$(o.text);if(!a)continue;let c=o.offset+a.index,u=!t.fenced[s]&&(a.negated||$c(i,c,10))?a.target?"lowconf":"skip":"none";er(e,u,"exfil-instruction",r,xe(i,c,60),a.severity,a.confidence);break}}}function _$(t,e){for(let n of t.active){let s=t.lines[n],i=de(OA,s);if(!i||t.kind==="instructions"&&!t.fenced[n]&&IC(s))continue;let r=i.match[0].length;er(e,nr(t,n,s,i.index,r,!0),"permission-bypass",n+1,()=>xe(s,i.index,r),"warning",.7)}}var S$=/[\p{Script=Hebrew}\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Nko}]/u,E$=/\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Emoji_Component}/u,k$=/[\p{L}\p{M}]/u,R$=/\p{Script=Mongolian}/u,C$=/\p{Cf}/u,A$=[[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]],Im=t=>"\\u{"+t.toString(16)+"}",Sc=new RegExp("["+A$.map(([t,e])=>Im(t)+"-"+Im(e)).join("")+"\\p{Cf}]","gu");function Ec(t){return t>=65024&&t<=65039||t>=917760&&t<=917999}function rg(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 kc=t=>t===void 0?void 0:String.fromCodePoint(t);function $$(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=rg(t,e),a=t.codePointAt(e+(n>65535?2:1));if(n===8204||n===8205){let c=l=>l!==void 0&&l>127&&(E$.test(kc(l))||k$.test(kc(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(Ec(n)){let c=a===void 0||!Ec(a);return o!==void 0&&o>127&&!Ec(o)&&c?void 0:"mild"}if(n>=6155&&n<=6159&&n!==6158)return o!==void 0&&R$.test(kc(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||C$.test(String.fromCodePoint(n)))return"mild"}function P$(t,e){for(let n of t.active){let s=t.lines[n];Sc.lastIndex=0;let i=Sc.exec(s);if(i===null)continue;let r,o=()=>r??=S$.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=rg(s,d);(m===void 0||m<917504||m>917631)&&(f=m)}let h=$$(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=Sc.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])=>`${bi(h)}\xD7${m}`).join(" "),p=a.size>4?` (+${a.size-4} more kinds)`:"";return`${d}${p} in: ${xe(s,c?u:l,1)}`},c?"high":"warning",c?.9:.7)}}function T$(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 I$(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(GA.test(o)||UA.test(o))return{index:s,match:tr(t,s,i+1)}}}function O$(t,e){t.content.includes("<!--")&&L$(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=I$(s);i&&e("hidden-html-element",n+1,xe(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=yt(YA,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 L$(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(VA.test(l.slice(0,200))&&l.length<=120&&!zA.test(l)&&!qA.test(l))continue;let u=de(KA,l);if(!u)continue;let f=T$(i,o+4+u.index),d=t.lines[f-1]??"",p=o+4+u.index-i[f-1];e("hidden-html-comment",f,()=>xe(d,p,u.match[0].length),"warning",.6)}}function N$(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 yt(/`([^`\n]{1,1000})`/g,s.text,50))nr(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 Om(t,e,n,s){let i=(r,o,a,c=.6)=>s("unpinned-remote-dep",r,xe(o,a,80),"warning",c);if(t.kind==="manifest")return M$(t,i,s);for(let{text:r,line:o}of e){if(n.has(o))continue;if(JA.test(r)){let f=yt(XA,r,10).find(d=>!Oc(Lc(d.match[0])));if(f){i(o,r,f.index);continue}}let a=o$(r);if(a){i(o,r,a.index,.5);continue}let c=de(e$,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))&&tg(p))){i(o,r,c.index);continue}let l=de(t$,r);if(l&&!/--(?:rev|tag)\s{1,5}\S/.test(r)){i(o,r,l.index);continue}let u=de(n$,r);if(u&&de(s$,r)&&i$.test(u.match[0])){i(o,r,u.index);continue}if(t.kind==="script"&&t.lang==="js"){let f=yt(r$,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 j$(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 ks().feed(c,1,!0);for(let{rule:u,found:f}of[...sg(c,!0),...l?[l]:[]])n(u,Ke(t.content,`"${a}"`),`scripts.${Qt(a)}: ${xe(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=Be.posix.dirname(t.path);return r.slice(0,5).map(a=>Be.posix.normalize(`${o}/${a.replace(/\\/g,"/")}`)).filter(a=>a.startsWith(`${o}/`))}function M$(t,e,n){if(Be.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=j$(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"||tg(f)){if(++o>$n)return r;let d=Ke(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=de(/\bgit\+[a-z]{1,10}:\/\/\S{1,500}/i,r);if(o&&!Oc(Lc(o.match[0]))){e(i+1,r,o.index);continue}let a=de(/\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 D$(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>=F$)return;c++;let p=rt(t,f);return a.set(f,p),p};for(let f of n.active){let d=n.lines[f];if(!(n.fenced[f]&&u$.has(n.fenceLang.get(f)??""))&&f$.test(d))for(let p of[c$,l$])for(let h of yt(p,d,10)){let m=h.match[1],g=m.replace(/^\.\//,""),y=o(m);if(!y)continue;let b=!1,v=!1;for(let x of y){let w=u(x);if(w===void 0)v=!0;else if(w){b=!0;break}}if(!b){if(v)return;if(!(s().has(g)||s().has(m))&&(i("missing-script",f+1,`${Qt(m)} not found (looked in: ${y.map(Qt).join(", ")})`,"warning",.6),++l>=$n))return}}}}var F$=200,H$=3e6;function Lm(t,e,n){let s=Buffer.alloc(n),i=Ot.readSync(t,s,0,n,e);return s.subarray(0,i)}function B$(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&&W$.test(u)&&o.push(l)}let a=new Uint8Array(r.length),c=new Map;if(e.kind==="instructions"&&(n.includes("```")||n.includes("~~~"))){let l=Se(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?lC(r):0,tail:i}}var W$=/[^ \t\r]/;function G$(t){let e=1;for(let n=t.indexOf(10);n>=0;n=t.indexOf(10,n+1))e++;return e}function U$(t,e,n,s,i){let r=s?"high":"warning",o=n?{kind:"instructions",lang:"other"}:Nm(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=Bt(t,e);if(!a)return{docs:[],unscanned:[]};if(!be(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=Ot.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=Ot.openSync(a,"r"),o==="probe"){let g=Lm(c,0,Math.min(u,yn));if(Gt(g))return{docs:[],unscanned:[{path:e,reason:`${cC(g)} \u2014 cannot be reviewed as text`,severity:"warning"}]};let y=aC(g.toString("utf8").split(/\r?\n/,1)[0]??"");o=y?{kind:"script",lang:y}:{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,y,b)=>{let v=Lm(c,g,y);return i.bytes-=v.length,i.lines-=G$(v),B$(e,f,v.toString("utf8"),n&&!b,b)};if(u<=2*ce){let g=Math.min(u,i.bytes),y=[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:y,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&&Ot.closeSync(c)}}function V$(t,e,n,s,i,r,o){let a=(p,h,m,g,y)=>{if(!r.accepts(p,n.path,g,y)){r.count(p,n.path);return}let b=n.tail?"(end of file) ":n.frontmatterEnd>0&&h<=n.frontmatterEnd?"(frontmatter) ":"";r.add(p,n.path,{line:n.tail?void 0:h,excerpt:`${b}${ng(m)}`,severity:g,confidence:y})};if(P$(n,a),_$(n,a),n.kind==="manifest")return Om(n,[],new Set,a);let{lines:c,capped:l}=pC(n);l.length>0&&o.push({path:n.path,reason:`continuation chain longer than ${Mm} lines / ${Dm} characters at line ${l[0]} \u2014 split for scanning (a download-fed loop body is followed up to ${Fm} lines / ${Hm} characters)`,severity:"warning"});let u=N$(n,c),d=g$(n,c,u,a,p=>{let h=p.replace(/^\.\//,"");return!h||h.startsWith("/")||/^[a-z]:/i.test(h)?!1:[`${Be.posix.dirname(n.path)}/${h}`,`${e}/${h}`,h].some(m=>rt(t,m))});return Om(n,u,d,a),n.kind==="instructions"?(x$(n,a),O$(n,a),s&&!n.tail&&D$(t,e,n,i,a)):b$(n,d,a),[]}var z$=["node_modules",".git","worktrees",".worktrees"],q$={node_modules:/(?:^|[\s'"`(=:/])node_modules\//m,".git":/(?:^|[\s'"`(=:])(?:\.\/)?\.git\//m,worktrees:/(?:^|[\s'"`(=:])(?:\.\/)?worktrees\//m,".worktrees":/(?:^|[\s'"`(=:])(?:\.\/)?\.worktrees\//m};function K$(t,e){let n=t.entries(`${e}/hooks`);if(typeof n=="string")return!1;for(let s of n.keys())if(!s.endsWith(".sample"))return!0;return!1}function Y$(t,e,n){switch(t.kind){case"dependency-dir":{let s=Be.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"&&K$(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 Nc(t,e={}){let n=V(t),s=t.aiConfig??{},i=s.allSkills??s.skills??[],r=new Set(s.skills??[]),o=i.map(h=>Be.posix.dirname(h)),a=h=>{let m=-1;return o.forEach((g,y)=>{qn(g)||!(h===g||h.startsWith(`${g}/`))||(m<0||g.length>o[m].length)&&(m=y)}),m},c=i.map((h,m)=>{let g={skillMd:h,dir:o[m],collector:new Cc,unscanned:[],alreadyReported:()=>new Set,referenced:new Set,queue:{priority:[],rest:[]},loaded:!1};if(r.has(h)){let y;g.alreadyReported=()=>y??=new Set(wc(g.headContent??"").map(b=>b.ref))}return g});for(let h of s.skillFiles??[]){let m=a(h);m>=0&&(xm(h)?c[m].queue.priority:c[m].queue.rest).push(h)}for(let h of s.skillFilesOverCap??[]){let m=a(h);m>=0&&c[m].unscanned.push({path:h,reason:"over the per-skill file cap \u2014 not scanned",severity:xm(h)?"high":"warning"})}let l={bytes:e.bytes??JR,files:e.files??XR,lines:e.lines??H$},u=(h,m)=>{if(!(m.kind!=="instructions"&&m.kind!=="script"&&!(m.kind==="text"&&m.lang==="sh")))for(let g of z$)q$[g].test(m.content)&&h.referenced.add(g)},f=new Set,d=(h,m,g,y)=>{if(f.has(m))return{docs:[],unscanned:[]};f.add(m);let b=U$(t.repoRoot,m,g,y,l);h.unscanned.push(...b.unscanned);let v=[];g&&(h.headContent=b.docs[0]?.content);for(let x of b.docs)u(h,x),v.push(...V$(n,h.dir,x,g,h.alreadyReported,h.collector,h.unscanned));for(let x of v)a(x)>=0&&d(h,x,!1,!0);return b};for(let h of c){let m=d(h,h.skillMd,!0,!0);h.loaded=m.docs.length>0||m.unscanned.length>0;for(let g of h.queue.priority)d(h,g,!1,!0)}for(let h of c)for(let m of h.queue.rest)d(h,m,!1,!1);let p=[];for(let h of c)if(h.loaded){for(let m of s.skillBundleSkips??[])a(m.path)===c.indexOf(h)&&h.unscanned.push(Y$(m,h.referenced,n));for(let m of h.unscanned)h.collector.add("unscanned-files",h.skillMd,{excerpt:`${Qt(m.path)}: ${m.reason}`,severity:m.severity,confidence:.8});p.push(...h.collector.toIssues(h.skillMd))}return Te(t.repoRoot,p)}var jc=R(require("node:path"),1);var J$={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."},X$=new Set(["sonnet","opus","haiku","inherit","default","opusplan"]),Z$=new Set(["Task","Bash","BashOutput","KillBash","KillShell","Glob","Grep","LS","Read","Edit","MultiEdit","Write","NotebookRead","NotebookEdit","WebFetch","WebSearch","TodoWrite","SlashCommand","ExitPlanMode","Agent"]),Q$=.8,eP=5;function Cs(t,e){return`ai-config-agent-${t}-${fe(e)}`}function tP(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 nP(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 Mc(t){let e=[],n=[];for(let i of t.aiConfig.agents){let r=ve(t.repoRoot,i);if(r===void 0)continue;let o=ht(r);if(e.push(...Tt(i,r,o,J$)),!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(B({id:Cs("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(B({id:Cs("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&&!X$.has(l.toLowerCase())&&!/^claude-/i.test(l)&&e.push(B({id:Cs("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=En(o.data.tools),f=u.filter(h=>h!=="*"&&!h.startsWith("mcp__")&&!Z$.has(h));f.length>0&&e.push(B({id:Cs("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=tP(d);n.push({filePath:i,bodyLines:p})}let s=n.filter(i=>i.bodyLines.size>=eP);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=nP(o.bodyLines,a.bodyLines);if(c>=Q$){let l=[o.filePath,a.filePath].sort();e.push(B({id:Cs("dup-prompt",l.join("|")),title:"Two subagents share near-identical system prompts",summary:`${Yt(jc.basename(l[0]))} and ${Yt(jc.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 sP=/\b(curl|wget)\b[^|]*\|\s*(sudo\s+)?(sh|bash|zsh|dash)\b/i;function sr(t,e){return`ai-config-hook-${t}-${fe(e)}`}function Fc(t,e,n){if(Array.isArray(t)){for(let i of t)Fc(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&&Fc(r,e===""?i:e,n)}var iP=new Set(["bash","sh","zsh","dash","node","deno","python","python3","ruby","ts-node","tsx","pwsh","powershell"]),rP=new Set(["npx","bunx","pnpm","yarn","uv","uvx","env","timeout","nice","sudo","exec","command"]);function Dc(t){return t.replace(/^['"]|['"]$/g,"").replace(/^\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/,"")}function oP(t){let e=new Set,n=(s,i)=>{if(s.startsWith("-"))return;let r=s.replace(/^['"]|['"]$/g,""),o=Dc(s);if(!o||o.includes("$")||/[<>{}*?|"'`]/.test(o)||o.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(o)||/^https?:/i.test(o)||o.includes("..")||!ss.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=Dc(i[0]);if(iP.has(r)||rP.has(r)){for(let o=1;o<i.length;o++)if(!i[o].startsWith("-")&&ss.test(Dc(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 aP(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 cP(t){for(let e of t.matchAll(/\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/g))if(!aP(t,e.index))return!0;return!1}function Hc(t){let e=[],n=V(t);for(let s of t.aiConfig.settings){let i=ve(t.repoRoot,s);if(i===void 0)continue;let r;try{r=JSON.parse(i)}catch(l){e.push(B({id:sr("invalid-json",s),severity:"high",title:"Settings file is not valid JSON",summary:`${s} could not be parsed as JSON, so Claude Code cannot load its hooks or permissions.`,filePaths:[s],locations:[{filePath:s,startLine:1,endLine:1}],evidence:[`Parse error: ${l.message}`],recommendation:"Fix the JSON syntax (trailing commas and comments are not allowed in settings.json).",confidence:.95}));continue}if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r.hooks;if(o===void 0)continue;let a=[];Fc(o,"",a);let c=new Set;for(let{command:l,event:u}of a){let f=Ke(i,l);sP.test(l)&&e.push(B({id:sr("curl-pipe-sh",`${s}|${l}`),severity:"high",impact:"high",title:"Hook pipes a remote download into a shell",summary:`A ${u||"hook"} command in ${s} pipes \`curl\`/\`wget\` output directly into a shell, running whatever the remote host serves with your permissions.`,filePaths:[s],locations:[{filePath:s,startLine:f,endLine:f}],evidence:[`Command: ${l.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})),cP(l)&&e.push(B({id:sr("unquoted-project-dir",`${s}|${l}`),severity:"info",title:"Hook uses an unquoted $CLAUDE_PROJECT_DIR path",summary:`A ${u||"hook"} command in ${s} expands \`$CLAUDE_PROJECT_DIR\` unquoted; if the project path contains a space the command breaks or runs the wrong file.`,filePaths:[s],locations:[{filePath:s,startLine:f,endLine:f}],evidence:[`Command: ${l.slice(0,160)}`],recommendation:'Wrap the path in double quotes, e.g. `"$CLAUDE_PROJECT_DIR/script.sh"`.',confidence:.5}));for(let d of oP(l)){if(rt(n,d))continue;let p=`${s}|${d}`;c.has(p)||(c.add(p),e.push(B({id:sr("missing-script",p),title:"Hook command references a script that does not exist",summary:`A ${u||"hook"} command in ${s} runs \`${d}\`, but that file is not present in the repository.`,filePaths:[s],locations:[{filePath:s,startLine:f,endLine:f}],evidence:[`Referenced script: ${d}`,`Command: ${l.slice(0,160)}`],recommendation:"Add the script, fix the path, or remove the hook.",confidence:.75})))}}}return Te(t.repoRoot,e)}function As(t,e){return`ai-config-mcp-${t}-${fe(e)}`}function lP(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 uP(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=lP(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 fP(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 dP(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("/")&&ss.test(o))&&n.add(o.replace(/\\/g,"/"))};t&&s(t,!1);for(let i of e)s(i,!0);return[...n]}function Bc(t){let e=[],n=V(t);for(let s of t.aiConfig.mcp){let i=ve(t.repoRoot,s);if(i===void 0)continue;let r;try{r=JSON.parse(i)}catch(a){e.push(B({id:As("invalid-json",s),severity:"high",title:"MCP config is not valid JSON",summary:`${s} could not be parsed as JSON, so no MCP servers will load from it.`,filePaths:[s],locations:[{filePath:s,startLine:1,endLine:1}],evidence:[`Parse error: ${a.message}`],recommendation:"Fix the JSON syntax (no trailing commas, no comments).",confidence:.95}));continue}if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r.mcpServers;if(!(typeof o!="object"||o===null||Array.isArray(o))){for(let a of uP(i))e.push(B({id:As("duplicate-name",`${s}|${a}`),title:"Duplicate MCP server name",summary:`${s} defines the server "${a}" more than once. JSON keeps only the last definition and silently discards the earlier one.`,filePaths:[s],locations:[{filePath:s,startLine:Ke(i,`"${a}"`),endLine:Ke(i,`"${a}"`)}],evidence:[`Duplicated server name: ${a}`],recommendation:"Rename or remove the duplicate so each server name is unique.",confidence:.85}));for(let[a,c]of Object.entries(o)){if(typeof c!="object"||c===null||Array.isArray(c))continue;let l=c,u=typeof l.command=="string"?l.command:void 0,f=typeof l.url=="string"?l.url:void 0,d=Array.isArray(l.args)?l.args.filter(h=>typeof h=="string"):[],p=Ke(i,`"${a}"`);if(!u&&!f&&e.push(B({id:As("no-command-or-url",`${s}|${a}`),title:"MCP server has neither a command nor a url",summary:`${s}: server "${a}" defines no \`command\` (stdio) and no \`url\` (http/sse), so it cannot start.`,filePaths:[s],locations:[{filePath:s,startLine:p,endLine:p}],evidence:[`Server: ${a}`,`Keys: ${Object.keys(l).join(", ")||"(none)"}`],recommendation:"Add a `command` (with `args`) for a stdio server, or a `url` for a remote server.",confidence:.8})),typeof l.env=="object"&&l.env!==null&&!Array.isArray(l.env))for(let[h,m]of Object.entries(l.env))typeof m!="string"||!fP(m)||e.push(B({id:As("placeholder-env",`${s}|${a}|${h}`),title:"MCP server env value is an unfilled placeholder",summary:`${s}: server "${a}" sets \`env.${h}\` to a placeholder (${JSON.stringify(m)}) that was never replaced with a real value.`,filePaths:[s],locations:[{filePath:s,startLine:Ke(i,`"${h}"`),endLine:Ke(i,`"${h}"`)}],evidence:[`${h}: ${m}`],recommendation:'Replace the placeholder with a real value, or reference a shell variable like `"${'+h+'}"`.',confidence:.7}));for(let h of dP(u,d))rt(n,h)||e.push(B({id:As("missing-command",`${s}|${a}|${h}`),title:"MCP server command path does not exist",summary:`${s}: server "${a}" references the local path \`${h}\`, which is not present in the repository.`,filePaths:[s],locations:[{filePath:s,startLine:p,endLine:p}],evidence:[`Referenced path: ${h}`,`Server: ${a}`],recommendation:"Fix the path, add the missing file, or install the server so the path resolves.",confidence:.7}))}}}return Te(t.repoRoot,e)}var ag=R(ft(),1);var pP={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},hP=["**/node_modules/**","**/.git/**"];function og(t,e){return`ai-config-cursor-${t}-${fe(e)}`}function mP(t){let e=t.trim();return!(!e||e.startsWith("!")||e.includes("$")||e.includes("<")||e.includes(">"))}function Wc(t){let e=[],n=t.aiConfig.cursorRules,s=null,i=r=>(s??=ot(t.repoRoot,["**/*"],hP),ag.default.some(s,r,{dot:!0}));for(let r of n){let o=ve(t.repoRoot,r);if(o===void 0)continue;let a=ht(o);if(e.push(...Tt(r,o,a,pP)),!a.present)continue;let c=typeof a.data.description=="string"?a.data.description.trim():"",l=En(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(B({id:og("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(!mP(f))continue;let d=f.replace(/^\//,""),p=d.includes("/")?[d]:[d,`**/${d}`];i(p)||e.push(B({id:og("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 Uc=R(ft(),1);var gP={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},yP=["**/node_modules/**","**/.git/**"],bP=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/out/**","**/coverage/**","**/worktrees/**","**/.worktrees/**"];function Gc(t,e){return`ai-config-copilot-${t}-${fe(e)}`}function wP(t){let e=t.trim();return!(!e||e.startsWith("!")||e.includes("$")||e.includes("<")||e.includes(">"))}function vP(t){let e=t.trim();return e==="**"||e==="**/*"}function Vc(t){let e=[],n=t.aiConfig.copilotInstructions,s=null,i=null,r=a=>(s??=ot(t.repoRoot,["**/*"],yP),Uc.default.some(s,a,{dot:!0})),o=a=>(i??=ot(t.repoRoot,["**/*"],bP),Uc.default.some(i,a,{dot:!0}));for(let a of n){let c=ve(t.repoRoot,a);if(c===void 0)continue;let l=ht(c);if(e.push(...Tt(a,c,l,gP)),!l.present)continue;let u=En(l.data.applyTo);if(u.length===0){e.push(B({id:Gc("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(!wP(d)||vP(d))continue;let p=d.replace(/^\//,""),h=p.includes("/")?[p]:[p,`**/${p}`];r(h)?o(h)||e.push(B({id:Gc("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(B({id:Gc("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 xP=[{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}],_P=2;function zc(t){let e=[],n=i=>i==="windsurf",s=[...t.files.filter(i=>i.fileType==="windsurf").map(i=>[i]),...es(Ut(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 xP)l.re.test(c)&&o.add(l.label)}if(o.size>=_P){let a=[...o].sort();e.push({id:`ai-config-windsurf-scope-${fe(N(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 cg=R(require("node:crypto"),1),lg=R(require("node:path"),1);var SP=he,EP=[/\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],kP=/^(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,RP=/\b(must|should|always|shall)\b/i,CP=8,AP=.4;function $P(t){return t.replace(/^\s*#{1,6}\s+/,"").replace(/^\s*[-*+]\s+/,"").replace(/^\s*\d+[.)]\s+/,"").replace(/^\s*>\s+/,"").trim()}function PP(t){return t.replace(/^[*_`]+/,"").trimStart()}function TP(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=$P(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 IP(t){let e=PP(t);if(kP.test(e))return"positive";for(let n of EP)if(n.test(t))return"negative";return RP.test(t)?"positive":"none"}function OP(t){return`negative-overload-${cg.createHash("sha1").update(`negative-overload:${t}`).digest("hex").slice(0,12)}`}function qc(t){let e=[];for(let n of t){if(!SP.has(n.fileType))continue;let s=TP(n.content),i=[],r=0;for(let f of s){let d=IP(f);d==="negative"?i.push(f):d==="positive"&&r++}let o=i.length+r;if(o<CP)continue;let a=i.length/o;if(a<=AP)continue;let c=lg.basename(n.path),l=Math.round(a*100),u=i.slice(0,3).map(f=>Z(f,100));e.push({id:OP(N(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 ug=R(require("node:crypto"),1),fg=R(require("node:path"),1);var LP=he,NP=[/\bnever\b/i,/\bcritical\b/i,/\bmust\s+not\b/i,/\bsecurity\b/i,/\bdangerous\b/i],jP=100,MP=.6;function DP(t){return NP.some(e=>e.test(t))}function FP(t){return`buried-critical-${ug.createHash("sha1").update(`buried-critical:${t}`).digest("hex").slice(0,12)}`}function Kc(t){let e=[];for(let n of t){if(!LP.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<=jP)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||DP(m)&&(o.push(h+1),h>=r&&a++)}if(o.length===0)continue;let l=a/o.length;if(l<=MP)continue;let u=fg.basename(n.path),f=Math.round(l*100),d=o.filter(h=>h>r),p=s[(d[0]??o[0])-1]??"";e.push({id:FP(N(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]}: "${Z(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 dg=R(require("node:crypto"),1);var HP=he,BP=6,WP=.65,GP=40,UP=8;function VP(t){return t.toLowerCase().replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+[.)]\s+/gm,"").replace(/\s+/g," ").trim()}function zP(t){return new Set(t.match(/\b\w+\b/g)??[])}function qP(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 KP(t){let e=t.text.split(`
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=VP(a),l=zP(c);c.length>=GP&&l.size>=UP&&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 YP(t,e){return`within-section-dup-${dg.createHash("sha1").update(`within-section-dup:${t}:${e}`).digest("hex").slice(0,12)}`}function Yc(t){let e=[];for(let n of t)if(HP.has(n.fileType))for(let s of n.sections){let i=KP(s);if(i.length<BP)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=qP(i[u].tokens,i[f].tokens);d>=WP&&(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:YP(N(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}: "${Z(r.a.text,120)}"`,`Paragraph ${r.b.number}: "${Z(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 JP=t=>he.has(t),$s=t=>cp(t.files,t.aliasFiles,JP),Jc=[{id:"duplicates",run:t=>la(t.files)},{id:"duplicate-headings",run:t=>ua(t.files)},{id:"within-section-dedup",run:t=>Yc($s(t))},{id:"conflicts",run:t=>da(t.files)},{id:"version-conflicts",run:t=>pa(t.files)},{id:"competing-tech-conflicts",run:t=>ha(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=>nm(t.files)},{id:"command-validity",run:t=>rh(t)},{id:"missing-context",run:t=>Xh(t.files,t.projectType)},{id:"manifest-consistency",run:t=>Ka(t)},{id:"dependency-staleness",run:t=>fc({...t,files:$s(t)})},{id:"vague-guidance",run:t=>om(t.files,{severityOverride:t.vagueGuidanceSeverity})},{id:"dead-references",run:t=>wa(t.files,t.repoRoot,t.tree)},{id:"agent-practices",run:t=>va(t.files,t.aliasFiles)},{id:"canonical-owner",run:t=>Hh(t.files)},{id:"ci-alignment",run:t=>Uh(t)},{id:"security-pack",run:t=>am(t)},{id:"action-pinning",run:t=>dc(t)},{id:"framework-packs",run:t=>hm(t)},{id:"prompt-cache-friendliness",run:t=>bm($s(t))},{id:"ai-config-skills",run:t=>vc(t)},{id:"skill-supply-chain",run:t=>Nc(t)},{id:"ai-config-subagents",run:t=>Mc(t)},{id:"ai-config-hooks-settings",run:t=>Hc(t)},{id:"ai-config-mcp",run:t=>Bc(t)},{id:"ai-config-cursor-rules",run:t=>Wc(t)},{id:"ai-config-copilot-instructions",run:t=>Vc(t)},{id:"ai-config-windsurf-rules",run:t=>zc(t)},{id:"negative-instructions",run:t=>qc($s(t))},{id:"buried-critical",run:t=>Kc($s(t))},{id:"custom-rules",run:t=>tc(t.files,t.customRules,t.repoRoot)}];function Xc(t){return Jc.flatMap(e=>e.run(t))}async function Zc(t){let e=await ps(t),n=Jc.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 en=R(require("node:path"),1);var ir=R(require("node:path"),1),pg=new Set(["duplicate","context_bloat","stale_instruction","conflict","vague_guidance"]);function hg(t){return Math.round(t/4)}var XP=process.platform==="win32"||process.platform==="darwin";function Qc(t){let e=ir.resolve(t).split(ir.sep).join("/");return XP?e.toLowerCase():e}function mg(t){let e=t.content.split(`
93
+ `;function Ds(t){return`${js.join(t)}${t}`}var ho=[{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."}],PR=[{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 $R(t){let e=t.entries(t.root);return typeof e=="string"?[]:[...e.values()].filter(n=>!n.isDirectory()).map(n=>n.name)}var ng=t=>/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(t)||t==="Directory.Build.props",IR=t=>["pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts"].includes(t),OR={bin:(t,e)=>e.some(n=>ng(n)||IR(n))&&!LR(t)&&!MR(t,"bin"),obj:(t,e)=>e.some(ng)};function LR(t){let e=t.readText("package.json",{maxBytes:1e6});if(e.state==="missing"||e.state==="outside")return!1;if(e.state!=="found")return!0;let n;try{n=JSON.parse(e.content)}catch{return!0}if(typeof n!="object"||n===null||Array.isArray(n))return!0;let{bin:s,directories:i}=n,o=typeof s=="string"?[s]:typeof s=="object"&&s!==null?Object.values(s):[];return i&&typeof i=="object"&&o.push(i.bin),o.some(r=>{if(typeof r!="string")return!1;let a=Ut.posix.normalize(r.replace(/\\/g,"/"));return a==="bin"||a.startsWith("bin/")})}var NR=/\.(?:sh|bash|zsh|fish|js|mjs|cjs|ts|mts|cts|py|rb|pl|php|ps1|cmd|bat)$/i;function MR(t,e){let n=t.entries(e);if(typeof n=="string")return!0;for(let s of n.values()){if(s.isDirectory())continue;if(NR.test(s.name))return!0;if(s.name.includes("."))continue;let i=t.readText(`${e}/${s.name}`,{maxBytes:256*1024});if(i.state!=="too-large"&&(i.state!=="found"||i.content.startsWith("#!")))return!0}return!1}function mo(t){return`security-pack-${yo.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function jR(t,e){return`destructive-command-${yo.createHash("sha1").update(`destructive-command:${t}:${e}`).digest("hex").slice(0,12)}`}function DR(t){return`security-pack-inspect-reports-first-${yo.createHash("sha1").update(`inspect-reports-first:${t}`).digest("hex").slice(0,12)}`}function Fs(t,e){return e.some(n=>n.test(t))}function go(t,e){return t.startsWith("!")?!1:t.replace(/^\/+|\/+$/g,"").split("/").includes(e)}function sg(t){let{files:e,repoRoot:n}=t;if(e.length===0)return[];let s=Z(t),i=[],o=e.map(v=>v.content).join(`
94
+ `),r=e.map(v=>v.path);if([".env",".env.example",".env.local",".env.development",".env.production"].some(v=>s.exists(v))||t.files.some(v=>/env\s+vars|environment\s+variables/i.test(v.content))){let v=ho.find(_=>_.id==="no-secret-safeguard");Fs(o,v.patterns)||i.push({id:mo(v.id),severity:v.severity,category:"security",title:v.title,summary:v.summary,filePaths:r,locations:[],evidence:["Environment variables detected but no safeguard instruction found."],recommendation:v.recommendation,fixRecipe:v.fixRecipe,confidence:v.confidence})}let l={...t.packageJson.dependencies,...t.packageJson.devDependencies,...t.packageJson.peerDependencies};if(s.exists("supabase/migrations")||Object.keys(l).some(v=>v==="@supabase/supabase-js"||v.startsWith("@supabase/"))){let v=ho.find(_=>_.id==="no-supabase-service-role-rule");Fs(o,v.patterns)||i.push({id:mo(v.id),severity:v.severity,category:"security",title:v.title,summary:v.summary,filePaths:r,locations:[],evidence:["Supabase detected but no service role safeguard instruction found."],recommendation:v.recommendation,fixRecipe:v.fixRecipe,confidence:v.confidence})}if(t.files.some(v=>{let _=v.path.replace(/\\/g,"/");return _.includes("/api/upload")||_.includes("/uploads/")||/multer|busboy|formidable/i.test(v.content)})){let v=ho.find(_=>_.id==="no-upload-boundary-docs");Fs(o,v.patterns)||i.push({id:mo(v.id),severity:v.severity,category:"security",title:v.title,summary:v.summary,filePaths:r,locations:[],evidence:["Upload features detected but no data boundary documentation found."],recommendation:v.recommendation,fixRecipe:v.fixRecipe,confidence:v.confidence})}if(s.exists(".promptci")){let v=ho.find(_=>_.id==="no-promptci-report-safeguard");Fs(o,v.patterns)||i.push({id:mo(v.id),severity:v.severity,category:"security",title:v.title,summary:v.summary,filePaths:r,locations:[],evidence:[".promptci/ folder detected but no report safeguard instruction found."],recommendation:v.recommendation,fixRecipe:v.fixRecipe,confidence:v.confidence})}for(let v of e)for(let _ of PR)if(_.pattern.test(v.content)){let A=[/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];Fs(v.content,A)||i.push({id:jR(G(v),_.name),severity:"warning",category:"security",title:`Destructive command "${_.name}" without safety language`,summary:`Instruction file contains a destructive command "${_.name}" but lacks safety language (e.g., "Ask before running").`,filePaths:[v.path],locations:[],evidence:[`Destructive command "${_.name}" found in ${Ut.basename(v.path)} without safety language.`],recommendation:`Add safety language such as "Ask for confirmation before running ${_.name}" to ensure destructive operations are not performed accidentally.`,confidence:.7})}let h=s.readText(".gitignore"),f=h.state==="unreadable"||h.state==="unfetched"||h.state==="too-large",g=(h.state==="found"?h.content:"").split(/\r?\n/).map(v=>v.trim()).filter(v=>v&&!v.startsWith("#"));!g.some(v=>go(v,".promptci"))&&!f&&i.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"+js.map(v=>` ${v}`).join(`
95
+ `)+"\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:Jc,autoApplySafe:!0,confidence:.9});let b=["coverage","dist","build",".next","bin","obj","temp","tmp","logs"],w=$R(s),S=f?[]:b.filter(v=>{if(!s.isDir(v))return!1;let _=OR[v];return _&&!_(s,w)?!1:!g.some(A=>go(A,v))});S.length>0&&i.push({id:"security-pack-unignored-dirs",severity:"warning",category:"context_bloat",title:"Unignored build, output, or coverage directories",summary:`The repository contains directory/directories (${S.join(", ")}) that are commonly generated but not ignored in .gitignore. AI tools may ingest these, inflating token costs.`,filePaths:[".gitignore"],locations:[],evidence:S.map(v=>`Directory "${v}" exists but is not ignored in .gitignore.`),recommendation:`Add generated directories to .gitignore. For example: "${S.map(v=>`${v}/`).join(", ")}"`,fixRecipe:S.map(v=>`echo "${v}/" >> .gitignore`).join(`
96
+ `),autoApplySafe:!0,confidence:.8});let C=!1;try{let v=s.readText(".promptci/config.json");if(v.state==="found"){let _=JSON.parse(v.content);if(Array.isArray(_.include)){let A=["**/*","**/*.md","*","*.*","**"];C=_.include.some(O=>A.includes(O.trim()))}}}catch{}if(C){let v=e.filter(_=>{let A=Ut.relative(n,_.path).replace(/\\/g,"/");return A.includes(".promptci/")||A.includes("coverage/")||A.includes(".next/")});v.length>0&&i.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:v.map(_=>`Scanned generated file: ${Ut.relative(n,_.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 v of e){let _=[{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 A of _)if(A.re.test(v.content)){i.push({id:DR(G(v)),severity:"info",category:"context_bloat",title:"Instruction prioritizing generated reports over source docs",summary:`Instruction file "${Ut.basename(v.path)}" tells the agent to inspect generated reports before source files, which can cause circular or outdated guidance ingestion.`,filePaths:[v.path],locations:[],evidence:[On(v.content,A.re,A.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 i}function ig(t){let e=[],{packageJson:n,files:s}=t,i=!!(n.dependencies.next||n.devDependencies.next),o=Z(t),r=["","apps/web/"].some(u=>["js","mjs","ts"].some(p=>o.isFile(`${u}next.config.${p}`)));if(!i&&!r)return[];let a=u=>["","src/","apps/web/","apps/web/src/"].some(p=>o.isDir(`${p}${u}`)),c=a("app"),l=a("pages");if(c&&(s.some(p=>p.content.toLowerCase().includes("app router")||p.content.toLowerCase().includes("server component")||p.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:s.map(p=>p.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})),c&&!l){let u=s.filter(p=>p.content.toLowerCase().includes("pages router")||p.content.toLowerCase().includes("getstaticprops")||p.content.toLowerCase().includes("getserversideprops"));u.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:u.map(p=>p.path),locations:u.map(p=>({filePath:p.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 bo=R(require("node:path"),1);function og(t){let e=[],{manifests:n,repoRoot:s,files:i}=t,o=!!n.pyproject,r=n.requirements!==void 0,a=Z(t),c=a.isFile("Pipfile"),l=a.isFile("environment.yml");if(!o&&!r&&!c&&!l)return[];(n.pyproject?.includes("pytest")||n.requirements?.includes("pytest"))&&(i.some(f=>f.content.toLowerCase().includes("pytest")||f.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(f=>f.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 p=[],d=[];return c&&p.push("Pipenv (Pipfile)"),c&&d.push(bo.join(s,"Pipfile")),l&&p.push("Conda (environment.yml)"),l&&d.push(bo.join(s,"environment.yml")),o&&n.pyproject?.includes("[tool.poetry]")&&p.push("Poetry (pyproject.toml)"),o&&n.pyproject?.includes("[tool.poetry]")&&d.push(bo.join(s,"pyproject.toml")),p.length>1&&e.push({id:"python-multiple-env-managers",severity:"warning",category:"conflict",title:"Multiple Python Environment Managers",summary:`Multiple environment managers detected: ${p.join(", ")}. This can lead to conflicting instructions.`,filePaths:d.length>0?d:i.map(h=>h.path),locations:[],evidence:[`Detected: ${p.join(", ")}`],recommendation:"Decide on a single environment manager and remove the others, or clearly document when to use each.",confidence:.9}),e}function rg(t){let e=[],{files:n}=t,s=Z(t),i=s.isDir("Assets"),o=s.isFile("ProjectSettings/ProjectVersion.txt"),r=n.map(d=>d.content).join(`
97
+ `),a=/\bunity\b.*\b(lts|editor|hub|engine)\b|\bmonobehaviour\b|\bunityengine\b|\bgameobject\b|\bprefab\b|\bscriptableobject\b/i.test(r);if(!(i&&o)&&!a)return[];let c=n.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(r)||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(r)||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(r)||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}function ag(t){let e=[],{repoRoot:n,files:s}=t,i=Z(t),o=i.entries(i.root),r=typeof o=="string"?[]:[...o.values()].filter(h=>!h.isDirectory()).map(h=>h.name).sort(),a=t.projectType==="dotnet"||r.some(h=>h.endsWith(".sln")||h.endsWith(".csproj")),c=s.map(h=>h.content).join(`
98
+ `),l=/\bdotnet\b|\.sln\b|\.csproj\b|\bxunit\b|\bnunit\b|\bmstest\b/i.test(c);if(!a&&!l)return[];let u=s.map(h=>h.path);/dotnet\s+(build|test|restore|run)/i.test(c)||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:u,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 d;try{let h=r.find(f=>f.endsWith(".csproj"));if(h){let f=Ie(n,h)??"",m=/<TargetFramework>(.*?)<\/TargetFramework>/.exec(f);m&&(d=m[1]?.trim())}}catch{}if(d){let h=/\b(netcoreapp\d+\.\d+|net5\.0|netcore)\b/i.test(c);/^net(?:[6-9]|[1-9]\d+)\.0/.test(d)&&h&&e.push({id:"dotnet-obsolete-framework-reference",severity:"warning",category:"stale_instruction",title:".NET Obsolete Framework Reference",summary:`The project targets modern .NET (${d}), but instructions still reference obsolete versions like .NET Core 3.1 or .NET 5.0.`,filePaths:u,locations:[],evidence:[`Project targets ${d}; obsolete framework references found in instructions.`],recommendation:`Update instructions to reference the current target framework version (${d}).`,fixRecipe:`Target .NET ${d} as the framework for this project. Do not use legacy .NET Core 3.1 or .NET 5.0 APIs.`,confidence:.8})}return e}function cg(t){let e=[],{files:n}=t,s=Z(t).isFile("go.mod"),i=n.map(c=>c.content).join(`
99
+ `),o=/\bgo\.mod\b/i.test(i)||/`[^`\n]*\bgo\s+(?:build|test|run|get|mod)\b[^`\n]*`/i.test(i);if(!s&&!o)return[];let r=n.map(c=>c.path);return/\bgo\s+test\b/i.test(i)||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:r,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}function lg(t){let e=[],{repoRoot:n,files:s}=t,i=Z(t).isFile("Cargo.toml"),o=s.map(u=>u.content).join(`
100
+ `),r=/\bcargo\.toml\b|\bcargo\s+(build|test|run|clippy|fmt)\b/i.test(o);if(!i&&!r)return[];let a=s.map(u=>u.path);/cargo\s+(test|clippy|fmt)/i.test(o)||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")??"",p=/^rust-version\s*=\s*["'](.*?)["']/m.exec(u);p&&(l=p[1]?.trim())}catch{}if(l){let u=h=>{let f=/^(\d+)\.(\d+)/.exec(h);return f?`${f[1]}.${f[2]}`:void 0},d=/\bRust\s+(\d+\.\d+(?:\.\d+)?)\b/i.exec(o);if(d){let h=d[1];u(h)!==u(l)&&e.push({id:"rust-version-mismatch",severity:"warning",category:"stale_instruction",title:"Rust Version Mismatch",summary:`Instructions mention Rust version ${h}, but Cargo.toml specifies rust-version = "${l}".`,filePaths:a,locations:[],evidence:[`Cargo.toml requires rust-version = ${l}; instructions mention Rust ${h}`],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 ug(t){let e=[];return e.push(...ig(t)),e.push(...og(t)),e.push(...rg(t)),e.push(...ag(t)),e.push(...cg(t)),e.push(...lg(t)),e}var pg=R(require("node:path"),1),fg=R(require("node:crypto"),1);function Hs(t,e){let n=fg.createHash("sha1").update(`prompt-cache-${t}:${e}`).digest("hex").slice(0,12);return`prompt-cache-${t}-${n}`}var FR=[{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"}],HR=[{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'}],BR=[{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"}],dg=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i;function hg(t){let e=[],n=t.filter(s=>Ae.has(s.fileType));for(let s of n){let i=pg.basename(s.path);for(let d of FR)if(d.re.test(s.content)){e.push({id:Hs("volatile-timestamp",G(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:[On(s.content,d.re,d.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 d of HR)if(d.re.test(s.content)){e.push({id:Hs("pasted-report",G(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:[On(s.content,d.re,d.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 d of BR)if(d.re.test(s.content)){e.push({id:Hs("volatile-branch-task",G(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:[On(s.content,d.re,d.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(dg.test(s.content)){let d=s.content.match(dg)?.[0]??"";e.push({id:Hs("local-paths",G(s)),severity:"warning",category:"context_bloat",title:"Local machine paths in instructions",summary:`The instruction file "${i}" contains absolute local machine paths ("${d}"). These paths change per environment, preventing prompt caching and causing instruction drift.`,filePaths:[s.path],locations:[],evidence:[`Found absolute local path: ${d}`],recommendation:"Use repository-relative paths instead of absolute local machine paths.",fixRecipe:"Replace absolute local paths with repository-relative paths.",confidence:.8})}let o=s.content.split(/\r?\n/),r=0,a=0,c=0,l=0,u=0,p=0;for(let[d,h]of o.entries()){let f=h.trim();if(f.startsWith("|")&&f.endsWith("|")){if(/^\|[-\s:|]+\|$/.test(f))continue;a===0&&(c=d+1),l=d+1,a++}else a>r&&(r=a,u=c,p=l),a=0}a>r&&(r=a,u=c,p=l),r>15&&e.push({id:Hs("large-table",G(s)),severity:"warning",category:"context_bloat",title:"Large table in instruction file",summary:`The instruction file "${i}" contains a large Markdown table (${r} rows). Large tables bloat prompt context and reduce caching friendliness.`,filePaths:[s.path],locations:[{filePath:s.path,startLine:u,endLine:p}],evidence:[`Markdown table with ${r} 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 Zc=R(require("node:path"),1);var mg=12,GR={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 Vn(t,e,n=""){return`ai-config-skill-${t}-${_e(`${e}|${n}`)}`}function WR(t){return t.toLowerCase().replace(/[`*_~]/g,"").replace(/[^a-z0-9]+/g," ").trim()}function VR(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 Qc(t){let e=[],n=new Set,s=(o,r)=>{if(!VR(o))return;let a=o.split("#")[0];n.has(a)||(n.add(a),e.push({ref:a,line:r}))},i=t.split(/\r?\n/);for(let o=0;o<i.length;o++){let r=i[o];for(let a of r.matchAll(/\[[^\]]*\]\(([^)]+)\)/g))s(a[1].split(/\s+/)[0].replace(/^<|>$/g,""),o+1);for(let a of r.matchAll(/`([^`]+)`/g))s(a[1].trim(),o+1)}return e}function UR(t,e){if(e.startsWith("/")){let o=e.slice(1);return zR.has(o.split("/")[0])?void 0:[o]}let n=/^(.*?)\/?skills\/[^/]+$/.exec(t)?.[1],i=[t,...n&&n!==".claude"&&n!==".agents"?[n]:[],"."];return[...new Set(i.map(o=>o==="."||o===""?e:`${o}/${e}`))]}var zR=new Set(["usr","var","etc","opt","tmp","home","Users","Library","bin","sbin","dev","proc","mnt","private","System"]);function qR(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function KR(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}\`?${qR(e)}`,"i").test(t)}function el(t){let e=[],n=[],s,i=Z(t);for(let o of t.aiConfig.skills){let r=Ie(t.repoRoot,o);if(r===void 0)continue;let a=dn(Zc.dirname(o)).split("/").pop()??"",c=Et(r);if(e.push(...Gt(o,r,c,GR)),!c.present)continue;let l=typeof c.data.name=="string"?c.data.name.trim():void 0,u=typeof c.data.description=="string"?c.data.description.trim():void 0;l?l!==a&&a&&e.push(K({id:Vn("name-dir-mismatch",o),title:"Skill `name` does not match its directory",summary:`${o}: frontmatter \`name: ${l}\` does not match the skill directory \`${a}/\`. Claude resolves skills by directory name.`,filePaths:[o],locations:[{filePath:o,startLine:c.keyLines.name??1,endLine:c.keyLines.name??1}],evidence:[`name: ${l}`,`directory: ${a}`],recommendation:"Rename the directory or the `name` field so they match.",confidence:.6})):e.push(K({id:Vn("missing-name",o),title:"Skill frontmatter is missing `name`",summary:`${o} has no \`name\` field. Claude uses \`name\` to identify and invoke the skill.`,filePaths:[o],locations:[{filePath:o,startLine:1,endLine:c.fenceEndLine>0?c.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(c.data).join(", ")||"(none)"}`],recommendation:"Add a `name` field to the frontmatter matching the skill directory name.",confidence:.85})),u?u.length<mg&&e.push(K({id:Vn("empty-description",o),title:"Skill `description` is too short to trigger reliably",summary:`${o}: \`description\` is only ${u.length} characters. Claude matches the description against the user's request to decide when to invoke the skill.`,filePaths:[o],locations:[{filePath:o,startLine:c.keyLines.description??1,endLine:c.keyLines.description??1}],evidence:[`description: ${u}`],recommendation:"Expand the description to describe the task and its trigger conditions.",confidence:.7})):e.push(K({id:Vn("missing-description",o),title:"Skill frontmatter is missing `description`",summary:`${o} has no \`description\`. The description is the trigger text Claude matches against \u2014 without it the skill rarely activates.`,filePaths:[o],locations:[{filePath:o,startLine:1,endLine:c.fenceEndLine>0?c.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(c.data).join(", ")||"(none)"}`],recommendation:"Add a `description` that says what the skill does and when to use it.",confidence:.85}));let p=dn(Zc.dirname(o)),d=r.split(/\r?\n/);for(let{ref:h,line:f}of Qc(r)){if(Ga(h)||/^\/?\.git\//.test(h))continue;let m=UR(p,h);if(!m||m.some(y=>gt(i,y))||(s??=Hi(i),m.some(y=>s(y)!==!1))||KR(d[f-1]??"",h))continue;let g=h.startsWith("/");e.push(K({id:Vn("dead-ref",o,h),title:"Skill references a bundled file that does not exist",summary:g?`${o} references \`${h}\`, but no such file exists at that path from the repository root.`:`${o} references \`${h}\`, but no such file exists relative to the skill directory or the repository root.`,filePaths:[o],locations:[{filePath:o,startLine:f,endLine:f}],evidence:[`Reference: ${h}`,`Looked in: ${m.join(", ")}`],recommendation:"Add the referenced file, fix the path, or remove the reference.",confidence:.75}))}u&&n.push({filePath:o,description:u})}return e.push(...YR(n)),Ge(t.repoRoot,e)}function YR(t){let e=[],n=new Map;for(let s of t){if(s.description.length<mg)continue;let i=WR(s.description);if(!i)continue;let o=n.get(i)??[];o.push(s),n.set(i,o)}for(let s of n.values()){if(s.length<2)continue;let i=[...s].sort((r,a)=>r.filePath.localeCompare(a.filePath)),o=i.map(r=>r.filePath);e.push(K({id:Vn("overlap",o.join("|")),title:"Multiple skills share the same trigger description",summary:`${o.length} skills have effectively identical \`description\` text, so Claude cannot tell which to invoke for a given request.`,filePaths:o,locations:i.map(r=>({filePath:r.filePath,startLine:1,endLine:1})),evidence:[`Shared description: ${i[0].description}`,`Skills: ${o.join(", ")}`],recommendation:"Give each skill a distinct description that states its unique trigger conditions.",confidence:.75}))}return e}var zt=R(require("node:fs"),1),Je=R(require("node:path"),1);var cl="skill-supply-chain",XR=20*1024*1024,JR=2e3,ZR={"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."}},QR=new Set(["md","mdx","markdown","txt"]),eT=new Set(["yml","yaml","json","jsonc","json5","toml","ini","cfg","conf","html","htm","xhtml","xml","svg"]),gg={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"},tT=new Set(["go","rs","java","c","cc","cpp","cxx","h","hpp","cs","swift","kt","kts","groovy","gradle","scala","tf","hcl","sql","service","desktop"]),nT=new Set(["vbs","vba","vbe","hta","applescript","wsf","jse","reg"]),sT=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"]),iT=new Set(["docx","xlsx","pptx","doc","xls","ppt","odt","sqlite","sqlite3","db"]),oT=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"]),rT=new Set([".ds_store","thumbs.db","desktop.ini"]);function $g(t){let e=Je.posix.basename(t);if(rT.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":QR.has(n)?{kind:"instructions",lang:"other"}:gg[n]?{kind:"script",lang:gg[n]}:n==="mk"||n==="dockerfile"?{kind:"text",lang:"sh"}:eT.has(n)?{kind:"text",lang:"other"}:tT.has(n)?{kind:"text",lang:"other",note:{reason:`.${n} source \u2014 only command and exfiltration patterns were checked`,severity:"info"}}:nT.has(n)?{kind:"script",lang:"other",note:{reason:`.${n} script \u2014 only command and exfiltration patterns were checked`,severity:"warning"}}:sT.has(n)?{report:`binary executable or archive (.${n}) \u2014 cannot be reviewed as text`,severity:"warning"}:iT.has(n)?{report:`.${n} document/database \u2014 not read`,severity:"info"}:oT.has(n)?{skip:"asset"}:"probe"}function yg(t){if(Je.posix.basename(t)==="SKILL.md")return!0;let e=$g(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 aT(t){let e=/^#!\s{0,5}(\S{1,200})(?:\s{1,5}(\S{1,100}))?/.exec(t);if(!e)return;let n=Je.posix.basename(e[1])==="env"?e[2]??"":Je.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 cT(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 lT(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 mn=Mi;function tl(t){let e=mn(t),n=Math.max(0,...(e.match(/`+/g)??[]).map(i=>i.length)),s="`".repeat(n+1);return`${s}${e}${s}`}function Oe(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),o=mn(t.slice(s,i)).replace(/\s+/g," ").trim();return`${s>0?"\u2026":""}${o}${i<t.length?"\u2026":""}`}var rt=2e3,Ig=600;function xo(t,e,n){return Object.assign([t.slice(e,n)],{index:e,input:t,groups:void 0})}function xe(t,e,n){if(e.length<=rt){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+=rt-Ig){let i=e.slice(s,s+rt),o=n&&!n(i)?null:t.exec(i);if(o)return{index:s+o.index,match:o};if(s+rt>=e.length)break}}function Rt(t,e,n=50){let s=[];if(e.length<=rt){for(let o of e.matchAll(t))if(s.push({index:o.index??0,match:o}),s.length>=n)break;return s}let i=new Set;for(let o=0;o<e.length;o+=rt-Ig){for(let r of e.slice(o,o+rt).matchAll(t)){let a=o+(r.index??0);if(!i.has(a)&&(i.add(a),s.push({index:a,match:r}),s.length>=n))return s}if(o+rt>=e.length)break}return s}var Og=20,Lg=4e3,Ng=200,Mg=2e4,uT=/\|\s{0,5}[({]?\s{0,3}(?:while|until)\b/,bg=/\bdo\b/g,wg=/\bdone\b/g,dT=/\|\s{0,5}rev\s{0,5}\|/,pT=t=>Ws.test(t)||zg.test(t)||dT.test(t);function fT(t){let e=[],n=[],s="",i=0,o=0,r=-2,a=!1,c=0,l=!1;for(let u of t.active){let p=t.lines[u];s!==""&&u!==r+1&&(e.push({text:s,line:i}),s="",a=!1),r=u,s===""&&(i=u+1,o=0);let d=p.trimEnd(),h=d.endsWith("\\")&&!d.endsWith("\\\\"),f=(d.endsWith("|")||d.endsWith("&&"))&&!(t.kind==="instructions"&&!t.fenced[u]&&p.trimStart().startsWith("|")),m=!1;if(!a&&d.includes("|")&&(t.kind!=="instructions"||t.fenced[u]===1)&&uT.test(d)&&pT(d)){let g=d.match(bg)?.length??0,y=d.match(wg)?.length??0;(g===0||g>y)&&(m=!0,c=g-y,l=g>0)}if(h||f||a||m){let g=a||m?p.trim():p,y=a||m;if(o<(y?Ng:Og)&&s.length+g.length<(y?Mg:Lg)){let b=!1;if(a){let C=g.match(bg)?.length??0,v=g.match(wg)?.length??0;C>0&&(l=!0),c+=C-v,b=l&&c<=0||!l&&v>0}let w=h||f||m&&/(?:\bdo|[;{(])$/.test(g)?" ":"; ",S=a||m?g:d;s+=`${h?S.slice(0,-1):S}${b?"":w}`,o++,m&&(a=!0),b&&(e.push({text:s,line:i}),s="",a=!1);continue}n.push(i),a=!1}e.push({text:s+p,line:i}),s=""}return s!==""&&e.push({text:s,line:i}),{lines:e,capped:n}}var hT=/\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,jg=/[,;:.!?]|\b(?:but|and|then|instead|so)\b/i,mT=2,gT=/^(?:run|pipe|use|execute|invoke|call|send|pass|type|paste)$/i;function Dg(t){return t.match(/[A-Za-z0-9_'-]+/g)??[]}var yT=/\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,bT=/^[`'")\]\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 Fg(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 Hg(t,e){return Fg(t.slice(Math.max(0,e-80),e),hT,n=>{if(n.length>30||jg.test(n))return!1;let s=Dg(n);return s.length===0||s.length===1&&gT.test(s[0])})}function ll(t,e,n){return bT.test(t.slice(e+n,e+n+60))?!0:Fg(t.slice(Math.max(0,e-80),e),yT,s=>s.length<=30&&!jg.test(s)&&Dg(s).length<=mT)}var wT=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"),Bg=/\b(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod)\b/gi,vT=/^(?:-K|--config|-i|--input-file|-T|--upload-file|--url|--url-query)(?:=|$)|^-K\S/;function ST(t){let e=0;for(let n of t.matchAll(Bg)){if(++e>8)break;if(Gg(t,n).some(s=>vT.test(s)||!s.startsWith("-")&&/[/.:@=$~\d[]/.test(s)))return!0}return Wg(t)&&(So(t,Ws,!1)!==void 0||AT(t))}function Gg(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 Wg(t,e=4){let n=t.slice(0,600),s=0;for(let i of n.matchAll(Bg)){if(++s>e)break;let o=kT(i[0].toLowerCase(),Gg(n,i));if(o!==void 0&&ET(o))return!0}return!1}var _T={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"])},xT=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 kT(t,e){let n=t==="curl"||t==="wget"?t:"iwr",s=_T[n];for(let i=0;i<e.length;i++){let o=e[i];if(n==="iwr"&&o.toLowerCase()==="-uri")return e[i+1];let r=n==="iwr"?o.toLowerCase():o;if(s.has(r)){i++;continue}if(!o.startsWith("-"))return o}}function ET(t){return/^[a-z][a-z0-9_-]{0,62}$/i.test(t)&&!xT.has(t.toLowerCase())}function AT(t){let e=dl(t,!1).slice(0,50);for(let n=0;n<e.length;n++){if(!Ws.test(e[n].text))continue;let s=Yg(e[n].text,"remote");if(s)for(let i=n+1;i<e.length&&i<=n+8;i++){let o=e[i].text;if(/^\s{0,5}(?:chmod|cat|ls|rm|mv|cp|echo|printf|test|\[)\b/i.test(o))continue;let r=Kg.exec(o);if(r&&Xe(r[1])===s)return!0}}return!1}function ul(t){let e=t.slice(0,600);return wT.test(e)||ST(e)}function ko(t,e,n,s,i,o=!1){return t.kind!=="instructions"||t.fenced[e]||!Hg(n,s)&&!ll(n,s,i)?"none":ul(n.slice(s,s+Math.max(i,1)+80))?"lowconf":o?Vg(n,s,s+i)||CT(n)?"skip":"lowconf":"skip"}function CT(t){return t.trimStart().startsWith("|")}var RT=/\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 TT(t,e,n){if(!Vg(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!RT.test(s.slice(0,Math.max(0,i)))}function Vg(t,e,n){let s=t.slice(Math.max(0,e-rt),e),i=t.slice(n,n+rt);for(let o of['"',"`"])if((s.split(o).length-1)%2===1&&i.includes(o))return!0;return s.lastIndexOf("\u201C")>s.lastIndexOf("\u201D")&&i.includes("\u201D")}var PT=/^\s{0,10}\|\s{0,5}`?(?:--[\w-]{2,60}|bypassPermissions)`?\s{0,5}\|/,$T=/`[^`]{0,200}`|\b(?:run|use|execute|launch|invoke|start|pass|add|set|enable|always|call|claude|codex|npx|bash|sh)\b/i;function IT(t){return PT.test(t)?!t.split(/(?<!\\)\|/).slice(2).some(n=>$T.test(n)):!1}function dl(t,e,n){let s=[],i=0,o="",r=0;for(let a=0;a<t.length;a++){let c=t[a];if(o){c==="\\"&&o==='"'?a++:c===o&&(o="",n&&n.length<50&&n.push({start:r+1,end:a}));continue}if(e&&(c==='"'||c==="'")&&(a===0||/[\s=(:,[{]/.test(t[a-1]))){o=c,r=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 OT=String.raw`(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod|aria2c|downloadstring|downloadfile)`,Ws=new RegExp(String.raw`(?:^|[\s(\x60{>"':=])${OT}\b`,"i"),Ug=/(?:^|[\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,LT=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'"])`,NT=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`${LT}|iex\b|invoke-expression\b|pwsh\b|powershell\b)`,MT=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}`,pl=String.raw`^\s{0,5}[({]?\s{0,3}(?:${MT}){0,6}`+String.raw`(?:[\w./-]{0,40}\/)?(?:env\s{1,5}(?:-\S{1,20}\s{1,5}){0,3})?`,vg=new RegExp(pl+NT,"i"),jT=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"),DT=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"),FT=/\beval\s{0,5}\(?\s{0,5}do\s{0,5}\{[^}\n]{0,100}(?:<STDIN>|<>)/i,HT=/(?:^|[;\s{(])\$?([A-Za-z_]\w{0,30})\s{0,3}=\s{0,3}[^;\n=]{0,60}$/,BT=600,GT=150;function WT(t){let e=t.slice(0,BT),n=[];for(let o of e.matchAll(DT))if(n.push(o.index??0),n.length>=16)break;if(n.length===0)return!1;if(FT.test(e))return!0;let s=0,i=0;for(let o of e.matchAll(jT)){if(++s>40)break;let r=(o.index??0)+o[0].length;for(;i<n.length&&n[i]<r;)i++;let a=n[i];if(a!==void 0&&a-r<=GT&&!/[;\n]/.test(e.slice(r,a)))return!0}for(let o of n.slice(0,4)){let r=HT.exec(e.slice(Math.max(0,o-80),o));if(r&&new RegExp(String.raw`\b(?:eval|exec|system)\s{0,5}\(?\s{0,5}\$?${r[1]}\b`).test(e.slice(o)))return!0}return!1}var VT=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}["']?`,UT=new RegExp(`${pl}${VT}`,"i"),zT=new RegExp(`${pl}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 Sg(t){let e=UT.exec(t);return e&&WT(t.slice(e.index+e[0].length))?!0:zT.test(t)}var qT=/^\s{0,5}[({]?\s{0,3}(?:sudo\s{1,5}(?:-\S{1,20}\s{1,5}){0,3})?(?:[\w./-]{0,40}\/)?tee\b/i,KT=/^\s{0,5}[({]?\s{0,3}(?:while|until)\b[^;|]{0,150}?\bread\b([^;|]{0,100})/i,YT=/^\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,XT=/^\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,JT=/^\s*do\b/,ZT=/^\s*done\b/,QT=new Set(["-p","-d","-n","-N","-t","-u","-i"]),e1=250;function t1(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(QT.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 n1(t,e,n){let s=n[e];if(s===void 0){let i=t[e],o=i.text.slice(0,400);if(ZT.test(o))s={kind:"done"};else{s={kind:JT.test(o)?"do":"other"};let r=YT.exec(o);r&&(s.runs=r[1]);let a=i.sep==="|"&&e+1<t.length?XT.exec(o):null;a&&(s.echoes=a[1])}n[e]=s}return s}function s1(t,e,n){let s=t[e].text;if(!s.includes("read")||!/while|until/i.test(s))return;let i=KT.exec(s.slice(0,400));if(!i)return;let o=t1(i[1]??""),r=0;for(let a=e+1;a<t.length&&a<=e+e1;a++){let c=n1(t,a,n);if(c.kind==="done"){if(--r<=0)return;continue}c.kind==="do"&&r++;let l=t[a];if(c.runs!==void 0&&o.has(c.runs))return l.start+Math.min(l.text.length,60);if(c.echoes!==void 0&&o.has(c.echoes)&&qg(t[a+1].text))return t[a+1].start+Math.min(t[a+1].text.length,60)}}var i1=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"),zg=new RegExp(`${Ug.source}|${i1.source}`,"i"),o1=16;function r1(t){let e="",n=0,s=0,i=!1,o=t.length;for(;n<o&&e.length<600&&s<400;){for(;n<o&&t.charCodeAt(n)<=32;)n++;if(n>=o)break;let r=n,a=0;for(;n<o;){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(r,Math.min(n,r+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>=o?e.slice(0,600):`${e} ${t.slice(n,n+600)}`.slice(0,600)}function qg(t){if(!_g.test(t))return!1;let e=r1(t);if(!_g.test(e))return!1;if(vg.test(e)||Sg(e))return!0;if(e.includes(">(")&&qT.test(e)){let n=e.indexOf(">(");for(let s=0;n>=0&&s<4;s++){let i=e.slice(n+2);if(vg.test(i)||Sg(i))return!0;n=e.indexOf(">(",n+2)}}return!1}function So(t,e,n,s=0){if(!t.includes("|"))return;let i=[],o=dl(t,n,i),r=a1(t,o,e);if(r||s>0)return r;for(let a of i){let c=So(t.slice(a.start,a.end),e,!0,s+1);if(c)return{index:a.start+c.index,match:xo(t,a.start+c.index,a.start+c.index+c.match[0].length)}}}var _g=/sh\b|SHELL|stdin|awk|python|node|perl|ruby|php|deno|bun|iex|invoke-expression|pwsh|powershell/i;function a1(t,e,n){let s=new Array(e.length),i=c=>(s[c]===void 0&&(s[c]=qg(e[c].text)),s[c]),o=new Array(e.length),r=new Array(e.length),a=c=>(o[c]===void 0&&(o[c]=s1(e,c,r)??null),o[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<=o1&&c+u<e.length;u++){let p=e[c+u],d=i(c+u)?void 0:a(c+u);if(d!==void 0||i(c+u)){let h=e[c].start+l.index,f=Math.min(t.length,d??p.start+Math.min(p.text.length,60));return{index:h,match:xo(t,h,f)}}if(p.sep!=="|")break}}}var c1=/^\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,l1=/^\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,Kg=/^\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,u1=/^\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,d1=/^\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 Xe(t){return Je.posix.basename(t.replace(/^['"]+|['"]+$/g,"").replace(/\\/g,"/"))}function xg(t){return new Set(t.split(/\s+/).filter(Boolean).map(Xe))}function Yg(t,e){let n=/(?:^|\s)>{1,2}\s{0,3}(\S{1,300})/.exec(t);if(e==="encoded")return n?Xe(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?Xe(i[1]):/\s-[a-zA-Z]{0,10}O\b|\s--remote-name\b/.test(t)&&s?Xe(s.split(/[?#]/)[0]):n?Xe(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:Xe(i[1]):s?Xe(s.split(/[?#]/)[0]):void 0}return n?Xe(n[1]):void 0}var p1=/^\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,f1=/^\s{0,5}(?:sudo\s{1,5})?(?:(?:sha(?:1|224|256|384|512)|md5|b2)sum|shasum|openssl\s{1,5}dgst)\b/i,h1=/curl|wget|iwr|irm|invoke-web|base64|xxd|openssl|uudecode|sum\b|gpg|cosign|minisign|slsa/i,Gs=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&&!h1.test(e))return;let o=dl(e,s).slice(0,500),r=o.findIndex(u=>/(?:^|\s)#/.test(u.text));if(r>=0){let u=o[r];o=[...o.slice(0,r),{...u,text:u.text.slice(0,u.text.search(/(?:^|\s)#/)),sep:""}]}let a=o.map(u=>c1.test(u.text)),c=(u,p)=>{for(let d=u;d<p;d++){let h=o[d].sep;if(h!=="&&"&&!(h==="|"&&a[d+1]))return!1}return!0},l=new Map;for(let u=0;u<o.length;u++){let p=o[u],d=p.text,h=p.start+Math.max(0,d.search(/\S/)),f=u1.exec(d);if(f){this.fetchedVars.set(f[1],{line:n,feed:i,index:h});continue}let m=Ws.test(d)&&(/https?:\/\//i.test(d)||Wg(d,1)),g=Ug.test(d);if(m||g){let _=m?"remote":"encoded",A=Yg(d,_);A&&this.produced.set(A,{kind:_,line:n,feed:i,seg:u,index:h});continue}let y=p1.exec(d);if(y){this.generated.add(Xe(y[1]));continue}if(a[u]){for(let _ of this.verifiedFiles(d,u>0&&o[u-1].sep==="|"?o[u-1].text:void 0))l.set(_,[...l.get(_)??[],u]);continue}let b=d1.exec(d);if(b&&this.fetchedVars.has(b[1])){let _=this.fetchedVars.get(b[1]);return this.hit("remote-exec",e,_.feed===i?_.index:h,p.start+d.length,_.line)}if(/^\s{0,5}(?:chmod|cat|ls|rm|mv|cp|echo|printf|test|\[)\b/i.test(d))continue;let w=Kg.exec(d);if(!w)continue;let S=Xe(w[1]),C=this.produced.get(S);if(!(!C||C.kind==="remote"&&C.feed===i&&(l.get(S)??[]).some(_=>_>C.seg&&c(C.seg,u))))return this.hit(C.kind==="remote"?"remote-exec":"encoded-exec",e,C.feed===i?C.index:h,p.start+d.length,C.line)}}verifiedFiles(e,n){let s=[...this.produced.keys()];if(/--ignore-missing\b|<<<|<\(/.test(e))return[];let i=l1.exec(e)?.[1];if(i!==void 0){if(i==="-"||i==="/dev/stdin"){if(n===void 0||f1.test(n)||/<\(|\$\(/.test(n))return[];let c=xg(n);return s.filter(l=>c.has(l))}let r=Xe(i);return i.startsWith("<")||this.generated.has(r)?[]:!(this.produced.get(r)?.kind==="remote")&&!this.manifestExists(i.replace(/^['"]+|['"]+$/g,""))?[]:s}let o=xg(e);return s.filter(r=>o.has(r))}hit(e,n,s,i,o){let r=Math.min(s,n.length);return{rule:e,found:{index:r,match:xo(n,r,Math.max(r,Math.min(n.length,i)))},fromLine:o}}},m1=[{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}],g1=[{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}],y1=/\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,nl=String.raw`(?:urllib\.request|urllib2|requests|httpx)`,wo=new RegExp([String.raw`\bfrom\s{1,5}${nl}\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}${nl}\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}${nl}\s{0,3}(?=$|[\s;#)])`].join("|"),"g"),b1=/\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,rl=["urlopen","get","post","request"],w1=new Set(rl),kg=/urlopen|urllib|requests|httpx/,Eg=new WeakMap;function v1(t,e){let n=[];if(t.length<=rt){wo.lastIndex=0;for(let s=wo.exec(t);s!==null&&n.length<20;s=wo.exec(t))n.push(s)}else for(let s of Rt(wo,t,20))n.push(s.match);for(let s of n){let i=s.groups??{};if(i.list!==void 0)for(let o of i.list.split(",").slice(0,12)){let[r,a]=o.trim().replace(/[()]/g,"").split(/\s{1,5}as\s{1,5}/i);r!==void 0&&w1.has(r)&&e.add((a??r).trim())}else if(i.ulist!==void 0)for(let o of i.ulist.split(",").slice(0,12)){let[r,a]=o.trim().replace(/[()]/g,"").split(/\s{1,5}as\s{1,5}/i);if(r==="request")for(let c of rl)e.add(`${(a??r).trim()}.${c}`)}else if(i.mod!==void 0||i.modassign!==void 0)for(let o of rl)e.add(`${i.mod??i.modassign}.${o}`);else i.fn!==void 0&&e.add(i.fn)}}function S1(t){let e=Eg.get(t);if(e!==void 0)return e;let n=null;if(kg.test(t.content)){let s=ey(t),i=new Map,o=new Set;for(let r of t.active){let a=t.lines[r];if(!a.includes("import")&&!a.includes("=")||!kg.test(a))continue;if(a.length<300){if(o.has(`${s(r)}|${a}`))continue;o.size<5e3&&o.add(`${s(r)}|${a}`)}let c=s(r),l=i.get(c);l||i.set(c,l=new Set),v1(a,l)}n={blockOf:s,byBlock:i}}return Eg.set(t,n),n}function Xg(t,e,n){let s=xe(y1,e);if(s)return s;let i=S1(t),o=i?.byBlock.get(i.blockOf(n));if(!(!o||o.size===0||!e.includes("("))){for(let r of Rt(b1,e,20))if(o.has(r.match[1]))return r}}var _1={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}[( ]/]},x1={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}\(/]},k1=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"),E1=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"),A1=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"),C1=[/\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],R1=/ignore|disregard|forget|you\s{1,5}are|<\||<<SYS|INST\]|system\s{1,5}prompt|precedence|priority/i,T1=/user|silently/i,P1=/without|disable|turn\s{1,5}off|bypass|circumvent|skip|override|approve/i,$1=[/\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],I1=[/\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],O1=/--dangerously-skip-permissions\b|--dangerously-bypass-approvals-and-sandbox\b|\bbypassPermissions\b|--yolo\b|--allow-all-tools\b/i,L1=[/\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],N1=/\b(?:send|upload|post|transmit|exfiltrate|forward|paste|leak|e-?mail)\b/gi,Ag=/\b(?:send|upload|post|transmit|exfiltrate|forward|paste|leak|e-?mail)\b/i,M1=/\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,j1=/\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,D1=/\b(?:to|into|at|via)\b/i,F1=/webhook|pastebin|paste\.|hastebin|discord|telegram|ngrok|requestbin|pipedream|interactsh|burpcollaborator|\.onion\b|https?:\/\/\d{1,3}(?:\.\d{1,3}){3}/i,H1=/https?:\/\/|\bserver\b|\bendpoint\b|\bremote\b|\bexternal\b|third[-\s]party|\battacker\b|e-?mail\s{1,5}address/i,B1=/\bexternal\b|third[-\s]party|\battacker\b/i,G1=/\b(?:header|authorization|authenticate|bearer\s{1,5}auth)\b|\s-H\s/i,W1=/\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,V1=/\shidden(?:\s|=|\/|$)/i,U1=/^\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,z1=/\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,q1=/\byou\b|\b(?:must|always|never|approve|run|ignore|execute|send|upload|install|delete|disable|download|fetch|read|print|reveal)\b/i,K1=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"),Y1=/(?<![A-Za-z0-9+/=])[A-Za-z0-9+/]{200,}={0,2}(?![A-Za-z0-9+/=])/g,X1=/\b(?:pip[0-9.]{0,5}|pipx|uvx|uv|npm|pnpm|yarn|bun|npx|bunx|go|cargo|gem|deno)\b/i,J1=/\bgit\+(?:https?|ssh|git|file):\/\/[^\s'"<>)`]{1,500}|\bgithub:[\w.-]{1,100}\/[\w.-]{1,100}(?:#[^\s'"<>)`]{0,100})?/gi,Z1=/(?<=[\w.-])@(?:latest|master|main|HEAD)(?![\w.-])/gi,Q1=/\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,eP=/\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,tP=/\bcargo\s{1,5}install\b[^\n;&|]{0,300}--git\s{1,5}\S/i,nP=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"),sP=/\b(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod|fetch|urlopen|requests\.get|download|downloadstring)\b/i,iP=/(?:\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|ps1|rb|pl)(?:[?#]|$)|install)/i,oP=/(?:\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 fl(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 hl(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("/"),o=i>=0?s.slice(i+1):s,r=o.lastIndexOf("@");return r>=0?o.slice(r+1):void 0}function Jg(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)?!fl(hl(e.startsWith("git")||e.includes(":")?e:`github:${e}`)):/^https?:\/\//i.test(e)?!/\d+\.\d+\.\d+|#sha(?:256|512)=/i.test(e):!1}function rP(t){if(/@(?:latest|master|main|head)/i.test(t)){for(let e of Rt(Z1,t,10))if(Q1.test(t.slice(Math.max(0,e.index-230),e.index)))return e}}var aP=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.\-/])`,cP=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}${aP}`,"gi"),lP=new RegExp(String.raw`(?:^|[\s\x60'"(;&|])(\.\/[\w@.\-/]{1,200}\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|rb|pl|ps1))(?![\w.\-/])`,"g"),uP=new Set(["json","jsonc","json5","yaml","yml","toml"]),dP=/\.(?:sh|bash|zsh|py|js|mjs|cjs|ts|mts|rb|pl|ps1)\b/i,Cg={info:0,warning:1,high:2,critical:3},pP=5,Un=25;function Bs(t,e){let n=Cg[t.severity]-Cg[e.severity];return n!==0?n>0:t.confidence>e.confidence}var al=class{groups=new Map;accepts(e,n,s,i){let o=this.groups.get(`${e}|${n}`);if(!o||o.hits.length<Un)return!0;let r={excerpt:"",severity:s,confidence:i};return o.hits.some(a=>Bs(r,a))}count(e,n){let s=this.groups.get(`${e}|${n}`);s&&s.total++}add(e,n,s){let i=`${e}|${n}`,o=this.groups.get(i);if(o||(o={rule:e,file:n,hits:[],total:0},this.groups.set(i,o)),o.hits.some(a=>a.line===s.line&&a.excerpt===s.excerpt))return;if(o.total++,o.hits.length<Un){o.hits.push(s);return}let r=0;for(let a=1;a<o.hits.length;a++)Bs(o.hits[r],o.hits[a])&&(r=a);Bs(s,o.hits[r])&&(o.hits[r]=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:o})=>fP(e,n,s,i,o))}};function fP(t,e,n,s,i){let o=ZR[e],r=s.map((d,h)=>({h:d,order:h})).sort((d,h)=>Bs(d.h,h.h)?-1:Bs(h.h,d.h)?1:d.order-h.order),a=r[0].h,c=r.slice(0,pP).sort((d,h)=>(d.h.line??0)-(h.h.line??0)||d.order-h.order).map(d=>d.h),l=mn(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 p=n===t?tl(t):`${tl(n)} (bundled with ${tl(t)})`;return{id:`skill-supply-chain-${e}-${_e(`${t}|${n}`)}`,severity:a.severity,category:o.category,title:o.title,summary:`${p}: ${o.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:o.recommendation,confidence:a.confidence,tags:[cl,e]}}var Zg=t=>typeof t=="function"?t():t,hP=.4;function _o(t,e,n,s,i,o,r){e!=="skip"&&(e==="lowconf"?t(n,s,()=>`(looks like documentation, but names a target) ${Zg(i)}`,o,hP):t(n,s,i,o,r))}var mP=/[|&;<$`]|>\(|iex|invoke-expression|atob|decode|FromBase64|powershell|pwsh/i;function Qg(t,e){let n=[];if(!mP.test(t))return n;let s=So(t,Ws,e);s&&n.push({rule:"remote-exec",found:s});let i=So(t,zg,e);if(i&&n.push({rule:"encoded-exec",found:i}),!n.some(o=>o.rule==="remote-exec"))for(let o of m1){let r=xe(o.pattern,t,o.requires);if(r){n.push({rule:"remote-exec",found:r});break}}if(!n.some(o=>o.rule==="encoded-exec"))for(let o of g1){let r=xe(o.pattern,t,o.requires);if(r){n.push({rule:"encoded-exec",found:r});break}}return n}function ey(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 gP(t,e,n,s,i){let o=new Set,r=ey(t),a=new Gs(i),c=Number.NaN;for(let{text:l,line:u}of e){let p=u-1,d=t.kind!=="instructions"||t.fenced[p]===1,h=r(p);h!==c&&(a=new Gs(i),c=h);let f=Qg(l,d),m=a.feed(l,u,d);m&&f.push({rule:m.rule,found:m.found,note:m.fromLine!==u?`(fetched/decoded at line ${m.fromLine}) `:void 0});for(let{rule:g,found:y,note:b}of f){let w=y.match[0].length,S=ko(t,p,l,y.index,w);_o(s,S,g,u,()=>`${b??""}${Oe(l,y.index,w)}`,"high",.85),S!=="skip"&&o.add(u)}}if(t.kind==="instructions")for(let{text:l,line:u}of n){if(o.has(u))continue;let p=Xg(t,l,u-1);p&&(o.add(u),s("remote-eval",u,Oe(l,p.index,p.match[0].length),"high",.85))}return o}function yP(t,e){for(let n of t.active){let s=xe(e,t.lines[n]);if(s)return{line:n+1,index:s.index}}}function bP(t,e,n){let s=yP(t,k1),i=[],o=[],r=_1[t.lang]??[],a=x1[t.lang]??[];for(let l of t.active){let u=l+1;if(e.has(u))continue;let p=t.lines[l],d=Xg(t,p,l);if(d){n("remote-eval",u,Oe(p,d.index,d.match[0].length),"high",.85);continue}if(i.length+o.length>=Un)continue;let h=r.map(m=>xe(m,p)).find(Boolean);if(h){i.push({line:u,index:h.index});continue}let f=a.map(m=>xe(m,p)).find(Boolean);f&&o.push({line:u,index:f.index})}if(s&&(i.length>0||o.length>0)){n("remote-eval",s.line,`network call: ${Oe(t.lines[s.line-1],s.index)}`,"high",.75);for(let l of[...i,...o])n("remote-eval",l.line,Oe(t.lines[l.line-1],l.index),"high",.75)}else for(let l of i)n("dynamic-eval",l.line,Oe(t.lines[l.line-1],l.index),"warning",.6);if(!s)return;let c=[];for(let l of t.active){if(c.length>=Un)break;let u=t.lines[l],p=xe(E1,u)??xe(A1,u);p&&(/(?:\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,p.index-300),p.index+1))||c.push({line:l+1,index:p.index}))}if(c.length!==0){n("credential-exfil",s.line,`network call: ${Oe(t.lines[s.line-1],s.index)}`,"high",.7);for(let l of c)n("credential-exfil",l.line,`credential/env read: ${Oe(t.lines[l.line-1],l.index)}`,"high",.7)}}function vo(t,e,n,s,i={}){for(let o of s){let r=xe(o,n);if(!r)continue;let a=r.match[0].length;if(i.skipQuoted&&TT(n,r.index,r.index+a))continue;let c;if(i.negatable===!1?c=!t.fenced[e]&&ll(n,r.index,a)?ul(n.slice(r.index,r.index+a+80))?"lowconf":"skip":"none":c=ko(t,e,n,r.index,a,i.targetless),c!=="skip")return{found:r,verdict:c}}}function wP(t){for(let e of Rt(N1,t,20)){let n=Hg(t,e.index),s=e.index+e.match[0].length,i=t.slice(s,s+120),o=M1.exec(i),r=o?null:j1.exec(i),a=o??r;if(!a)continue;let c=s+a.index+a[0].length,l=D1.exec(t.slice(c,c+120));if(!l)continue;let u=c+l.index+l[0].length,p=t.slice(u,u+100),d=F1.test(p);if(!d&&G1.test(t))continue;let h=ul(p),f={index:e.index,strong:d,negated:n,target:h};if(d)return{...f,severity:"high",confidence:.75};if(o&&H1.test(p))return{...f,severity:"warning",confidence:.6};if(r&&B1.test(p))return{...f,severity:"warning",confidence:.6}}}function vP(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 SP(t,e){let n=(s,i,o,r,a,c)=>_o(e,r.verdict,s,i,Oe(o,r.found.index,r.found.match[0].length),a,c);for(let s of t.active){let i=t.lines[s];if(i.length<8)continue;let o=s+1;if(R1.test(i)){let r=vo(t,s,i,C1,{skipQuoted:!0,targetless:!0});r&&n("instruction-override",o,i,r,"high",.8)}if(T1.test(i)){let r=vo(t,s,i,$1,{targetless:!0}),a=r?void 0:vo(t,s,i,I1,{negatable:!1});r?n("conceal-from-user",o,i,r,"high",.75):a&&n("conceal-from-user",o,i,a,"warning",.6)}if(P1.test(i)){let r=vo(t,s,i,L1,{targetless:!0});r&&n("permission-bypass",o,i,r,"warning",.6)}if(Ag.test(i))for(let r of vP(i)){if(!Ag.test(r.text))continue;let a=wP(r.text);if(!a)continue;let c=r.offset+a.index,u=!t.fenced[s]&&(a.negated||ll(i,c,10))?a.target?"lowconf":"skip":"none";_o(e,u,"exfil-instruction",o,Oe(i,c,60),a.severity,a.confidence);break}}}function _P(t,e){for(let n of t.active){let s=t.lines[n],i=xe(O1,s);if(!i||t.kind==="instructions"&&!t.fenced[n]&&IT(s))continue;let o=i.match[0].length;_o(e,ko(t,n,s,i.index,o,!0),"permission-bypass",n+1,()=>Oe(s,i.index,o),"warning",.7)}}var xP=/[\p{Script=Hebrew}\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Nko}]/u,kP=/\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Emoji_Component}/u,EP=/[\p{L}\p{M}]/u,AP=/\p{Script=Mongolian}/u,CP=/\p{Cf}/u,RP=[[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]],Rg=t=>"\\u{"+t.toString(16)+"}",sl=new RegExp("["+RP.map(([t,e])=>Rg(t)+"-"+Rg(e)).join("")+"\\p{Cf}]","gu");function il(t){return t>=65024&&t<=65039||t>=917760&&t<=917999}function ty(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 ol=t=>t===void 0?void 0:String.fromCodePoint(t);function TP(t,e,n,s,i,o){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 r=ty(t,e),a=t.codePointAt(e+(n>65535?2:1));if(n===8204||n===8205){let c=l=>l!==void 0&&l>127&&(kP.test(ol(l))||EP.test(ol(l)));return c(r)||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 o()?void 0:"mild";if(il(n)){let c=a===void 0||!il(a);return r!==void 0&&r>127&&!il(r)&&c?void 0:"mild"}if(n>=6155&&n<=6159&&n!==6158)return r!==void 0&&AP.test(ol(r))?void 0:"mild";if(n===4447||n===4448){let c=l=>l!==void 0&&l>=4352&&l<=4607;return c(r)||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||CP.test(String.fromCodePoint(n)))return"mild"}function PP(t,e){for(let n of t.active){let s=t.lines[n];sl.lastIndex=0;let i=sl.exec(s);if(i===null)continue;let o,r=()=>o??=xP.test(s),a=new Map,c=!1,l=-1,u=-1,p;for(;i!==null;){let d=i.index,h=s.codePointAt(d);if(h>=917504&&h<=917631){let m=ty(s,d);(m===void 0||m<917504||m>917631)&&(p=m)}let f=TP(s,d,h,n===0,p,r);f&&(f==="severe"&&(c=!0,u<0&&(u=d)),a.set(h,(a.get(h)??0)+1),l<0&&(l=d)),i=sl.exec(s)}a.size!==0&&e("hidden-unicode",n+1,()=>{let d=[...a.entries()].sort((f,m)=>f[0]-m[0]).slice(0,4).map(([f,m])=>`${Ni(f)}\xD7${m}`).join(" "),h=a.size>4?` (+${a.size-4} more kinds)`:"";return`${d}${h} in: ${Oe(s,c?u:l,1)}`},c?"high":"warning",c?.9:.7)}}function $P(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 IP(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,o=t.indexOf("<",s+1);if(o>=0&&o<i){e=o;continue}if(e=i+1,i-s>600||!/^<[a-z]/i.test(t.slice(s,s+2)))continue;let r=t.slice(s,i);if(W1.test(r)||V1.test(r))return{index:s,match:xo(t,s,i+1)}}}function OP(t,e){t.content.includes("<!--")&&LP(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=IP(s);i&&e("hidden-html-element",n+1,Oe(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=Rt(Y1,s,5).find(o=>{let r=o.match[0];return/(?:base64,|data:[^,\s]{0,100},)\s{0,5}$/i.test(s.slice(Math.max(0,o.index-120),o.index))||!/[0-9]/.test(r)||!/[A-Z]/.test(r)||!/[a-z]/.test(r)?!1:(r.match(/\//g)?.length??0)<=r.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 LP(t,e){let n=t.lines.map((r,a)=>t.fenced[a]?"":r),s=n.join(`
101
+ `),i=[0];for(let r=0;r<n.length-1;r++)i.push(i[r]+n[r].length+1);let o=0;for(;o<s.length;){let r=s.indexOf("<!--",o);if(r<0)break;let a=s.indexOf("-->",r+4),c=a<0?s.length:a;o=a<0?s.length:a+3;let l=s.slice(r+4,c);if(U1.test(l.slice(0,200))&&l.length<=120&&!z1.test(l)&&!q1.test(l))continue;let u=xe(K1,l);if(!u)continue;let p=$P(i,r+4+u.index),d=t.lines[p-1]??"",h=r+4+u.index-i[p-1];e("hidden-html-comment",p,()=>Oe(d,h,u.match[0].length),"warning",.6)}}function NP(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 Rt(/`([^`\n]{1,1000})`/g,s.text,50))ko(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 Tg(t,e,n,s){let i=(o,r,a,c=.6)=>s("unpinned-remote-dep",o,Oe(r,a,80),"warning",c);if(t.kind==="manifest")return jP(t,i,s);for(let{text:o,line:r}of e){if(n.has(r))continue;if(X1.test(o)){let p=Rt(J1,o,10).find(d=>!fl(hl(d.match[0])));if(p){i(r,o,p.index);continue}}let a=rP(o);if(a){i(r,o,a.index,.5);continue}let c=xe(eP,o);if(c&&(c.match[1]??"").trim().split(/\s+/).filter(h=>h&&!h.startsWith("-")).find(h=>!h.startsWith("@")&&!h.startsWith(".")&&!h.startsWith("/")&&!h.startsWith("file:")&&!/\.(?:js|mjs|cjs|ts|json|md|sh|py|txt)$/i.test(h)&&(/^[A-Za-z0-9][\w.-]{0,100}\/[\w.-]{1,100}(?:#\S{0,100})?$/.test(h)||/^https?:\/\//i.test(h))&&Jg(h))){i(r,o,c.index);continue}let l=xe(tP,o);if(l&&!/--(?:rev|tag)\s{1,5}\S/.test(o)){i(r,o,l.index);continue}let u=xe(nP,o);if(u&&xe(sP,o)&&iP.test(u.match[0])){i(r,o,u.index);continue}if(t.kind==="script"&&t.lang==="js"){let p=Rt(oP,o,10).find(d=>!/@v?\d+(?:\.\d+)*|@[0-9a-f]{7,40}|\/v?\d+\.\d+\.\d+\//i.test(d.match[1]));p&&i(r,o,p.index)}}return[]}function MP(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 Gs().feed(c,1,!0);for(let{rule:u,found:p}of[...Qg(c,!0),...l?[l]:[]])n(u,it(t.content,`"${a}"`),`scripts.${mn(a)}: ${Oe(c,p.index,p.match[0].length)}`,"high",.85)}let i=e.bin,o=typeof i=="string"?[i]:typeof i=="object"&&i!==null?Object.values(i).filter(a=>typeof a=="string"):[],r=Je.posix.dirname(t.path);return o.slice(0,5).map(a=>Je.posix.normalize(`${r}/${a.replace(/\\/g,"/")}`)).filter(a=>a.startsWith(`${r}/`))}function jP(t,e,n){if(Je.posix.basename(t.path)==="package.json"){let i;try{i=JSON.parse(t.content)}catch{return[]}if(typeof i!="object"||i===null)return[];let o=MP(t,i,n),r=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 p=u.trim();if(p===""||p==="*"||p==="latest"||Jg(p)){if(++r>Un)return o;let d=it(t.content,`"${l}"`);e(d,t.lines[d-1]??`"${l}": "${u}"`,0)}}}return o}for(let i of t.active){let o=t.lines[i].replace(/\s#.*$/,""),r=xe(/\bgit\+[a-z]{1,10}:\/\/\S{1,500}/i,o);if(r&&!fl(hl(r.match[0]))){e(i+1,o,r.index);continue}let a=xe(/\bhttps?:\/\/\S{1,500}?\.(?:zip|tar\.gz|tgz|whl)\S{0,200}/i,o);a&&!/\d+\.\d+|#sha256=/i.test(a.match[0])&&e(i+1,o,a.index)}return[]}function DP(t,e,n,s,i){let o=/^(.*?)\/?skills\/[^/]+$/.exec(e)?.[1],r=p=>{let d=p,h,f=/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?\/(.*)$/.exec(d);if(f){let m=f[1];if(d=f[2],m==="CLAUDE_SKILL_DIR"||m==="SKILL_DIR")h=[e];else if(m==="CLAUDE_PLUGIN_ROOT"&&o!==void 0)h=[o||"."];else if(m==="CLAUDE_PROJECT_DIR")h=["."];else return}else if(d.startsWith("{baseDir}/"))d=d.slice(10),h=[e];else{if(d=d.replace(/^\.\//,""),!d.includes("/"))return;h=[...new Set([e,...o?[o]:[],"."])]}if(!(!d||d.includes("..")||d.startsWith("/")))return h.map(m=>m==="."?d:`${m}/${d}`)},a=new Map,c=0,l=0,u=p=>{let d=a.get(p);if(d!==void 0)return d;if(c>=FP)return;c++;let h=gt(t,p);return a.set(p,h),h};for(let p of n.active){let d=n.lines[p];if(!(n.fenced[p]&&uP.has(n.fenceLang.get(p)??""))&&dP.test(d))for(let h of[cP,lP])for(let f of Rt(h,d,10)){let m=f.match[1],g=m.replace(/^\.\//,""),y=r(m);if(!y)continue;let b=!1,w=!1;for(let S of y){let C=u(S);if(C===void 0)w=!0;else if(C){b=!0;break}}if(!b){if(w)return;if(!(s().has(g)||s().has(m))&&(i("missing-script",p+1,`${mn(m)} not found (looked in: ${y.map(mn).join(", ")})`,"warning",.6),++l>=Un))return}}}}var FP=200,HP=3e6;function Pg(t,e,n){let s=Buffer.alloc(n),i=zt.readSync(t,s,0,n,e);return s.subarray(0,i)}function BP(t,e,n,s,i){let o=n.split(/\r?\n/),r=[];for(let l=0;l<o.length;l++){let u=o[l];u.length>0&&GP.test(u)&&r.push(l)}let a=new Uint8Array(o.length),c=new Map;if(e.kind==="instructions"&&(n.includes("```")||n.includes("~~~"))){let l=we(n.replace(/\r\n/g,`
102
+ `));for(let u=0;u<o.length;u++){let p=l[u];p?.inFence&&(a[u]=1,p.lang&&c.set(u,p.lang))}}return{path:t,kind:e.kind,lang:e.lang,content:n,lines:o,active:r,fenced:a,fenceLang:c,frontmatterEnd:s&&!i?lT(o):0,tail:i}}var GP=/[^ \t\r]/;function WP(t){let e=1;for(let n=t.indexOf(10);n>=0;n=t.indexOf(10,n+1))e++;return e}function VP(t,e,n,s,i){let o=s?"high":"warning",r=n?{kind:"instructions",lang:"other"}:$g(e);if(typeof r=="object"&&"skip"in r)return{docs:[],unscanned:[]};if(typeof r=="object"&&"report"in r)return{docs:[],unscanned:[{path:e,reason:r.report,severity:r.severity}]};let a=tn(t,e);if(!a)return{docs:[],unscanned:[]};if(!Pe(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=zt.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:o}]};if(c=zt.openSync(a,"r"),r==="probe"){let g=Pg(c,0,Math.min(u,In));if(sn(g))return{docs:[],unscanned:[{path:e,reason:`${cT(g)} \u2014 cannot be reviewed as text`,severity:"warning"}]};let y=aT(g.toString("utf8").split(/\r?\n/,1)[0]??"");r=y?{kind:"script",lang:y}:{kind:"text",lang:"other"}}let p=r,d=p.note?[{path:e,reason:p.note.reason,severity:p.note.severity}]:[];i.files--;let h=(g,y,b)=>{let w=Pg(c,g,y);return i.bytes-=w.length,i.lines-=WP(w),BP(e,p,w.toString("utf8"),n&&!b,b)};if(u<=2*ye){let g=Math.min(u,i.bytes),y=[h(0,g,!1)];return g<u&&d.push({path:e,reason:"per-scan budget exhausted part-way \u2014 the rest was not scanned",severity:o}),{docs:y,unscanned:d}}let f=[h(0,Math.min(ye,i.bytes),!1)],m=Math.min(ye,i.bytes);return m>0&&f.push(h(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":o}),{docs:f,unscanned:d}}catch{return{docs:[],unscanned:[]}}finally{c!==void 0&&zt.closeSync(c)}}function UP(t,e,n,s,i,o,r){let a=(h,f,m,g,y)=>{if(!o.accepts(h,n.path,g,y)){o.count(h,n.path);return}let b=n.tail?"(end of file) ":n.frontmatterEnd>0&&f<=n.frontmatterEnd?"(frontmatter) ":"";o.add(h,n.path,{line:n.tail?void 0:f,excerpt:`${b}${Zg(m)}`,severity:g,confidence:y})};if(PP(n,a),_P(n,a),n.kind==="manifest")return Tg(n,[],new Set,a);let{lines:c,capped:l}=fT(n);l.length>0&&r.push({path:n.path,reason:`continuation chain longer than ${Og} lines / ${Lg} characters at line ${l[0]} \u2014 split for scanning (a download-fed loop body is followed up to ${Ng} lines / ${Mg} characters)`,severity:"warning"});let u=NP(n,c),d=gP(n,c,u,a,h=>{let f=h.replace(/^\.\//,"");return!f||f.startsWith("/")||/^[a-z]:/i.test(f)?!1:[`${Je.posix.dirname(n.path)}/${f}`,`${e}/${f}`,f].some(m=>gt(t,m))});return Tg(n,u,d,a),n.kind==="instructions"?(SP(n,a),OP(n,a),s&&!n.tail&&DP(t,e,n,i,a)):bP(n,d,a),[]}var zP=["node_modules",".git","worktrees",".worktrees"],qP={node_modules:/(?:^|[\s'"`(=:/])node_modules\//m,".git":/(?:^|[\s'"`(=:])(?:\.\/)?\.git\//m,worktrees:/(?:^|[\s'"`(=:])(?:\.\/)?worktrees\//m,".worktrees":/(?:^|[\s'"`(=:])(?:\.\/)?\.worktrees\//m};function KP(t,e){let n=t.entries(`${e}/hooks`);if(typeof n=="string")return!1;for(let s of n.keys())if(!s.endsWith(".sample"))return!0;return!1}function YP(t,e,n){switch(t.kind){case"dependency-dir":{let s=Je.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"&&KP(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 ml(t,e={}){let n=Z(t),s=t.aiConfig??{},i=s.allSkills??s.skills??[],o=new Set(s.skills??[]),r=i.map(f=>Je.posix.dirname(f)),a=f=>{let m=-1;return r.forEach((g,y)=>{ls(g)||!(f===g||f.startsWith(`${g}/`))||(m<0||g.length>r[m].length)&&(m=y)}),m},c=i.map((f,m)=>{let g={skillMd:f,dir:r[m],collector:new al,unscanned:[],alreadyReported:()=>new Set,referenced:new Set,queue:{priority:[],rest:[]},loaded:!1};if(o.has(f)){let y;g.alreadyReported=()=>y??=new Set(Qc(g.headContent??"").map(b=>b.ref))}return g});for(let f of s.skillFiles??[]){let m=a(f);m>=0&&(yg(f)?c[m].queue.priority:c[m].queue.rest).push(f)}for(let f of s.skillFilesOverCap??[]){let m=a(f);m>=0&&c[m].unscanned.push({path:f,reason:"over the per-skill file cap \u2014 not scanned",severity:yg(f)?"high":"warning"})}let l={bytes:e.bytes??XR,files:e.files??JR,lines:e.lines??HP},u=(f,m)=>{if(!(m.kind!=="instructions"&&m.kind!=="script"&&!(m.kind==="text"&&m.lang==="sh")))for(let g of zP)qP[g].test(m.content)&&f.referenced.add(g)},p=new Set,d=(f,m,g,y)=>{if(p.has(m))return{docs:[],unscanned:[]};p.add(m);let b=VP(t.repoRoot,m,g,y,l);f.unscanned.push(...b.unscanned);let w=[];g&&(f.headContent=b.docs[0]?.content);for(let S of b.docs)u(f,S),w.push(...UP(n,f.dir,S,g,f.alreadyReported,f.collector,f.unscanned));for(let S of w)a(S)>=0&&d(f,S,!1,!0);return b};for(let f of c){let m=d(f,f.skillMd,!0,!0);f.loaded=m.docs.length>0||m.unscanned.length>0;for(let g of f.queue.priority)d(f,g,!1,!0)}for(let f of c)for(let m of f.queue.rest)d(f,m,!1,!1);let h=[];for(let f of c)if(f.loaded){for(let m of s.skillBundleSkips??[])a(m.path)===c.indexOf(f)&&f.unscanned.push(YP(m,f.referenced,n));for(let m of f.unscanned)f.collector.add("unscanned-files",f.skillMd,{excerpt:`${mn(m.path)}: ${m.reason}`,severity:m.severity,confidence:.8});h.push(...f.collector.toIssues(f.skillMd))}return Ge(t.repoRoot,h)}var gl=R(require("node:path"),1);var XP={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."},JP=new Set(["sonnet","opus","haiku","inherit","default","opusplan"]),ZP=new Set(["Task","Bash","BashOutput","KillBash","KillShell","Glob","Grep","LS","Read","Edit","MultiEdit","Write","NotebookRead","NotebookEdit","WebFetch","WebSearch","TodoWrite","SlashCommand","ExitPlanMode","Agent"]),QP=.8,e$=5;function Vs(t,e){return`ai-config-agent-${t}-${_e(e)}`}function t$(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 n$(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 r of s)i.has(r)&&n++;let o=t.size+e.size-n;return o===0?0:n/o}function yl(t){let e=[],n=[];for(let i of t.aiConfig.agents){let o=Ie(t.repoRoot,i);if(o===void 0)continue;let r=Et(o);if(e.push(...Gt(i,o,r,XP)),!r.present)continue;let a=typeof r.data.name=="string"?r.data.name.trim():void 0,c=typeof r.data.description=="string"?r.data.description.trim():void 0;a||e.push(K({id:Vs("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:r.fenceEndLine>0?r.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(r.data).join(", ")||"(none)"}`],recommendation:"Add a `name` field to the frontmatter.",confidence:.85})),c||e.push(K({id:Vs("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:r.fenceEndLine>0?r.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(r.data).join(", ")||"(none)"}`],recommendation:"Add a `description` explaining what the agent is for and when to use it.",confidence:.85}));let l=typeof r.data.model=="string"?r.data.model.trim():void 0;l&&!JP.has(l.toLowerCase())&&!/^claude-/i.test(l)&&e.push(K({id:Vs("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:r.keyLines.model??1,endLine:r.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=Hn(r.data.tools),p=u.filter(f=>f!=="*"&&!f.startsWith("mcp__")&&!ZP.has(f));p.length>0&&e.push(K({id:Vs("unknown-tools",`${i}|${p.join(",")}`),severity:"info",title:"Subagent grants tools that may not exist",summary:`${i} lists ${p.length} tool name(s) that are not built-in tools or \`mcp__*\` tools: ${p.join(", ")}.`,filePaths:[i],locations:[{filePath:i,startLine:r.keyLines.tools??1,endLine:r.keyLines.tools??1}],evidence:[`Unrecognized: ${p.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=o.split(/\r?\n/).slice(Math.max(0,r.bodyStartLine-1)).join(`
103
+ `),h=t$(d);n.push({filePath:i,bodyLines:h})}let s=n.filter(i=>i.bodyLines.size>=e$);for(let i=0;i<s.length;i++)for(let o=i+1;o<s.length;o++){let r=s[i],a=s[o],c=n$(r.bodyLines,a.bodyLines);if(c>=QP){let l=[r.filePath,a.filePath].sort();e.push(K({id:Vs("dup-prompt",l.join("|")),title:"Two subagents share near-identical system prompts",summary:`${dn(gl.basename(l[0]))} and ${dn(gl.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 Ge(t.repoRoot,e)}var s$=/\b(curl|wget)\b[^|]*\|\s*(sudo\s+)?(sh|bash|zsh|dash)\b/i;function Eo(t,e){return`ai-config-hook-${t}-${_e(e)}`}function wl(t,e,n){if(Array.isArray(t)){for(let i of t)wl(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,o]of Object.entries(s))typeof o=="object"&&o!==null&&wl(o,e===""?i:e,n)}var i$=new Set(["bash","sh","zsh","dash","node","deno","python","python3","ruby","ts-node","tsx","pwsh","powershell"]),o$=new Set(["npx","bunx","pnpm","yarn","uv","uvx","env","timeout","nice","sudo","exec","command"]);function bl(t){return t.replace(/^['"]|['"]$/g,"").replace(/^\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/,"")}function r$(t){let e=new Set,n=(s,i)=>{if(s.startsWith("-"))return;let o=s.replace(/^['"]|['"]$/g,""),r=bl(s);if(!r||r.includes("$")||/[<>{}*?|"'`]/.test(r)||r.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||/^https?:/i.test(r)||r.includes("..")||!vs.test(r))return;let a=o.startsWith("./")||o.startsWith(".claude/")||/^\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/.test(o);(i||a)&&e.add(r.replace(/\\/g,"/"))};for(let s of t.split(/&&|\|\||;|\|/)){let i=s.trim().split(/\s+/).filter(Boolean);if(i.length===0)continue;let o=bl(i[0]);if(i$.has(o)||o$.has(o)){for(let r=1;r<i.length;r++)if(!i[r].startsWith("-")&&vs.test(bl(i[r]))){n(i[r],!0);break}}else n(i[0],!0);for(let r=1;r<i.length;r++)n(i[r],!1)}return[...e]}function a$(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 c$(t){for(let e of t.matchAll(/\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/g))if(!a$(t,e.index))return!0;return!1}function vl(t){let e=[],n=Z(t);for(let s of t.aiConfig.settings){let i=Ie(t.repoRoot,s);if(i===void 0)continue;let o;try{o=JSON.parse(i)}catch(l){e.push(K({id:Eo("invalid-json",s),severity:"high",title:"Settings file is not valid JSON",summary:`${s} could not be parsed as JSON, so Claude Code cannot load its hooks or permissions.`,filePaths:[s],locations:[{filePath:s,startLine:1,endLine:1}],evidence:[`Parse error: ${l.message}`],recommendation:"Fix the JSON syntax (trailing commas and comments are not allowed in settings.json).",confidence:.95}));continue}if(typeof o!="object"||o===null||Array.isArray(o))continue;let r=o.hooks;if(r===void 0)continue;let a=[];wl(r,"",a);let c=new Set;for(let{command:l,event:u}of a){let p=it(i,l);s$.test(l)&&e.push(K({id:Eo("curl-pipe-sh",`${s}|${l}`),severity:"high",impact:"high",title:"Hook pipes a remote download into a shell",summary:`A ${u||"hook"} command in ${s} pipes \`curl\`/\`wget\` output directly into a shell, running whatever the remote host serves with your permissions.`,filePaths:[s],locations:[{filePath:s,startLine:p,endLine:p}],evidence:[`Command: ${l.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})),c$(l)&&e.push(K({id:Eo("unquoted-project-dir",`${s}|${l}`),severity:"info",title:"Hook uses an unquoted $CLAUDE_PROJECT_DIR path",summary:`A ${u||"hook"} command in ${s} expands \`$CLAUDE_PROJECT_DIR\` unquoted; if the project path contains a space the command breaks or runs the wrong file.`,filePaths:[s],locations:[{filePath:s,startLine:p,endLine:p}],evidence:[`Command: ${l.slice(0,160)}`],recommendation:'Wrap the path in double quotes, e.g. `"$CLAUDE_PROJECT_DIR/script.sh"`.',confidence:.5}));for(let d of r$(l)){if(gt(n,d))continue;let h=`${s}|${d}`;c.has(h)||(c.add(h),e.push(K({id:Eo("missing-script",h),title:"Hook command references a script that does not exist",summary:`A ${u||"hook"} command in ${s} runs \`${d}\`, but that file is not present in the repository.`,filePaths:[s],locations:[{filePath:s,startLine:p,endLine:p}],evidence:[`Referenced script: ${d}`,`Command: ${l.slice(0,160)}`],recommendation:"Add the script, fix the path, or remove the hook.",confidence:.75})))}}}return Ge(t.repoRoot,e)}function Us(t,e){return`ai-config-mcp-${t}-${_e(e)}`}function l$(t,e){let n=[],s=0,i=!1,o=!1,r="",a=null;for(let c=e;c<t.length;c++){let l=t[c];if(i){if(o){o=!1,r+=l;continue}if(l==="\\"){o=!0;continue}if(l==='"'){i=!1,s===1&&(a=r);continue}r+=l;continue}if(l==='"'){i=!0,r="";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 u$(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=l$(t,n),i=new Map;for(let o of s)i.set(o,(i.get(o)??0)+1);return[...i.entries()].filter(([,o])=>o>1).map(([o])=>o).sort()}function d$(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 p$(t,e){let n=new Set,s=(i,o)=>{let r=i.replace(/^['"]|['"]$/g,"");if(!r||r.startsWith("-")||r.includes("$")||/[<>{}*?]/.test(r)||r.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||/^https?:/i.test(r)||r.includes(".."))return;let a=r.startsWith("./")||r.startsWith(".claude/");o&&!a||(a||r.includes("/")&&vs.test(r))&&n.add(r.replace(/\\/g,"/"))};t&&s(t,!1);for(let i of e)s(i,!0);return[...n]}function Sl(t){let e=[],n=Z(t);for(let s of t.aiConfig.mcp){let i=Ie(t.repoRoot,s);if(i===void 0)continue;let o;try{o=JSON.parse(i)}catch(a){e.push(K({id:Us("invalid-json",s),severity:"high",title:"MCP config is not valid JSON",summary:`${s} could not be parsed as JSON, so no MCP servers will load from it.`,filePaths:[s],locations:[{filePath:s,startLine:1,endLine:1}],evidence:[`Parse error: ${a.message}`],recommendation:"Fix the JSON syntax (no trailing commas, no comments).",confidence:.95}));continue}if(typeof o!="object"||o===null||Array.isArray(o))continue;let r=o.mcpServers;if(!(typeof r!="object"||r===null||Array.isArray(r))){for(let a of u$(i))e.push(K({id:Us("duplicate-name",`${s}|${a}`),title:"Duplicate MCP server name",summary:`${s} defines the server "${a}" more than once. JSON keeps only the last definition and silently discards the earlier one.`,filePaths:[s],locations:[{filePath:s,startLine:it(i,`"${a}"`),endLine:it(i,`"${a}"`)}],evidence:[`Duplicated server name: ${a}`],recommendation:"Rename or remove the duplicate so each server name is unique.",confidence:.85}));for(let[a,c]of Object.entries(r)){if(typeof c!="object"||c===null||Array.isArray(c))continue;let l=c,u=typeof l.command=="string"?l.command:void 0,p=typeof l.url=="string"?l.url:void 0,d=Array.isArray(l.args)?l.args.filter(f=>typeof f=="string"):[],h=it(i,`"${a}"`);if(!u&&!p&&e.push(K({id:Us("no-command-or-url",`${s}|${a}`),title:"MCP server has neither a command nor a url",summary:`${s}: server "${a}" defines no \`command\` (stdio) and no \`url\` (http/sse), so it cannot start.`,filePaths:[s],locations:[{filePath:s,startLine:h,endLine:h}],evidence:[`Server: ${a}`,`Keys: ${Object.keys(l).join(", ")||"(none)"}`],recommendation:"Add a `command` (with `args`) for a stdio server, or a `url` for a remote server.",confidence:.8})),typeof l.env=="object"&&l.env!==null&&!Array.isArray(l.env))for(let[f,m]of Object.entries(l.env))typeof m!="string"||!d$(m)||e.push(K({id:Us("placeholder-env",`${s}|${a}|${f}`),title:"MCP server env value is an unfilled placeholder",summary:`${s}: server "${a}" sets \`env.${f}\` to a placeholder (${JSON.stringify(m)}) that was never replaced with a real value.`,filePaths:[s],locations:[{filePath:s,startLine:it(i,`"${f}"`),endLine:it(i,`"${f}"`)}],evidence:[`${f}: ${m}`],recommendation:'Replace the placeholder with a real value, or reference a shell variable like `"${'+f+'}"`.',confidence:.7}));for(let f of p$(u,d))gt(n,f)||e.push(K({id:Us("missing-command",`${s}|${a}|${f}`),title:"MCP server command path does not exist",summary:`${s}: server "${a}" references the local path \`${f}\`, which is not present in the repository.`,filePaths:[s],locations:[{filePath:s,startLine:h,endLine:h}],evidence:[`Referenced path: ${f}`,`Server: ${a}`],recommendation:"Fix the path, add the missing file, or install the server so the path resolves.",confidence:.7}))}}}return Ge(t.repoRoot,e)}var sy=R(_t(),1);var f$={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},h$=["**/node_modules/**","**/.git/**"];function ny(t,e){return`ai-config-cursor-${t}-${_e(e)}`}function m$(t){let e=t.trim();return!(!e||e.startsWith("!")||e.includes("$")||e.includes("<")||e.includes(">"))}function _l(t){let e=[],n=t.aiConfig.cursorRules,s=null,i=o=>(s??=yt(t.repoRoot,["**/*"],h$),sy.default.some(s,o,{dot:!0}));for(let o of n){let r=Ie(t.repoRoot,o);if(r===void 0)continue;let a=Et(r);if(e.push(...Gt(o,r,a,f$)),!a.present)continue;let c=typeof a.data.description=="string"?a.data.description.trim():"",l=Hn(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(K({id:ny("no-trigger",o),title:"Cursor rule has no trigger",summary:`${o} defines no \`description\`, no \`globs\`, and \`alwaysApply\` is not set, so Cursor has no signal for when to apply it.`,filePaths:[o],locations:[{filePath:o,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 p of l){if(!m$(p))continue;let d=p.replace(/^\//,""),h=d.includes("/")?[d]:[d,`**/${d}`];i(h)||e.push(K({id:ny("dead-glob",`${o}|${p}`),title:"Cursor rule glob matches no files",summary:`${o}: the \`globs\` pattern \`${p}\` matches no files in the repository, so this auto-attached rule never fires.`,filePaths:[o],locations:[{filePath:o,startLine:a.keyLines.globs??1,endLine:a.keyLines.globs??1}],evidence:[`Glob: ${p}`],recommendation:"Update the glob to match real paths, or remove the rule if the code it targeted is gone.",confidence:.6}))}}return Ge(t.repoRoot,e)}var kl=R(_t(),1);var g$={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},y$=["**/node_modules/**","**/.git/**"],b$=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/out/**","**/coverage/**","**/worktrees/**","**/.worktrees/**"];function xl(t,e){return`ai-config-copilot-${t}-${_e(e)}`}function w$(t){let e=t.trim();return!(!e||e.startsWith("!")||e.includes("$")||e.includes("<")||e.includes(">"))}function v$(t){let e=t.trim();return e==="**"||e==="**/*"}function El(t){let e=[],n=t.aiConfig.copilotInstructions,s=null,i=null,o=a=>(s??=yt(t.repoRoot,["**/*"],y$),kl.default.some(s,a,{dot:!0})),r=a=>(i??=yt(t.repoRoot,["**/*"],b$),kl.default.some(i,a,{dot:!0}));for(let a of n){let c=Ie(t.repoRoot,a);if(c===void 0)continue;let l=Et(c);if(e.push(...Gt(a,c,l,g$)),!l.present)continue;let u=Hn(l.data.applyTo);if(u.length===0){e.push(K({id:xl("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 p=l.keyLines.applyTo??1;for(let d of u){if(!w$(d)||v$(d))continue;let h=d.replace(/^\//,""),f=h.includes("/")?[h]:[h,`**/${h}`];o(f)?r(f)||e.push(K({id:xl("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:p,endLine:p}],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(K({id:xl("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:p,endLine:p}],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 Ge(t.repoRoot,e)}var S$=[{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}],_$=2;function Al(t){let e=[],n=i=>i==="windsurf",s=[...t.files.filter(i=>i.fileType==="windsurf").map(i=>[i]),...ys(on(t.files,t.aliasFiles??[],n))];for(let i of s){let o=i[0],r=new Set;for(let a of o.sections){let c=a.heading;if(c)for(let l of S$)l.re.test(c)&&r.add(l.label)}if(r.size>=_$){let a=[...r].sort();e.push({id:`ai-config-windsurf-scope-${_e(G(o))}`,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 iy=R(require("node:crypto"),1),oy=R(require("node:path"),1);var x$=Ae,k$=[/\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],E$=/^(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,A$=/\b(must|should|always|shall)\b/i,C$=8,R$=.4;function T$(t){return t.replace(/^\s*#{1,6}\s+/,"").replace(/^\s*[-*+]\s+/,"").replace(/^\s*\d+[.)]\s+/,"").replace(/^\s*>\s+/,"").trim()}function P$(t){return t.replace(/^[*_`]+/,"").trimStart()}function $$(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 r=T$(i);if(r)for(let a of r.split(/(?<=[.!?])\s+/)){let c=a.trim();c.split(/\s+/).length>=3&&n.push(c)}}return n}function I$(t){let e=P$(t);if(E$.test(e))return"positive";for(let n of k$)if(n.test(t))return"negative";return A$.test(t)?"positive":"none"}function O$(t){return`negative-overload-${iy.createHash("sha1").update(`negative-overload:${t}`).digest("hex").slice(0,12)}`}function Cl(t){let e=[];for(let n of t){if(!x$.has(n.fileType))continue;let s=$$(n.content),i=[],o=0;for(let p of s){let d=I$(p);d==="negative"?i.push(p):d==="positive"&&o++}let r=i.length+o;if(r<C$)continue;let a=i.length/r;if(a<=R$)continue;let c=oy.basename(n.path),l=Math.round(a*100),u=i.slice(0,3).map(p=>se(p,100));e.push({id:O$(G(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 ${r}). 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(p=>`Negative directive: "${p}"`),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 ry=R(require("node:crypto"),1),ay=R(require("node:path"),1);var L$=Ae,N$=[/\bnever\b/i,/\bcritical\b/i,/\bmust\s+not\b/i,/\bsecurity\b/i,/\bdangerous\b/i],M$=100,j$=.6;function D$(t){return N$.some(e=>e.test(t))}function F$(t){return`buried-critical-${ry.createHash("sha1").update(`buried-critical:${t}`).digest("hex").slice(0,12)}`}function Rl(t){let e=[];for(let n of t){if(!L$.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<=M$)continue;let o=Math.floor(i/2),r=[],a=0,c=!1;for(let f=0;f<i;f++){let m=s[f]??"";if(/^\s*(```|~~~)/.test(m)){c=!c;continue}c||D$(m)&&(r.push(f+1),f>=o&&a++)}if(r.length===0)continue;let l=a/r.length;if(l<=j$)continue;let u=ay.basename(n.path),p=Math.round(l*100),d=r.filter(f=>f>o),h=s[(d[0]??r[0])-1]??"";e.push({id:F$(G(n)),severity:"info",category:"structure",title:"Critical instructions near the bottom of a long file",summary:`${p}% of the high-severity lines in "${u}" (${a} of ${r.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(f=>({filePath:n.path,startLine:f,endLine:f})),evidence:[`Keyword lines in bottom half: ${d.slice(0,8).join(", ")}`+(d.length>8?", \u2026":""),`e.g. line ${d[0]??r[0]}: "${se(h,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 cy=R(require("node:crypto"),1);var H$=Ae,B$=6,G$=.65,W$=40,V$=8;function U$(t){return t.toLowerCase().replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+[.)]\s+/gm,"").replace(/\s+/g," ").trim()}function z$(t){return new Set(t.match(/\b\w+\b/g)??[])}function q$(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 K$(t){let e=t.text.split(`
104
+ `),n=[],s=[],i=t.startLine,o=0,r=()=>{if(s.length===0)return;o++;let a=s.join(`
105
+ `);if(!a.includes("```")&&!a.includes("~~~")){let c=U$(a),l=z$(c);c.length>=W$&&l.size>=V$&&n.push({number:o,text:a,startLine:i,tokens:l})}s=[]};for(let a=0;a<e.length;a++){let c=e[a]??"";c.trim()===""?r():(s.length===0&&(i=t.startLine+a),s.push(c))}return r(),n}function Y$(t,e){return`within-section-dup-${cy.createHash("sha1").update(`within-section-dup:${t}:${e}`).digest("hex").slice(0,12)}`}function Tl(t){let e=[];for(let n of t)if(H$.has(n.fileType))for(let s of n.sections){let i=K$(s);if(i.length<B$)continue;let o=null,r=0;for(let u=0;u<i.length;u++)for(let p=u+1;p<i.length;p++){let d=q$(i[u].tokens,i[p].tokens);d>=G$&&(r++,(!o||d>o.sim)&&(o={a:i[u],b:i[p],sim:d}))}if(!o)continue;let a=s.heading??"(untitled section)",c=Math.round(o.sim*100),l=r>1?` (${r} similar pairs in total)`:"";e.push({id:Y$(G(n),s.startLine),severity:"info",category:"duplicate",title:`Possible repetition within section: ${a}`,summary:`Within "${a}", paragraphs ${o.a.number} and ${o.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:o.a.startLine,endLine:o.a.startLine},{filePath:n.path,startLine:o.b.startLine,endLine:o.b.startLine}],evidence:[`Paragraph ${o.a.number}: "${se(o.a.text,120)}"`,`Paragraph ${o.b.number}: "${se(o.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 X$=t=>Ae.has(t),zs=t=>Xf(t.files,t.aliasFiles,X$),Pl=[{id:"duplicates",run:t=>Oa(t.files)},{id:"duplicate-headings",run:t=>La(t.files)},{id:"within-section-dedup",run:t=>Tl(zs(t))},{id:"conflicts",run:t=>Ma(t.files)},{id:"version-conflicts",run:t=>ja(t.files)},{id:"competing-tech-conflicts",run:t=>Da(t.files)},{id:"context-bloat",run:t=>Wm(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=>Jm(t.files)},{id:"command-validity",run:t=>em(t)},{id:"missing-context",run:t=>zm(t.files,t.projectType)},{id:"manifest-consistency",run:t=>Tc(t)},{id:"dependency-staleness",run:t=>zc({...t,files:zs(t)})},{id:"vague-guidance",run:t=>tg(t.files,{severityOverride:t.vagueGuidanceSeverity})},{id:"dead-references",run:t=>Wa(t.files,t.repoRoot,t.tree)},{id:"agent-practices",run:t=>qa(t.files,t.aliasFiles)},{id:"canonical-owner",run:t=>Fm(t.files)},{id:"ci-alignment",run:t=>im(t)},{id:"security-pack",run:t=>sg(t)},{id:"action-pinning",run:t=>Kc(t)},{id:"framework-packs",run:t=>ug(t)},{id:"prompt-cache-friendliness",run:t=>hg(zs(t))},{id:"ai-config-skills",run:t=>el(t)},{id:"skill-supply-chain",run:t=>ml(t)},{id:"ai-config-subagents",run:t=>yl(t)},{id:"ai-config-hooks-settings",run:t=>vl(t)},{id:"ai-config-mcp",run:t=>Sl(t)},{id:"ai-config-cursor-rules",run:t=>_l(t)},{id:"ai-config-copilot-instructions",run:t=>El(t)},{id:"ai-config-windsurf-rules",run:t=>Al(t)},{id:"negative-instructions",run:t=>Cl(zs(t))},{id:"buried-critical",run:t=>Rl(zs(t))},{id:"custom-rules",run:t=>Mc(t.files,t.customRules,t.repoRoot)}];function $l(t){return Pl.flatMap(e=>e.run(t))}async function Il(t){let e=await Ps(t),n=Pl.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 gn=R(require("node:path"),1);var Ao=R(require("node:path"),1),ly=new Set(["duplicate","context_bloat","stale_instruction","conflict","vague_guidance"]);function uy(t){return Math.round(t/4)}var J$=process.platform==="win32"||process.platform==="darwin";function Ol(t){let e=Ao.resolve(t).split(Ao.sep).join("/");return J$?e.toLowerCase():e}function dy(t){let e=t.content.split(`
97
106
  `);return t.content.endsWith(`
98
- `)&&e.pop(),e.map(n=>n.length+1)}function ZP(t){let e=[...t].sort((s,i)=>s[0]-i[0]||s[1]-i[1]),n=[];for(let[s,i]of e){let r=n[n.length-1];r&&s<=r[1]+1?r[1]=Math.max(r[1],i):n.push([s,i])}return n}function gg(t,e,n){let s=0;for(let[i,r]of ZP(n))for(let o=Math.max(1,i);o<=Math.min(r,e.length);o++)s+=e[o-1];return Math.min(hg(s),t.estimatedTokens)}function yg(t,e=[]){let n=new Map;for(let i of t)n.set(Qc(i.path),i);let s=new Map;for(let i of t)i.relativePath&&s.set(i.relativePath,i);for(let i of e){let r=i.aliasOf?s.get(i.aliasOf):void 0;r&&n.set(Qc(i.path),r)}return i=>n.get(Qc(i))}function QP(t,e){if(t.startLine===void 0)return[1,Math.max(1,e.lineCount)];let n=Math.max(1,t.startLine);return[n,Math.max(n,t.endLine??t.startLine)]}function bg(t,e){let n=[];for(let s of t.locations??[]){let i=e(s.filePath);i&&n.push({file:i,range:QP(s,i),whole:s.startLine===void 0})}return n}function e1(t){let e=new Map;for(let{file:n,range:s}of t){let i=e.get(n)??[];i.push(s),e.set(n,i)}return e}function rr(t,e,n=[]){let s=yg(e,n),i=new Map;return t.map(r=>{let o=e1(bg(r,s));if(o.size===0)return r;let a=0;for(let[c,l]of o){let u=i.get(c);u||i.set(c,u=mg(c)),a+=gg(c,u,l)}return{...r,estimatedTokens:a}})}var t1=new Set(["duplicate","conflict"]);function el(t,e,n=[]){let s=yg(e,n),i=new Map,r=u=>{let f=i.get(u);return f||i.set(u,f=mg(u)),f},o=u=>{let f=r(u.file),d=0;for(let p=Math.max(1,u.range[0]);p<=Math.min(u.range[1],f.length);p++)d+=f[p-1];return d},a=new Map;for(let u of t){if(!pg.has(u.category))continue;let f=bg(u,s).filter(d=>!d.whole);if(t1.has(u.category)&&f.length>1){let d=0;f.forEach((p,h)=>{o(p)>o(f[d])&&(d=h)}),f=f.filter((p,h)=>h!==d)}for(let{file:d,range:p}of f){let h=a.get(d);h?h.push(p):a.set(d,[p])}}let c=0;for(let[u,f]of a)c+=gg(u,r(u),f);let l=e.reduce((u,f)=>u+f.estimatedTokens,0);return Math.min(c,l)}function n1(t,e,n){let s=(n.aiConfig?.allSkills??n.aiConfig?.skills??[]).map(l=>en.dirname(en.resolve(n.repoRoot,l))+en.sep),i=e.filter(l=>!s.some(u=>en.resolve(l.filePath).startsWith(u))),r=l=>l.tags?.[0]===Ac,o=Ai(t.filter(l=>!r(l)),e),a=Ai(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 Ne(t){let e=await ps(t),n=Xc(e),s=[...e.files,...e.onDemandFiles],i=xa(s),r=[...n,..._a(i)],{active:o,suppressed:a}=n1(r,i,e),c=rr(o,s,e.aliasFiles),l=rr(a,s,e.aliasFiles),u=Ea(c),f=ka(c),d,p;if(t.baseline){let h=xn(c,t.baseline,e.repoRoot);d=h.newIssues,p=h.baselinedIssues}return{schemaVersion:"0.1",generatedAt:new Date().toISOString(),repoPath:e.repoRoot,projectType:e.projectType,healthScore:u,metrics:{...e.metrics,estimatedAddressableTokens:el(c,e.files,e.aliasFiles)},filesScanned:[...s,...(e.aliasFiles??[]).map(h=>({...h,content:"",sections:[],lineCount:0,charCount:0,estimatedTokens:0}))],issues:c,topFixes:f,newIssues:d,baselinedIssues:p,suppressedIssues:l.length>0?l:void 0}}var Ie=R(require("node:path"),1),Ps=R(require("node:fs/promises"),1);function wg(t,e){return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")).some(n=>Ki(n,e))}function Pn(t,e){let n=Ie.resolve(t),s=Ie.isAbsolute(e)?Ie.resolve(e):Ie.resolve(n,e);if(!X(n,s))throw new Error(`Path traversal detected: "${e}" is outside repo root "${n}"`);return s}function s1(t,e){let n=0;for(let s=t.indexOf(e);s!==-1;s=t.indexOf(e,s+e.length))n++;return n}async function i1(t,e){let n=new Map;for(let i of t){let r=Pn(e,i.filePath),o=n.get(r)??[];o.push(i),n.set(r,o)}let s=[];for(let[i,r]of n){if(!be(Ie.resolve(e),i))return[];let o;try{o=await Ps.readFile(i,"utf-8")}catch{return[]}let a=o.split(/(?<=\n)/);for(let{line:l,find:u,replace:f}of r){let d=l-1,p=a[d];if(p===void 0||!u||u.includes(`
99
- `))return[];if(s1(p,u)!==1)return[];let h=p.indexOf(u);a[d]=p.slice(0,h)+f+p.slice(h+u.length)}let c=a.join("");c!==o&&s.push({filePath:i,originalContent:o,newContent:c})}return s}async function tl(t,e){let n=[];if(t.fixEdits&&t.fixEdits.length>0)return i1(t.fixEdits,e);if(t.id==="security-pack-no-promptci-gitignore"){let s=Pn(e,".gitignore"),i="";try{i=await Ps.readFile(s,"utf-8")}catch{}if(!wg(i,".promptci")){let r=i.includes(`\r
107
+ `)&&e.pop(),e.map(n=>n.length+1)}function Z$(t){let e=[...t].sort((s,i)=>s[0]-i[0]||s[1]-i[1]),n=[];for(let[s,i]of e){let o=n[n.length-1];o&&s<=o[1]+1?o[1]=Math.max(o[1],i):n.push([s,i])}return n}function py(t,e,n){let s=0;for(let[i,o]of Z$(n))for(let r=Math.max(1,i);r<=Math.min(o,e.length);r++)s+=e[r-1];return Math.min(uy(s),t.estimatedTokens)}function fy(t,e=[]){let n=new Map;for(let i of t)n.set(Ol(i.path),i);let s=new Map;for(let i of t)i.relativePath&&s.set(i.relativePath,i);for(let i of e){let o=i.aliasOf?s.get(i.aliasOf):void 0;o&&n.set(Ol(i.path),o)}return i=>n.get(Ol(i))}function Q$(t,e){if(t.startLine===void 0)return[1,Math.max(1,e.lineCount)];let n=Math.max(1,t.startLine);return[n,Math.max(n,t.endLine??t.startLine)]}function hy(t,e){let n=[];for(let s of t.locations??[]){let i=e(s.filePath);i&&n.push({file:i,range:Q$(s,i),whole:s.startLine===void 0})}return n}function eI(t){let e=new Map;for(let{file:n,range:s}of t){let i=e.get(n)??[];i.push(s),e.set(n,i)}return e}function Co(t,e,n=[]){let s=fy(e,n),i=new Map;return t.map(o=>{let r=eI(hy(o,s));if(r.size===0)return o;let a=0;for(let[c,l]of r){let u=i.get(c);u||i.set(c,u=dy(c)),a+=py(c,u,l)}return{...o,estimatedTokens:a}})}var tI=new Set(["duplicate","conflict"]);function Ll(t,e,n=[]){let s=fy(e,n),i=new Map,o=u=>{let p=i.get(u);return p||i.set(u,p=dy(u)),p},r=u=>{let p=o(u.file),d=0;for(let h=Math.max(1,u.range[0]);h<=Math.min(u.range[1],p.length);h++)d+=p[h-1];return d},a=new Map;for(let u of t){if(!ly.has(u.category))continue;let p=hy(u,s).filter(d=>!d.whole);if(tI.has(u.category)&&p.length>1){let d=0;p.forEach((h,f)=>{r(h)>r(p[d])&&(d=f)}),p=p.filter((h,f)=>f!==d)}for(let{file:d,range:h}of p){let f=a.get(d);f?f.push(h):a.set(d,[h])}}let c=0;for(let[u,p]of a)c+=py(u,o(u),p);let l=e.reduce((u,p)=>u+p.estimatedTokens,0);return Math.min(c,l)}function nI(t,e,n){let s=(n.aiConfig?.allSkills??n.aiConfig?.skills??[]).map(l=>gn.dirname(gn.resolve(n.repoRoot,l))+gn.sep),i=e.filter(l=>!s.some(u=>gn.resolve(l.filePath).startsWith(u))),o=l=>l.tags?.[0]===cl,r=zi(t.filter(l=>!o(l)),e),a=zi(t.filter(o),i),c=new Set([...r.suppressed,...a.suppressed]);return{active:t.filter(l=>!c.has(l)),suppressed:t.filter(l=>c.has(l))}}async function ze(t){let e=await Ps(t),n=$l(e),s=[...e.files,...e.onDemandFiles],i=Ka(s),o=[...n,...Ya(i)],{active:r,suppressed:a}=nI(o,i,e),c=Co(r,s,e.aliasFiles),l=Co(a,s,e.aliasFiles),u=Ua(c),p=za(c),d,h;if(t.baseline){let f=jn(c,t.baseline,e.repoRoot);d=f.newIssues,h=f.baselinedIssues}return{schemaVersion:"0.1",generatedAt:new Date().toISOString(),repoPath:e.repoRoot,projectType:e.projectType,healthScore:u,metrics:{...e.metrics,estimatedAddressableTokens:Ll(c,e.files,e.aliasFiles)},filesScanned:[...s,...(e.aliasFiles??[]).map(f=>({...f,content:"",sections:[],lineCount:0,charCount:0,estimatedTokens:0}))],issues:c,topFixes:p,newIssues:d,baselinedIssues:h,suppressedIssues:l.length>0?l:void 0}}var We=R(require("node:path"),1),qs=R(require("node:fs/promises"),1);function my(t,e){return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")).some(n=>go(n,e))}function zn(t,e){let n=We.resolve(t),s=We.isAbsolute(e)?We.resolve(e):We.resolve(n,e);if(!ue(n,s))throw new Error(`Path traversal detected: "${e}" is outside repo root "${n}"`);return s}function sI(t,e){let n=0;for(let s=t.indexOf(e);s!==-1;s=t.indexOf(e,s+e.length))n++;return n}async function iI(t,e){let n=new Map;for(let i of t){let o=zn(e,i.filePath),r=n.get(o)??[];r.push(i),n.set(o,r)}let s=[];for(let[i,o]of n){if(!Pe(We.resolve(e),i))return[];let r;try{r=await qs.readFile(i,"utf-8")}catch{return[]}let a=r.split(/(?<=\n)/);for(let{line:l,find:u,replace:p}of o){let d=l-1,h=a[d];if(h===void 0||!u||u.includes(`
108
+ `))return[];if(sI(h,u)!==1)return[];let f=h.indexOf(u);a[d]=h.slice(0,f)+p+h.slice(f+u.length)}let c=a.join("");c!==r&&s.push({filePath:i,originalContent:r,newContent:c})}return s}async function Nl(t,e){let n=[];if(t.fixEdits&&t.fixEdits.length>0)return iI(t.fixEdits,e);if(t.id==="security-pack-no-promptci-gitignore"){let s=zn(e,".gitignore"),i="";try{i=await qs.readFile(s,"utf-8")}catch{}if(!my(i,".promptci")){let o=i.includes(`\r
100
109
  `)?`\r
101
110
  `:`
102
- `,o=xs(r),a=i.endsWith(`
103
- `)||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=Pn(e,".gitignore"),i="";try{i=await Ps.readFile(s,"utf-8")}catch{}let r="",o=i.includes(`\r
111
+ `,r=Ds(o),a=i.endsWith(`
112
+ `)||i.endsWith("\r")?r:`${o}${r}`;n.push({filePath:s,originalContent:i,newContent:i+a})}return n}if(t.id==="security-pack-unignored-dirs"){let s=zn(e,".gitignore"),i="";try{i=await qs.readFile(s,"utf-8")}catch{}let o="",r=i.includes(`\r
104
113
  `)?`\r
105
114
  `:`
106
- `;for(let a of t.evidence){let c=/Directory "([^"]+)" exists/.exec(a);if(c&&c[1]){let l=c[1];wg(i,l)||(r+=`${l}/${o}`)}}if(r){let a=i.endsWith(`
107
- `)||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=>Ie.basename(a.filePath).toLowerCase()==="agents.md");s||(s=t.locations[0]);let i=Pn(e,s.filePath),r=Ie.basename(i),o=new Map;for(let a of t.locations){let c=Pn(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 Ps.readFile(a,"utf-8")}catch{continue}let u=l.split(/\r?\n/),f=l.includes(`\r
115
+ `;for(let a of t.evidence){let c=/Directory "([^"]+)" exists/.exec(a);if(c&&c[1]){let l=c[1];my(i,l)||(o+=`${l}/${r}`)}}if(o){let a=i.endsWith(`
116
+ `)||i.endsWith("\r")?o:`${r}${o}`;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=>We.basename(a.filePath).toLowerCase()==="agents.md");s||(s=t.locations[0]);let i=zn(e,s.filePath),o=We.basename(i),r=new Map;for(let a of t.locations){let c=zn(e,a.filePath);if(c===i)continue;let l=r.get(c)??[];l.push(a),r.set(c,l)}for(let[a,c]of r){let l;try{l=await qs.readFile(a,"utf-8")}catch{continue}let u=l.split(/\r?\n/),p=l.includes(`\r
108
117
  `)?`\r
109
118
  `:`
110
- `,d=Ie.relative(Ie.dirname(a),i).replace(/\\/g,"/"),p=d.startsWith(".")?d:`./${d}`,h=`See canonical instructions in [${r}](${p}) for details.`,m=c.map(y=>({startIdx:(y.startLine??1)-1,endIdx:(y.endLine??u.length)-1})).sort((y,b)=>b.startIdx-y.startIdx),g=u;for(let{startIdx:y,endIdx:b}of m){let v=g.slice(y,b+1),w=v.length>0&&v[0].trim().startsWith("#")?y+1:y;g=[...g.slice(0,w),h,...g.slice(b+1)]}n.push({filePath:a,originalContent:l,newContent:g.join(f)})}}return n}function nl(t){return t.autoApplySafe===!0}var We=R(require("node:path"),1),xg=require("node:fs");var r1=[/\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],o1=[/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],a1=[/current\s+branch\s*:\s*\S+/i,/git\s+branch\s*:\s*\S+/i,/current\s+task\s*:\s*\S+/i],c1=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i,l1=[...r1,...o1,...a1,c1],u1=/^\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 vg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f1(t,e){let n=e.replace(/\//g,"\\"),s=e.replace(/\\/g,"/"),i=t,r=vg(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=vg(s),c=new RegExp(a+`([^\\s"'\\)\\>]*)`,"gi");return i=i.replace(c,(l,u)=>{let f=u;return"."+(f.startsWith("/")?f:"/"+f)}),i}function d1(t){let n=t.split(/\r?\n/).filter(i=>!u1.test(i)),s=t.includes(`\r
119
+ `,d=We.relative(We.dirname(a),i).replace(/\\/g,"/"),h=d.startsWith(".")?d:`./${d}`,f=`See canonical instructions in [${o}](${h}) for details.`,m=c.map(y=>({startIdx:(y.startLine??1)-1,endIdx:(y.endLine??u.length)-1})).sort((y,b)=>b.startIdx-y.startIdx),g=u;for(let{startIdx:y,endIdx:b}of m){let w=g.slice(y,b+1),C=w.length>0&&w[0].trim().startsWith("#")?y+1:y;g=[...g.slice(0,C),f,...g.slice(b+1)]}n.push({filePath:a,originalContent:l,newContent:g.join(p)})}}return n}function Ml(t){return t.autoApplySafe===!0}var Ze=R(require("node:path"),1),yy=require("node:fs");var oI=[/\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],rI=[/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],aI=[/current\s+branch\s*:\s*\S+/i,/git\s+branch\s*:\s*\S+/i,/current\s+task\s*:\s*\S+/i],cI=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i,lI=[...oI,...rI,...aI,cI],uI=/^\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 gy(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dI(t,e){let n=e.replace(/\//g,"\\"),s=e.replace(/\\/g,"/"),i=t,o=gy(n),r=new RegExp(o+`([^\\s"'\\)\\>]*)`,"gi");i=i.replace(r,(l,u)=>{let p=u.replace(/\\/g,"/");return"."+(p.startsWith("/")?p:"/"+p)});let a=gy(s),c=new RegExp(a+`([^\\s"'\\)\\>]*)`,"gi");return i=i.replace(c,(l,u)=>{let p=u;return"."+(p.startsWith("/")?p:"/"+p)}),i}function pI(t){let n=t.split(/\r?\n/).filter(i=>!uI.test(i)),s=t.includes(`\r
111
120
  `);return n.join(s?`\r
112
121
  `:`
113
- `)}function p1(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}async function sl(t,e){let n=We.resolve(e.repoRoot),s=e.characterLimit??2e3,i=e.docsDir;if(!i){let l=new Ee(n);l.isDir("Docs")?i="Docs":l.isDir("docs")?i="docs/ai":i="Docs"}let r=We.resolve(n,i),o=new Set,a=[],c=t.filter(l=>he.has(l.fileType)&&l.fileType!=="persona");for(let l of c){let u=l.content,f=d1(u);f=f1(f,n);let d=Wt(f,l.path),p=[];for(let b of d){if(!b.heading)continue;let v=b.text.length>s,x=l1.some(w=>w.test(b.text));if(v||x){let w=p1(b.heading);w||(w="section");let _=`${w}.md`,A=1;for(;o.has(_.toLowerCase())||(0,xg.existsSync)(We.join(r,_));)A++,_=`${w}-${A}.md`;o.add(_.toLowerCase());let C=We.join(r,_),O=We.relative(We.dirname(l.path),C).replace(/\\/g,"/");p.push({section:b,targetPath:C,relPath:O})}}if(p.length===0){f!==u&&a.push({filePath:l.path,originalContent:u,newContent:f});continue}let h=f.replace(/\r\n/g,`
122
+ `)}function fI(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}async function jl(t,e){let n=Ze.resolve(e.repoRoot),s=e.characterLimit??2e3,i=e.docsDir;if(!i){let l=new Le(n);l.isDir("Docs")?i="Docs":l.isDir("docs")?i="docs/ai":i="Docs"}let o=Ze.resolve(n,i),r=new Set,a=[],c=t.filter(l=>Ae.has(l.fileType)&&l.fileType!=="persona");for(let l of c){let u=l.content,p=pI(u);p=dI(p,n);let d=nn(p,l.path),h=[];for(let b of d){if(!b.heading)continue;let w=b.text.length>s,S=lI.some(C=>C.test(b.text));if(w||S){let C=fI(b.heading);C||(C="section");let v=`${C}.md`,_=1;for(;r.has(v.toLowerCase())||(0,yy.existsSync)(Ze.join(o,v));)_++,v=`${C}-${_}.md`;r.add(v.toLowerCase());let A=Ze.join(o,v),O=Ze.relative(Ze.dirname(l.path),A).replace(/\\/g,"/");h.push({section:b,targetPath:A,relPath:O})}}if(h.length===0){p!==u&&a.push({filePath:l.path,originalContent:u,newContent:p});continue}let f=p.replace(/\r\n/g,`
114
123
  `).split(`
115
- `),g=f.includes(`\r
124
+ `),g=p.includes(`\r
116
125
  `)?`\r
117
126
  `:`
118
- `;p.sort((b,v)=>v.section.startLine-b.section.startLine);for(let b of p){let{section:v,targetPath:x,relPath:w}=b,_=v.text,A=/^(#{1,3})\s+(.+)$/m.exec(_);if(A){let U=A[2];_=_.replace(/^(#{1,3})\s+(.+)$/m,`# ${U}`)}a.push({filePath:x,originalContent:"",newContent:_+g});let C=v.startLine-1,O=v.endLine-1,E=[h[C],"",`For details, see [${i}/${We.basename(x)}](${w}).`];h.splice(C,O-C+1,...E)}let y=h.join(g);y!==u&&a.push({filePath:l.path,originalContent:u,newContent:y})}return{changes:a}}var or=R(require("node:fs/promises"),1),Tn=R(require("node:path"),1);var _g=Tn.join(".promptci","config.json"),Eg=["info","warning","high","critical"],kg=Ds;function h1(t){return typeof t=="string"&&Eg.includes(t)}function m1(t){return typeof t=="string"&&kg.includes(t)}function Sg(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}async function Re(t){let e=ie(Tn.resolve(t),_g);if(e===null){let o=Tn.join(Tn.resolve(t),_g),a=!1;try{await or.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.
119
- `),{}}let n;try{n=await or.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(!Sg(i.include))throw new Error("config.include must be an array of strings");r.include=i.include}if("exclude"in i){if(!Sg(i.exclude))throw new Error("config.exclude must be an array of strings");r.exclude=i.exclude}if("severityThreshold"in i){if(!h1(i.severityThreshold))throw new Error(`config.severityThreshold must be one of: ${Eg.join(", ")}`);r.severityThreshold=i.severityThreshold}if("projectType"in i){if(!m1(i.projectType))throw new Error(`config.projectType must be one of: ${kg.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"||Rn(i.targetModel)===void 0)throw new Error(`config.targetModel must be one of: ${us.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 $g=R(require("node:path"),1);var g1="https://promptci.seriousgeese.dev";function Rg(t){return Number.isFinite(t)&&t>0?Math.min(Math.floor(t),Number.MAX_SAFE_INTEGER):0}function Cg(t,e){return`${g1}/?tokens=${Rg(t)}&addressable=${Rg(e)}#estimate`}var y1={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},b1=["critical","high","warning","info"],w1={critical:3,high:2,warning:1,info:0};function Ag(t){return w1[t]}function il(t,e){return Ag(t)>=Ag(e)}function Ts(t,e){return t.issues.some(n=>il(n.severity,e))}function v1(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 Pg(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=b1.filter(p=>(r[p]??0)>0).map(p=>`${y1[p]} ${r[p]} ${p}`).join(" \xB7 "),a=e.previousEntry!=null?v1(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;if(u>0&&l.push(` Suppressed: ${u} (see report for details)`),t.metrics&&t.metrics.instructionFileCount>0){let p=t.metrics.estimatedInstructionTokens,h=Math.min(t.metrics.estimatedAddressableTokens??0,p);l.push(""),l.push(` Tokens loaded per agent turn: ${p}`),l.push(` In flagged sections: up to ${h}`),l.push(` Estimate savings: ${Cg(p,h)}`)}i.length>0&&(l.push(""),l.push(" Top fixes:"),i.forEach((p,h)=>{l.push(` ${h+1}. ${p.title}`)}));let f=p=>$g.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(`
120
- `)}var rl=["info","warning","high","critical"],Tg=["json","sarif"];function ar(t){return rl.includes(t)}function x1(t){return Tg.includes(t)}async function Ig(t){let e=t.scanPath??process.cwd(),n=Ge.resolve(e);try{(await at.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 Re(n)}catch(p){console.error(`Error: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}let i=t.targetModel??s.targetModel;i!==void 0&&Rn(i)===void 0&&(console.error(`Error: invalid --target-model value "${i}". Must be one of: ${us.join(", ")} (or a family alias like "claude"/"gpt"/"gemini").`),process.exit(1));let r=t.failOn??s.severityThreshold;r!==void 0&&!ar(r)&&(console.error(`Error: invalid --fail-on value "${r}". Must be one of: ${rl.join(", ")}`),process.exit(1)),t.failOnNew!==void 0&&!ar(t.failOnNew)&&(console.error(`Error: invalid --fail-on-new value "${t.failOnNew}". Must be one of: ${rl.join(", ")}`),process.exit(1)),t.format!==void 0&&!x1(t.format)&&(console.error(`Error: invalid --format value "${t.format}". Must be one of: ${Tg.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 p=Ge.resolve(n,t.baseline);X(n,p)&&ie(n,p)===null&&(console.error(`Error: baseline file "${p}" is a symlink that resolves outside the scan path; refusing to read it.`),process.exit(1));try{let h=await at.readFile(p,"utf-8"),m;try{m=JSON.parse(h)}catch(g){console.error(`Error: baseline file "${p}" contains invalid JSON: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}try{Ra(m),o=m}catch(g){console.error(`Error: baseline file "${p}" has an unexpected format: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}}catch(h){h.code!=="ENOENT"&&(console.error(`Error loading baseline: ${h instanceof Error?h.message:String(h)}`),process.exit(1)),o=[]}}let a=await Ne({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&&t.format!=="sarif"?Ge.resolve(t.output):void 0,l=c?await Pi(a,{mdPath:c,archive:!1}):await Pi(a),u;if(t.format==="sarif"){let p=t.output?Ge.resolve(t.output):Ge.join(n,".promptci","report.sarif");gn(n,p)||(console.error(`Error: SARIF output "${p}" resolves outside the scan path through a symlink; refusing to write it.`),process.exit(1)),await at.mkdir(Ge.dirname(p),{recursive:!0}),u=Oa(a,t.cliVersion??"0.0.0"),await at.writeFile(p,u,"utf8")}if(t.updateBaseline){let p=vn(a.issues,n),h=t.baseline?Ge.resolve(n,t.baseline):Ge.join(n,".promptci","baseline.json");gn(n,h)||(console.error(`Error: baseline file "${h}" resolves outside the scan path through a symlink; refusing to write it.`),process.exit(1)),await at.mkdir(Ge.dirname(h),{recursive:!0}),await at.writeFile(h,JSON.stringify(p,null,2)),!t.json&&t.format===void 0?process.stdout.write(`
121
- Baseline updated: ${h}
122
- `):process.stderr.write(`Baseline updated: ${h}
123
- `)}let f=t.json||t.format==="json";if(t.format==="sarif"?process.stdout.write(`${u}
124
- `):f?process.stdout.write($i(a)+`
125
- `):process.stdout.write(Pg(a,{mdPath:l.mdPath,jsonPath:l.jsonPath,previousEntry:l.archivedEntry})),r&&Ts(a,r)){let p=a.issues.filter(m=>ar(m.severity)&&Ts({...a,issues:[m]},r)).length,h=t.failOn!==void 0?"from --fail-on":"from severityThreshold in .promptci/config.json";console.error(`
126
- Failed: ${p} issue(s) at or above the "${r}" threshold (${h}). See ${l.mdPath} for details.
127
- Raise the gate with --fail-on <severity> or edit severityThreshold to only fail on higher severities.`),process.exit(1)}let d=t.failOnNew;if(d){let p=a.newIssues??[];if(Ts({...a,issues:p},d)){let h=p.filter(m=>ar(m.severity)&&Ts({...a,issues:[m]},d)).length;console.error(`
128
- Failed: ${h} NEW issue(s) at or above "${d}" threshold. See ${l.mdPath} for details.`),process.exit(1)}}if(t.failOnBudget){let p=a.issues.filter(h=>h.category==="context_bloat");p.length>0&&(console.error(`
129
- Failed: ${p.length} context bloat issue(s) found and --fail-on-budget is enabled. See ${l.mdPath} for details.`),process.exit(1))}}var Ng=R(require("node:fs/promises"),1),Lt=R(require("node:path"),1);var _1=3,Og={critical:3,high:2,warning:1,info:0};function S1(t,e=_1){return[...t].sort((n,s)=>Og[s.severity]-Og[n.severity]||s.confidence-n.confidence||n.id.localeCompare(s.id)).slice(0,e)}var E1=/[\u0000-\u001f\u007f-\u009f]/g,ol=t=>t.replace(E1," ").replace(/\s+/g," ").trim(),Lg=160,k1=t=>{let e=ol(t);return e.length>Lg?`${e.slice(0,Lg-1).trimEnd()}\u2026`:e};function R1(t,e){let n=t.locations[0],s=n?.filePath??t.filePaths[0];if(!s)return;let r=((Lt.isAbsolute(s)?Lt.relative(e,s):s)||s).split(Lt.sep).join("/");return n?.startLine!==void 0?`${r}:${n.startLine}`:r}function C1(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(`
130
- `);let n=t.issues.length;if(e.push(`PromptCI instruction health: ${t.healthScore}/100 (${_n(t.healthScore)})`),n===0)e.push("No findings. Nice.");else{let s=S1(t.issues);e.push(""),e.push(`Top ${s.length} finding${s.length===1?"":"s"} (of ${n}):`),s.forEach((i,r)=>{let o=R1(i,t.repoPath);e.push(` ${r+1}. [${i.severity}] ${ol(i.title)}${o?` (${ol(o)})`:""}`),e.push(` Fix: ${k1(i.recommendation)}`)})}return e.push(""),e.join(`
131
- `)}async function jg(t){let e=Lt.resolve(t.scanPath??process.cwd());try{(await Ng.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 Re(e)}catch(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exit(1)}let s=await Ne({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(C1(s))}var Ce=R(require("node:fs/promises"),1),tn=R(require("node:path"),1),Fg=R(require("node:readline"),1);var Is=Ds.filter(t=>t!=="auto"),Mg={severityThreshold:"high",projectType:"auto"},Dg={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
127
+ `;h.sort((b,w)=>w.section.startLine-b.section.startLine);for(let b of h){let{section:w,targetPath:S,relPath:C}=b,v=w.text,_=/^(#{1,3})\s+(.+)$/m.exec(v);if(_){let D=_[2];v=v.replace(/^(#{1,3})\s+(.+)$/m,`# ${D}`)}a.push({filePath:S,originalContent:"",newContent:v+g});let A=w.startLine-1,O=w.endLine-1,x=[f[A],"",`For details, see [${i}/${Ze.basename(S)}](${C}).`];f.splice(A,O-A+1,...x)}let y=f.join(g);y!==u&&a.push({filePath:l.path,originalContent:u,newContent:y})}return{changes:a}}var by="Claude agent backfill (pcic-kvv3.1), pending human review",ie={date:"2026-11-13",by},qn={date:"2026-11-14",by},hI={ccMemory:{url:"https://code.claude.com/docs/en/memory",title:"Claude Code docs: How Claude remembers your project",readOn:"2026-11-13"},ccBest:{url:"https://code.claude.com/docs/en/best-practices",title:"Claude Code docs: Best practices",readOn:"2026-11-13"},ccCache:{url:"https://code.claude.com/docs/en/prompt-caching",title:"Claude Code docs: How Claude Code uses prompt caching",readOn:"2026-11-14"},ccContext:{url:"https://code.claude.com/docs/en/context-window",title:"Claude Code docs: Explore the context window",readOn:"2026-11-14"},apiCache:{url:"https://platform.claude.com/docs/en/build-with-claude/prompt-caching",title:"Claude API docs: Prompt caching",readOn:"2026-11-13"},apiPrompt:{url:"https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices",title:"Claude API docs: Prompting best practices",readOn:"2026-11-13"},anthContext:{url:"https://www.anthropic.com/research/effective-context-engineering-for-ai-agents",title:"Anthropic engineering: Effective context engineering for AI agents",readOn:"2026-11-14"},codex:{url:"https://learn.chatgpt.com/docs/agent-configuration/agents-md",title:"Codex docs: AGENTS.md (redirect target of developers.openai.com/codex/guides/agents-md)",readOn:"2026-11-13"},agentsMd:{url:"https://agents.md/",title:"agents.md: the AGENTS.md format",readOn:"2026-11-13"},cursor:{url:"https://cursor.com/docs/rules",title:"Cursor docs: Rules",readOn:"2026-11-13"},windsurf:{url:"https://docs.devin.ai/desktop/devin-local/customizations",title:"Devin Local docs: Customizations (docs.windsurf.com redirects here; Windsurf has no docs of its own to read, so this is another product's documentation)",readOn:"2026-11-13"},ghRepo:{url:"https://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/add-custom-instructions/add-repository-instructions",title:"GitHub Docs: Adding repository custom instructions for GitHub Copilot",readOn:"2026-11-13"},ghConcept:{url:"https://docs.github.com/en/copilot/concepts/prompting-and-context/custom-instructions",title:"GitHub Docs: About customizing GitHub Copilot responses",readOn:"2026-11-14"},gemini:{url:"https://geminicli.com/docs/cli/gemini-md/",title:"Gemini CLI docs: GEMINI.md context files",readOn:"2026-11-13"}},N=(t,e,n)=>({...hI[t],stance:e,note:n}),V=(t,e,n,s)=>({name:t,value:e,unit:n,where:s,source:"unverified"}),wy=[{id:"context-bloat/always-loaded-cost",detector:"context-bloat",title:"Instruction file size is a per-turn context cost",kind:"tool-fact",claim:"Instruction files are loaded into the model context at the start of every session or on every request, so each added line costs context on every turn and a long file reduces how well the rules in it are followed.",appliesTo:["claude-code","codex","cursor","copilot","gemini-cli","windsurf"],sources:[N("ccMemory","supports","Says CLAUDE.md is read at the start of every session and advises under 200 lines per file because longer files consume more context and reduce adherence, and that imports do not reduce the cost."),N("ccBest","supports","Says every CLAUDE.md line takes a little of the attention on every task and that a line gets lost once the file has grown long."),N("cursor","supports","Says rule contents are included at the start of the model context and advises keeping rules under 500 lines."),N("windsurf","context","Devin Local docs, not Windsurf docs: Says rules are injected at the start of every session and advises short specific rules because they cost tokens on every message; the page states no character limit."),N("ghConcept","supports","Says custom instructions are sent with every chat message, so they should be broadly applicable to most requests; the page states no length limit."),N("gemini","supports","Says the CLI concatenates all found context files and sends them to the model with every prompt; the page states no size limit."),N("codex","supports","Says Codex stops adding AGENTS.md files once their combined size reaches project_doc_max_bytes, 32 KiB by default."),N("anthContext","context","Treats context as a finite resource with diminishing marginal returns and a limited attention budget, which is the general mechanism behind the claim.")],thresholds:[V("fileWarning",8e3,"characters per instruction file","context-bloat.ts:DEFAULTS.fileWarning"),V("fileHigh",2e4,"characters per instruction file","context-bloat.ts:DEFAULTS.fileHigh"),V("totalWarning",3e4,"characters across all instruction files","context-bloat.ts:DEFAULTS.totalWarning"),V("totalHigh",6e4,"characters across all instruction files","context-bloat.ts:DEFAULTS.totalHigh"),V("contextBudget high multiplier",2,"times the configured contextBudget","detectors.ts:DETECTORS"),V("fileContextBudget high multiplier",2.5,"times the configured fileContextBudget","detectors.ts:DETECTORS")],caveat:"geminicli.com carries a banner (read 2026-11-14): Gemini CLI was replaced by Antigravity CLI on June 18th, 2026 for unpaid-tier and Google One users, and it has not been optimized for Gemini 4 Argon; a claim about gemini-cli may not hold for the replacement.",lastVerified:qn},{id:"context-bloat/copilot-line-limit",detector:"context-bloat",title:"Copilot instructions file line limit",kind:"tool-fact",claim:"A Copilot instructions file of more than 1,000 lines may be truncated or degrade response quality.",appliesTo:["copilot"],sources:[N("ghRepo","context","The only length statement is in the sample prompt for generating the file, which says instructions must be no longer than 2 pages; the page does not mention 1,000 lines or 1,000 characters.")],unverified:!0,thresholds:[V("copilotLineWarning",1e3,"lines per copilot-instructions file","context-bloat.ts:DEFAULTS.copilotLineWarning")],lastVerified:ie},{id:"context-bloat/windsurf-truncation",detector:"context-bloat",title:"Windsurf rules file truncation",kind:"tool-fact",claim:"Windsurf silently truncates a rules file past about 6,000 characters and its combined global and workspace rules budget is about 12,000 characters.",appliesTo:["windsurf"],sources:[],unverified:!0,thresholds:[V("windsurfFileWarning",6e3,"characters per .windsurfrules file","context-bloat.ts:DEFAULTS.windsurfFileWarning"),V("windsurfFileHigh",12e3,"characters per .windsurfrules file","context-bloat.ts:DEFAULTS.windsurfFileHigh")],lastVerified:ie},{id:"context-bloat/readme-dominance",unverified:!0,detector:"context-bloat",title:"README carrying most of the agent context",kind:"opinion",claim:"A README that makes up most of the scanned instruction text is carried into agent context on every turn although it is written for people, so AI-specific guidance is cheaper in a smaller canonical file such as AGENTS.md.",appliesTo:"all",sources:[N("agentsMd","context","Describes AGENTS.md as a README for agents and says the extra detail agents need, such as build steps and conventions, would clutter a README written for humans."),N("ccMemory","context","Lists the files Claude Code loads at start (CLAUDE.md, AGENTS.md, rules, auto memory) and mentions README only as an @README import example, so a README is not shown to be loaded on every turn; this is inferred from the page listing, not stated.")],thresholds:[V("README_DOMINANCE_RATIO",.5,"share of scanned instruction tokens","context-bloat.ts:README_DOMINANCE_RATIO"),V("README_DOMINANCE_MIN_TOKENS",1e3,"estimated tokens","context-bloat.ts:README_DOMINANCE_MIN_TOKENS"),V("readmeFileWarning",15e3,"characters per README","context-bloat.ts:DEFAULTS.readmeFileWarning"),V("readmeFileHigh",3e4,"characters per README","context-bloat.ts:DEFAULTS.readmeFileHigh")],lastVerified:ie},{id:"prompt-cache-friendliness/volatile-content",detector:"prompt-cache-friendliness",title:"Volatile content in always-loaded instructions",kind:"tool-fact",claim:"A date, timestamp, branch name, current-task line or pasted scan report in an always-loaded instruction file changes the prompt prefix whenever it is edited, so the cached prefix is rebuilt and the next request is slower and costlier.",appliesTo:["claude-code"],refuted:!0,sources:[N("ccCache","contradicts","Says that editing CLAUDE.md in the middle of a session does not invalidate the cache, because project-root and user-level CLAUDE.md files are read once at session start and the edit applies only after /clear, /compact or a restart."),N("apiCache","context","The Claude API (not a Claude Code page) says cache hits need identical prompt segments up to the breakpoint and that a change at one level invalidates that level and all later ones; see prompt-cache-friendliness/volatile-content-api.")],lastVerified:qn},{id:"prompt-cache-friendliness/volatile-content-api",detector:"prompt-cache-friendliness",title:"A changed prompt prefix invalidates the Claude API cache",kind:"tool-fact",claim:"On the Claude API a cache hit requires every segment of the prompt up to the cache breakpoint to be identical, and a change at one level invalidates that level and every later one.",appliesTo:"n/a",sources:[N("apiCache","supports","Says cache hits require 100 percent identical prompt segments up to the cache breakpoint and that a change at one level invalidates that level and all later levels.")],lastVerified:qn},{id:"prompt-cache-friendliness/local-paths",refuted:!0,detector:"prompt-cache-friendliness",title:"Absolute local machine paths in instructions",kind:"tool-fact",claim:"Absolute local machine paths in an always-loaded instruction file differ between environments and so prevent prompt-cache reuse across them.",appliesTo:["claude-code"],sources:[N("ccCache","contradicts","Says that in Claude Code the cache is effectively scoped to one machine and directory because the system prompt embeds the auto memory paths and the conversation opens with the working directory, platform and shell, so sessions on different machines or directories already miss each other cache whatever paths CLAUDE.md contains.")],lastVerified:qn},{id:"prompt-cache-friendliness/large-table",unverified:!0,detector:"prompt-cache-friendliness",title:"Large table in always-loaded instructions",kind:"opinion",claim:"A Markdown table of more than 15 rows in an always-loaded instruction file bloats context and makes the prompt less cache-friendly than the same facts kept in a separate document read on demand.",appliesTo:"all",sources:[N("apiCache","contradicts","Says to place static content such as system instructions and context at the beginning of the prompt and cache it, and makes cache hits depend on identical prefix text and not on its size, so a large stable table does not reduce cache hits; it only costs tokens."),N("ccMemory","context","Advises moving entries that matter for only part of the codebase out of CLAUDE.md into skills or path-scoped rules because longer files consume more context.")],thresholds:[V("maxTableRows",15,"table rows","prompt-cache.ts:detectPromptCacheFriendliness (maxTableRows > 15)")],lastVerified:ie},{id:"negative-instructions",unverified:!0,detector:"negative-instructions",title:"Mostly-prohibition instruction files",kind:"opinion",claim:"Models follow positive directives more reliably than prohibitions, so an instruction file whose directives are mostly prohibitions is harder to follow than the same guidance phrased positively.",appliesTo:"all",sources:[N("apiPrompt","context","Advises telling Claude what to do instead of what not to do, but only in an output-formatting example (do not use markdown versus flowing prose), and its own sample prompt for limiting over-engineering is written as prohibitions."),N("ccBest","context","Its recommended sample CLAUDE.md contains prohibitions (never throw raw strings, do not copy legacy patterns), so the page does not treat a prohibition as a defect.")],thresholds:[V("MIN_DIRECTIVES",8,"directive sentences","negative-instructions.ts:MIN_DIRECTIVES"),V("NEGATIVE_RATIO_THRESHOLD",.4,"share of directives that are prohibitions","negative-instructions.ts:NEGATIVE_RATIO_THRESHOLD")],lastVerified:ie},{id:"buried-critical",refuted:!0,detector:"buried-critical",title:"Critical instructions near the bottom of a long file",kind:"opinion",claim:"Models weight earlier context more heavily than later context, so high-stakes instructions placed in the bottom half of a long instruction file are applied less reliably than the same lines near the top.",appliesTo:"all",sources:[N("apiPrompt","contradicts","In long-context guidance (20k-plus-token prompts) it says to put long documents at the top above the query, instructions and examples, and that queries at the end can improve response quality by up to 30 percent, which favours later instructions and not earlier ones."),N("ccMemory","context","About truncation, not weighting: says that when an on-demand subdirectory CLAUDE.md or rules file is over a per-file size limit Claude receives only the start of it, so later instructions are not in context."),N("ccContext","context","About truncation, not weighting: says truncation of an over-cap invoked skill keeps the start of the file, so the most important instructions belong near the top of SKILL.md."),N("ccBest","context","Attributes a CLAUDE.md line that keeps being missed to the file having grown long and says to shorten the file, and says nothing about where in the file a line sits.")],thresholds:[V("MIN_LINES",100,"lines in the file","buried-critical.ts:MIN_LINES"),V("BOTTOM_HALF_RATIO_THRESHOLD",.6,"share of high-severity lines in the bottom half","buried-critical.ts:BOTTOM_HALF_RATIO_THRESHOLD")],lastVerified:qn},{id:"vague-guidance/platitudes",unverified:!0,detector:"vague-guidance",title:"Non-actionable quality platitudes",kind:"opinion",claim:"Broad exhortations such as write clean code or follow best practices give an agent no constraint to act on, whereas concrete commands and checkable rules are followed more consistently.",appliesTo:"all",sources:[N("ccMemory","context","Says the more specific and concise the instructions the more consistently Claude follows them and contrasts Use 2-space indentation with Format code properly."),N("apiPrompt","context","Says Claude responds well to clear explicit instructions and gives a test of whether a colleague with no context would be confused."),N("anthContext","context","Names vague high-level guidance that fails to give concrete signals as one of two failure modes for prompt altitude."),N("cursor","context","Says rules should be focused, actionable and scoped and should avoid vague guidance."),N("windsurf","context","Devin Local docs, not Windsurf docs: Advises skipping generic rules such as write good code.")],thresholds:[V("MAX_LINE_LENGTH_TO_FLAG",120,"characters in the matching line","vague-guidance.ts:MAX_LINE_LENGTH_TO_FLAG")],lastVerified:qn},{id:"vague-guidance/subjective-ui",detector:"vague-guidance",title:"Subjective UI and paradigm wording",kind:"opinion",claim:"Subjective UI and paradigm wording such as looks polished, feels native or idiomatic code names no criterion an agent could check, so it does not change what the agent produces.",appliesTo:"all",sources:[],unverified:!0,lastVerified:ie},{id:"agent-practices/verification-loop",unverified:!0,detector:"agent-practices",title:"Verification loop before reporting done",kind:"opinion",claim:"An instruction to run lint, typecheck and tests before reporting work done, or a documented command to run, makes an agent more likely to check its own work before it says it is finished.",appliesTo:"all",sources:[N("ccBest","context","Says to give Claude a check it can run and that the single most useful CLAUDE.md line is the command that runs it, while noting that a line such as Always typecheck before you finish works most of the time and not every time and that a Stop hook enforces it."),N("ghRepo","context","The onboarding prompt asks for build, test and lint steps with verified commands and the checks run before check-in.")],lastVerified:ie},{id:"agent-practices/grounding",unverified:!0,detector:"agent-practices",title:"Read before edit and report failures honestly",kind:"opinion",claim:"Telling an agent to read a file before editing it and to report failures instead of claiming success reduces confidently wrong work and false completion reports.",appliesTo:"all",sources:[N("apiPrompt","context","Its sample prompts say never to speculate about code that was not opened and to read the file before answering, and to inform the user rather than work around incorrect tests; they are suggested prompts and not measured results."),N("ccBest","context","Attributes a Claude that said it was done when it was not mainly to having no way to check its own work, and not to a missing instruction to report honestly.")],lastVerified:ie},{id:"agent-practices/ask-when-unsure",detector:"agent-practices",title:"Ask when unsure instead of guessing",kind:"opinion",claim:"An agent told to say so and ask when it is unsure produces fewer confidently wrong results than one left to guess.",appliesTo:"all",sources:[],unverified:!0,lastVerified:ie},{id:"agent-practices/scope-control",unverified:!0,detector:"agent-practices",title:"Keep diffs focused",kind:"opinion",claim:"Unconstrained agents often refactor or rewrite code they were not asked to touch, and an instruction to prefer small focused diffs prevents it.",appliesTo:"all",sources:[N("apiPrompt","context","Its Overeagerness section says Claude Opus 4.5 and 4.6 tend to over-engineer with extra files and abstractions and gives a sample prompt to make only directly requested changes; the section names those two models."),N("ccBest","contradicts","Says Claude tends to read a request conservatively and build the smallest thing that satisfies it and that lines telling it to keep going are more likely to cause over-work than fix a stall, which runs against the premise that current Claude Code needs guidance to avoid sweeping changes.")],lastVerified:ie},{id:"agent-practices/code-preservation",detector:"agent-practices",title:"Preserve existing code and unrelated edits",kind:"opinion",claim:"Without an instruction to preserve existing code, agents delete working code, drop tests or overwrite unrelated edits to reach a passing state.",appliesTo:"all",sources:[],unverified:!0,lastVerified:ie},{id:"agent-practices/plan-first",unverified:!0,detector:"agent-practices",title:"Outline the approach before coding",kind:"opinion",claim:"Asking an agent to outline its approach before writing code on a complex or multi-file task significantly reduces wasted implementation effort.",appliesTo:"all",sources:[N("ccBest","context","Recommends having Claude interview you and write a SPEC.md before building from it in a fresh session, which is plan-before-implementing guidance, but gives no measurement of how much effort it saves.")],lastVerified:ie},{id:"agent-practices/per-tool-file-gap",detector:"agent-practices",title:"Behavioural rules must be in the file each tool reads",kind:"tool-fact",claim:"Each of Claude Code, Cursor, Windsurf, Copilot and Gemini CLI reads only its own tool-specific instruction file, so behavioural rules that live only in AGENTS.md or another tool file are invisible to it.",appliesTo:["claude-code","cursor","windsurf","copilot","gemini-cli"],sources:[N("ccMemory","supports","Says Claude Code reads AGENTS.md by default only when there is no CLAUDE.md or CLAUDE.local.md in the working directory or above it, so a CLAUDE.md without the rules hides AGENTS.md."),N("gemini","context","Shows AGENTS.md only as a context.fileName configuration example and does not say it is read by default, so it neither supports nor contradicts the claim."),N("cursor","contradicts","Says AGENTS.md in the project root or subdirectories is read as an alternative to .cursor/rules, so Cursor does see rules that exist only in AGENTS.md."),N("windsurf","context","Devin Local docs, not Windsurf docs: Says AGENTS.md, AGENTS.local.md and AGENT.md are read as always-on rules at the workspace root and in directories down to the working directory, so Windsurf sees rules that exist only in AGENTS.md."),N("ghRepo","contradicts","Says Copilot uses the nearest AGENTS.md in the directory tree and alternatively a root CLAUDE.md or GEMINI.md besides copilot-instructions.md, so Copilot sees rules that exist only in those files.")],caveat:"geminicli.com carries a banner (read 2026-11-14): Gemini CLI was replaced by Antigravity CLI on June 18th, 2026 for unpaid-tier and Google One users, and it has not been optimized for Gemini 4 Argon; a claim about gemini-cli may not hold for the replacement.",lastVerified:ie},{id:"agent-practices/forwarding-pointer",refuted:!0,detector:"agent-practices",title:"Prose forwarding pointer to AGENTS.md",kind:"tool-fact",claim:"A one-line prose pointer such as Follow AGENTS.md at the top of a tool-specific file makes that tool apply the rules in the file it points to.",appliesTo:["claude-code"],sources:[N("ccMemory","contradicts","Says a CLAUDE.md that tells Claude in words to read AGENTS.md works only if Claude decides to open the file, and recommends an @AGENTS.md import or a symlink so the content is actually loaded.")],thresholds:[V("forwarding pointer head window",12,"lines from the top of the file","agent-practices.ts:isForwardingFile (slice(0, 12))"),V("legacy forwarding file length",20,"lines (file shorter than this may point anywhere in the file)","agent-practices.ts:isForwardingFile (lineCount < 20)")],lastVerified:ie},{id:"agent-practices/do-not-edit-header",detector:"agent-practices",title:"Do not edit header on a human-maintained file",kind:"opinion",claim:"A do not edit or auto-generated header on a hand-written instruction file stops the agents and people who must keep it current from updating it.",appliesTo:"all",sources:[],unverified:!0,thresholds:[V("header search window",500,"characters from the top of the file","agent-practices.ts:detectAgentPractices (content.slice(0, 500))"),V("auto-generated header misleading above",5,"lines in the file","agent-practices.ts:detectAgentPractices (lineCount > 5)")],lastVerified:ie},{id:"agent-practices/claude-xml-tags",unverified:!0,detector:"agent-practices",title:"Claude-specific XML tags in other tools files",kind:"tool-fact",claim:"Claude-specific XML tags such as claude:thinking are meaningful only to Claude, so other tools treat them as literal text or ignore them.",appliesTo:["claude-code","cursor","copilot","windsurf","gemini-cli","codex"],sources:[N("apiPrompt","context","Presents XML tags as an author-chosen structuring technique with consistent descriptive names such as instructions, context and input, and mentions no claude: namespaced tag vocabulary; this is inferred from the page text, not stated.")],caveat:"geminicli.com carries a banner (read 2026-11-14): Gemini CLI was replaced by Antigravity CLI on June 18th, 2026 for unpaid-tier and Google One users, and it has not been optimized for Gemini 4 Argon; a claim about gemini-cli may not hold for the replacement.",lastVerified:ie},{id:"missing-context/setup-commands",unverified:!0,detector:"missing-context",title:"Install, build, test commands and environment variables",kind:"opinion",claim:"Instruction files that omit install, build and test commands, or the environment variables a project needs, leave an agent unable to set up and verify the project reliably.",appliesTo:"all",sources:[N("ccBest","context","Lists the exact test, typecheck and lint commands as what CLAUDE.md should hold and its sample file notes that integration tests need DATABASE_URL set, see .env.example."),N("agentsMd","context","Suggests covering build and test commands in AGENTS.md."),N("ghRepo","context","The onboarding prompt asks for build, test and lint steps with verified commands and runtime versions.")],thresholds:[V("distinct environment variable names before flagging",3,"names","missing-context.ts:checkEnvVarList (envVarNames.size < 3)"),V("minimum environment variable name length",4,"characters","missing-context.ts:ENV_VAR_NAME_RE")],lastVerified:ie},{id:"missing-context/project-type-keywords",unverified:!0,detector:"missing-context",title:"Stack-specific build and test context",kind:"opinion",claim:"Instruction files for a detected Unity, TypeScript, .NET, Next.js, Python, Go or Rust project that mention none of that stack build, test or tooling terms give agents too little project-specific context.",appliesTo:"all",sources:[N("ccBest","context","Says CLAUDE.md should hold the exact test, typecheck and lint commands, but its stop-doing table also says describing architecture and file layout in CLAUDE.md is advice to drop because Claude reads the repo itself, which is in tension with the recommendation to add common project patterns."),N("ccMemory","context","Says the /doctor checkup cuts directory layouts, dependency lists and architecture overviews that Claude can derive from the codebase and keeps pitfalls, rationale and conventions that differ from tool defaults.")],thresholds:[V("minimumPresent",1,"matching keywords per project type","missing-context.ts:PROJECT_TYPE_RULES")],lastVerified:ie},{id:"missing-context/security-and-secrets",unverified:!0,detector:"missing-context",title:"Security and secret-handling guidance",kind:"opinion",claim:"Instruction files that never mention authentication, secrets or input validation, or that describe credential storage without scopes, validation, expiry or rotation, leave agents without the security rules they need.",appliesTo:"all",sources:[N("agentsMd","context","Lists security considerations among the content AGENTS.md can cover; the page says nothing about token scopes, expiry or rotation.")],lastVerified:ie},{id:"missing-context/copilot-topic-silence",refuted:!0,detector:"missing-context",title:"Copilot reads only its own instruction files",kind:"tool-fact",claim:"GitHub Copilot reads only its own instruction files, so a naming convention documented in AGENTS.md or CLAUDE.md is invisible to it.",appliesTo:["copilot"],sources:[N("ghRepo","contradicts","Says Copilot uses the nearest AGENTS.md in the directory tree and alternatively a single CLAUDE.md or GEMINI.md in the repository root, and that all relevant instruction sets are provided to it, so a convention in AGENTS.md is visible to Copilot.")],lastVerified:ie},{id:"within-section-dedup",detector:"within-section-dedup",title:"Same point restated within one section",kind:"opinion",claim:"A section that restates the same point in two near-identical paragraphs costs context and can drift out of sync, so merging them helps an agent.",appliesTo:"all",sources:[],unverified:!0,thresholds:[V("MIN_PARAGRAPHS",6,"comparable paragraphs in the section","within-section-dedup.ts:MIN_PARAGRAPHS"),V("PARAGRAPH_JACCARD_THRESHOLD",.65,"Jaccard similarity of word sets","within-section-dedup.ts:PARAGRAPH_JACCARD_THRESHOLD"),V("MIN_PARAGRAPH_CHARS",40,"normalised characters","within-section-dedup.ts:MIN_PARAGRAPH_CHARS"),V("MIN_PARAGRAPH_TOKENS",8,"distinct words","within-section-dedup.ts:MIN_PARAGRAPH_TOKENS")],lastVerified:ie},{id:"duplicates/identical-sections",detector:"duplicates",title:"Sections repeated across instruction files",kind:"repo-fact",claim:"Two or more sections of the scanned instruction files have identical text or heavily overlapping word sets once markdown and whitespace are normalised.",appliesTo:"all",sources:[],thresholds:[V("MIN_SECTION_LENGTH",150,"normalised characters (cross-file)","duplicates.ts:MIN_SECTION_LENGTH"),V("WITHIN_FILE_MIN_SECTION_LENGTH",80,"normalised characters (same file)","duplicates.ts:WITHIN_FILE_MIN_SECTION_LENGTH"),V("MIN_TOKEN_COUNT",10,"distinct words","duplicates.ts:MIN_TOKEN_COUNT"),V("CROSS_FILE_JACCARD_THRESHOLD",.8,"Jaccard similarity (warning)","duplicates.ts:CROSS_FILE_JACCARD_THRESHOLD"),V("CROSS_FILE_JACCARD_THRESHOLD_INFO",.6,"Jaccard similarity (info)","duplicates.ts:CROSS_FILE_JACCARD_THRESHOLD_INFO"),V("WITHIN_FILE_JACCARD_THRESHOLD",.6,"Jaccard similarity (same file)","duplicates.ts:WITHIN_FILE_JACCARD_THRESHOLD")],lastVerified:ie},{id:"duplicates/cost-and-drift",unverified:!0,detector:"duplicates",title:"Duplicate sections cost context and drift apart",kind:"opinion",claim:"Near-identical sections kept in several instruction files are loaded more than once and can drift apart, so one canonical copy with a pointer is better.",appliesTo:"all",sources:[N("ccMemory","context","Says Claude Code skips an AGENTS.md it has already loaded so an imported or symlinked copy is not read twice, that a SessionStart hook printing AGENTS.md adds a second copy to the context, and that contradictory instructions across files may be resolved arbitrarily."),N("ccMemory","contradicts","Says a CLAUDE.md that tells Claude in words to read AGENTS.md works only if Claude decides to open the file, which undercuts the detector recommendation of a forwarding pointer to save tokens; an @AGENTS.md import or a symlink is the documented way."),N("codex","context","Says Codex concatenates AGENTS.md files from the root downward into one prompt, with files nearer the working directory appearing later."),N("ghRepo","context","Advises avoiding conflicting sets of instructions and says all relevant sets are provided to Copilot.")],lastVerified:ie},{id:"duplicate-headings",detector:"duplicate-headings",title:"Same heading twice in one instruction file",kind:"opinion",claim:"The same heading appearing twice at one level in an instruction file, or one heading being a whole-word prefix of another, almost always marks an accidental duplicate that should be merged.",appliesTo:"all",sources:[],unverified:!0,thresholds:[V("minimum normalised heading length",3,"characters","duplicates.ts:detectDuplicateHeadings (key.length < 3)"),V("minimum prefix heading length",4,"characters","duplicates.ts:detectDuplicateHeadings (shorter.length < 4)")],lastVerified:ie},{id:"canonical-owner/ambiguous-authority",unverified:!0,detector:"canonical-owner",title:"Several files claim to be the canonical source",kind:"opinion",claim:"When several instruction files each declare themselves the canonical source of truth, agents cannot tell which one takes precedence.",appliesTo:"all",sources:[N("ccMemory","context","Says that when two instructions contradict each other Claude may pick one arbitrarily and that conflicting files should be removed or reconciled."),N("agentsMd","context","Says agents read the nearest AGENTS.md so the closest one takes precedence and explicit chat prompts override everything, which sets precedence by location and not by a canonical declaration inside a file."),N("codex","context","Says files closer to the current directory override earlier guidance and an AGENTS.override.md replaces AGENTS.md in the same directory, so precedence is positional.")],lastVerified:ie},{id:"canonical-owner/duplicated-behavior",unverified:!0,detector:"canonical-owner",title:"Large duplicated behaviour in a tool-specific file",kind:"opinion",claim:"A section of more than 50 lines in a tool-specific instruction file that matches a section of AGENTS.md duplicates behaviour that a pointer could share, costing tokens every session and inviting drift.",appliesTo:"all",sources:[N("ccMemory","context","Documents keeping AGENTS.md as the one shared file and importing it with @AGENTS.md or symlinking so the content is read once, not twice."),N("ccMemory","contradicts","Says a CLAUDE.md that tells Claude in words to read AGENTS.md works only if Claude decides to open the file, which undercuts the detector recommendation of a forwarding pointer such as Follow AGENTS.md.")],thresholds:[V("tool-specific file minimum length",50,"lines (file.lineCount > 50)","canonical-owner.ts:detectCanonicalOwner"),V("duplicated section minimum length",50,"lines (endLine - startLine > 50)","canonical-owner.ts:detectCanonicalOwner"),V("long-section comparison prefix",500,"characters (bodies over 500 characters match on their first 500)","canonical-owner.ts:detectCanonicalOwner")],lastVerified:ie},{id:"custom-rules",detector:"custom-rules",title:"User-defined rules run as written",kind:"repo-fact",claim:"A rule in .promptci/custom-rules.json matched, or failed to match, the scanned instruction files exactly as its pattern, heading or targeted file globs state.",appliesTo:"all",sources:[],lastVerified:ie}];var mI="2026-11-13",W={date:"2026-11-13",by:"Claude agent backfill (pcic-kvv3.1), pending human review"},L=(t,e,n,s)=>({url:t,title:e,readOn:mI,stance:n,note:s}),vy=L("https://docs.npmjs.com/cli/v11/commands/npm-run","npm run documentation","supports","Lists run-script among the aliases of run, says npm run puts node_modules/.bin on the PATH of a script, and says run is used by the test, start, restart and stop commands."),Sy=L("https://pnpm.io/cli/run","pnpm run documentation","supports","Lists run-script as an alias, says pnpm <script> is shorthand for pnpm run <script> only when the name is not a pnpm command, and says a built-in command runs instead of a same-named script; the page does not list the built-ins."),_y=L("https://yarnpkg.com/cli/run","Yarn run documentation","supports","Says yarn run checks package.json scripts first and then runs a dependency binary of the same name, and shows yarn <name> as the same thing without the run keyword."),xy=L("https://bun.sh/docs/runtime","bun run documentation","supports","Says bun <script> works without run, that a built-in bun command takes precedence over a same-named script, and that bun run resolves binaries from project packages."),gI=L("https://pnpm.io/filtering","pnpm filtering documentation","context","Documents --filter and -F as the workspace selector; it does not define -r or --recursive, so the detector treating pnpm -r as running in every workspace package is not covered by this page."),yI=L("https://docs.npmjs.com/cli/v11/using-npm/workspaces","npm workspaces documentation","supports","Documents the workspaces field of package.json, -w and --workspace to target one workspace, and --workspaces to run in all of them; the -ws short form is not mentioned on the page."),bI=L("https://pnpm.io/settings","pnpm-workspace.yaml documentation","contradicts","Says pnpm reads workspaces only from pnpm-workspace.yaml and not from the workspaces field of the root package.json, while workspace-manifests.ts merges package.json workspaces globs with pnpm-workspace.yaml globs for every repository whatever its package manager."),wI=L("https://www.gnu.org/software/make/manual/html_node/Makefile-Names.html","GNU make manual, makefile names","supports","Says GNU make looks for GNUmakefile, then makefile, then Makefile, and that -f disables the search."),vI=L("https://docs.npmjs.com/cli/v11/configuring-npm/package-json","npm package.json documentation","supports","Documents engines.node as the Node.js versions a package works on and says the field is advisory unless engine-strict is set; it documents packageManager only under devEngines, not as a top-level field."),SI=L("https://github.com/nodejs/corepack","Corepack README","supports","Says to set the package manager with the packageManager field of package.json in name@version form and lists yarn, npm and pnpm as permitted values; bun is not among them."),ky=L("https://python-poetry.org/docs/pyproject/","Poetry pyproject.toml documentation","supports","Documents the [tool.poetry] table, the [project] table with requires-python, and the python dependency constraint that Poetry uses for locking; it does not explain caret syntax."),_I=L("https://packaging.python.org/en/latest/specifications/pyproject-toml/","PyPA pyproject.toml specification","supports","Lists requires-python as a [project] key giving the Python version requirements, and says the [tool] table holds per-tool configuration such as [tool.flit]."),xI=L("https://pipenv.pypa.io/en/latest/pipfile.html","Pipenv Pipfile documentation","supports","Describes the Pipfile as the TOML dependency manifest that Pipenv uses in place of requirements.txt."),kI=L("https://docs.conda.io/projects/conda/en/stable/user-guide/tasks/manage-environments.html","conda environment management","supports","Says environments are created from a YAML file such as environment.yml, and that conda env create --file still works but conda create --file is now preferred."),EI=L("https://docs.pytest.org/en/stable/getting-started.html","pytest getting started","supports","Shows that running pytest finds test_*.py or *_test.py files and reports which tests passed or failed."),Ey=L("https://devguide.python.org/versions/","Python developer guide, status of Python versions","supports","Lists Python 2.7 end of life on 2020-01-01, 3.8 on 2024-10-07 and 3.9 on 2025-10-31, and also lists 3.10 as end of life on 2026-10-01, which the detector does not flag."),Ay=L("https://nodejs.org/en/about/previous-releases","Node.js previous releases","supports","Lists every Node.js release line up to v20 and v25 as EOL, including v12, v14 and v16; v18 is also EOL, so the detector cut-off of 16 understates what is end of life."),AI=L("https://nextjs.org/docs/app/getting-started/server-and-client-components","Next.js server and client components","supports","Says layouts and pages in the App Router are Server Components by default and that the use client directive marks a Client Component boundary."),CI=L("https://nextjs.org/docs/app/guides/migrating/app-router-migration","Next.js migrating from Pages to the App Router","contradicts","Says the app directory is intentionally designed to work simultaneously with the pages directory for incremental migration and that the two routers can be used together, which contradicts treating pages router and app router as mutually exclusive; it also says getServerSideProps, getStaticProps and getInitialProps are replaced inside app."),Cy=L("https://nextjs.org/docs/app/guides/migrating/app-router-migration","Next.js migrating from Pages to the App Router","supports","Says data fetching functions such as getServerSideProps and getStaticProps have been replaced by a new API inside app, and that getInitialProps is replaced too."),Ry=L("https://nextjs.org/docs/pages/api-reference/functions/get-initial-props","Next.js getInitialProps","supports","Documents getInitialProps as a legacy Pages Router API usable only in top-level files under pages, and points to the App Router for component-level data fetching."),RI=L("https://nextjs.org/docs/app/api-reference/config/next-config-js","Next.js next.config.js reference","supports","Accepts next.config.js in the project root, next.config.mjs for ES modules and next.config.ts for TypeScript, and says the .cjs and .cts extensions are not supported."),TI=L("https://nextjs.org/docs/app/getting-started/project-structure","Next.js project structure","supports","Lists app as the App Router folder and pages as the Pages Router folder at the top level, allows an optional src folder for application code, and names page and layout as the routing files."),Ty=L("https://react.dev/blog/2024/04/25/react-19-upgrade-guide","React 19 upgrade guide","supports","Says ReactDOM.render was deprecated in 18.0.0 and removed in React 19, with createRoot from react-dom/client as the replacement."),Py=L("https://react.dev/blog/2022/03/08/react-18-upgrade-guide","React 18 upgrade guide","supports","Says ReactDOM.render is deprecated in React 18, warns and runs the app in React 17 mode, and that createRoot enables the concurrent renderer."),PI=L("https://angular.dev/guide/components","Angular components guide","contradicts","Says components are standalone by default and that in versions before 19.0.0 the standalone option defaults to false, while the detector treats Angular 17 and 18 as already standalone by default; the page does not say what ng new generated in those versions."),$I=L("https://angular.dev/guide/ngmodules/overview","Angular NgModules overview","supports","Says the Angular team recommends standalone components instead of NgModule for all new code and bootstrapApplication instead of bootstrapModule."),II=L("https://momentjs.com/docs/#/-project-status/","Moment.js project status","supports","States that Moment.js is a legacy project in maintenance mode."),OI=L("https://github.com/palantir/tslint","TSLint repository README","supports","Says TSLint is deprecated, points to ESLint as the replacement, and shows the repository archived on 2021-03-25."),LI=L("https://sass-lang.com/blog/libsass-is-deprecated/","Sass blog, LibSass is deprecated","contradicts","Says LibSass and Node Sass are deprecated and Dart Sass is the replacement, but also says LibSass and Node Sass will continue to be maintained indefinitely on a best-effort basis, which contradicts the detector wording that LibSass is no longer maintained."),NI=L("https://github.com/request/request/issues/3142","request issue 3142, consider deprecating","context","Shows the maintainers discussing maintenance mode and deprecation and an npm warning that request has been deprecated quoted in an October 2022 comment; no 2020 deprecation date appears on the page."),MI=L("https://registry.npmjs.org/request/latest","npm registry entry for the latest request release","supports","The registry marks the latest release deprecated with the message: request has been deprecated, see https://github.com/request/request/issues/3142."),jI=L("https://react.dev/blog/2025/02/14/sunsetting-create-react-app","React blog, sunsetting Create React App","supports","Announces on 2025-02-14 that Create React App is deprecated for new apps and in maintenance mode; the page never names the react-scripts package."),DI=L("https://github.com/enzymejs/enzyme","Enzyme repository README","context","Lists adapters only up to enzyme-adapter-react-16 and states no maintenance status or React 17 or 18 adapter, so it neither confirms nor refutes that Enzyme is unmaintained."),FI=L("https://v2.vuejs.org/","Vue 2 documentation","supports","States that Vue 2 has reached EOL and is no longer actively maintained, without giving a date on the page."),HI=L("https://doc.rust-lang.org/cargo/reference/rust-version.html","Cargo rust-version reference","supports","Says rust-version sets the minimum supported Rust version, must be a bare version number without operators, and makes Cargo error on an older toolchain."),BI=L("https://doc.rust-lang.org/cargo/commands/cargo-test.html","cargo test reference","supports","Says cargo test compiles and runs a package unit, integration and documentation tests."),GI=L("https://doc.rust-lang.org/clippy/usage.html","Clippy usage","supports","Says Clippy can be used as a cargo subcommand or directly with the clippy-driver binary; the page does not state in one sentence what Clippy is for."),WI=L("https://doc.rust-lang.org/cargo/commands/cargo-fmt.html","cargo fmt reference","context","Documents cargo fmt as formatting the bin and lib files of a crate, shipped as an optional toolchain component that may need installing separately."),VI=L("https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html","Cargo specifying dependencies","supports","Says for versions below 1.0 the left-most non-zero component decides compatibility, so ^0.2.3 allows >=0.2.3 and <0.3.0, which backs treating a 0.2 to 0.3 change as significant for crates such as tokio and axum."),UI=L("https://doc.rust-lang.org/edition-guide/editions/index.html","Rust edition guide, what are editions","context","Says each crate chooses its edition in Cargo.toml and that crates of different editions interoperate; the fetched page names only the 2018 edition, so the year values the detector compares are not listed on it."),$y=L("https://go.dev/ref/mod","Go modules reference","supports","Says a module is defined by a go.mod file in its root directory and that the go directive sets the minimum Go version and changes behaviour at thresholds such as go 1.14, 1.16 and 1.17."),zI=L("https://pkg.go.dev/cmd/go#hdr-Test_packages","go command, test packages","supports","Says go test compiles each named package with its _test.go files, runs the test binary and prints a summary; the visible text does not define the ./... pattern."),Iy=L("https://go.dev/doc/go1.18","Go 1.18 release notes","supports","Says Go 1.18 includes an implementation of generics as described by the type parameters proposal."),qI=L("https://learn.microsoft.com/en-us/dotnet/standard/frameworks","Target frameworks in SDK-style projects","supports","Lists net5.0 and later and netcoreapp3.1 as target framework monikers, specified with the TargetFramework element in the project file."),Dl=L("https://dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core",".NET support policy","supports","Lists .NET 5 as ended on 2022-05-10 and .NET Core 3.1 on 2022-12-13, and also lists .NET 6, 7, 8 and 9 as ended, so the detector cut-off at .NET 5 understates what is out of support."),KI=L("https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-build","dotnet build command","context","Says dotnet build accepts a project file or a solution file with a .sln or .slnx extension; the detector recognises .sln and .csproj but not .slnx."),YI=L("https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-test","dotnet test command","supports","Says dotnet test builds the solution and runs the tests with VSTest or Microsoft Testing Platform."),XI=L("https://docs.unity.com/en-us/engine/6000.6/manual/scripting/get-started/fundamental-unity-types/class-mono-behaviour","Unity manual, MonoBehaviour","supports","Warns that defining a constructor for a MonoBehaviour interferes with the normal operation of Unity, and describes Start and Update as the initialisation and per-frame hooks; it says nothing about empty methods costing performance."),JI=L("https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/monobehaviour","Unity script reference, MonoBehaviour","supports","Says a MonoBehaviour always exists as a Component of a GameObject and can be instantiated with GameObject.AddComponent; it does not explicitly forbid new and does not mention empty event methods."),ZI=L("https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/serializefield","Unity script reference, SerializeField","supports","Says SerializeField forces Unity to serialize a private field and that Unity only serializes public fields by default; the page does not mention the Inspector."),QI=L("https://docs.unity.com/en-us/engine/6000.6/manual/assets-and-media/import-assets/asset-metadata","Unity manual, asset metadata","supports","Says Unity creates a .meta file per asset holding its unique ID and import settings, that losing it breaks references to the asset, and that moving an asset outside Unity requires moving its .meta file too; it does not say never to edit it."),eO=L("https://docs.unity3d.com/Packages/com.unity.test-framework@1.4/manual/index.html","Unity Test Framework manual","supports","Says the Unity Test Framework tests code in Edit Mode and Play Mode and was previously called the Unity Test Runner; the menu path is not given on the page."),Oy=L("https://git-scm.com/docs/gitignore","gitignore documentation","supports","Says the last matching pattern decides, lower-level .gitignore files override higher ones, a trailing slash matches only directories, and it is not possible to re-include a file if a parent directory is excluded."),tO=L("https://git-scm.com/docs/git-push","git push documentation","context","Says --force can cause the remote repository to lose commits and describes --force-with-lease as saying you expect the remote to hold the history you are replacing; the page does not recommend one over the other."),nO=L("https://docs.github.com/en/actions/reference/security/secure-use","GitHub Actions secure use reference","supports","Says pinning an action to a full-length commit SHA mitigates a backdoor being added to the action repository and that a tag can be moved or deleted if a bad actor gains access to the repository."),Ly=L("https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax","GitHub Actions workflow syntax","supports","Says the commit SHA of a released action version is the safest for stability and security, a branch reference is risky, ./ refers to an action in the same repository, and docker:// references use image tags."),sO=L("https://supabase.com/docs/guides/getting-started/api-keys","Supabase API keys","supports","Says the secret and service_role key bypasses every Row Level Security policy and must never be put in a browser, a shipped application or source control."),iO=L("https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html","OWASP Secrets Management Cheat Sheet","supports","Advises avoiding checking secrets into code, says secrets should never be logged, and warns against hardcoding them; it has no blanket rule about printing to a console."),oO=L("https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html","OWASP File Upload Cheat Sheet","supports","Recommends an allowlist of extensions, not trusting the Content-Type header and setting a file size limit for uploads."),rO=L("https://cursor.com/docs/reference/ignore-file","Cursor ignore files","contradicts","Says Cursor ignores files in .gitignore and also a default ignore list (.env*, *.lock, node_modules/, .git/) and blocks Agent and Tab access to files in .cursorignore, so it skips more than gitignored paths; terminal and MCP tools are not blocked."),aO=L("https://code.claude.com/docs/en/settings-reference","Claude Code settings reference","context","Lists respectGitignore only as keeping gitignored files out of the @ file picker and shows no setting making gitignore govern file reads, which are controlled by permissions.deny rules."),cO=L("https://code.claude.com/docs/en/memory","Claude Code memory and CLAUDE.md","supports","Says CLAUDE.md files import other files with @path/to/import syntax, relative paths resolve against the importing file, imports nest to a depth of four, and code spans and fenced blocks are skipped."),lO=L("https://code.claude.com/docs/en/best-practices","Claude Code best practices","supports","Says that when a repo already has a check, the single most useful line in CLAUDE.md is the command that runs it, because Claude otherwise has no way to verify its own work."),uO=L("https://www.typescriptlang.org/tsconfig/#noEmit","TypeScript tsconfig reference, noEmit","supports","Says noEmit stops the compiler producing output files and leaves TypeScript for editor integration and type checking."),Ny=[{id:"dead-references",detector:"dead-references",title:"Dead file and directory references",kind:"repo-fact",claim:"A link, @-reference or code-span path in an instruction file that names a file or directory absent from the scanned repository is a dead reference.",appliesTo:"all",sources:[],thresholds:[{name:"MAX_UNANCHORED_DEPTH",value:2,unit:"missing path levels below a first segment that exists",where:"dead-references.ts:MAX_UNANCHORED_DEPTH",source:"unverified"},{name:"MIN_CONFIDENCE",value:.45,unit:"confidence score",where:"dead-references.ts:MIN_CONFIDENCE",source:"unverified"},{name:"minimum path segments for a code-span directory",value:2,unit:"path segments",where:"dead-references.ts:BACKTICK_DIR_RE",source:"unverified"}],lastVerified:W},{id:"dead-references/at-imports",detector:"dead-references",title:"At-sign file imports",kind:"tool-fact",claim:"An @path reference in a CLAUDE.md file is a file import that Claude Code resolves relative to the importing file, so a missing target is a broken instruction.",appliesTo:["claude-code"],sources:[cO],lastVerified:W},{id:"dead-references/gitignore-matching",detector:"dead-references",title:"Gitignored paths are expected to be absent",kind:"tool-fact",claim:"A path that the repository gitignore rules exclude is expected to be missing from a checkout, with the last matching rule winning, deeper gitignore files overriding shallower ones and files under an ignored directory ignored.",appliesTo:"n/a",sources:[Oy],lastVerified:W},{id:"dead-references/credential-paths",detector:"dead-references",title:"Credential and local-config paths are expected to be absent",kind:"opinion",claim:"A referenced .env file, secrets file, local-override config, private key or certificate is deliberately kept out of the repository, so its absence is not a stale reference.",appliesTo:"all",sources:[],unverified:!0,lastVerified:W},{id:"command-validity",detector:"command-validity",title:"Documented commands name scripts, files and targets that exist",kind:"repo-fact",claim:"A command in an instruction file that names a package script, file path or make target that the scanned repository does not define will fail when run.",appliesTo:"all",sources:[],thresholds:[{name:"MAX_MANIFEST_DIRS",value:2e3,unit:"directories",where:"command-validity.ts:MAX_MANIFEST_DIRS",source:"unverified"},{name:"MAX_MANIFEST_DEPTH",value:12,unit:"directory levels",where:"command-validity.ts:MAX_MANIFEST_DEPTH",source:"unverified"},{name:"MAX_MANIFEST_BYTES",value:524288,unit:"bytes per package.json",where:"command-validity.ts:MAX_MANIFEST_BYTES",source:"unverified"},{name:"MAX_TOKENS",value:24,unit:"directory names read from the text around a command",where:"command-context.ts:MAX_TOKENS",source:"unverified"},{name:"MAX_WORKSPACE_MANIFESTS",value:200,unit:"package.json files",where:"workspace-manifests.ts:MAX_WORKSPACE_MANIFESTS",source:"unverified"},{name:"CLOSE_MATCH_MAX_DISTANCE",value:2,unit:"edits",where:"close-match.ts:CLOSE_MATCH_MAX_DISTANCE",source:"unverified"},{name:"CLOSE_MATCH_MIN_LENGTH",value:4,unit:"characters",where:"close-match.ts:CLOSE_MATCH_MIN_LENGTH",source:"unverified"},{name:"MECHANICAL_TWO_EDIT_MIN_LENGTH",value:8,unit:"characters",where:"close-match.ts:MECHANICAL_TWO_EDIT_MIN_LENGTH",source:"unverified"},{name:"MECHANICAL_SEGMENT_MIN_LENGTH",value:5,unit:"characters",where:"close-match.ts:MECHANICAL_SEGMENT_MIN_LENGTH",source:"unverified"}],lastVerified:W},{id:"command-validity/package-manager-scripts",detector:"command-validity",title:"How npm, pnpm, yarn and bun resolve a script name",kind:"tool-fact",claim:"npm and pnpm treat run-script as an alias of run, pnpm and yarn and bun also run a script or an installed binary through the bare form, and a built-in command takes precedence over a same-named script.",appliesTo:"n/a",sources:[vy,Sy,_y,xy],lastVerified:W},{id:"command-validity/workspaces",detector:"command-validity",title:"Workspace selectors and where workspace packages come from",kind:"tool-fact",claim:"pnpm --filter, npm -w and --workspace, and the workspaces globs of package.json or pnpm-workspace.yaml decide which workspace package a script command runs in, with conventional apps, packages and libs roots assumed when none are declared.",appliesTo:"n/a",sources:[gI,yI,bI],lastVerified:W},{id:"command-validity/make-targets",detector:"command-validity",title:"Which Makefile make reads and what counts as a target",kind:"tool-fact",claim:"GNU make reads GNUmakefile, then makefile, then Makefile when no -f is given, and a target can come from an explicit rule, a .PHONY name, a pattern rule or a built-in implicit rule.",appliesTo:"n/a",sources:[wI],lastVerified:W},{id:"manifest-consistency",detector:"manifest-consistency",title:"Instructions agree with the repository manifests",kind:"repo-fact",claim:"An instruction file that names a Python or Node.js version, a library major version, a package manager, a script or a test tool that differs from what pyproject.toml, package.json or the lockfile declares disagrees with the repository.",appliesTo:"all",sources:[],thresholds:[{name:"Python library intent window before",value:80,unit:"characters",where:"manifest-consistency.ts:hasCompatibilityIntent",source:"unverified"},{name:"Python library intent window after",value:120,unit:"characters",where:"manifest-consistency.ts:hasCompatibilityIntent",source:"unverified"},{name:"JavaScript library intent window before",value:100,unit:"characters",where:"manifest-consistency.ts:hasJsVersionIntent",source:"unverified"},{name:"JavaScript library intent window after",value:140,unit:"characters",where:"manifest-consistency.ts:hasJsVersionIntent",source:"unverified"}],lastVerified:W},{id:"manifest-consistency/package-manager-and-engines",detector:"manifest-consistency",title:"packageManager field, lockfiles and engines.node",kind:"tool-fact",claim:"The packageManager field of package.json names the project package manager as name@version, the lockfile is the fallback signal, and engines.node states the Node.js versions the package works on.",appliesTo:"n/a",sources:[SI,vI],lastVerified:W},{id:"manifest-consistency/python-manifest",detector:"manifest-consistency",title:"Python version and Poetry projects in pyproject.toml",kind:"tool-fact",claim:"A pyproject.toml states the required Python version in requires-python or in the Poetry python dependency, and a Poetry project is installed from pyproject.toml rather than from a requirements.txt.",appliesTo:"n/a",sources:[ky,_I],lastVerified:W},{id:"dependency-staleness",detector:"dependency-staleness",title:"Packages named in instructions that no manifest declares",kind:"repo-fact",claim:"An npm package named by an install command or import line in an instruction file that no package.json in the scanned repository declares is a missing dependency.",appliesTo:"all",sources:[],thresholds:[{name:"EXTRA_MANIFEST_LIMIT",value:200,unit:"package.json files",where:"dependency-staleness.ts:EXTRA_MANIFEST_LIMIT",source:"unverified"},{name:"NgModule file search depth",value:8,unit:"directory levels",where:"dependency-staleness.ts:hasNgModuleFiles",source:"unverified"}],lastVerified:W},{id:"dependency-staleness/deprecated-packages",detector:"dependency-staleness",title:"Packages their maintainers have deprecated or stopped maintaining",kind:"tool-fact",claim:"moment is in maintenance mode, request, tslint and node-sass are deprecated, react-scripts belongs to the deprecated Create React App, and enzyme has no adapter for current React versions.",appliesTo:"n/a",sources:[II,MI,NI,OI,LI,jI,DI],lastVerified:W},{id:"dependency-staleness/version-gated-apis",detector:"dependency-staleness",title:"APIs that a framework major version removed or replaced",kind:"tool-fact",claim:"ReactDOM.render was deprecated in React 18 and removed in React 19, and getInitialProps belongs to the Next.js Pages Router only.",appliesTo:"n/a",sources:[Ty,Py,Ry,Cy],thresholds:[{name:"ReactDOM.render warning at React major",value:18,unit:"major version",where:"dependency-staleness.ts:checkReactRender",source:Py},{name:"ReactDOM.render removed at React major",value:19,unit:"major version",where:"dependency-staleness.ts:checkReactRender",source:Ty}],lastVerified:W},{id:"dependency-staleness/angular-standalone-default",refuted:!0,detector:"dependency-staleness",title:"Angular standalone components by default",kind:"tool-fact",claim:"Angular 17 and later projects default to standalone components rather than NgModules.",appliesTo:"n/a",sources:[PI,{...$I,stance:"context"}],thresholds:[{name:"NgModule guidance stale from Angular major (the detector value; the standalone default arrives in 19.0.0)",value:17,unit:"major version",where:"dependency-staleness.ts:checkNgModule",source:"unverified"}],lastVerified:W},{id:"ci-alignment",detector:"ci-alignment",title:"CI runs checks the instructions do not mention",kind:"repo-fact",claim:"A GitHub workflow that runs lint, typecheck, test, build or format while no instruction file tells the agent to run it, or that uses a different package manager than the instructions, is out of step with the instructions.",appliesTo:"all",sources:[],lastVerified:W},{id:"ci-alignment/package-scripts",detector:"ci-alignment",title:"Package-manager command forms used to recognise CI tasks",kind:"tool-fact",claim:"npm, pnpm, yarn and bun run a package script through the run form, and npm test, start, stop and restart are built-in lifecycle commands rather than user scripts.",appliesTo:"n/a",sources:[vy,Sy,_y,xy],lastVerified:W},{id:"ci-alignment/typecheck-vs-build",detector:"ci-alignment",title:"tsc --noEmit is a typecheck and bare tsc is a build",kind:"tool-fact",claim:"Running tsc with --noEmit type-checks without writing output files, while running tsc without it emits compiled output as a build.",appliesTo:"n/a",sources:[uO],lastVerified:W},{id:"conflicts",detector:"conflicts",title:"Contradictory directives in instruction files",kind:"repo-fact",claim:"Two instruction sections that carry opposite directives such as use against do not use, or always against never, about the same or a highly similar subject contradict each other.",appliesTo:"all",sources:[],thresholds:[{name:"subject word overlap for a partial match",value:.5,unit:"Jaccard similarity",where:"conflicts.ts:detectConflicts",source:"unverified"},{name:"minimum confidence to report",value:.4,unit:"confidence score",where:"conflicts.ts:detectConflicts",source:"unverified"},{name:"confidence at which severity becomes high",value:.7,unit:"confidence score",where:"conflicts.ts:detectConflicts",source:"unverified"},{name:"subject words kept after a directive",value:3,unit:"words",where:"conflicts.ts:extractSubjectWords",source:"unverified"},{name:"subject words kept before a directive",value:4,unit:"words",where:"conflicts.ts:extractSubjectWordsBefore",source:"unverified"},{name:"minimum tokens per side for a partial match",value:2,unit:"words",where:"conflicts.ts:detectConflicts",source:"unverified"},{name:"MIN_SECTION_LENGTH",value:1,unit:"characters",where:"conflicts.ts:MIN_SECTION_LENGTH",source:"unverified"}],lastVerified:W},{id:"version-conflicts",detector:"version-conflicts",title:"Instruction files state different versions of one framework",kind:"repo-fact",claim:"Two different instruction files that each positively state a different version of the same framework or runtime disagree with each other.",appliesTo:"all",sources:[],thresholds:[{name:"minimum instruction files",value:2,unit:"files",where:"conflicts.ts:detectVersionConflicts",source:"unverified"},{name:"finding confidence",value:.75,unit:"confidence score",where:"conflicts.ts:detectVersionConflicts",source:"unverified"}],lastVerified:W},{id:"version-conflicts/version-significance",detector:"version-conflicts",title:"Which version differences are significant",kind:"tool-fact",claim:"A difference in major version is significant for most frameworks, a difference in Go minor version is significant, and for Rust crates below 1.0 a change of minor version is a compatibility break.",appliesTo:"n/a",sources:[VI,$y,UI],lastVerified:W},{id:"competing-tech-conflicts",detector:"competing-tech-conflicts",title:"Mutually exclusive technology choices",kind:"opinion",claim:"Instruction files that recommend competing options for one dimension, such as redux against zustand, kebab-case against camelCase file names or pip against poetry, leave an agent unable to choose.",appliesTo:"all",sources:[],unverified:!0,thresholds:[{name:"minimum instruction files",value:2,unit:"files",where:"conflicts.ts:detectCompetingTechConflicts",source:"unverified"},{name:"finding confidence",value:.6,unit:"confidence score",where:"conflicts.ts:detectCompetingTechConflicts",source:"unverified"}],lastVerified:W},{id:"competing-tech-conflicts/nextjs-routers",refuted:!0,detector:"competing-tech-conflicts",title:"Pages Router and App Router treated as exclusive",kind:"tool-fact",claim:"The Next.js Pages Router and App Router are mutually exclusive routing strategies, so instruction files recommending one and the other conflict.",appliesTo:"n/a",sources:[CI],lastVerified:W},{id:"stale-instructions",detector:"stale-instructions",title:"Past years, cleanup markers and deprecated notes",kind:"opinion",claim:"An instruction section that names a calendar year from the last seven, a workaround or temporary fix marker, a dated TODO comment or a deprecated tool is likely out of date.",appliesTo:"all",sources:[],unverified:!0,thresholds:[{name:"STALE_YEAR_WINDOW",value:7,unit:"years before the current year",where:"stale-instructions.ts:STALE_YEAR_WINDOW",source:"unverified"},{name:"negation context lookback",value:80,unit:"characters",where:"stale-instructions.ts:isVersionInNegationContext",source:"unverified"},{name:"deprecated-near-tool window",value:60,unit:"characters",where:"stale-instructions.ts:DEPRECATED_NEAR_VERSION_RE",source:"unverified"}],lastVerified:W},{id:"stale-instructions/end-of-life-runtimes",detector:"stale-instructions",title:"End-of-life runtime versions",kind:"tool-fact",claim:"Node.js 16 and earlier, Python 3.9 and earlier, Python 2, .NET 5 and earlier and Vue 2 are past end of life, and Go 1.17 and earlier pre-date generics.",appliesTo:"n/a",sources:[Ay,Ey,Dl,FI,Iy],thresholds:[{name:"Node.js newest flagged major",value:16,unit:"major version",where:"stale-instructions.ts:OLD_VERSION_PATTERNS",source:Ay},{name:"Python newest flagged 3.x minor",value:9,unit:"minor version of 3",where:"stale-instructions.ts:OLD_VERSION_PATTERNS",source:Ey},{name:".NET newest flagged major",value:5,unit:"major version",where:"stale-instructions.ts:OLD_VERSION_PATTERNS",source:Dl},{name:"Go newest flagged 1.x minor",value:17,unit:"minor version of 1",where:"stale-instructions.ts:OLD_VERSION_PATTERNS",source:Iy}],lastVerified:W},{id:"stale-instructions/old-framework-majors",detector:"stale-instructions",title:"Old framework and tool majors",kind:"tool-fact",claim:"React 16 and earlier, Next.js 9 and earlier, Angular 9 and earlier, Webpack 3 and earlier, Babel 6 and earlier, TypeScript 3 and earlier and Unity 2019 and earlier are old enough that instructions naming them are stale.",appliesTo:"n/a",sources:[],unverified:!0,thresholds:[{name:"React newest flagged major",value:16,unit:"major version",where:"stale-instructions.ts:OLD_VERSION_PATTERNS",source:"unverified"},{name:"Next.js newest flagged major",value:9,unit:"major version",where:"stale-instructions.ts:OLD_VERSION_PATTERNS",source:"unverified"},{name:"Angular newest flagged major",value:9,unit:"major version",where:"stale-instructions.ts:OLD_VERSION_PATTERNS",source:"unverified"},{name:"Webpack newest flagged major",value:3,unit:"major version",where:"stale-instructions.ts:OLD_VERSION_PATTERNS",source:"unverified"},{name:"Babel newest flagged major",value:6,unit:"major version",where:"stale-instructions.ts:OLD_VERSION_PATTERNS",source:"unverified"},{name:"TypeScript newest flagged major",value:3,unit:"major version",where:"stale-instructions.ts:OLD_VERSION_PATTERNS",source:"unverified"},{name:"Unity newest flagged year",value:2019,unit:"release year",where:"stale-instructions.ts:OLD_VERSION_PATTERNS",source:"unverified"}],lastVerified:W},{id:"action-pinning",detector:"action-pinning",title:"Tag and branch action references are mutable",kind:"tool-fact",claim:"A GitHub Actions uses reference pinned to a tag or branch can be moved by whoever controls the action repository, while a full commit SHA cannot be repointed.",appliesTo:"n/a",sources:[nO,Ly],thresholds:[{name:"SHA-1 commit id length",value:40,unit:"hex characters",where:"action-pinning.ts:FULL_SHA_RE",source:"unverified"},{name:"SHA-256 commit id length",value:64,unit:"hex characters",where:"action-pinning.ts:FULL_SHA_RE",source:"unverified"}],lastVerified:W},{id:"action-pinning/exempt-references",detector:"action-pinning",title:"Local and container action references have no git ref to pin",kind:"tool-fact",claim:"A local ./ action lives in the same repository and a docker:// action names an image rather than a git ref, so a commit SHA pin does not apply to either.",appliesTo:"n/a",sources:[Ly],lastVerified:W},{id:"action-pinning/first-party-owners",detector:"action-pinning",title:"GitHub-maintained actions carry a lower risk",kind:"opinion",claim:"An unpinned action owned by the actions or github organisations is a lower risk than an unpinned third-party action, though still a mutable pointer.",appliesTo:"all",sources:[],unverified:!0,lastVerified:W},{id:"security-pack",detector:"security-pack",title:"Security signals in the repository",kind:"repo-fact",claim:"A repository that has an env file, a Supabase dependency, upload code or a .promptci directory while no instruction file carries the matching safeguard wording lacks that safeguard in its instructions.",appliesTo:"all",sources:[],lastVerified:W},{id:"security-pack/secret-handling",unverified:!0,detector:"security-pack",title:"Instructions should say never to print or commit secrets",kind:"opinion",claim:"A repository that uses environment variables should tell the agent in its instructions never to print, log or commit secrets, API keys or credentials.",appliesTo:"all",sources:[{...iO,stance:"context"}],lastVerified:W},{id:"security-pack/supabase-service-role",detector:"security-pack",title:"Supabase service role key stays server-side",kind:"tool-fact",claim:"The Supabase service role key bypasses Row Level Security and must only be used server-side, never in browser code, logs or committed files.",appliesTo:"n/a",sources:[sO],lastVerified:W},{id:"security-pack/upload-validation",unverified:!0,detector:"security-pack",title:"Instructions should define upload validation",kind:"opinion",claim:"A repository with file upload code should document allowed file types, a size limit and validation steps for user-provided files in its instructions.",appliesTo:"all",sources:[{...oO,stance:"context"}],lastVerified:W},{id:"security-pack/destructive-commands",unverified:!0,detector:"security-pack",title:"Destructive commands need safety language",kind:"opinion",claim:"An instruction file that names rm -rf, drop table or git push --force should carry nearby language such as ask before running or confirm before, so an agent does not run it unprompted.",appliesTo:"all",sources:[tO],lastVerified:W},{id:"security-pack/gitignore-semantics",detector:"security-pack",title:"How gitignore matches and re-includes paths",kind:"tool-fact",claim:"A gitignore negation cannot re-include a file under an excluded parent directory, so ignoring .promptci with a carve-out needs .promptci/* rather than .promptci/, and a line ignores a directory only when a path segment matches its name exactly.",appliesTo:"n/a",sources:[Oy],lastVerified:W},{id:"security-pack/generated-directories",refuted:!0,detector:"security-pack",title:"Unignored generated directories reach AI tools",kind:"tool-fact",claim:"Directories such as coverage, dist, build and .next that are not gitignored can be read into the context of AI coding tools, which inflates token cost, because tools such as Cursor skip only gitignored paths.",appliesTo:["cursor","claude-code"],sources:[rO,aO],lastVerified:W},{id:"framework-packs/nextjs",detector:"framework-packs",title:"Next.js pack",kind:"tool-fact",claim:"In Next.js the app directory is the App Router whose layouts and pages are Server Components by default, getStaticProps and getServerSideProps and getInitialProps are Pages Router APIs, and the config file is next.config.js, .mjs or .ts.",appliesTo:"n/a",sources:[AI,Cy,Ry,RI,TI],lastVerified:W},{id:"framework-packs/python",detector:"framework-packs",title:"Python pack",kind:"tool-fact",claim:"A Pipfile marks a Pipenv project, an environment.yml marks a Conda environment, a [tool.poetry] table marks a Poetry project, and pytest runs tests by discovering test_*.py or *_test.py files.",appliesTo:"n/a",sources:[xI,kI,ky,EI],lastVerified:W},{id:"framework-packs/rust",detector:"framework-packs",title:"Rust pack",kind:"tool-fact",claim:"The rust-version key of Cargo.toml is the minimum supported Rust version, and cargo test, cargo clippy and cargo fmt are the standard Rust verification commands.",appliesTo:"n/a",sources:[HI,BI,GI,WI],lastVerified:W},{id:"framework-packs/go",detector:"framework-packs",title:"Go pack",kind:"tool-fact",claim:"A go.mod file in the root directory defines a Go module, and go test with the three-dot package pattern runs the tests of every package in it.",appliesTo:"n/a",sources:[$y,zI],lastVerified:W},{id:"framework-packs/dotnet",detector:"framework-packs",title:".NET pack",kind:"tool-fact",claim:"A .sln or .csproj file marks a .NET project, its TargetFramework is a moniker such as net8.0, netcoreapp3.1 and net5.0 are out of support, and dotnet build and dotnet test are the validation commands.",appliesTo:"n/a",sources:[qI,Dl,KI,YI],lastVerified:W},{id:"framework-packs/unity",detector:"framework-packs",title:"Unity pack",kind:"tool-fact",claim:"A MonoBehaviour is attached to a GameObject rather than created with a constructor, SerializeField makes Unity serialize a private field, a missing .meta file breaks asset references, and the Unity Test Framework runs Edit Mode and Play Mode tests.",appliesTo:"n/a",sources:[XI,JI,ZI,QI,eO],lastVerified:W},{id:"framework-packs/verification-guidance",unverified:!0,detector:"framework-packs",title:"Instructions should name the verification command",kind:"opinion",claim:"Instructions for a repository that uses a framework should name its verification commands so an agent runs them before declaring work complete.",appliesTo:["claude-code"],sources:[{...lO,stance:"context"}],lastVerified:W}];var Fl="2026-11-13",ke="2026-11-14",F={ccSkills:{url:"https://code.claude.com/docs/en/skills",title:"Claude Code: Skills",readOn:Fl},agentSkillsSpec:{url:"https://agentskills.io/specification",title:"Agent Skills specification",readOn:Fl},ccSubagents:{url:"https://code.claude.com/docs/en/sub-agents",title:"Claude Code: Subagents",readOn:Fl},ccHooks:{url:"https://code.claude.com/docs/en/hooks",title:"Claude Code: Hooks reference",readOn:ke},ccSettings:{url:"https://code.claude.com/docs/en/settings",title:"Claude Code: Settings files and precedence",readOn:ke},ccMcp:{url:"https://code.claude.com/docs/en/mcp",title:"Claude Code: Connect to tools via MCP",readOn:ke},ccCli:{url:"https://code.claude.com/docs/en/cli-reference",title:"Claude Code: CLI reference",readOn:ke},ccTools:{url:"https://code.claude.com/docs/en/tools-reference",title:"Claude Code: Tools reference",readOn:ke},skillsOverview:{url:"https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview",title:"Anthropic: Agent Skills overview",readOn:ke},codexSkills:{url:"https://learn.chatgpt.com/docs/build-skills",title:"OpenAI Codex: Build skills",readOn:ke},codexCli:{url:"https://learn.chatgpt.com/docs/developer-commands?surface=cli",title:"OpenAI Codex: CLI command reference",readOn:ke},geminiCli:{url:"https://geminicli.com/docs/cli/cli-reference/",title:"Gemini CLI: CLI reference",readOn:ke},copilotCli:{url:"https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-command-reference",title:"GitHub Copilot CLI: command reference",readOn:ke},cursorRules:{url:"https://cursor.com/docs/rules",title:"Cursor: Rules",readOn:ke},ghRepoInstructions:{url:"https://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/add-custom-instructions/add-repository-instructions",title:"GitHub Docs: Adding repository custom instructions for Copilot",readOn:ke},vscodeInstructionsRef:{url:"https://code.visualstudio.com/docs/agents/reference/custom-instructions-reference",title:"VS Code: Custom instructions reference",readOn:ke},vscodeInstructions:{url:"https://code.visualstudio.com/docs/agent-customization/custom-instructions",title:"VS Code: Custom instructions",readOn:ke},windsurfRules:{url:"https://docs.devin.ai/desktop/devin-local/customizations",title:"Devin Local docs: Customizations (docs.windsurf.com redirects here; Windsurf has no docs of its own to read, so this is another product's documentation)",readOn:ke},rfc8259:{url:"https://www.rfc-editor.org/info/rfc8259/",title:"RFC 8259: The JSON Data Interchange Format",readOn:ke}},H=(t,e,n)=>({...t,stance:e,note:n}),ee={date:ke,by:"Claude agent backfill (pcic-kvv3.1), pending human review"},ce=(t,e,n,s)=>({name:t,value:e,...s?{unit:s}:{},where:n,source:"unverified"}),My=[{id:"ai-config-skills/frontmatter-fields",detector:"ai-config-skills",title:"Skill frontmatter fields",kind:"tool-fact",claim:"A SKILL.md without `name` and `description` frontmatter is skipped by strict loaders such as Codex, Claude Code needs `name` to identify and invoke a skill, and nested maps in the frontmatter are unsupported.",appliesTo:["claude-code","codex"],sources:[H(F.ccSkills,"contradicts","Says every frontmatter field is optional and that `name` defaults to the directory name, so Claude Code does not need `name` to identify the skill and the missing-name finding overstates it."),H(F.ccSkills,"contradicts","Documents `hooks` and `metadata` as nested YAML maps in skill frontmatter and says an unrecognised key is ignored without error, so the finding that a nested key is unsupported is wrong for Claude Code."),H(F.agentSkillsSpec,"supports","Marks `name` and `description` as required frontmatter fields, which is why a portable skill needs both."),H(F.codexSkills,"supports",'States that SKILL.md must include `name` and `description`, but does not say what Codex does with a skill that lacks them, so "skipped" is not confirmed.')],lastVerified:ee},{id:"ai-config-skills/name-matches-directory",detector:"ai-config-skills",title:"Skill name matches its directory",kind:"tool-fact",claim:"Claude resolves a skill by its directory name, so a frontmatter `name` that differs from the skill directory is a mistake.",appliesTo:["claude-code","codex"],sources:[H(F.ccSkills,"contradicts","Describes `name` as the command name shown in the `/` menu that only defaults to the directory name, and does not require the two to match, so the page does not say Claude resolves skills by directory name."),H(F.agentSkillsSpec,"supports","The portable spec says `name` must match the parent directory name, which supports the check for the open format but is not Claude Code behaviour."),H(F.codexSkills,"context","Does not say whether `name` must match the directory.")],lastVerified:ee},{id:"ai-config-skills/description-trigger",detector:"ai-config-skills",title:"Skill description is the trigger text",kind:"tool-fact",claim:"A skill's `description` is the text the agent matches against a request to decide whether to invoke it, so an empty or very short description rarely triggers and two identical descriptions compete for the same triggers.",appliesTo:["claude-code","codex"],sources:[H(F.skillsOverview,"supports","Says the description is what Claude matches a request against to decide whether to trigger the skill, and requires it to be non-empty and at most 1,024 characters."),H(F.ccSkills,"contradicts","Says an omitted description falls back to the first non-empty line of the body, so a missing description does not always leave a skill untriggerable, and truncates description plus when_to_use at 1,536 characters in the listing."),H(F.codexSkills,"supports","Says Codex can select a skill when a task matches its description and advises front-loading the key use case."),H(F.agentSkillsSpec,"context","Requires a description of 1 to 1,024 characters that says what the skill does and when to use it, with no 12-character minimum.")],thresholds:[ce("MIN_DESCRIPTION_CHARS",12,"skills-detector.ts:MIN_DESCRIPTION_CHARS","characters")],lastVerified:ee},{id:"ai-config-skills/locations-and-bundled-refs",detector:"ai-config-skills",title:"Where skills live and how bundled files resolve",kind:"tool-fact",claim:"Agent Skills are discovered under `.claude/skills/`, `.agents/skills/` and plugin `skills/<name>/` directories, and files a skill references by relative path resolve from the skill's own directory.",appliesTo:["claude-code","codex"],sources:[H(F.ccSkills,"supports","Lists .claude/skills/<name>/SKILL.md for projects and <plugin>/skills/<name>/SKILL.md for plugins, and shows supporting files linked by relative path from SKILL.md; it never mentions .agents/skills."),H(F.codexSkills,"supports","Lists .agents/skills in the working directory, its parents and the repository root as Codex repository skill locations, and does not list .codex/skills."),H(F.agentSkillsSpec,"supports","Says file references inside a skill use relative paths from the skill root.")],lastVerified:ee},{id:"ai-config-subagents/frontmatter-and-location",detector:"ai-config-subagents",title:"Subagent file and frontmatter",kind:"tool-fact",claim:"Claude Code registers a subagent from a Markdown file under `.claude/agents/` only when its frontmatter has `name` and `description`, and nested maps in that frontmatter are unsupported.",appliesTo:["claude-code"],sources:[H(F.ccSubagents,"supports","Says only `name` and `description` are required and that .claude/agents/ is scanned recursively."),H(F.ccSubagents,"contradicts","Documents `hooks`, `mcpServers` and `experimental` as nested YAML maps in subagent frontmatter, so the finding that a nested key is unsupported is wrong for Claude Code.")],lastVerified:ee},{id:"ai-config-subagents/model-values",refuted:!0,detector:"ai-config-subagents",title:"Subagent model values",kind:"tool-fact",claim:"A subagent's `model` frontmatter accepts only the aliases sonnet, opus, haiku, inherit, default or opusplan, or a full `claude-*` model id.",appliesTo:["claude-code"],sources:[H(F.ccSubagents,"contradicts","Lists the accepted values as sonnet, opus, haiku, fable, a full model ID or inherit, so `fable` is valid but missing from the detector alias set, and `default` and `opusplan` are not listed as valid values.")],lastVerified:ee},{id:"ai-config-subagents/tool-names",refuted:!0,detector:"ai-config-subagents",title:"Subagent tool names",kind:"tool-fact",claim:"A subagent `tools` entry must be one of a fixed list of built-in tool names, an `mcp__` tool name or `*`, and any other name is a likely typo.",appliesTo:["claude-code"],sources:[H(F.ccSubagents,"contradicts","Documents `Agent(agent_type)` parenthesised entries (honoured for a main-thread agent, ignored in a subagent definition), the legacy `Task(...)` alias, and built-in tools such as Skill, LSP, PowerShell, ToolSearch and Monitor that the detector list omits, so valid entries are reported as typos."),H(F.ccTools,"contradicts","Its tool table lists current tools such as Skill, LSP, PowerShell, Monitor, TaskStop, SendMessage and ToolSearch that the detector list omits, and has no row for LS, MultiEdit, NotebookRead, BashOutput, KillBash, KillShell or SlashCommand, which the detector list still accepts.")],lastVerified:ee},{id:"ai-config-subagents/duplicate-prompts",detector:"ai-config-subagents",title:"Near-identical subagent prompts",kind:"opinion",claim:"Two subagents whose prompt bodies are at least 80 percent identical are usually a copy-paste that should be consolidated or differentiated.",appliesTo:["claude-code"],sources:[],unverified:!0,thresholds:[ce("DUP_SIMILARITY",.8,"subagents-detector.ts:DUP_SIMILARITY","Jaccard similarity"),ce("MIN_BODY_LINES",5,"subagents-detector.ts:MIN_BODY_LINES","normalized lines"),ce("minimum normalized line length",8,"subagents-detector.ts:normalizeBodyLines","characters")],lastVerified:ee},{id:"ai-config-hooks-settings/settings-files",detector:"ai-config-hooks-settings",title:"Hooks in Claude Code settings files",kind:"tool-fact",claim:"Claude Code reads `hooks` from `.claude/settings.json` and `.claude/settings.local.json` as event-keyed groups of `{type: command, command}` entries, and a file that is not valid strict JSON is not loaded.",appliesTo:["claude-code"],sources:[H(F.ccHooks,"supports","Lists .claude/settings.json and .claude/settings.local.json as hook locations and shows event, matcher group and hooks array nesting with `type: command` handlers, alongside http, mcp_tool, prompt and agent handler types the detector does not audit."),H(F.ccSettings,"supports","Says settings files are strict JSON so a comment or trailing comma is a syntax error, and that an invalid project or local file raises a Settings Error and is skipped in a -p run.")],lastVerified:ee},{id:"ai-config-hooks-settings/project-dir-quoting",detector:"ai-config-hooks-settings",title:"Quoting the project directory in hook commands",kind:"tool-fact",claim:"An unquoted `$CLAUDE_PROJECT_DIR` path in a hook command breaks when the project path contains a space.",appliesTo:["claude-code"],sources:[H(F.ccHooks,"supports","Says that in shell form the command string is tokenized by a shell and each path placeholder should be wrapped in double quotes."),H(F.ccHooks,"contradicts",'Says a hook with `args` set runs in exec form with no shell, so a placeholder needs no quotes there, and its own example passes an unquoted ${CLAUDE_PROJECT_DIR} path with `"args": []`, which the detector would still flag.')],lastVerified:ee},{id:"ai-config-hooks-settings/remote-pipe",detector:"ai-config-hooks-settings",title:"Hook that pipes a download into a shell",kind:"opinion",claim:"A hook command that pipes curl or wget output straight into a shell runs whatever the remote host serves with the user's own permissions.",appliesTo:["claude-code"],sources:[],unverified:!0,lastVerified:ee},{id:"ai-config-hooks-settings/missing-script",detector:"ai-config-hooks-settings",title:"Hook script missing from the repository",kind:"repo-fact",claim:"A repo-relative script that a hook command runs is not present in the scanned repository.",appliesTo:"all",sources:[],lastVerified:ee},{id:"ai-config-mcp/file-format",detector:"ai-config-mcp",title:"Project MCP config format",kind:"tool-fact",claim:"Claude Code reads project MCP servers from `.mcp.json` under a top-level `mcpServers` key, where a stdio server needs a `command` and a remote server needs only a `url`.",appliesTo:["claude-code"],sources:[H(F.ccMcp,"supports","Shows project servers in .mcp.json under a top-level mcpServers key, with command, args and env for stdio servers and type plus url for http or sse servers."),H(F.ccMcp,"contradicts","Says an entry with a `url` but no `type` is read as a stdio server and skipped with a configuration error, so the detector accepting any `url` as a valid remote server is too lax.")],lastVerified:ee},{id:"ai-config-mcp/duplicate-names",unverified:!0,detector:"ai-config-mcp",title:"Duplicate MCP server names",kind:"tool-fact",claim:"When `.mcp.json` defines the same server name twice, JSON parsing keeps only the last definition and silently drops the earlier one.",appliesTo:["claude-code"],sources:[H(F.rfc8259,"context","Says behaviour for non-unique object names is unpredictable and that many implementations report only the last pair, while others reject the text or keep every pair."),H(F.ccMcp,"context","Says duplicate server names across scopes resolve to the highest-precedence source, and does not say how a duplicate key inside one .mcp.json file is handled.")],lastVerified:ee},{id:"ai-config-mcp/placeholders-and-paths",detector:"ai-config-mcp",title:"MCP placeholders and local paths",kind:"repo-fact",claim:"An `env` value in `.mcp.json` that is empty or a placeholder was never filled in, and a local command or script path in it does not exist in the repository.",appliesTo:"all",sources:[H(F.ccMcp,"context","Documents ${VAR} expansion in env values, which is what the detector recommends in place of a placeholder, and says an unset ${VAR} is passed through unexpanded.")],lastVerified:ee},{id:"ai-config-cursor-rules/rule-files",detector:"ai-config-cursor-rules",title:"Cursor rule files and frontmatter",kind:"tool-fact",claim:"Cursor project rules are `.mdc` files under `.cursor/rules/` whose frontmatter holds `description`, `globs` and `alwaysApply`.",appliesTo:["cursor"],sources:[H(F.cursorRules,"supports","Says project rules live in .cursor/rules, must use the .mdc extension, may sit in subfolders and carry description, globs and alwaysApply frontmatter.")],lastVerified:ee},{id:"ai-config-cursor-rules/no-trigger",refuted:!0,detector:"ai-config-cursor-rules",title:"Cursor rule with no trigger",kind:"tool-fact",claim:"A Cursor rule with no `description`, no `globs` and `alwaysApply` unset has no signal for when to apply and can never activate.",appliesTo:["cursor"],sources:[H(F.cursorRules,"contradicts","Says a rule with alwaysApply false and neither globs nor a description is included when you @-mention it in chat, so it can activate manually rather than never.")],lastVerified:ee},{id:"ai-config-cursor-rules/glob-semantics",detector:"ai-config-cursor-rules",title:"Cursor rule glob matching",kind:"tool-fact",claim:"Cursor matches a slashless glob such as `*.tsx` at any depth, and a rule whose `globs` match no file in the repository is auto-attached to nothing.",appliesTo:["cursor"],sources:[H(F.cursorRules,"contradicts","Documents `*.ts` as the .ts files in the root and `**/*.ts` as .ts files in any directory, so a slashless glob is root-level only and the detector any-depth fallback hides rules that never fire."),H(F.cursorRules,"supports","Says a rule with globs is auto-attached when a matching file is in context.")],lastVerified:ee},{id:"ai-config-copilot-instructions/path-specific-files",detector:"ai-config-copilot-instructions",title:"Copilot path-specific instruction files",kind:"tool-fact",claim:"Copilot reads path-specific instructions from `.md` files under `.github/instructions/` that scope themselves with an `applyTo` frontmatter glob, while `.github/copilot-instructions.md` is always on and has no `applyTo`.",appliesTo:["copilot"],sources:[H(F.ghRepoInstructions,"contradicts","Says a path-specific instructions file name must end with .instructions.md, whereas discovery audits every .md file under .github/instructions/."),H(F.ghRepoInstructions,"supports","Says .github/copilot-instructions.md is repository-wide and automatically added to requests."),H(F.vscodeInstructionsRef,"supports","Places targeted instructions at .github/instructions/**/*.instructions.md with an optional applyTo glob and says copilot-instructions.md needs no frontmatter.")],lastVerified:ee},{id:"ai-config-copilot-instructions/apply-to-default",refuted:!0,detector:"ai-config-copilot-instructions",title:"Copilot instructions without applyTo",kind:"tool-fact",claim:"A path-specific Copilot instructions file with no `applyTo` glob is applied to every request by default.",appliesTo:["copilot"],sources:[H(F.vscodeInstructionsRef,"contradicts","Says that in Local sessions a file omitting both description and applyTo is left available for manual attachment rather than automatic activation, and that applyTo has no default pattern."),H(F.ghRepoInstructions,"context","Does not say what happens when applyTo is omitted."),H(F.vscodeInstructions,"context","Does not describe a file without applyTo.")],lastVerified:ee},{id:"ai-config-copilot-instructions/glob-semantics",refuted:!0,detector:"ai-config-copilot-instructions",title:"Copilot applyTo glob matching",kind:"tool-fact",claim:"An `applyTo` glob such as `*.ts` without a slash matches files at any depth, and a glob that matches no file never applies.",appliesTo:["copilot"],sources:[H(F.ghRepoInstructions,"contradicts","Gives `*.py` as matching the .py files in the current directory only, and `**` or `**/*` as matching all files in all directories."),H(F.vscodeInstructionsRef,"contradicts","Says patterns are relative to the project root and that `*.py` matches only root-level files.")],lastVerified:ee},{id:"ai-config-windsurf-rules/legacy-always-on",unverified:!0,detector:"ai-config-windsurf-rules",title:"Windsurf legacy rules file",kind:"tool-fact",claim:"`.windsurfrules` is Windsurf's legacy workspace-wide rules file and every rule in it is fed to the model on every request.",appliesTo:["windsurf"],sources:[H(F.windsurfRules,"context","Says the legacy .windsurf/rules/*.md, .windsurf/global_rules.md and .windsurfrules files are imported by default and names global_rules.md as always-on, but does not describe .windsurfrules as always-on, and the page has moved to docs.devin.ai with .devin/rules as the primary location.")],lastVerified:ee},{id:"ai-config-windsurf-rules/scoped-rules",unverified:!0,detector:"ai-config-windsurf-rules",title:"Windsurf scoped rule files",kind:"tool-fact",claim:"Windsurf supports scoped rule files in `.windsurf/rules/*.md` that activate by glob, manually or by model decision.",appliesTo:["windsurf"],sources:[H(F.windsurfRules,"context","Documents Devin Local, not Windsurf: lists always_on, glob, model_decision and manual triggers for rule files with globs set in frontmatter, and says legacy .windsurf/rules/*.md files are still imported.")],lastVerified:ee},{id:"ai-config-windsurf-rules/language-scoping",unverified:!0,detector:"ai-config-windsurf-rules",title:"Language-specific rules belong in scoped files",kind:"opinion",claim:"An always-on rules file with headings for two or more distinct languages or frameworks mixes rule sets that are cheaper as glob-scoped rules.",appliesTo:["windsurf"],sources:[H(F.windsurfRules,"context","Says rules cost tokens on every message and should be short and specific, with a skill preferred for occasional needs, but does not recommend splitting language-specific rules into glob-triggered files.")],thresholds:[ce("MIN_DISTINCT_TOPICS",2,"windsurf-detector.ts:MIN_DISTINCT_TOPICS","distinct topics")],lastVerified:ee},{id:"skill-supply-chain/trust-model",detector:"skill-supply-chain",title:"A skill is untrusted code",kind:"tool-fact",claim:"An installed Agent Skill is instructions plus bundled scripts that the agent loads on demand and runs with the user's own permissions, so a third-party skill is untrusted code.",appliesTo:["claude-code","codex"],sources:[H(F.skillsOverview,"supports","Says to use skills only from trusted sources, that a malicious skill can direct Claude to call tools or run code, and that in Claude Code skills have the same network access as any other program on the user's computer."),H(F.ccSkills,"supports","Warns that a project skill can grant itself broad tool access through allowed-tools even in an untrusted folder so repository skills need review, but does not state in so many words that scripts run with user permissions."),H(F.agentSkillsSpec,"context","Defines scripts/ as executable code agents can run and says the SKILL.md body loads when the skill activates."),H(F.codexSkills,"context","Says Codex loads the full SKILL.md only when it uses the skill and that scripts are optional, and says nothing about approval or sandboxing of skill scripts.")],lastVerified:ee},{id:"skill-supply-chain/code-abuse-patterns",unverified:!0,detector:"skill-supply-chain",title:"Code patterns typical of a malicious or fragile skill",kind:"opinion",claim:"Piping fetched content into a shell or eval, decoding then executing a payload, reading credential stores next to network calls and installing unpinned remote dependencies are characteristic of a malicious or fragile skill.",appliesTo:["claude-code","codex"],sources:[H(F.skillsOverview,"context","Tells reviewers to look for unexpected network calls and file access, and says skills that fetch external URLs pose particular risk and can be compromised if their dependencies change; it names no specific pipe-to-shell or encoding pattern.")],lastVerified:ee},{id:"skill-supply-chain/hidden-and-injected-text",detector:"skill-supply-chain",title:"Hidden and injected text in a skill",kind:"tool-fact",claim:"An agent reads a skill's raw text including HTML comments, hidden-element markup and invisible Unicode characters that rendered Markdown hides from a human reviewer, so such text can carry instructions.",appliesTo:["claude-code","codex"],sources:[],unverified:!0,thresholds:[ce("BLOB_RE minimum run",200,"skill-supply-chain.ts:BLOB_RE","base64 characters")],lastVerified:ee},{id:"skill-supply-chain/permission-bypass-flags",detector:"skill-supply-chain",title:"Flags that switch off agent permission prompts",kind:"tool-fact",claim:"`--dangerously-skip-permissions`, `bypassPermissions`, `--dangerously-bypass-approvals-and-sandbox`, `--yolo` and `--allow-all-tools` each switch off an AI coding tool permission prompts or sandbox.",appliesTo:["claude-code","codex","gemini-cli","copilot"],sources:[H(F.ccCli,"supports","Describes --dangerously-skip-permissions as skipping permission prompts and equivalent to --permission-mode bypassPermissions."),H(F.codexCli,"supports","Lists --dangerously-bypass-approvals-and-sandbox with the alias --yolo as running every command without approvals or sandboxing, for use only in a hardened environment."),H(F.geminiCli,"supports","Lists --yolo as a deprecated auto-approve flag replaced by --approval-mode=yolo, a newer spelling the detector flag list does not match."),H(F.copilotCli,"supports","Says --allow-all-tools grants blanket tool permissions without a model safety review or approval prompts; --yolo appears only as a slash-command alias in the part of the page read.")],caveat:"geminicli.com carries a banner (read 2026-11-14): Gemini CLI was replaced by Antigravity CLI on June 18th, 2026 for unpaid-tier and Google One users, and it has not been optimized for Gemini 4 Argon; a claim about gemini-cli may not hold for the replacement.",lastVerified:ee},{id:"skill-supply-chain/bundle-completeness",detector:"skill-supply-chain",title:"Skill content the scan could not review",kind:"repo-fact",claim:"Skill content past the scan caps, such as binaries, archives, oversized files and bundles of more than 200 files, was not inspected, and a SKILL.md that runs a script found nowhere cannot be reviewed.",appliesTo:"all",sources:[],thresholds:[ce("MAX_BUNDLED_FILES_PER_SKILL",200,"discovery.ts:MAX_BUNDLED_FILES_PER_SKILL","files"),ce("MAX_SCAN_BYTES",20*1024*1024,"skill-supply-chain.ts:MAX_SCAN_BYTES","bytes"),ce("MAX_SCAN_FILES",2e3,"skill-supply-chain.ts:MAX_SCAN_FILES","files"),ce("MAX_SCAN_LINES",3e6,"skill-supply-chain.ts:MAX_SCAN_LINES","lines"),ce("MAX_FILE_SIZE",500*1024,"discovery.ts:MAX_FILE_SIZE","bytes"),ce("oversized file head and tail window",500*1024,"skill-supply-chain.ts:loadDocs (MAX_FILE_SIZE)","bytes"),ce("BINARY_CHECK_BYTES",512,"discovery.ts:BINARY_CHECK_BYTES","bytes"),ce("MAX_SCAN_WINDOW",2e3,"skill-supply-chain.ts:MAX_SCAN_WINDOW","characters"),ce("WINDOW_OVERLAP",600,"skill-supply-chain.ts:WINDOW_OVERLAP","characters"),ce("MAX_HITS_PER_RULE_FILE",25,"skill-supply-chain.ts:MAX_HITS_PER_RULE_FILE","hits"),ce("MAX_EVIDENCE",5,"skill-supply-chain.ts:MAX_EVIDENCE","evidence lines"),ce("MAX_FS_CHECKS_PER_DOC",200,"skill-supply-chain.ts:MAX_FS_CHECKS_PER_DOC","lookups"),ce("MAX_PIPE_HOPS",16,"skill-supply-chain.ts:MAX_PIPE_HOPS","pipe stages"),ce("MAX_JOINED_LINES",20,"skill-supply-chain.ts:MAX_JOINED_LINES","lines"),ce("MAX_JOINED_CHARS",4e3,"skill-supply-chain.ts:MAX_JOINED_CHARS","characters"),ce("MAX_LOOP_JOINED_LINES",200,"skill-supply-chain.ts:MAX_LOOP_JOINED_LINES","lines"),ce("MAX_LOOP_JOINED_CHARS",2e4,"skill-supply-chain.ts:MAX_LOOP_JOINED_CHARS","characters"),ce("MAX_BUNDLE_LISTING",2e4,"ai-config.ts:MAX_BUNDLE_LISTING","directory entries"),ce("MAX_OVER_CAP_NAMES",1e3,"ai-config.ts:MAX_OVER_CAP_NAMES","file names")],lastVerified:ee}];var NH=[...My,...wy,...Ny];var Ro=R(require("node:fs/promises"),1),Kn=R(require("node:path"),1);var jy=Kn.join(".promptci","config.json"),Fy=["info","warning","high","critical"],Hy=ti;function dO(t){return typeof t=="string"&&Fy.includes(t)}function pO(t){return typeof t=="string"&&Hy.includes(t)}function Dy(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}async function Me(t){let e=he(Kn.resolve(t),jy);if(e===null){let r=Kn.join(Kn.resolve(t),jy),a=!1;try{await Ro.lstat(r),a=!0}catch{}return a&&process.stderr.write(`Warning: ignoring ${r}: it resolves outside the scan path through a symlink, so its settings were not applied.
128
+ `),{}}let n;try{n=await Ro.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,o={};if("include"in i){if(!Dy(i.include))throw new Error("config.include must be an array of strings");o.include=i.include}if("exclude"in i){if(!Dy(i.exclude))throw new Error("config.exclude must be an array of strings");o.exclude=i.exclude}if("severityThreshold"in i){if(!dO(i.severityThreshold))throw new Error(`config.severityThreshold must be one of: ${Fy.join(", ")}`);o.severityThreshold=i.severityThreshold}if("projectType"in i){if(!pO(i.projectType))throw new Error(`config.projectType must be one of: ${Hy.join(", ")}`);o.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");o.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");o.fileContextBudget=i.fileContextBudget}if("targetModel"in i){if(typeof i.targetModel!="string"||Wn(i.targetModel)===void 0)throw new Error(`config.targetModel must be one of: ${Cs.join(", ")} (or a family alias like "claude"/"gpt"/"gemini")`);o.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");o.vagueGuidanceSeverity=i.vagueGuidanceSeverity}return o}var Vy=R(require("node:path"),1);var fO="https://promptci.seriousgeese.dev";function By(t){return Number.isFinite(t)&&t>0?Math.min(Math.floor(t),Number.MAX_SAFE_INTEGER):0}function Gy(t,e){return`${fO}/?tokens=${By(t)}&addressable=${By(e)}#estimate`}var hO={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},mO=["critical","high","warning","info"],gO={critical:3,high:2,warning:1,info:0};function Wy(t){return gO[t]}function Hl(t,e){return Wy(t)>=Wy(e)}function Ks(t,e){return t.issues.some(n=>Hl(n.severity,e))}function yO(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 Uy(t,e={}){let{healthScore:n,issues:s,topFixes:i}=t,o={};for(let h of s)o[h.severity]=(o[h.severity]??0)+1;let r=mO.filter(h=>(o[h]??0)>0).map(h=>`${hO[h]} ${o[h]} ${h}`).join(" \xB7 "),a=e.previousEntry!=null?yO(n,e.previousEntry.healthScore):"",c=` Health score: ${n}/100`;if(t.trend){let h=t.trend,f=h.scoreDelta,m;f>0?m=`\x1B[32m(+${f} vs last scan)\x1B[0m`:f<0?m=`\x1B[31m(${f} vs last scan)\x1B[0m`:m="\x1B[90m(+0 vs last scan)\x1B[0m",c+=` ${m}; new issues: ${h.newIssuesCount}; resolved: ${h.resolvedIssuesCount}`}else e.previousEntry!=null&&(c+=a);let l=[];l.push(""),l.push("\u2714 Scan complete"),l.push(""),l.push(c),l.push(` Issues: ${r||"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;if(u>0&&l.push(` Suppressed: ${u} (see report for details)`),t.metrics&&t.metrics.instructionFileCount>0){let h=t.metrics.estimatedInstructionTokens,f=Math.min(t.metrics.estimatedAddressableTokens??0,h);l.push(""),l.push(` Tokens loaded per agent turn: ${h}`),l.push(` In flagged sections: up to ${f}`),l.push(` Estimate savings: ${Gy(h,f)}`)}i.length>0&&(l.push(""),l.push(" Top fixes:"),i.forEach((h,f)=>{l.push(` ${f+1}. ${h.title}`)}));let p=h=>Vy.relative(process.cwd(),h)||h,d=[];return e.mdPath&&d.push(` Markdown : ${p(e.mdPath)}`),e.jsonPath&&d.push(` JSON : ${p(e.jsonPath)}`),d.length>0&&(l.push(""),l.push(" Output:"),l.push(...d)),l.push(""),l.join(`
129
+ `)}var Bl=["info","warning","high","critical"],zy=["json","sarif"];function To(t){return Bl.includes(t)}function bO(t){return zy.includes(t)}async function qy(t){let e=t.scanPath??process.cwd(),n=Qe.resolve(e);try{(await bt.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 Me(n)}catch(h){console.error(`Error: ${h instanceof Error?h.message:String(h)}`),process.exit(1)}let i=t.targetModel??s.targetModel;i!==void 0&&Wn(i)===void 0&&(console.error(`Error: invalid --target-model value "${i}". Must be one of: ${Cs.join(", ")} (or a family alias like "claude"/"gpt"/"gemini").`),process.exit(1));let o=t.failOn??s.severityThreshold;o!==void 0&&!To(o)&&(console.error(`Error: invalid --fail-on value "${o}". Must be one of: ${Bl.join(", ")}`),process.exit(1)),t.failOnNew!==void 0&&!To(t.failOnNew)&&(console.error(`Error: invalid --fail-on-new value "${t.failOnNew}". Must be one of: ${Bl.join(", ")}`),process.exit(1)),t.format!==void 0&&!bO(t.format)&&(console.error(`Error: invalid --format value "${t.format}". Must be one of: ${zy.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 r;if(t.baseline){let h=Qe.resolve(n,t.baseline);ue(n,h)&&he(n,h)===null&&(console.error(`Error: baseline file "${h}" is a symlink that resolves outside the scan path; refusing to read it.`),process.exit(1));try{let f=await bt.readFile(h,"utf-8"),m;try{m=JSON.parse(f)}catch(g){console.error(`Error: baseline file "${h}" contains invalid JSON: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}try{Ja(m),r=m}catch(g){console.error(`Error: baseline file "${h}" has an unexpected format: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}}catch(f){f.code!=="ENOENT"&&(console.error(`Error loading baseline: ${f instanceof Error?f.message:String(f)}`),process.exit(1)),r=[]}}let a=await ze({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude,baseline:r,contextBudget:t.contextBudget??s.contextBudget,fileContextBudget:t.fileContextBudget??s.fileContextBudget,targetModel:i,vagueGuidanceSeverity:s.vagueGuidanceSeverity}),c=t.output&&t.format!=="sarif"?Qe.resolve(t.output):void 0,l=c?await Ki(a,{mdPath:c,archive:!1}):await Ki(a),u;if(t.format==="sarif"){let h=t.output?Qe.resolve(t.output):Qe.join(n,".promptci","report.sarif");$n(n,h)||(console.error(`Error: SARIF output "${h}" resolves outside the scan path through a symlink; refusing to write it.`),process.exit(1)),await bt.mkdir(Qe.dirname(h),{recursive:!0}),u=ic(a,t.cliVersion??"0.0.0"),await bt.writeFile(h,u,"utf8")}if(t.updateBaseline){let h=Mn(a.issues,n),f=t.baseline?Qe.resolve(n,t.baseline):Qe.join(n,".promptci","baseline.json");$n(n,f)||(console.error(`Error: baseline file "${f}" resolves outside the scan path through a symlink; refusing to write it.`),process.exit(1)),await bt.mkdir(Qe.dirname(f),{recursive:!0}),await bt.writeFile(f,JSON.stringify(h,null,2)),!t.json&&t.format===void 0?process.stdout.write(`
130
+ Baseline updated: ${f}
131
+ `):process.stderr.write(`Baseline updated: ${f}
132
+ `)}let p=t.json||t.format==="json";if(t.format==="sarif"?process.stdout.write(`${u}
133
+ `):p?process.stdout.write(qi(a)+`
134
+ `):process.stdout.write(Uy(a,{mdPath:l.mdPath,jsonPath:l.jsonPath,previousEntry:l.archivedEntry})),o&&Ks(a,o)){let h=a.issues.filter(m=>To(m.severity)&&Ks({...a,issues:[m]},o)).length,f=t.failOn!==void 0?"from --fail-on":"from severityThreshold in .promptci/config.json";console.error(`
135
+ Failed: ${h} issue(s) at or above the "${o}" threshold (${f}). See ${l.mdPath} for details.
136
+ Raise the gate with --fail-on <severity> or edit severityThreshold to only fail on higher severities.`),process.exit(1)}let d=t.failOnNew;if(d){let h=a.newIssues??[];if(Ks({...a,issues:h},d)){let f=h.filter(m=>To(m.severity)&&Ks({...a,issues:[m]},d)).length;console.error(`
137
+ Failed: ${f} NEW issue(s) at or above "${d}" threshold. See ${l.mdPath} for details.`),process.exit(1)}}if(t.failOnBudget){let h=a.issues.filter(f=>f.category==="context_bloat");h.length>0&&(console.error(`
138
+ Failed: ${h.length} context bloat issue(s) found and --fail-on-budget is enabled. See ${l.mdPath} for details.`),process.exit(1))}}var Xy=R(require("node:fs/promises"),1),qt=R(require("node:path"),1);var wO=3,Ky={critical:3,high:2,warning:1,info:0};function vO(t,e=wO){return[...t].sort((n,s)=>Ky[s.severity]-Ky[n.severity]||s.confidence-n.confidence||n.id.localeCompare(s.id)).slice(0,e)}var SO=/[\u0000-\u001f\u007f-\u009f]/g,Gl=t=>t.replace(SO," ").replace(/\s+/g," ").trim(),Yy=160,_O=t=>{let e=Gl(t);return e.length>Yy?`${e.slice(0,Yy-1).trimEnd()}\u2026`:e};function xO(t,e){let n=t.locations[0],s=n?.filePath??t.filePaths[0];if(!s)return;let o=((qt.isAbsolute(s)?qt.relative(e,s):s)||s).split(qt.sep).join("/");return n?.startLine!==void 0?`${o}:${n.startLine}`:o}function kO(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(`
139
+ `);let n=t.issues.length;if(e.push(`PromptCI instruction health: ${t.healthScore}/100 (${Dn(t.healthScore)})`),n===0)e.push("No findings. Nice.");else{let s=vO(t.issues);e.push(""),e.push(`Top ${s.length} finding${s.length===1?"":"s"} (of ${n}):`),s.forEach((i,o)=>{let r=xO(i,t.repoPath);e.push(` ${o+1}. [${i.severity}] ${Gl(i.title)}${r?` (${Gl(r)})`:""}`),e.push(` Fix: ${_O(i.recommendation)}`)})}return e.push(""),e.join(`
140
+ `)}async function Jy(t){let e=qt.resolve(t.scanPath??process.cwd());try{(await Xy.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 Me(e)}catch(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exit(1)}let s=await ze({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(kO(s))}var je=R(require("node:fs/promises"),1),yn=R(require("node:path"),1),eb=R(require("node:readline"),1);var Ys=ti.filter(t=>t!=="auto"),Zy={severityThreshold:"high",projectType:"auto"},Qy={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
132
141
 
133
142
  ## Project Type
134
143
  TypeScript (General)
@@ -276,57 +285,57 @@ Before finalizing any changes, perform these steps:
276
285
  ## Commands & Scripts
277
286
  - Locate any setup, build, and test scripts in the root directory (e.g. \`Makefile\`, \`package.json\`, or shell scripts).
278
287
  - Run validation commands before considering a task completed.
279
- `};function cr(t,e){let n=tn.resolve(t),s=tn.resolve(n,e);if(!X(n,s))throw new Error(`Path escapes target directory: ${e}`);return s}async function al(t){try{return await Ce.access(t),!0}catch{return!1}}async function Hg(t,e){let n=cr(t,".promptci"),s=tn.join(n,"config.json");await Ce.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=Fg.createInterface({input:process.stdin,output:process.stdout});return new Promise(d=>{f.question(u,p=>{f.close(),d(p.trim())})})},a="auto",c=await Jn(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 y=Is.map((x,w)=>`${w+1}: ${x}`).join(`
280
- `),b=await o(`Select project type:
288
+ `};function Po(t,e){let n=yn.resolve(t),s=yn.resolve(n,e);if(!ue(n,s))throw new Error(`Path escapes target directory: ${e}`);return s}async function Wl(t){try{return await je.access(t),!0}catch{return!1}}async function tb(t,e){let n=Po(t,".promptci"),s=yn.join(n,"config.json");await je.mkdir(n,{recursive:!0});let i=e?.interactive??!1,o=0,r=u=>{if(e?.answers&&o<e.answers.length){let d=e.answers[o];return o++,console.log(`${u}${d}`),Promise.resolve(d)}let p=eb.createInterface({input:process.stdin,output:process.stdout});return new Promise(d=>{p.question(u,h=>{p.close(),d(h.trim())})})},a="auto",c=await ps(t);if(i){let u=await r(`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 y=Ys.map((S,C)=>`${C+1}: ${S}`).join(`
289
+ `),b=await r(`Select project type:
281
290
  ${y}
282
- Enter choice (1-${Is.length} or name): `),v=parseInt(b,10);if(v>=1&&v<=Is.length)a=Is[v-1],m=!0;else{let x=b.toLowerCase().trim();Is.includes(x)?(a=x,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 Ce.access(s),d=!0,console.log(`Config already exists: ${s}`)}catch{}if(!d){let m={...Mg,projectType:a};await Ce.writeFile(s,JSON.stringify(m,null,2)+`
283
- `,"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=cr(t,m);if(await al(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 y,b=0;for(;!y&&b<5;){b++;let v=await o(`Which file type would you like to create?
291
+ Enter choice (1-${Ys.length} or name): `),w=parseInt(b,10);if(w>=1&&w<=Ys.length)a=Ys[w-1],m=!0;else{let S=b.toLowerCase().trim();Ys.includes(S)?(a=S,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 je.access(s),d=!0,console.log(`Config already exists: ${s}`)}catch{}if(!d){let m={...Zy,projectType:a};await je.writeFile(s,JSON.stringify(m,null,2)+`
292
+ `,"utf-8"),console.log(`Created ${s}`)}let h=["AGENTS.md",".cursorrules","CLAUDE.md",".github/copilot-instructions.md"],f=!1;for(let m of h){let g=Po(t,m);if(await Wl(g)){f=!0;break}}if(!f){let m=await r("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 y,b=0;for(;!y&&b<5;){b++;let w=await r(`Which file type would you like to create?
284
293
  1: AGENTS.md (Recommended for monorepos & multi-agent instructions)
285
294
  2: .cursorrules (For Cursor users)
286
295
  3: CLAUDE.md (For Cline/Claude-dev users)
287
- Enter choice (1-3 or name): `);v==="1"||v.toLowerCase()==="agents.md"||v.toLowerCase()==="agents"?y="AGENTS.md":v==="2"||v.toLowerCase()===".cursorrules"||v.toLowerCase()==="cursorrules"?y=".cursorrules":v==="3"||v.toLowerCase()==="claude.md"||v.toLowerCase()==="claude"?y="CLAUDE.md":console.log("Invalid selection. Please try again.")}if(y){let v=cr(t,y);if(await al(v))console.log(`Safety Warning: File already exists: ${v}. Skip writing.`);else{let x=Dg[a]||Dg.unknown;await Ce.mkdir(tn.dirname(v),{recursive:!0}),await Ce.writeFile(v,x,"utf-8"),console.log(`Created starter template: ${v}`)}}else console.log("No valid template selection received. Skipping template generation.")}}}else{try{await Ce.access(s),console.log(`Config already exists: ${s}`),console.log("Remove it first if you want to reinitialize.");return}catch{}await Ce.writeFile(s,JSON.stringify(Mg,null,2)+`
288
- `,"utf-8"),console.log(`Created ${s}`),console.log("Edit it to set include/exclude patterns, severityThreshold, and projectType.")}let l=cr(t,".gitignore");if(await al(l)){let u=await Ce.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
296
+ Enter choice (1-3 or name): `);w==="1"||w.toLowerCase()==="agents.md"||w.toLowerCase()==="agents"?y="AGENTS.md":w==="2"||w.toLowerCase()===".cursorrules"||w.toLowerCase()==="cursorrules"?y=".cursorrules":w==="3"||w.toLowerCase()==="claude.md"||w.toLowerCase()==="claude"?y="CLAUDE.md":console.log("Invalid selection. Please try again.")}if(y){let w=Po(t,y);if(await Wl(w))console.log(`Safety Warning: File already exists: ${w}. Skip writing.`);else{let S=Qy[a]||Qy.unknown;await je.mkdir(yn.dirname(w),{recursive:!0}),await je.writeFile(w,S,"utf-8"),console.log(`Created starter template: ${w}`)}}else console.log("No valid template selection received. Skipping template generation.")}}}else{try{await je.access(s),console.log(`Config already exists: ${s}`),console.log("Remove it first if you want to reinitialize.");return}catch{}await je.writeFile(s,JSON.stringify(Zy,null,2)+`
297
+ `,"utf-8"),console.log(`Created ${s}`),console.log("Edit it to set include/exclude patterns, severityThreshold, and projectType.")}let l=Po(t,".gitignore");if(await Wl(l)){let u=await je.readFile(l,"utf-8");if(!u.split(/\r?\n/).some(h=>{let f=h.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\//,"");return f===".promptci"||f.startsWith(".promptci/")||f.endsWith("/.promptci")||f.includes("/.promptci/")})){let h;if(i){let f=await r("Ignore .promptci/ reports in .gitignore (keeping baseline.json and config.json committed)? (recommended) [Y/n]: ");h=f===""||f.toLowerCase()==="y"||f.toLowerCase()==="yes"}else h=!0;if(h){let f=u.includes(`\r
289
298
  `)?`\r
290
299
  `:`
291
300
  `,g=`${u.length>0&&!u.endsWith(`
292
- `)?h:""}${xs(h)}`;await Ce.appendFile(l,g,"utf-8"),console.log("\u2714 Added .promptci/ report ignore to .gitignore (baseline.json and config.json stay committed)")}}}}var Gg=R(require("node:fs/promises"),1),cl=R(require("node:path"),1);var lr=R(require("node:fs/promises"),1),ct=R(require("node:path"),1),Wg=R(require("node:readline/promises"),1);var nn=class extends Error{constructor(e){super(e),this.name="NonInteractiveError"}},Bg="=".repeat(80),A1="-".repeat(80);async function ur(t,e){let n=e.log??((h="")=>console.log(h)),s=e.interactive!==!1,i=e.promptText??`
293
- Apply this change? (y/N): `,r=!e.dryRun&&s&&!e.answers?Wg.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(x=>ct.resolve(e.repoRoot,x)).filter(x=>p.has(x));if(m.length>0){n(`
294
- `+Bg);for(let w of h.headerLines??[])n(w);let x=m.map(w=>ct.relative(e.repoRoot,w)).join(", ");n(`Skipped: ${x} 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,y=$1(g);if(y.length===0)continue;n(`
295
- `+Bg);let b=h.headerLines??[];for(let x of b)n(x);b.length>0&&n(A1);for(let x of y)P1(x,e.repoRoot,n);if(e.dryRun){n(`
296
- [Dry run] No changes written.`);continue}let v=!0;if(s)if(e.answers){let x=e.answers[d]??"n";d++,n(`${i}${x}`),v=x.toLowerCase().trim()==="y"}else if(r){let x=await l(i);if(x===null)throw new nn("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.");v=x.toLowerCase().trim()==="y"}else v=!1;if(!v){n("Skipped.");continue}for(let x of y){let w=ct.resolve(e.repoRoot,x.filePath);if(!X(e.repoRoot,w))throw new Error(`Path traversal guard triggered: "${x.filePath}" is outside repo root.`);await lr.mkdir(ct.dirname(w),{recursive:!0}),await lr.writeFile(w,x.newContent,"utf-8"),p.add(w),n(`Applied change to ${ct.relative(e.repoRoot,w)}`)}u++}}finally{r?.close()}return{appliedCount:u,staleSkippedCount:f}}function $1(t){let e=new Map;for(let n of t){let s=ct.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 P1(t,e,n){let s=ct.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 Ug(t){let e=t.scanPath??process.cwd(),n=cl.resolve(e);try{(await Gg.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 Re(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 Ne({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude,vagueGuidanceSeverity:s.vagueGuidanceSeverity}),r=i.issues.filter(l=>nl(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:()=>tl(l,n),skipIfModified:l.category==="duplicate"?l.locations.map(u=>cl.resolve(n,u.filePath)):void 0})),a,c;try{({appliedCount:a,staleSkippedCount:c}=await ur(o,{repoRoot:n,dryRun:t.dryRun,interactive:t.interactive,answers:t.answers,promptText:`
297
- Apply this fix? (y/N): `}))}catch(l){throw l instanceof nn&&(console.error(`Error: ${l.message}`),process.exit(1)),l}if(a>0&&!t.dryRun){console.log(`
298
- Re-scanning repository...`);let l=await Ne({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude,vagueGuidanceSeverity:s.vagueGuidanceSeverity});console.log(`
301
+ `)?f:""}${Ds(f)}`;await je.appendFile(l,g,"utf-8"),console.log("\u2714 Added .promptci/ report ignore to .gitignore (baseline.json and config.json stay committed)")}}}}var ib=R(require("node:fs/promises"),1),Vl=R(require("node:path"),1);var $o=R(require("node:fs/promises"),1),wt=R(require("node:path"),1),sb=R(require("node:readline/promises"),1);var bn=class extends Error{constructor(e){super(e),this.name="NonInteractiveError"}},nb="=".repeat(80),EO="-".repeat(80);async function Io(t,e){let n=e.log??((f="")=>console.log(f)),s=e.interactive!==!1,i=e.promptText??`
302
+ Apply this change? (y/N): `,o=!e.dryRun&&s&&!e.answers?sb.createInterface({input:e.input??process.stdin,output:process.stdout}):null,r=[],a=null,c=!1;o&&(o.on("line",f=>{if(a){let m=a;a=null,m(f)}else r.push(f)}),o.on("close",()=>{if(c=!0,a){let f=a;a=null,f(null)}}));function l(f){return process.stdout.write(f),r.length>0?Promise.resolve(r.shift()):c?Promise.resolve(null):new Promise(m=>{a=m})}let u=0,p=0,d=0,h=new Set;try{for(let f of t){let m=(f.skipIfModified??[]).map(S=>wt.resolve(e.repoRoot,S)).filter(S=>h.has(S));if(m.length>0){n(`
303
+ `+nb);for(let C of f.headerLines??[])n(C);let S=m.map(C=>wt.relative(e.repoRoot,C)).join(", ");n(`Skipped: ${S} 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.`),p++;continue}let g=typeof f.changes=="function"?await f.changes():f.changes,y=AO(g);if(y.length===0)continue;n(`
304
+ `+nb);let b=f.headerLines??[];for(let S of b)n(S);b.length>0&&n(EO);for(let S of y)CO(S,e.repoRoot,n);if(e.dryRun){n(`
305
+ [Dry run] No changes written.`);continue}let w=!0;if(s)if(e.answers){let S=e.answers[d]??"n";d++,n(`${i}${S}`),w=S.toLowerCase().trim()==="y"}else if(o){let S=await l(i);if(S===null)throw new bn("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.");w=S.toLowerCase().trim()==="y"}else w=!1;if(!w){n("Skipped.");continue}for(let S of y){let C=wt.resolve(e.repoRoot,S.filePath);if(!ue(e.repoRoot,C))throw new Error(`Path traversal guard triggered: "${S.filePath}" is outside repo root.`);await $o.mkdir(wt.dirname(C),{recursive:!0}),await $o.writeFile(C,S.newContent,"utf-8"),h.add(C),n(`Applied change to ${wt.relative(e.repoRoot,C)}`)}u++}}finally{o?.close()}return{appliedCount:u,staleSkippedCount:p}}function AO(t){let e=new Map;for(let n of t){let s=wt.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 CO(t,e,n){let s=wt.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/),o=t.newContent.split(/\r?\n/);if(i.length===o.length){for(let l=0;l<i.length;l++)i[l]!==o[l]&&(n(` Line ${l+1}:`),n(`\x1B[31m- ${i[l]}\x1B[0m`),n(`\x1B[32m+ ${o[l]}\x1B[0m`));return}let r=0;for(;r<i.length&&r<o.length&&i[r]===o[r];)r++;let a=i.length-1,c=o.length-1;for(;a>=r&&c>=r&&i[a]===o[c];)a--,c--;n(` Replacement in lines ${r+1} to ${a+1}:`);for(let l=r;l<=a;l++)i[l]!==void 0&&n(`\x1B[31m- ${i[l]}\x1B[0m`);for(let l=r;l<=c;l++)o[l]!==void 0&&n(`\x1B[32m+ ${o[l]}\x1B[0m`)}async function ob(t){let e=t.scanPath??process.cwd(),n=Vl.resolve(e);try{(await ib.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 Me(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 ze({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude,vagueGuidanceSeverity:s.vagueGuidanceSeverity}),o=i.issues.filter(l=>Ml(l));if(t.issueId){let l=o.find(u=>u.id===t.issueId);l||(console.error(`Error: No repairable issue found with ID "${t.issueId}".`),process.exit(1)),o=[l]}if(o.length===0){console.log("No repairable issues found.");return}let r=o.map(l=>({headerLines:[`Issue ID: ${l.id}`,`Title: ${l.title}`,`Severity: ${l.severity.toUpperCase()}`,`Summary: ${l.summary}`],changes:()=>Nl(l,n),skipIfModified:l.category==="duplicate"?l.locations.map(u=>Vl.resolve(n,u.filePath)):void 0})),a,c;try{({appliedCount:a,staleSkippedCount:c}=await Io(r,{repoRoot:n,dryRun:t.dryRun,interactive:t.interactive,answers:t.answers,promptText:`
306
+ Apply this fix? (y/N): `}))}catch(l){throw l instanceof bn&&(console.error(`Error: ${l.message}`),process.exit(1)),l}if(a>0&&!t.dryRun){console.log(`
307
+ Re-scanning repository...`);let l=await ze({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude,vagueGuidanceSeverity:s.vagueGuidanceSeverity});console.log(`
299
308
  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(`
300
309
  Dry run complete. No changes were made.`):console.log(`
301
- No changes applied.`)}var Nt=R(require("node:fs/promises"),1),pe=R(require("node:path"),1),zg=R(require("node:os"),1),qg=require("node:child_process");var Kg=["info","warning","high","critical"];function T1(t){return Kg.includes(t)}async function I1(t){try{return await Nt.access(t),!0}catch{return!1}}function sn(t,e){return(0,qg.execFileSync)("git",t,{cwd:e,stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:32*1024*1024}).trim()}function Vg(t,e,n){sn(["worktree","add","--detach",n,e],t)}function O1(t){try{return sn(["rev-parse","--is-shallow-repository"],t)==="true"}catch{return!1}}function L1(t,e){try{sn(["worktree","remove","--force",e],t)}catch{}}async function Yg(t){let e=t.scanPath??process.cwd(),n=pe.resolve(e);t.failOn!==void 0&&!T1(t.failOn)&&(console.error(`Error: invalid --fail-on value "${t.failOn}". Must be one of: ${Kg.join(", ")}`),process.exit(1));let s;try{s=pe.resolve(sn(["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=pe.relative(s,n),r;try{r=sn(["rev-parse","--verify",`${t.baseBranch}^{commit}`],s)}catch{let p=O1(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=sn(["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 Re(n)}catch(p){console.error(`Error: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}let c=await Nt.mkdtemp(pe.join(zg.tmpdir(),"promptci-review-")),l=pe.join(c,"base"),u=pe.join(c,"head"),f=[],d=!1;try{try{Vg(s,r,l),f.push(l),o&&(Vg(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=pe.join(l,i);if(i!==""&&!await I1(p)){let j=pe.join(c,"empty-base");await Nt.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?pe.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 Ne({repoPath:p,...m}),y=await Ne({repoPath:h,...m}),b=(j,I)=>(pe.isAbsolute(j)?pe.relative(I,j):j).replace(/\\/g,"/"),v=(j,I)=>j.map(ee=>({...ee,filePaths:ee.filePaths.map(re=>b(re,I)),locations:ee.locations.map(re=>({...re,filePath:b(re.filePath,I)}))})),x=(j,I)=>j.map(ee=>{let re=ee.filePaths.map(lt=>pe.resolve(I,lt)),_e=ee.locations.map(lt=>({...lt,filePath:pe.resolve(I,lt.filePath)}));return{...ee,filePaths:re,locations:_e}}),w=v(g.issues,p),_=v(y.issues,h),A=g.healthScore,C=y.healthScore,O=C-A,M=vn(w),E=vn(_),{newIssues:U}=xn(_,M),{newIssues:H}=xn(w,E),ne=x(U,n),S=x(H,n);if(t.json){let j={baseScore:A,currentScore:C,scoreDelta:O,newIssuesCount:ne.length,resolvedIssuesCount:S.length,newIssues:ne.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(j,null,2)+`
302
- `)}else{console.log(`PromptCI Branch Review (compared to ${t.baseBranch})`),console.log("--------------------------------------------------");let j="\x1B[32m";if(O<0?j="\x1B[31m":O===0&&(j="\x1B[0m"),console.log(`Health Score: ${A} -> ${C} (${j}${O>=0?"+":""}${O}\x1B[0m points)`),console.log(`New Issues: ${ne.length}`),console.log(`Resolved: ${S.length}`),ne.length>0){console.log(`
303
- [+] New Issues:`);for(let I of ne){let ee=I.locations.length>0?`${I.locations[0].filePath}:${I.locations[0].startLine??""}`:I.filePaths.join(", "),re=I.severity==="critical"||I.severity==="high"?"\x1B[31m":"\x1B[33m";console.log(` - ${re}${I.severity.toUpperCase()}\x1B[0m: ${I.title} (${ee})`),console.log(` Summary: ${I.summary}`),console.log(` Recommend: ${I.recommendation}`)}}if(S.length>0){console.log(`
304
- [-] Resolved Issues:`);for(let I of S)console.log(` - \x1B[32mRESOLVED\x1B[0m: ${I.title}`)}}t.failOnRegression&&(O<0||ne.length>0)&&(d=!0,t.json||console.error(`
305
- \x1B[31mFailed: Regression detected in instruction files.\x1B[0m`));let k=t.failOn;if(k){let j=y.issues.filter(I=>il(I.severity,k)).length;j>0&&(d=!0,t.json||console.error(`
306
- \x1B[31mFailed: ${j} issue(s) at or above "${k}" threshold on this branch.\x1B[0m`))}}finally{for(let p of f)L1(s,p);try{await Nt.rm(c,{recursive:!0,force:!0})}catch{}try{sn(["worktree","prune"],s)}catch{}}d&&process.exit(1)}var Xg=R(require("node:fs/promises"),1),Zg=R(require("node:path"),1);async function Qg(t){let e=Zg.resolve(t);try{(await Xg.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 Jg(t){return{critical:0,high:1,warning:2,info:3}[t.severity]}function N1(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)=>Jg(s)-Jg(i)))e.push(`- [${n.severity}] ${n.title}`)}return e.push(""),e.join(`
307
- `)}async function ey(t){let e=await Qg(t.scanPath??process.cwd()),n;try{n=await Re(e)}catch(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exit(1)}let s=await Zc({repoPath:e,projectType:n.projectType,include:n.include,exclude:n.exclude});t.json?process.stdout.write(JSON.stringify(s,null,2)+`
308
- `):process.stdout.write(N1(s))}async function ty(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 Qg(t.scanPath??process.cwd()),s;try{s=await Re(n)}catch(c){console.error(`Error loading config: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}let i=await ia({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude}),{changes:r}=await sl(i,{repoRoot:n});if(r.length===0){rn("No cache optimization changes needed.");return}rn(e?`
309
- Applying caching optimization changes (${r.length} change(s)):`:`
310
- Proposed caching optimization changes (${r.length} change(s)):`);let o=r.map(c=>({changes:[c]})),a;try{({appliedCount:a}=await ur(o,{repoRoot:n,dryRun:!e,interactive:t.interactive??!1,answers:t.answers,input:t.input,promptText:`
311
- Apply this change? (y/N): `,log:rn}))}catch(c){throw c instanceof nn&&(console.error(`Error: ${c.message}`),process.exit(1)),c}e?a>0?rn(`
312
- Optimization complete.`):rn(`
313
- No changes applied.`):rn(`
314
- Preview only \u2014 no changes were made. Re-run with --write to apply them.`)}function rn(t=""){process.stdout.write(t+`
315
- `)}var on=R(require("node:fs/promises"),1),In=R(require("node:path"),1),ny=require("node:child_process");var ul=22;async function M1(t){try{return await on.access(t),!0}catch{return!1}}async function sy(t){let e=t.scanPath??process.cwd(),n=In.resolve(e);try{(await on.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)>=ul,o=ll().version,a,c="";try{c=(0,ny.execSync)("promptci --version",{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim(),a=c===o}catch{a=null}let l=!0,u,f=In.join(n,".promptci","config.json");try{await on.access(f);try{await Re(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 M1(In.join(n,".git")),m=In.join(n,".gitignore");try{(await on.readFile(m,"utf-8")).split(/\r?\n/).some(v=>{let x=v.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\//,"");return x===".promptci"||x.startsWith(".promptci/")||x.endsWith("/.promptci")||x.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 >= ${ul} (${process.version})`):(console.log(`\x1B[31m[\u2717]\x1B[0m Node.js version is too old (${process.version}). Upgrade to Node ${ul}+`),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 ay=require("node:fs"),jt=R(require("node:fs/promises"),1),Ue=R(require("node:path"),1);var fl="instruction health";function D1(t){switch(_n(t)){case"Healthy":return"brightgreen";case"Fair":return"yellowgreen";case"Needs attention":return"orange";default:return"red"}}function iy(t,e=fl){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:D1(n)}}function ry(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 oy(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 F1=Ue.join(".promptci","health-badge.json");async function H1(t){let e;try{e=await jt.stat(t)}catch{throw new Error(`path does not exist: "${t}"`)}if(!e.isDirectory())throw new Error(`"${t}" is not a directory.`)}async function B1(t){let e;try{e=await jt.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 W1(t){let e=await Re(t);return(await Ne({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 G1(t){let e=t;for(;;){if((0,ay.existsSync)(Ue.join(e,".git")))return e;let n=Ue.dirname(e);if(n===e)return t;e=n}}async function cy(t){let e=Ue.resolve(t.scanPath??process.cwd());await H1(e);let n=t.label?.trim()||fl,s=t.report?await B1(Ue.resolve(e,t.report)):await W1(e),i=iy(s,n),r=Ue.resolve(e,t.output??F1);await jt.mkdir(Ue.dirname(r),{recursive:!0}),await jt.writeFile(r,JSON.stringify(i,null,2)+`
316
- `,"utf-8");let o=u=>Ue.relative(u,r).replace(/\\/g,"/")||r,a=o(e),c=o(G1(e));process.stdout.write(`Wrote ${a} (${i.message}, ${i.color}).
310
+ No changes applied.`)}var Kt=R(require("node:fs/promises"),1),Ee=R(require("node:path"),1),ab=R(require("node:os"),1),cb=require("node:child_process");var lb=["info","warning","high","critical"];function RO(t){return lb.includes(t)}async function TO(t){try{return await Kt.access(t),!0}catch{return!1}}function wn(t,e){return(0,cb.execFileSync)("git",t,{cwd:e,stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:32*1024*1024}).trim()}function rb(t,e,n){wn(["worktree","add","--detach",n,e],t)}function PO(t){try{return wn(["rev-parse","--is-shallow-repository"],t)==="true"}catch{return!1}}function $O(t,e){try{wn(["worktree","remove","--force",e],t)}catch{}}async function ub(t){let e=t.scanPath??process.cwd(),n=Ee.resolve(e);t.failOn!==void 0&&!RO(t.failOn)&&(console.error(`Error: invalid --fail-on value "${t.failOn}". Must be one of: ${lb.join(", ")}`),process.exit(1));let s;try{s=Ee.resolve(wn(["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=Ee.relative(s,n),o;try{o=wn(["rev-parse","--verify",`${t.baseBranch}^{commit}`],s)}catch{let h=PO(s);console.error(`Error: Could not resolve base branch/commit "${t.baseBranch}".`),console.error(h?"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 r;if(!t.workingTree)try{r=wn(["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 Me(n)}catch(h){console.error(`Error: ${h instanceof Error?h.message:String(h)}`),process.exit(1)}let c=await Kt.mkdtemp(Ee.join(ab.tmpdir(),"promptci-review-")),l=Ee.join(c,"base"),u=Ee.join(c,"head"),p=[],d=!1;try{try{rb(s,o,l),p.push(l),r&&(rb(s,r,u),p.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 h=Ee.join(l,i);if(i!==""&&!await TO(h)){let M=Ee.join(c,"empty-base");await Kt.mkdir(M,{recursive:!0}),h=M,console.error(`Note: "${i.replace(/\\/g,"/")}" does not exist in the base commit (${o.slice(0,8)}); every finding under it is reported as new.`)}let f=r?Ee.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 ze({repoPath:h,...m}),y=await ze({repoPath:f,...m}),b=(M,T)=>(Ee.isAbsolute(M)?Ee.relative(T,M):M).replace(/\\/g,"/"),w=(M,T)=>M.map(ne=>({...ne,filePaths:ne.filePaths.map(de=>b(de,T)),locations:ne.locations.map(de=>({...de,filePath:b(de.filePath,T)}))})),S=(M,T)=>M.map(ne=>{let de=ne.filePaths.map(vt=>Ee.resolve(T,vt)),be=ne.locations.map(vt=>({...vt,filePath:Ee.resolve(T,vt.filePath)}));return{...ne,filePaths:de,locations:be}}),C=w(g.issues,h),v=w(y.issues,f),_=g.healthScore,A=y.healthScore,O=A-_,j=Mn(C),x=Mn(v),{newIssues:D}=jn(v,j),{newIssues:U}=jn(C,x),te=S(D,n),k=S(U,n);if(t.json){let M={baseScore:_,currentScore:A,scoreDelta:O,newIssuesCount:te.length,resolvedIssuesCount:k.length,newIssues:te.map(T=>({id:T.id,category:T.category,severity:T.severity,title:T.title,summary:T.summary,filePaths:T.filePaths,locations:T.locations})),resolvedIssues:k.map(T=>({id:T.id,category:T.category,severity:T.severity,title:T.title}))};process.stdout.write(JSON.stringify(M,null,2)+`
311
+ `)}else{console.log(`PromptCI Branch Review (compared to ${t.baseBranch})`),console.log("--------------------------------------------------");let M="\x1B[32m";if(O<0?M="\x1B[31m":O===0&&(M="\x1B[0m"),console.log(`Health Score: ${_} -> ${A} (${M}${O>=0?"+":""}${O}\x1B[0m points)`),console.log(`New Issues: ${te.length}`),console.log(`Resolved: ${k.length}`),te.length>0){console.log(`
312
+ [+] New Issues:`);for(let T of te){let ne=T.locations.length>0?`${T.locations[0].filePath}:${T.locations[0].startLine??""}`:T.filePaths.join(", "),de=T.severity==="critical"||T.severity==="high"?"\x1B[31m":"\x1B[33m";console.log(` - ${de}${T.severity.toUpperCase()}\x1B[0m: ${T.title} (${ne})`),console.log(` Summary: ${T.summary}`),console.log(` Recommend: ${T.recommendation}`)}}if(k.length>0){console.log(`
313
+ [-] Resolved Issues:`);for(let T of k)console.log(` - \x1B[32mRESOLVED\x1B[0m: ${T.title}`)}}t.failOnRegression&&(O<0||te.length>0)&&(d=!0,t.json||console.error(`
314
+ \x1B[31mFailed: Regression detected in instruction files.\x1B[0m`));let E=t.failOn;if(E){let M=y.issues.filter(T=>Hl(T.severity,E)).length;M>0&&(d=!0,t.json||console.error(`
315
+ \x1B[31mFailed: ${M} issue(s) at or above "${E}" threshold on this branch.\x1B[0m`))}}finally{for(let h of p)$O(s,h);try{await Kt.rm(c,{recursive:!0,force:!0})}catch{}try{wn(["worktree","prune"],s)}catch{}}d&&process.exit(1)}var pb=R(require("node:fs/promises"),1),fb=R(require("node:path"),1);async function hb(t){let e=fb.resolve(t);try{(await pb.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 db(t){return{critical:0,high:1,warning:2,info:3}[t.severity]}function IO(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)=>db(s)-db(i)))e.push(`- [${n.severity}] ${n.title}`)}return e.push(""),e.join(`
316
+ `)}async function mb(t){let e=await hb(t.scanPath??process.cwd()),n;try{n=await Me(e)}catch(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exit(1)}let s=await Il({repoPath:e,projectType:n.projectType,include:n.include,exclude:n.exclude});t.json?process.stdout.write(JSON.stringify(s,null,2)+`
317
+ `):process.stdout.write(IO(s))}async function gb(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 hb(t.scanPath??process.cwd()),s;try{s=await Me(n)}catch(c){console.error(`Error loading config: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}let i=await Ea({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude}),{changes:o}=await jl(i,{repoRoot:n});if(o.length===0){vn("No cache optimization changes needed.");return}vn(e?`
318
+ Applying caching optimization changes (${o.length} change(s)):`:`
319
+ Proposed caching optimization changes (${o.length} change(s)):`);let r=o.map(c=>({changes:[c]})),a;try{({appliedCount:a}=await Io(r,{repoRoot:n,dryRun:!e,interactive:t.interactive??!1,answers:t.answers,input:t.input,promptText:`
320
+ Apply this change? (y/N): `,log:vn}))}catch(c){throw c instanceof bn&&(console.error(`Error: ${c.message}`),process.exit(1)),c}e?a>0?vn(`
321
+ Optimization complete.`):vn(`
322
+ No changes applied.`):vn(`
323
+ Preview only \u2014 no changes were made. Re-run with --write to apply them.`)}function vn(t=""){process.stdout.write(t+`
324
+ `)}var Sn=R(require("node:fs/promises"),1),Yn=R(require("node:path"),1),yb=require("node:child_process");var zl=22;async function LO(t){try{return await Sn.access(t),!0}catch{return!1}}async function bb(t){let e=t.scanPath??process.cwd(),n=Yn.resolve(e);try{(await Sn.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,o=parseInt(process.versions.node.split(".")[0],10)>=zl,r=Ul().version,a,c="";try{c=(0,yb.execSync)("promptci --version",{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim(),a=c===r}catch{a=null}let l=!0,u,p=Yn.join(n,".promptci","config.json");try{await Sn.access(p);try{await Me(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,h,f=await LO(Yn.join(n,".git")),m=Yn.join(n,".gitignore");try{(await Sn.readFile(m,"utf-8")).split(/\r?\n/).some(w=>{let S=w.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\//,"");return S===".promptci"||S.startsWith(".promptci/")||S.endsWith("/.promptci")||S.includes("/.promptci/")})?(d="ok",h=".promptci/ is ignored in .gitignore"):(d="missing-rule",h=".promptci/ is not ignored in .gitignore")}catch{f?(d="no-gitignore",h='No .gitignore file found (run "promptci init" to add the .promptci/ rules)'):(d="not-a-repo",h="Not a git repository \u2014 .promptci/ ignore check skipped")}console.log("PromptCI System Diagnostics (Doctor)"),console.log("--------------------------------------------------"),o?console.log(`\x1B[32m[\u2713]\x1B[0m Node.js version >= ${zl} (${process.version})`):(console.log(`\x1B[31m[\u2717]\x1B[0m Node.js version is too old (${process.version}). Upgrade to Node ${zl}+`),s=!0),console.log(`\x1B[32m[\u2713]\x1B[0m PromptCI CLI version (running): ${r}`),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: ${h}`):d==="missing-rule"?(console.log(`\x1B[31m[\u2717]\x1B[0m Gitignore protection: ${h}`),s=!0):console.log(d==="no-gitignore"?`\x1B[33m[!]\x1B[0m Gitignore protection: ${h}`:`\x1B[36m[i]\x1B[0m Gitignore protection: ${h}`),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 _b=require("node:fs"),Yt=R(require("node:fs/promises"),1),et=R(require("node:path"),1);var ql="instruction health";function NO(t){switch(Dn(t)){case"Healthy":return"brightgreen";case"Fair":return"yellowgreen";case"Needs attention":return"orange";default:return"red"}}function wb(t,e=ql){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:NO(n)}}function vb(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 Sb(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 MO=et.join(".promptci","health-badge.json");async function jO(t){let e;try{e=await Yt.stat(t)}catch{throw new Error(`path does not exist: "${t}"`)}if(!e.isDirectory())throw new Error(`"${t}" is not a directory.`)}async function DO(t){let e;try{e=await Yt.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 FO(t){let e=await Me(t);return(await ze({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 HO(t){let e=t;for(;;){if((0,_b.existsSync)(et.join(e,".git")))return e;let n=et.dirname(e);if(n===e)return t;e=n}}async function xb(t){let e=et.resolve(t.scanPath??process.cwd());await jO(e);let n=t.label?.trim()||ql,s=t.report?await DO(et.resolve(e,t.report)):await FO(e),i=wb(s,n),o=et.resolve(e,t.output??MO);await Yt.mkdir(et.dirname(o),{recursive:!0}),await Yt.writeFile(o,JSON.stringify(i,null,2)+`
325
+ `,"utf-8");let r=u=>et.relative(u,o).replace(/\\/g,"/")||o,a=r(e),c=r(HO(e));process.stdout.write(`Wrote ${a} (${i.message}, ${i.color}).
317
326
 
318
327
  Commit it, then add a shields.io endpoint badge to your README:
319
328
 
320
- ${ry(n,c)}
321
- `);let l=oy(c);return l&&process.stdout.write(`
329
+ ${vb(n,c)}
330
+ `);let l=Sb(c);return l&&process.stdout.write(`
322
331
  The recommended PromptCI .gitignore stanza ignores .promptci/*; add an exception so the
323
332
  badge file can be committed:
324
333
 
325
334
  ${l}
326
- `),{outputPath:r,badge:i,score:s}}var On=R(require("node:fs/promises"),1),fr=R(require("node:path"),1),ly=R(require("node:os"),1),U1="https://registry.npmjs.org/@promptci/cli/latest",dl=fr.join(ly.homedir(),".promptci","update-check.json"),V1=1440*60*1e3,z1=2e3;function q1(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 K1(){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 Y1(t){try{let e=JSON.parse(await On.readFile(dl,"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 J1(t){await On.mkdir(fr.dirname(dl),{recursive:!0}),await On.writeFile(dl,JSON.stringify(t,null,2),"utf-8")}async function X1(){try{let t=await fetch(U1,{signal:AbortSignal.timeout(z1)});if(!t.ok)return null;let e=await t.json();return typeof e.version=="string"?e.version:null}catch{return null}}async function uy(t){if(K1())return null;try{let e=Date.now(),n=await Y1(e),s=n?.latest;return(!n||e-n.checkedAt>V1)&&(s=await X1()??s,await J1({checkedAt:e,latest:s})),s&&q1(s,t)?`
335
+ `),{outputPath:o,badge:i,score:s}}var Xn=R(require("node:fs/promises"),1),Oo=R(require("node:path"),1),kb=R(require("node:os"),1),BO="https://registry.npmjs.org/@promptci/cli/latest",Kl=Oo.join(kb.homedir(),".promptci","update-check.json"),GO=1440*60*1e3,WO=2e3;function VO(t,e){let n=o=>{let[r="",...a]=o.trim().replace(/^v/,"").split("-");return{nums:r.split(".").map(c=>parseInt(c,10)||0),pre:a.length>0}},s=n(t),i=n(e);for(let o=0;o<Math.max(s.nums.length,i.nums.length);o++){let r=s.nums[o]??0,a=i.nums[o]??0;if(r!==a)return r>a}return!s.pre&&i.pre}function UO(){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 zO(t){try{let e=JSON.parse(await Xn.readFile(Kl,"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 qO(t){await Xn.mkdir(Oo.dirname(Kl),{recursive:!0}),await Xn.writeFile(Kl,JSON.stringify(t,null,2),"utf-8")}async function KO(){try{let t=await fetch(BO,{signal:AbortSignal.timeout(WO)});if(!t.ok)return null;let e=await t.json();return typeof e.version=="string"?e.version:null}catch{return null}}async function Eb(t){if(UO())return null;try{let e=Date.now(),n=await zO(e),s=n?.latest;return(!n||e-n.checkedAt>GO)&&(s=await KO()??s,await qO({checkedAt:e,latest:s})),s&&VO(s,t)?`
327
336
  A new version of promptci is available: ${t} \u2192 ${s}
328
337
  Update with: npm install -g @promptci/cli (or however you installed it)
329
- `:null}catch{return null}}var{version:pl}=ll(),Je=new cn;Je.name("promptci").description("Instruction health for AI coding workflows").version(pl,"-v, --version","print version");Je.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 jg({scanPath:t.path})});Je.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("--format <format>","output format for stdout and the extra report file: json or sarif (default: human-readable summary; markdown/JSON reports are always written)").option("--output <file>","write markdown report to this path instead of default (SARIF path instead, when --format sarif is set)").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 Ig({scanPath:t.path,json:t.json,format:t.format,cliVersion:pl,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})});Je.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 Ug({scanPath:t.path,issueId:t.issue,interactive:t.interactive,dryRun:t.dryRun||!1})});Je.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 Yg({baseBranch:t.base||"main",scanPath:t.path,json:t.json||!1,failOnRegression:t.failOnRegression||!1,failOn:t.failOn,workingTree:t.workingTree||!1})});Je.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 cy({scanPath:t.path,report:t.report,output:t.output,label:t.label})});Je.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 Hg(t.path??process.cwd(),{interactive:process.stdin.isTTY})});Je.command("doctor").description("Verify local PromptCI configuration, gitignore settings, and system dependencies").option("--path <dir>","target directory (default: current directory)").action(async t=>{await sy({scanPath:t.path})});var fy=Je.command("context").description("Analyze instruction context size, cost, and retrieval-readiness");fy.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 ey({scanPath:t.path,json:t.json})});fy.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 ty({scanPath:t.path,dryRun:t.dryRun,write:t.write})});var Z1=new Set(["score"]);async function Q1(){let t=Promise.resolve(null);Je.hook("preAction",(s,i)=>{Z1.has(i.name())||(t=uy(pl))});let e=process.argv.length<=2?[...process.argv,"score"]:process.argv;await Je.parseAsync(e);let n=await t;n&&process.stderr.write(n)}Q1().catch(t=>{console.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)});
338
+ `:null}catch{return null}}var{version:Yl}=Ul(),at=new xn;at.name("promptci").description("Instruction health for AI coding workflows").version(Yl,"-v, --version","print version");at.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 Jy({scanPath:t.path})});at.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("--format <format>","output format for stdout and the extra report file: json or sarif (default: human-readable summary; markdown/JSON reports are always written)").option("--output <file>","write markdown report to this path instead of default (SARIF path instead, when --format sarif is set)").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 qy({scanPath:t.path,json:t.json,format:t.format,cliVersion:Yl,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})});at.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 ob({scanPath:t.path,issueId:t.issue,interactive:t.interactive,dryRun:t.dryRun||!1})});at.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 ub({baseBranch:t.base||"main",scanPath:t.path,json:t.json||!1,failOnRegression:t.failOnRegression||!1,failOn:t.failOn,workingTree:t.workingTree||!1})});at.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 xb({scanPath:t.path,report:t.report,output:t.output,label:t.label})});at.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 tb(t.path??process.cwd(),{interactive:process.stdin.isTTY})});at.command("doctor").description("Verify local PromptCI configuration, gitignore settings, and system dependencies").option("--path <dir>","target directory (default: current directory)").action(async t=>{await bb({scanPath:t.path})});var Ab=at.command("context").description("Analyze instruction context size, cost, and retrieval-readiness");Ab.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 mb({scanPath:t.path,json:t.json})});Ab.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 gb({scanPath:t.path,dryRun:t.dryRun,write:t.write})});var YO=new Set(["score"]);async function XO(){let t=Promise.resolve(null);at.hook("preAction",(s,i)=>{YO.has(i.name())||(t=Eb(Yl))});let e=process.argv.length<=2?[...process.argv,"score"]:process.argv;await at.parseAsync(e);let n=await t;n&&process.stderr.write(n)}XO().catch(t=>{console.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)});
330
339
  /*! Bundled license information:
331
340
 
332
341
  is-extglob/index.js: