@promptci/cli 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +1 -1
  3. package/dist/cli.cjs +128 -199
  4. package/package.json +12 -11
package/dist/cli.cjs CHANGED
@@ -1,127 +1,113 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var wd=Object.create;var xr=Object.defineProperty;var xd=Object.getOwnPropertyDescriptor;var _d=Object.getOwnPropertyNames;var Sd=Object.getPrototypeOf,Pd=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Cd=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _d(e))!Pd.call(t,i)&&i!==n&&xr(t,i,{get:()=>e[i],enumerable:!(s=xd(e,i))||s.enumerable});return t};var E=(t,e,n)=>(n=t!=null?wd(Sd(t)):{},Cd(e||!t||!t.__esModule?xr(n,"default",{value:t,enumerable:!0}):n,t));var Ft=R(gs=>{var mn=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}},ms=class extends mn{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};gs.CommanderError=mn;gs.InvalidArgumentError=ms});var gn=R(bs=>{var{InvalidArgumentError:Ed}=Ft(),ys=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.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}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 Ed(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,s):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function kd(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}bs.Argument=ys;bs.humanReadableArgName=kd});var ws=R(_r=>{var{humanReadableArgName:Ad}=gn(),vs=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}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=>Ad(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,n.subcommandTerm(i).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((s,i)=>Math.max(s,n.optionTerm(i).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((s,i)=>Math.max(s,n.optionTerm(i).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((s,i)=>Math.max(s,n.argumentTerm(i).length),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=[];return 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?`${e.description} (${n.join(", ")})`: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}formatHelp(e,n){let s=n.padWidth(e,n),i=n.helpWidth||80,o=2,r=2;function a(h,g){if(g){let v=`${h.padEnd(s+r)}${g}`;return n.wrap(v,i-o,s+r)}return h}function c(h){return h.join(`
3
- `).replace(/^/gm," ".repeat(o))}let l=[`Usage: ${n.commandUsage(e)}`,""],u=n.commandDescription(e);u.length>0&&(l=l.concat([n.wrap(u,i,0),""]));let p=n.visibleArguments(e).map(h=>a(n.argumentTerm(h),n.argumentDescription(h)));p.length>0&&(l=l.concat(["Arguments:",c(p),""]));let d=n.visibleOptions(e).map(h=>a(n.optionTerm(h),n.optionDescription(h)));if(d.length>0&&(l=l.concat(["Options:",c(d),""])),this.showGlobalOptions){let h=n.visibleGlobalOptions(e).map(g=>a(n.optionTerm(g),n.optionDescription(g)));h.length>0&&(l=l.concat(["Global Options:",c(h),""]))}let f=n.visibleCommands(e).map(h=>a(n.subcommandTerm(h),n.subcommandDescription(h)));return f.length>0&&(l=l.concat(["Commands:",c(f),""])),l.join(`
4
- `)}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}wrap(e,n,s,i=40){let o=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",r=new RegExp(`[\\n][${o}]+`);if(e.match(r))return e;let a=n-s;if(a<i)return e;let c=e.slice(0,s),l=e.slice(s).replace(`\r
5
- `,`
6
- `),u=" ".repeat(s),d="\\s\u200B",f=new RegExp(`
7
- |.{1,${a-1}}([${d}]|$)|[^${d}]+?([${d}]|$)`,"g"),h=l.match(f)||[];return c+h.map((g,v)=>g===`
8
- `?"":(v>0?u:"")+g.trimEnd()).join(`
9
- `)}};_r.Help=vs});var Ps=R(Ss=>{var{InvalidArgumentError:Rd}=Ft(),xs=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=Td(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}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}_concatValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,s)=>{if(!this.argChoices.includes(n))throw new Rd(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,s):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return $d(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},_s=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 $d(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function Td(t){let e,n,s=t.split(/[ |,]+/);return s.length>1&&!/^[[<]/.test(s[1])&&(e=s.shift()),n=s.shift(),!e&&/^-[^-]$/.test(n)&&(e=n,n=void 0),{shortFlag:e,longFlag:n}}Ss.Option=xs;Ss.DualOptions=_s});var Pr=R(Sr=>{function Ld(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=1;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 Id(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=Ld(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?`
10
- (Did you mean one of ${s.join(", ")}?)`:s.length===1?`
11
- (Did you mean ${s[0]}?)`:""}Sr.suggestSimilar=Id});var Rr=R(Ar=>{var Od=require("node:events").EventEmitter,Cs=require("node:child_process"),Fe=require("node:path"),Es=require("node:fs"),G=require("node:process"),{Argument:jd,humanReadableArgName:Nd}=gn(),{CommanderError:ks}=Ft(),{Help:Md}=ws(),{Option:Cr,DualOptions:Dd}=Ps(),{suggestSimilar:Er}=Pr(),As=class t extends Od{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,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._outputConfiguration={writeOut:n=>G.stdout.write(n),writeErr:n=>G.stderr.write(n),getOutHelpWidth:()=>G.stdout.isTTY?G.stdout.columns:void 0,getErrHelpWidth:()=>G.stderr.isTTY?G.stderr.columns:void 0,outputError:(n,s)=>s(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}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 Md,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(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
12
- - 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 jd(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&&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,this;e=e??"help [command]";let[,s,i]=e.match(/([^ ]+) *(.*)/),o=n??"display help for command",r=this.createCommand(s);return r.helpOption(!1),i&&r.arguments(i),o&&r.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=r,this}addHelpCommand(e,n){return typeof e!="object"?(this.helpCommand(e,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=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}'.
13
- 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 ks(e,n,s)),G.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 Cr(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}'
14
- - already used by option '${n.flags}'`)}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.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),s=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(s,e.defaultValue===void 0?!0:e.defaultValue,"default")}else 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._concatValue(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 Cr)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){G.versions?.electron&&(n.from="electron");let i=G.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(n.from="eval")}e===void 0&&(e=G.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":G.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){let s=this._prepareUserArgs(e,n);return this._parseCommand([],s),this}async parseAsync(e,n){let s=this._prepareUserArgs(e,n);return await this._parseCommand([],s),this}_executeSubCommand(e,n){n=n.slice();let s=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function o(u,p){let d=Fe.resolve(u,p);if(Es.existsSync(d))return d;if(i.includes(Fe.extname(p)))return;let f=i.find(h=>Es.existsSync(`${d}${h}`));if(f)return`${d}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Es.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Fe.resolve(Fe.dirname(u),a)}if(a){let u=o(a,r);if(!u&&!e._executableFile&&this._scriptPath){let p=Fe.basename(this._scriptPath,Fe.extname(this._scriptPath));p!==this._name&&(u=o(a,`${p}-${e._name}`))}r=u||r}s=i.includes(Fe.extname(r));let c;G.platform!=="win32"?s?(n.unshift(r),n=kr(G.execArgv).concat(n),c=Cs.spawn(G.argv[0],n,{stdio:"inherit"})):c=Cs.spawn(r,n,{stdio:"inherit"}):(n.unshift(r),n=kr(G.execArgv).concat(n),c=Cs.spawn(G.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{G.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 ks(u,"commander.executeSubCommandAsync","(close)")):G.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT"){let p=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",d=`'${r}' does not exist
15
- - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2
+ "use strict";var ff=Object.create;var pa=Object.defineProperty;var hf=Object.getOwnPropertyDescriptor;var mf=Object.getOwnPropertyNames;var gf=Object.getPrototypeOf,yf=Object.prototype.hasOwnProperty;var k=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var bf=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of mf(e))!yf.call(t,s)&&s!==n&&pa(t,s,{get:()=>e[s],enumerable:!(i=hf(e,s))||i.enumerable});return t};var E=(t,e,n)=>(n=t!=null?ff(gf(t)):{},bf(e||!t||!t.__esModule?pa(n,"default",{value:t,enumerable:!0}):n,t));var va=k(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.splitWhen=Ot.flatten=void 0;function xf(t){return t.reduce((e,n)=>[].concat(e,n),[])}Ot.flatten=xf;function Sf(t,e){let n=[[]],i=0;for(let s of t)e(s)?(i++,n[i]=[]):n[i].push(s);return n}Ot.splitWhen=Sf});var wa=k(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.isEnoentCodeError=void 0;function Ef(t){return t.code==="ENOENT"}Gn.isEnoentCodeError=Ef});var _a=k(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.createDirentFromStats=void 0;var Ji=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 Cf(t,e){return new Ji(t,e)}Wn.createDirentFromStats=Cf});var Ca=k(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.convertPosixPathToPattern=Y.convertWindowsPathToPattern=Y.convertPathToPattern=Y.escapePosixPath=Y.escapeWindowsPath=Y.escape=Y.removeLeadingDotSegment=Y.makeAbsolute=Y.unixify=void 0;var Pf=require("os"),Af=require("path"),xa=Pf.platform()==="win32",Rf=2,kf=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,$f=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,Tf=/^\\\\([.?])/,Of=/\\(?![!()+@[\]{}])/g;function Lf(t){return t.replace(/\\/g,"/")}Y.unixify=Lf;function If(t,e){return Af.resolve(t,e)}Y.makeAbsolute=If;function jf(t){if(t.charAt(0)==="."){let e=t.charAt(1);if(e==="/"||e==="\\")return t.slice(Rf)}return t}Y.removeLeadingDotSegment=jf;Y.escape=xa?Yi:Xi;function Yi(t){return t.replace($f,"\\$2")}Y.escapeWindowsPath=Yi;function Xi(t){return t.replace(kf,"\\$2")}Y.escapePosixPath=Xi;Y.convertPathToPattern=xa?Sa:Ea;function Sa(t){return Yi(t).replace(Tf,"//$1").replace(Of,"/")}Y.convertWindowsPathToPattern=Sa;function Ea(t){return Xi(t)}Y.convertPosixPathToPattern=Ea});var Aa=k((gS,Pa)=>{Pa.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 $a=k((yS,ka)=>{var Nf=Aa(),Ra={"{":"}","(":")","[":"]"},Mf=function(t){if(t[0]==="!")return!0;for(var e=0,n=-2,i=-2,s=-2,r=-2,o=-2;e<t.length;){if(t[e]==="*"||t[e+1]==="?"&&/[\].+)]/.test(t[e])||i!==-1&&t[e]==="["&&t[e+1]!=="]"&&(i<e&&(i=t.indexOf("]",e)),i>e&&(o===-1||o>i||(o=t.indexOf("\\",e),o===-1||o>i)))||s!==-1&&t[e]==="{"&&t[e+1]!=="}"&&(s=t.indexOf("}",e),s>e&&(o=t.indexOf("\\",e),o===-1||o>s))||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=Ra[a];if(c){var l=t.indexOf(c,e);l!==-1&&(e=l+1)}if(t[e]==="!")return!0}else e++}return!1},Df=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 i=Ra[n];if(i){var s=t.indexOf(i,e);s!==-1&&(e=s+1)}if(t[e]==="!")return!0}else e++}return!1};ka.exports=function(e,n){if(typeof e!="string"||e==="")return!1;if(Nf(e))return!0;var i=Mf;return n&&n.strict===!1&&(i=Df),i(e)}});var Oa=k((bS,Ta)=>{"use strict";var Ff=$a(),Hf=require("path").posix.dirname,Bf=require("os").platform()==="win32",Qi="/",Gf=/\\/g,Wf=/[\{\[].*[\}\]]$/,Vf=/(^|[^\\])([\{\[]|\([^\)]+$)/,qf=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Ta.exports=function(e,n){var i=Object.assign({flipBackslashes:!0},n);i.flipBackslashes&&Bf&&e.indexOf(Qi)<0&&(e=e.replace(Gf,Qi)),Wf.test(e)&&(e+=Qi),e+="a";do e=Hf(e);while(Ff(e)||Vf.test(e));return e.replace(qf,"$1")}});var Vn=k(_e=>{"use strict";_e.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;_e.find=(t,e)=>t.nodes.find(n=>n.type===e);_e.exceedsLimit=(t,e,n=1,i)=>i===!1||!_e.isInteger(t)||!_e.isInteger(e)?!1:(Number(e)-Number(t))/Number(n)>=i;_e.escapeNode=(t,e=0,n)=>{let i=t.nodes[e];i&&(n&&i.type===n||i.type==="open"||i.type==="close")&&i.escaped!==!0&&(i.value="\\"+i.value,i.escaped=!0)};_e.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;_e.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;_e.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;_e.reduce=t=>t.reduce((e,n)=>(n.type==="text"&&e.push(n.value),n.type==="range"&&(n.type="text"),e),[]);_e.flatten=(...t)=>{let e=[],n=i=>{for(let s=0;s<i.length;s++){let r=i[s];if(Array.isArray(r)){n(r);continue}r!==void 0&&e.push(r)}return e};return n(t),e}});var qn=k((wS,Ia)=>{"use strict";var La=Vn();Ia.exports=(t,e={})=>{let n=(i,s={})=>{let r=e.escapeInvalid&&La.isInvalidBrace(s),o=i.invalid===!0&&e.escapeInvalid===!0,a="";if(i.value)return(r||o)&&La.isOpenOrClose(i)?"\\"+i.value:i.value;if(i.value)return i.value;if(i.nodes)for(let c of i.nodes)a+=n(c);return a};return n(t)}});var Na=k((_S,ja)=>{"use strict";ja.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var qa=k((xS,Va)=>{"use strict";var Ma=Na(),ft=(t,e,n)=>{if(Ma(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(Ma(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let i={relaxZeros:!0,...n};typeof i.strictZeros=="boolean"&&(i.relaxZeros=i.strictZeros===!1);let s=String(i.relaxZeros),r=String(i.shorthand),o=String(i.capture),a=String(i.wrap),c=t+":"+e+"="+s+r+o+a;if(ft.cache.hasOwnProperty(c))return ft.cache[c].result;let l=Math.min(t,e),p=Math.max(t,e);if(Math.abs(l-p)===1){let m=t+"|"+e;return i.capture?`(${m})`:i.wrap===!1?m:`(?:${m})`}let u=Wa(t)||Wa(e),d={min:t,max:e,a:l,b:p},f=[],h=[];if(u&&(d.isPadded=u,d.maxLen=String(d.max).length),l<0){let m=p<0?Math.abs(p):1;h=Da(m,Math.abs(l),d,i),l=d.a=0}return p>=0&&(f=Da(l,p,d,i)),d.negatives=h,d.positives=f,d.result=Uf(h,f,i),i.capture===!0?d.result=`(${d.result})`:i.wrap!==!1&&f.length+h.length>1&&(d.result=`(?:${d.result})`),ft.cache[c]=d,d.result};function Uf(t,e,n){let i=Zi(t,e,"-",!1,n)||[],s=Zi(e,t,"",!1,n)||[],r=Zi(t,e,"-?",!0,n)||[];return i.concat(r).concat(s).join("|")}function zf(t,e){let n=1,i=1,s=Ha(t,n),r=new Set([e]);for(;t<=s&&s<=e;)r.add(s),n+=1,s=Ha(t,n);for(s=Ba(e+1,i)-1;t<s&&s<=e;)r.add(s),i+=1,s=Ba(e+1,i)-1;return r=[...r],r.sort(Yf),r}function Kf(t,e,n){if(t===e)return{pattern:t,count:[],digits:0};let i=Jf(t,e),s=i.length,r="",o=0;for(let a=0;a<s;a++){let[c,l]=i[a];c===l?r+=c:c!=="0"||l!=="9"?r+=Xf(c,l,n):o++}return o&&(r+=n.shorthand===!0?"\\d":"[0-9]"),{pattern:r,count:[o],digits:s}}function Da(t,e,n,i){let s=zf(t,e),r=[],o=t,a;for(let c=0;c<s.length;c++){let l=s[c],p=Kf(String(o),String(l),i),u="";if(!n.isPadded&&a&&a.pattern===p.pattern){a.count.length>1&&a.count.pop(),a.count.push(p.count[0]),a.string=a.pattern+Ga(a.count),o=l+1;continue}n.isPadded&&(u=Qf(l,n,i)),p.string=u+p.pattern+Ga(p.count),r.push(p),o=l+1,a=p}return r}function Zi(t,e,n,i,s){let r=[];for(let o of t){let{string:a}=o;!i&&!Fa(e,"string",a)&&r.push(n+a),i&&Fa(e,"string",a)&&r.push(n+a)}return r}function Jf(t,e){let n=[];for(let i=0;i<t.length;i++)n.push([t[i],e[i]]);return n}function Yf(t,e){return t>e?1:e>t?-1:0}function Fa(t,e,n){return t.some(i=>i[e]===n)}function Ha(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function Ba(t,e){return t-t%Math.pow(10,e)}function Ga(t){let[e=0,n=""]=t;return n||e>1?`{${e+(n?","+n:"")}}`:""}function Xf(t,e,n){return`[${t}${e-t===1?"":"-"}${e}]`}function Wa(t){return/^-?(0+)\d/.test(t)}function Qf(t,e,n){if(!e.isPadded)return t;let i=Math.abs(e.maxLen-String(t).length),s=n.relaxZeros!==!1;switch(i){case 0:return"";case 1:return s?"0?":"0";case 2:return s?"0{0,2}":"00";default:return s?`0{0,${i}}`:`0{${i}}`}}ft.cache={};ft.clearCache=()=>ft.cache={};Va.exports=ft});var ns=k((SS,Qa)=>{"use strict";var Zf=require("util"),za=qa(),Ua=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),eh=t=>e=>t===!0?Number(e):String(e),es=t=>typeof t=="number"||typeof t=="string"&&t!=="",on=t=>Number.isInteger(+t),ts=t=>{let e=`${t}`,n=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++n]==="0";);return n>0},th=(t,e,n)=>typeof t=="string"||typeof e=="string"?!0:n.stringify===!0,nh=(t,e,n)=>{if(e>0){let i=t[0]==="-"?"-":"";i&&(t=t.slice(1)),t=i+t.padStart(i?e-1:e,"0")}return n===!1?String(t):t},zn=(t,e)=>{let n=t[0]==="-"?"-":"";for(n&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return n?"-"+t:t},ih=(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 i=e.capture?"":"?:",s="",r="",o;return t.positives.length&&(s=t.positives.map(a=>zn(String(a),n)).join("|")),t.negatives.length&&(r=`-(${i}${t.negatives.map(a=>zn(String(a),n)).join("|")})`),s&&r?o=`${s}|${r}`:o=s||r,e.wrap?`(${i}${o})`:o},Ka=(t,e,n,i)=>{if(n)return za(t,e,{wrap:!1,...i});let s=String.fromCharCode(t);if(t===e)return s;let r=String.fromCharCode(e);return`[${s}-${r}]`},Ja=(t,e,n)=>{if(Array.isArray(t)){let i=n.wrap===!0,s=n.capture?"":"?:";return i?`(${s}${t.join("|")})`:t.join("|")}return za(t,e,n)},Ya=(...t)=>new RangeError("Invalid range arguments: "+Zf.inspect(...t)),Xa=(t,e,n)=>{if(n.strictRanges===!0)throw Ya([t,e]);return[]},sh=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},rh=(t,e,n=1,i={})=>{let s=Number(t),r=Number(e);if(!Number.isInteger(s)||!Number.isInteger(r)){if(i.strictRanges===!0)throw Ya([t,e]);return[]}s===0&&(s=0),r===0&&(r=0);let o=s>r,a=String(t),c=String(e),l=String(n);n=Math.max(Math.abs(n),1);let p=ts(a)||ts(c)||ts(l),u=p?Math.max(a.length,c.length,l.length):0,d=p===!1&&th(t,e,i)===!1,f=i.transform||eh(d);if(i.toRegex&&n===1)return Ka(zn(t,u),zn(e,u),!0,i);let h={negatives:[],positives:[]},m=v=>h[v<0?"negatives":"positives"].push(Math.abs(v)),b=[],y=0;for(;o?s>=r:s<=r;)i.toRegex===!0&&n>1?m(s):b.push(nh(f(s,y),u,d)),s=o?s-n:s+n,y++;return i.toRegex===!0?n>1?ih(h,i,u):Ja(b,null,{wrap:!1,...i}):b},oh=(t,e,n=1,i={})=>{if(!on(t)&&t.length>1||!on(e)&&e.length>1)return Xa(t,e,i);let s=i.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(i.toRegex&&n===1)return Ka(c,l,!1,i);let p=[],u=0;for(;a?r>=o:r<=o;)p.push(s(r,u)),r=a?r-n:r+n,u++;return i.toRegex===!0?Ja(p,null,{wrap:!1,options:i}):p},Un=(t,e,n,i={})=>{if(e==null&&es(t))return[t];if(!es(t)||!es(e))return Xa(t,e,i);if(typeof n=="function")return Un(t,e,1,{transform:n});if(Ua(n))return Un(t,e,0,n);let s={...i};return s.capture===!0&&(s.wrap=!0),n=n||s.step||1,on(n)?on(t)&&on(e)?rh(t,e,n,s):oh(t,e,Math.max(Math.abs(n),1),s):n!=null&&!Ua(n)?sh(n,s):Un(t,e,1,n)};Qa.exports=Un});var tc=k((ES,ec)=>{"use strict";var ah=ns(),Za=Vn(),ch=(t,e={})=>{let n=(i,s={})=>{let r=Za.isInvalidBrace(s),o=i.invalid===!0&&e.escapeInvalid===!0,a=r===!0||o===!0,c=e.escapeInvalid===!0?"\\":"",l="";if(i.isOpen===!0)return c+i.value;if(i.isClose===!0)return console.log("node.isClose",c,i.value),c+i.value;if(i.type==="open")return a?c+i.value:"(";if(i.type==="close")return a?c+i.value:")";if(i.type==="comma")return i.prev.type==="comma"?"":a?i.value:"|";if(i.value)return i.value;if(i.nodes&&i.ranges>0){let p=Za.reduce(i.nodes),u=ah(...p,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(u.length!==0)return p.length>1&&u.length>1?`(${u})`:u}if(i.nodes)for(let p of i.nodes)l+=n(p,i);return l};return n(t)};ec.exports=ch});var sc=k((CS,ic)=>{"use strict";var lh=ns(),nc=qn(),Lt=Vn(),ht=(t="",e="",n=!1)=>{let i=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return n?Lt.flatten(e).map(s=>`{${s}}`):e;for(let s of t)if(Array.isArray(s))for(let r of s)i.push(ht(r,e,n));else for(let r of e)n===!0&&typeof r=="string"&&(r=`{${r}}`),i.push(Array.isArray(r)?ht(s,r,n):s+r);return Lt.flatten(i)},uh=(t,e={})=>{let n=e.rangeLimit===void 0?1e3:e.rangeLimit,i=(s,r={})=>{s.queue=[];let o=r,a=r.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(s.invalid||s.dollar){a.push(ht(a.pop(),nc(s,e)));return}if(s.type==="brace"&&s.invalid!==!0&&s.nodes.length===2){a.push(ht(a.pop(),["{}"]));return}if(s.nodes&&s.ranges>0){let u=Lt.reduce(s.nodes);if(Lt.exceedsLimit(...u,e.step,n))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let d=lh(...u,e);d.length===0&&(d=nc(s,e)),a.push(ht(a.pop(),d)),s.nodes=[];return}let c=Lt.encloseBrace(s),l=s.queue,p=s;for(;p.type!=="brace"&&p.type!=="root"&&p.parent;)p=p.parent,l=p.queue;for(let u=0;u<s.nodes.length;u++){let d=s.nodes[u];if(d.type==="comma"&&s.type==="brace"){u===1&&l.push(""),l.push("");continue}if(d.type==="close"){a.push(ht(a.pop(),l,c));continue}if(d.value&&d.type!=="open"){l.push(ht(l.pop(),d.value));continue}d.nodes&&i(d,s)}return l};return Lt.flatten(i(t))};ic.exports=uh});var oc=k((PS,rc)=>{"use strict";rc.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 pc=k((AS,uc)=>{"use strict";var ph=qn(),{MAX_LENGTH:ac,CHAR_BACKSLASH:is,CHAR_BACKTICK:dh,CHAR_COMMA:fh,CHAR_DOT:hh,CHAR_LEFT_PARENTHESES:mh,CHAR_RIGHT_PARENTHESES:gh,CHAR_LEFT_CURLY_BRACE:yh,CHAR_RIGHT_CURLY_BRACE:bh,CHAR_LEFT_SQUARE_BRACKET:cc,CHAR_RIGHT_SQUARE_BRACKET:lc,CHAR_DOUBLE_QUOTE:vh,CHAR_SINGLE_QUOTE:wh,CHAR_NO_BREAK_SPACE:_h,CHAR_ZERO_WIDTH_NOBREAK_SPACE:xh}=oc(),Sh=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let n=e||{},i=typeof n.maxLength=="number"?Math.min(ac,n.maxLength):ac;if(t.length>i)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${i})`);let s={type:"root",input:t,nodes:[]},r=[s],o=s,a=s,c=0,l=t.length,p=0,u=0,d,f=()=>t[p++],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"});p<l;)if(o=r[r.length-1],d=f(),!(d===xh||d===_h)){if(d===is){h({type:"text",value:(e.keepEscaping?d:"")+f()});continue}if(d===lc){h({type:"text",value:"\\"+d});continue}if(d===cc){c++;let m;for(;p<l&&(m=f());){if(d+=m,m===cc){c++;continue}if(m===is){d+=f();continue}if(m===lc&&(c--,c===0))break}h({type:"text",value:d});continue}if(d===mh){o=h({type:"paren",nodes:[]}),r.push(o),h({type:"text",value:d});continue}if(d===gh){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===vh||d===wh||d===dh){let m=d,b;for(e.keepQuotes!==!0&&(d="");p<l&&(b=f());){if(b===is){d+=b+f();continue}if(b===m){e.keepQuotes===!0&&(d+=b);break}d+=b}h({type:"text",value:d});continue}if(d===yh){u++;let b={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:u,commas:0,ranges:0,nodes:[]};o=h(b),r.push(o),h({type:"open",value:d});continue}if(d===bh){if(o.type!=="brace"){h({type:"text",value:d});continue}let m="close";o=r.pop(),o.close=!0,h({type:m,value:d}),u--,o=r[r.length-1];continue}if(d===fh&&u>0){if(o.ranges>0){o.ranges=0;let m=o.nodes.shift();o.nodes=[m,{type:"text",value:ph(o)}]}h({type:"comma",value:d}),o.commas++;continue}if(d===hh&&u>0&&o.commas===0){let m=o.nodes;if(u===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 b=m[m.length-1];b.value+=a.value+d,a=b,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],b=m.nodes.indexOf(o);m.nodes.splice(b,1,...o.nodes)}while(r.length>0);return h({type:"eos"}),s};uc.exports=Sh});var hc=k((RS,fc)=>{"use strict";var dc=qn(),Eh=tc(),Ch=sc(),Ph=pc(),ye=(t,e={})=>{let n=[];if(Array.isArray(t))for(let i of t){let s=ye.create(i,e);Array.isArray(s)?n.push(...s):n.push(s)}else n=[].concat(ye.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(n=[...new Set(n)]),n};ye.parse=(t,e={})=>Ph(t,e);ye.stringify=(t,e={})=>dc(typeof t=="string"?ye.parse(t,e):t,e);ye.compile=(t,e={})=>(typeof t=="string"&&(t=ye.parse(t,e)),Eh(t,e));ye.expand=(t,e={})=>{typeof t=="string"&&(t=ye.parse(t,e));let n=Ch(t,e);return e.noempty===!0&&(n=n.filter(Boolean)),e.nodupes===!0&&(n=[...new Set(n)]),n};ye.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?ye.compile(t,e):ye.expand(t,e);fc.exports=ye});var an=k((kS,vc)=>{"use strict";var Ah=require("path"),Ne="\\\\/",mc=`[^${Ne}]`,Rh=0,Ve="\\.",kh="\\+",$h="\\?",Kn="\\/",Th="(?=.)",gc="[^/]",ss=`(?:${Kn}|$)`,yc=`(?:^|${Kn})`,rs=`${Ve}{1,2}${ss}`,Oh=`(?!${Ve})`,Lh=`(?!${yc}${rs})`,Ih=`(?!${Ve}{0,1}${ss})`,jh=`(?!${rs})`,Nh=`[^.${Kn}]`,Mh=`${gc}*?`,bc={DOT_LITERAL:Ve,PLUS_LITERAL:kh,QMARK_LITERAL:$h,SLASH_LITERAL:Kn,ONE_CHAR:Th,QMARK:gc,END_ANCHOR:ss,DOTS_SLASH:rs,NO_DOT:Oh,NO_DOTS:Lh,NO_DOT_SLASH:Ih,NO_DOTS_SLASH:jh,QMARK_NO_DOT:Nh,STAR:Mh,START_ANCHOR:yc},Dh={...bc,SLASH_LITERAL:`[${Ne}]`,QMARK:mc,STAR:`${mc}*?`,DOTS_SLASH:`${Ve}{1,2}(?:[${Ne}]|$)`,NO_DOT:`(?!${Ve})`,NO_DOTS:`(?!(?:^|[${Ne}])${Ve}{1,2}(?:[${Ne}]|$))`,NO_DOT_SLASH:`(?!${Ve}{0,1}(?:[${Ne}]|$))`,NO_DOTS_SLASH:`(?!${Ve}{1,2}(?:[${Ne}]|$))`,QMARK_NO_DOT:`[^.${Ne}]`,START_ANCHOR:`(?:^|[${Ne}])`,END_ANCHOR:`(?:[${Ne}]|$)`},Fh={__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"};vc.exports={DEFAULT_MAX_EXTGLOB_RECURSION:Rh,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Fh,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:Ah.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?Dh:bc}}});var cn=k(fe=>{"use strict";var Hh=require("path"),Bh=process.platform==="win32",{REGEX_BACKSLASH:Gh,REGEX_REMOVE_BACKSLASH:Wh,REGEX_SPECIAL_CHARS:Vh,REGEX_SPECIAL_CHARS_GLOBAL:qh}=an();fe.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);fe.hasRegexChars=t=>Vh.test(t);fe.isRegexChar=t=>t.length===1&&fe.hasRegexChars(t);fe.escapeRegex=t=>t.replace(qh,"\\$1");fe.toPosixSlashes=t=>t.replace(Gh,"/");fe.removeBackslashes=t=>t.replace(Wh,e=>e==="\\"?"":e);fe.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};fe.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:Bh===!0||Hh.sep==="\\";fe.escapeLast=(t,e,n)=>{let i=t.lastIndexOf(e,n);return i===-1?t:t[i-1]==="\\"?fe.escapeLast(t,e,i-1):`${t.slice(0,i)}\\${t.slice(i)}`};fe.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};fe.wrapOutput=(t,e={},n={})=>{let i=n.contains?"":"^",s=n.contains?"":"$",r=`${i}(?:${t})${s}`;return e.negated===!0&&(r=`(?:^(?!${r}).*$)`),r}});var Ac=k((TS,Pc)=>{"use strict";var wc=cn(),{CHAR_ASTERISK:os,CHAR_AT:Uh,CHAR_BACKWARD_SLASH:ln,CHAR_COMMA:zh,CHAR_DOT:as,CHAR_EXCLAMATION_MARK:cs,CHAR_FORWARD_SLASH:Cc,CHAR_LEFT_CURLY_BRACE:ls,CHAR_LEFT_PARENTHESES:us,CHAR_LEFT_SQUARE_BRACKET:Kh,CHAR_PLUS:Jh,CHAR_QUESTION_MARK:_c,CHAR_RIGHT_CURLY_BRACE:Yh,CHAR_RIGHT_PARENTHESES:xc,CHAR_RIGHT_SQUARE_BRACKET:Xh}=an(),Sc=t=>t===Cc||t===ln,Ec=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},Qh=(t,e)=>{let n=e||{},i=t.length-1,s=n.parts===!0||n.scanToEnd===!0,r=[],o=[],a=[],c=t,l=-1,p=0,u=0,d=!1,f=!1,h=!1,m=!1,b=!1,y=!1,v=!1,g=!1,S=!1,$=!1,P=0,O,C,I={value:"",depth:0,isGlob:!1},U=()=>l>=i,x=()=>c.charCodeAt(l+1),H=()=>(O=C,c.charCodeAt(++l));for(;l<i;){C=H();let j;if(C===ln){v=I.backslashes=!0,C=H(),C===ls&&(y=!0);continue}if(y===!0||C===ls){for(P++;U()!==!0&&(C=H());){if(C===ln){v=I.backslashes=!0,H();continue}if(C===ls){P++;continue}if(y!==!0&&C===as&&(C=H())===as){if(d=I.isBrace=!0,h=I.isGlob=!0,$=!0,s===!0)continue;break}if(y!==!0&&C===zh){if(d=I.isBrace=!0,h=I.isGlob=!0,$=!0,s===!0)continue;break}if(C===Yh&&(P--,P===0)){y=!1,d=I.isBrace=!0,$=!0;break}}if(s===!0)continue;break}if(C===Cc){if(r.push(l),o.push(I),I={value:"",depth:0,isGlob:!1},$===!0)continue;if(O===as&&l===p+1){p+=2;continue}u=l+1;continue}if(n.noext!==!0&&(C===Jh||C===Uh||C===os||C===_c||C===cs)===!0&&x()===us){if(h=I.isGlob=!0,m=I.isExtglob=!0,$=!0,C===cs&&l===p&&(S=!0),s===!0){for(;U()!==!0&&(C=H());){if(C===ln){v=I.backslashes=!0,C=H();continue}if(C===xc){h=I.isGlob=!0,$=!0;break}}continue}break}if(C===os){if(O===os&&(b=I.isGlobstar=!0),h=I.isGlob=!0,$=!0,s===!0)continue;break}if(C===_c){if(h=I.isGlob=!0,$=!0,s===!0)continue;break}if(C===Kh){for(;U()!==!0&&(j=H());){if(j===ln){v=I.backslashes=!0,H();continue}if(j===Xh){f=I.isBracket=!0,h=I.isGlob=!0,$=!0;break}}if(s===!0)continue;break}if(n.nonegate!==!0&&C===cs&&l===p){g=I.negated=!0,p++;continue}if(n.noparen!==!0&&C===us){if(h=I.isGlob=!0,s===!0){for(;U()!==!0&&(C=H());){if(C===us){v=I.backslashes=!0,C=H();continue}if(C===xc){$=!0;break}}continue}break}if(h===!0){if($=!0,s===!0)continue;break}}n.noext===!0&&(m=!1,h=!1);let B=c,oe="",w="";p>0&&(oe=c.slice(0,p),c=c.slice(p),u-=p),B&&h===!0&&u>0?(B=c.slice(0,u),w=c.slice(u)):h===!0?(B="",w=c):B=c,B&&B!==""&&B!=="/"&&B!==c&&Sc(B.charCodeAt(B.length-1))&&(B=B.slice(0,-1)),n.unescape===!0&&(w&&(w=wc.removeBackslashes(w)),B&&v===!0&&(B=wc.removeBackslashes(B)));let _={prefix:oe,input:t,start:p,base:B,glob:w,isBrace:d,isBracket:f,isGlob:h,isExtglob:m,isGlobstar:b,negated:g,negatedExtglob:S};if(n.tokens===!0&&(_.maxDepth=0,Sc(C)||o.push(I),_.tokens=o),n.parts===!0||n.tokens===!0){let j;for(let T=0;T<r.length;T++){let z=j?j+1:p,X=r[T],ae=t.slice(z,X);n.tokens&&(T===0&&p!==0?(o[T].isPrefix=!0,o[T].value=oe):o[T].value=ae,Ec(o[T]),_.maxDepth+=o[T].depth),(T!==0||ae!=="")&&a.push(ae),j=X}if(j&&j+1<t.length){let T=t.slice(j+1);a.push(T),n.tokens&&(o[o.length-1].value=T,Ec(o[o.length-1]),_.maxDepth+=o[o.length-1].depth)}_.slashes=r,_.parts=a}return _};Pc.exports=Qh});var Oc=k((OS,Tc)=>{"use strict";var un=an(),te=cn(),{MAX_LENGTH:Jn,POSIX_REGEX_SOURCE:Zh,REGEX_NON_SPECIAL_CHARS:em,REGEX_SPECIAL_CHARS_BACKREF:tm,REPLACEMENTS:Rc}=un,nm=(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(s=>te.escapeRegex(s)).join("..")}return n},It=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,kc=t=>{let e=[],n=0,i=0,s=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==='"'){s=s===1?0:1,r+=a;continue}if(s===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")i++;else if(a===")"&&i>0)i--;else if(a==="|"&&i===0){e.push(r),r="";continue}}}r+=a}return e.push(r),e},im=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},$c=t=>{let e=t.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=!0);if(im(e))return e.replace(/\\(.)/g,"$1")},sm=t=>{let e=t.map($c).filter(Boolean);for(let n=0;n<e.length;n++)for(let i=n+1;i<e.length;i++){let s=e[n],r=e[i],o=s[0];if(!(!o||s!==o.repeat(s.length)||r!==o.repeat(r.length))&&(s===r||s.startsWith(r)||r.startsWith(s)))return!0}return!1},ps=(t,e=!0)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let n=0,i=0,s=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==='"'){s=s===1?0:1;continue}if(s!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){i++;continue}if(a===")"&&(i--,i===0))return e===!0&&o!==t.length-1?void 0:{type:t[0],body:t.slice(2,o),end:o}}}}},rm=t=>{let e=0,n=[];for(;e<t.length;){let s=ps(t.slice(e),!1);if(!s||s.type!=="*")return;let r=kc(s.body).map(a=>a.trim());if(r.length!==1)return;let o=$c(r[0]);if(!o||o.length!==1)return;n.push(o),e+=s.end+1}return n.length<1?void 0:`${n.length===1?te.escapeRegex(n[0]):`[${n.map(s=>te.escapeRegex(s)).join("")}]`}*`},om=t=>{let e=0,n=t.trim(),i=ps(n);for(;i;)e++,n=i.body.trim(),i=ps(n);return e},am=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:un.DEFAULT_MAX_EXTGLOB_RECURSION,i=kc(t).map(s=>s.trim());if(i.length>1&&(i.some(s=>s==="")||i.some(s=>/^[*?]+$/.test(s))||sm(i)))return{risky:!0};for(let s of i){let r=rm(s);if(r)return{risky:!0,safeOutput:r};if(om(s)>n)return{risky:!0}}return{risky:!1}},ds=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=Rc[t]||t;let n={...e},i=typeof n.maxLength=="number"?Math.min(Jn,n.maxLength):Jn,s=t.length;if(s>i)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${i}`);let r={type:"bos",value:"",output:n.prepend||""},o=[r],a=n.capture?"":"?:",c=te.isWindows(e),l=un.globChars(c),p=un.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:m,NO_DOT:b,NO_DOT_SLASH:y,NO_DOTS_SLASH:v,QMARK:g,QMARK_NO_DOT:S,STAR:$,START_ANCHOR:P}=l,O=R=>`(${a}(?:(?!${P}${R.dot?m:u}).)*?)`,C=n.dot?"":b,I=n.dot?g:S,U=n.bash===!0?O(n):$;n.capture&&(U=`(${U})`),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:o};t=te.removePrefix(t,x),s=t.length;let H=[],B=[],oe=[],w=r,_,j=()=>x.index===s-1,T=x.peek=(R=1)=>t[x.index+R],z=x.advance=()=>t[++x.index]||"",X=()=>t.slice(x.index+1),ae=(R="",q=0)=>{x.consumed+=R,x.index+=q},We=R=>{x.output+=R.output!=null?R.output:R.value,ae(R.value)},pf=()=>{let R=1;for(;T()==="!"&&(T(2)!=="("||T(3)==="?");)z(),x.start++,R++;return R%2===0?!1:(x.negated=!0,x.start++,!0)},Nn=R=>{x[R]++,oe.push(R)},Je=R=>{x[R]--,oe.pop()},M=R=>{if(w.type==="globstar"){let q=x.braces>0&&(R.type==="comma"||R.type==="brace"),A=R.extglob===!0||H.length&&(R.type==="pipe"||R.type==="paren");R.type!=="slash"&&R.type!=="paren"&&!q&&!A&&(x.output=x.output.slice(0,-w.output.length),w.type="star",w.value="*",w.output=U,x.output+=w.output)}if(H.length&&R.type!=="paren"&&(H[H.length-1].inner+=R.value),(R.value||R.output)&&We(R),w&&w.type==="text"&&R.type==="text"){w.value+=R.value,w.output=(w.output||"")+R.value;return}R.prev=w,o.push(R),w=R},Mn=(R,q)=>{let A={...p[q],conditions:1,inner:""};A.prev=w,A.parens=x.parens,A.output=x.output,A.startIndex=x.index,A.tokensIndex=o.length;let N=(n.capture?"(":"")+A.open;Nn("parens"),M({type:R,value:q,output:x.output?"":h}),M({type:"paren",extglob:!0,value:z(),output:N}),H.push(A)},df=R=>{let q=t.slice(R.startIndex,x.index+1),A=t.slice(R.startIndex+2,x.index),N=am(A,n);if((R.type==="plus"||R.type==="star")&&N.risky){let G=N.safeOutput?(R.output?"":h)+(n.capture?`(${N.safeOutput})`:N.safeOutput):void 0,Le=o[R.tokensIndex];Le.type="text",Le.value=q,Le.output=G||te.escapeRegex(q);for(let Ie=R.tokensIndex+1;Ie<o.length;Ie++)o[Ie].value="",o[Ie].output="",delete o[Ie].suffix;x.output=R.output+Le.output,x.backtrack=!0,M({type:"paren",extglob:!0,value:_,output:""}),Je("parens");return}let W=R.close+(n.capture?")":""),Q;if(R.type==="negate"){let G=U;if(R.inner&&R.inner.length>1&&R.inner.includes("/")&&(G=O(n)),(G!==U||j()||/^\)+$/.test(X()))&&(W=R.close=`)$))${G}`),R.inner.includes("*")&&(Q=X())&&/^\.[^\\/.]+$/.test(Q)){let Le=ds(Q,{...e,fastpaths:!1}).output;W=R.close=`)${Le})${G})`}R.prev.type==="bos"&&(x.negatedExtglob=!0)}M({type:"paren",extglob:!0,value:_,output:W}),Je("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let R=!1,q=t.replace(tm,(A,N,W,Q,G,Le)=>Q==="\\"?(R=!0,A):Q==="?"?N?N+Q+(G?g.repeat(G.length):""):Le===0?I+(G?g.repeat(G.length):""):g.repeat(W.length):Q==="."?u.repeat(W.length):Q==="*"?N?N+Q+(G?U:""):U:N?A:`\\${A}`);return R===!0&&(n.unescape===!0?q=q.replace(/\\/g,""):q=q.replace(/\\+/g,A=>A.length%2===0?"\\\\":A?"\\":"")),q===t&&n.contains===!0?(x.output=t,x):(x.output=te.wrapOutput(q,x,e),x)}for(;!j();){if(_=z(),_==="\0")continue;if(_==="\\"){let A=T();if(A==="/"&&n.bash!==!0||A==="."||A===";")continue;if(!A){_+="\\",M({type:"text",value:_});continue}let N=/^\\+/.exec(X()),W=0;if(N&&N[0].length>2&&(W=N[0].length,x.index+=W,W%2!==0&&(_+="\\")),n.unescape===!0?_=z():_+=z(),x.brackets===0){M({type:"text",value:_});continue}}if(x.brackets>0&&(_!=="]"||w.value==="["||w.value==="[^")){if(n.posix!==!1&&_===":"){let A=w.value.slice(1);if(A.includes("[")&&(w.posix=!0,A.includes(":"))){let N=w.value.lastIndexOf("["),W=w.value.slice(0,N),Q=w.value.slice(N+2),G=Zh[Q];if(G){w.value=W+G,x.backtrack=!0,z(),!r.output&&o.indexOf(w)===1&&(r.output=h);continue}}}(_==="["&&T()!==":"||_==="-"&&T()==="]")&&(_=`\\${_}`),_==="]"&&(w.value==="["||w.value==="[^")&&(_=`\\${_}`),n.posix===!0&&_==="!"&&w.value==="["&&(_="^"),w.value+=_,We({value:_});continue}if(x.quotes===1&&_!=='"'){_=te.escapeRegex(_),w.value+=_,We({value:_});continue}if(_==='"'){x.quotes=x.quotes===1?0:1,n.keepQuotes===!0&&M({type:"text",value:_});continue}if(_==="("){Nn("parens"),M({type:"paren",value:_});continue}if(_===")"){if(x.parens===0&&n.strictBrackets===!0)throw new SyntaxError(It("opening","("));let A=H[H.length-1];if(A&&x.parens===A.parens+1){df(H.pop());continue}M({type:"paren",value:_,output:x.parens?")":"\\)"}),Je("parens");continue}if(_==="["){if(n.nobracket===!0||!X().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(It("closing","]"));_=`\\${_}`}else Nn("brackets");M({type:"bracket",value:_});continue}if(_==="]"){if(n.nobracket===!0||w&&w.type==="bracket"&&w.value.length===1){M({type:"text",value:_,output:`\\${_}`});continue}if(x.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(It("opening","["));M({type:"text",value:_,output:`\\${_}`});continue}Je("brackets");let A=w.value.slice(1);if(w.posix!==!0&&A[0]==="^"&&!A.includes("/")&&(_=`/${_}`),w.value+=_,We({value:_}),n.literalBrackets===!1||te.hasRegexChars(A))continue;let N=te.escapeRegex(w.value);if(x.output=x.output.slice(0,-w.value.length),n.literalBrackets===!0){x.output+=N,w.value=N;continue}w.value=`(${a}${N}|${w.value})`,x.output+=w.value;continue}if(_==="{"&&n.nobrace!==!0){Nn("braces");let A={type:"brace",value:_,output:"(",outputIndex:x.output.length,tokensIndex:x.tokens.length};B.push(A),M(A);continue}if(_==="}"){let A=B[B.length-1];if(n.nobrace===!0||!A){M({type:"text",value:_,output:_});continue}let N=")";if(A.dots===!0){let W=o.slice(),Q=[];for(let G=W.length-1;G>=0&&(o.pop(),W[G].type!=="brace");G--)W[G].type!=="dots"&&Q.unshift(W[G].value);N=nm(Q,n),x.backtrack=!0}if(A.comma!==!0&&A.dots!==!0){let W=x.output.slice(0,A.outputIndex),Q=x.tokens.slice(A.tokensIndex);A.value=A.output="\\{",_=N="\\}",x.output=W;for(let G of Q)x.output+=G.output||G.value}M({type:"brace",value:_,output:N}),Je("braces"),B.pop();continue}if(_==="|"){H.length>0&&H[H.length-1].conditions++,M({type:"text",value:_});continue}if(_===","){let A=_,N=B[B.length-1];N&&oe[oe.length-1]==="braces"&&(N.comma=!0,A="|"),M({type:"comma",value:_,output:A});continue}if(_==="/"){if(w.type==="dot"&&x.index===x.start+1){x.start=x.index+1,x.consumed="",x.output="",o.pop(),w=r;continue}M({type:"slash",value:_,output:f});continue}if(_==="."){if(x.braces>0&&w.type==="dot"){w.value==="."&&(w.output=u);let A=B[B.length-1];w.type="dots",w.output+=_,w.value+=_,A.dots=!0;continue}if(x.braces+x.parens===0&&w.type!=="bos"&&w.type!=="slash"){M({type:"text",value:_,output:u});continue}M({type:"dot",value:_,output:u});continue}if(_==="?"){if(!(w&&w.value==="(")&&n.noextglob!==!0&&T()==="("&&T(2)!=="?"){Mn("qmark",_);continue}if(w&&w.type==="paren"){let N=T(),W=_;if(N==="<"&&!te.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(w.value==="("&&!/[!=<:]/.test(N)||N==="<"&&!/<([!=]|\w+>)/.test(X()))&&(W=`\\${_}`),M({type:"text",value:_,output:W});continue}if(n.dot!==!0&&(w.type==="slash"||w.type==="bos")){M({type:"qmark",value:_,output:S});continue}M({type:"qmark",value:_,output:g});continue}if(_==="!"){if(n.noextglob!==!0&&T()==="("&&(T(2)!=="?"||!/[!=<:]/.test(T(3)))){Mn("negate",_);continue}if(n.nonegate!==!0&&x.index===0){pf();continue}}if(_==="+"){if(n.noextglob!==!0&&T()==="("&&T(2)!=="?"){Mn("plus",_);continue}if(w&&w.value==="("||n.regex===!1){M({type:"plus",value:_,output:d});continue}if(w&&(w.type==="bracket"||w.type==="paren"||w.type==="brace")||x.parens>0){M({type:"plus",value:_});continue}M({type:"plus",value:d});continue}if(_==="@"){if(n.noextglob!==!0&&T()==="("&&T(2)!=="?"){M({type:"at",extglob:!0,value:_,output:""});continue}M({type:"text",value:_});continue}if(_!=="*"){(_==="$"||_==="^")&&(_=`\\${_}`);let A=em.exec(X());A&&(_+=A[0],x.index+=A[0].length),M({type:"text",value:_});continue}if(w&&(w.type==="globstar"||w.star===!0)){w.type="star",w.star=!0,w.value+=_,w.output=U,x.backtrack=!0,x.globstar=!0,ae(_);continue}let R=X();if(n.noextglob!==!0&&/^\([^?]/.test(R)){Mn("star",_);continue}if(w.type==="star"){if(n.noglobstar===!0){ae(_);continue}let A=w.prev,N=A.prev,W=A.type==="slash"||A.type==="bos",Q=N&&(N.type==="star"||N.type==="globstar");if(n.bash===!0&&(!W||R[0]&&R[0]!=="/")){M({type:"star",value:_,output:""});continue}let G=x.braces>0&&(A.type==="comma"||A.type==="brace"),Le=H.length&&(A.type==="pipe"||A.type==="paren");if(!W&&A.type!=="paren"&&!G&&!Le){M({type:"star",value:_,output:""});continue}for(;R.slice(0,3)==="/**";){let Ie=t[x.index+4];if(Ie&&Ie!=="/")break;R=R.slice(3),ae("/**",3)}if(A.type==="bos"&&j()){w.type="globstar",w.value+=_,w.output=O(n),x.output=w.output,x.globstar=!0,ae(_);continue}if(A.type==="slash"&&A.prev.type!=="bos"&&!Q&&j()){x.output=x.output.slice(0,-(A.output+w.output).length),A.output=`(?:${A.output}`,w.type="globstar",w.output=O(n)+(n.strictSlashes?")":"|$)"),w.value+=_,x.globstar=!0,x.output+=A.output+w.output,ae(_);continue}if(A.type==="slash"&&A.prev.type!=="bos"&&R[0]==="/"){let Ie=R[1]!==void 0?"|$":"";x.output=x.output.slice(0,-(A.output+w.output).length),A.output=`(?:${A.output}`,w.type="globstar",w.output=`${O(n)}${f}|${f}${Ie})`,w.value+=_,x.output+=A.output+w.output,x.globstar=!0,ae(_+z()),M({type:"slash",value:"/",output:""});continue}if(A.type==="bos"&&R[0]==="/"){w.type="globstar",w.value+=_,w.output=`(?:^|${f}|${O(n)}${f})`,x.output=w.output,x.globstar=!0,ae(_+z()),M({type:"slash",value:"/",output:""});continue}x.output=x.output.slice(0,-w.output.length),w.type="globstar",w.output=O(n),w.value+=_,x.output+=w.output,x.globstar=!0,ae(_);continue}let q={type:"star",value:_,output:U};if(n.bash===!0){q.output=".*?",(w.type==="bos"||w.type==="slash")&&(q.output=C+q.output),M(q);continue}if(w&&(w.type==="bracket"||w.type==="paren")&&n.regex===!0){q.output=_,M(q);continue}(x.index===x.start||w.type==="slash"||w.type==="dot")&&(w.type==="dot"?(x.output+=y,w.output+=y):n.dot===!0?(x.output+=v,w.output+=v):(x.output+=C,w.output+=C),T()!=="*"&&(x.output+=h,w.output+=h)),M(q)}for(;x.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(It("closing","]"));x.output=te.escapeLast(x.output,"["),Je("brackets")}for(;x.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(It("closing",")"));x.output=te.escapeLast(x.output,"("),Je("parens")}for(;x.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(It("closing","}"));x.output=te.escapeLast(x.output,"{"),Je("braces")}if(n.strictSlashes!==!0&&(w.type==="star"||w.type==="bracket")&&M({type:"maybe_slash",value:"",output:`${f}?`}),x.backtrack===!0){x.output="";for(let R of x.tokens)x.output+=R.output!=null?R.output:R.value,R.suffix&&(x.output+=R.suffix)}return x};ds.fastpaths=(t,e)=>{let n={...e},i=typeof n.maxLength=="number"?Math.min(Jn,n.maxLength):Jn,s=t.length;if(s>i)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${i}`);t=Rc[t]||t;let r=te.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:l,NO_DOT:p,NO_DOTS:u,NO_DOTS_SLASH:d,STAR:f,START_ANCHOR:h}=un.globChars(r),m=n.dot?u:p,b=n.dot?d:p,y=n.capture?"":"?:",v={negated:!1,prefix:""},g=n.bash===!0?".*?":f;n.capture&&(g=`(${g})`);let S=C=>C.noglobstar===!0?g:`(${y}(?:(?!${h}${C.dot?l:o}).)*?)`,$=C=>{switch(C){case"*":return`${m}${c}${g}`;case".*":return`${o}${c}${g}`;case"*.*":return`${m}${g}${o}${c}${g}`;case"*/*":return`${m}${g}${a}${c}${b}${g}`;case"**":return m+S(n);case"**/*":return`(?:${m}${S(n)}${a})?${b}${c}${g}`;case"**/*.*":return`(?:${m}${S(n)}${a})?${b}${g}${o}${c}${g}`;case"**/.*":return`(?:${m}${S(n)}${a})?${o}${c}${g}`;default:{let I=/^(.*?)\.(\w+)$/.exec(C);if(!I)return;let U=$(I[1]);return U?U+o+I[2]:void 0}}},P=te.removePrefix(t,v),O=$(P);return O&&n.strictSlashes!==!0&&(O+=`${a}?`),O};Tc.exports=ds});var Ic=k((LS,Lc)=>{"use strict";var cm=require("path"),lm=Ac(),fs=Oc(),hs=cn(),um=an(),pm=t=>t&&typeof t=="object"&&!Array.isArray(t),K=(t,e,n=!1)=>{if(Array.isArray(t)){let p=t.map(d=>K(d,e,n));return d=>{for(let f of p){let h=f(d);if(h)return h}return!1}}let i=pm(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!i)throw new TypeError("Expected pattern to be a non-empty string");let s=e||{},r=hs.isWindows(e),o=i?K.compileRe(t,e):K.makeRe(t,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(s.ignore){let p={...e,ignore:null,onMatch:null,onResult:null};c=K(s.ignore,p,n)}let l=(p,u=!1)=>{let{isMatch:d,match:f,output:h}=K.test(p,o,e,{glob:t,posix:r}),m={glob:t,state:a,regex:o,posix:r,input:p,output:h,match:f,isMatch:d};return typeof s.onResult=="function"&&s.onResult(m),d===!1?(m.isMatch=!1,u?m:!1):c(p)?(typeof s.onIgnore=="function"&&s.onIgnore(m),m.isMatch=!1,u?m:!1):(typeof s.onMatch=="function"&&s.onMatch(m),u?m:!0)};return n&&(l.state=a),l};K.test=(t,e,n,{glob:i,posix:s}={})=>{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||(s?hs.toPosixSlashes:null),a=t===i,c=a&&o?o(t):t;return a===!1&&(c=o?o(t):t,a=c===i),(a===!1||r.capture===!0)&&(r.matchBase===!0||r.basename===!0?a=K.matchBase(t,e,n,s):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};K.matchBase=(t,e,n,i=hs.isWindows(n))=>(e instanceof RegExp?e:K.makeRe(e,n)).test(cm.basename(t));K.isMatch=(t,e,n)=>K(e,n)(t);K.parse=(t,e)=>Array.isArray(t)?t.map(n=>K.parse(n,e)):fs(t,{...e,fastpaths:!1});K.scan=(t,e)=>lm(t,e);K.compileRe=(t,e,n=!1,i=!1)=>{if(n===!0)return t.output;let s=e||{},r=s.contains?"":"^",o=s.contains?"":"$",a=`${r}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let c=K.toRegex(a,e);return i===!0&&(c.state=t),c};K.makeRe=(t,e={},n=!1,i=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let s={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(s.output=fs.fastpaths(t,e)),s.output||(s=fs(t,e)),K.compileRe(s,e,n,i)};K.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/$^/}};K.constants=um;Lc.exports=K});var Nc=k((IS,jc)=>{"use strict";jc.exports=Ic()});var jt=k((jS,Bc)=>{"use strict";var Dc=require("util"),Fc=hc(),Me=Nc(),ms=cn(),Mc=t=>t===""||t==="./",Hc=t=>{let e=t.indexOf("{");return e>-1&&t.indexOf("}",e)>-1},V=(t,e,n)=>{e=[].concat(e),t=[].concat(t);let i=new Set,s=new Set,r=new Set,o=0,a=p=>{r.add(p.output),n&&n.onResult&&n.onResult(p)};for(let p=0;p<e.length;p++){let u=Me(String(e[p]),{...n,onResult:a},!0),d=u.state.negated||u.state.negatedExtglob;d&&o++;for(let f of t){let h=u(f,!0);(d?!h.isMatch:h.isMatch)&&(d?i.add(h.output):(i.delete(h.output),s.add(h.output)))}}let l=(o===e.length?[...r]:[...s]).filter(p=>!i.has(p));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(p=>p.replace(/\\/g,"")):e}return l};V.match=V;V.matcher=(t,e)=>Me(t,e);V.isMatch=(t,e,n)=>Me(e,n)(t);V.any=V.isMatch;V.not=(t,e,n={})=>{e=[].concat(e).map(String);let i=new Set,s=[],r=a=>{n.onResult&&n.onResult(a),s.push(a.output)},o=new Set(V(t,e,{...n,onResult:r}));for(let a of s)o.has(a)||i.add(a);return[...i]};V.contains=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${Dc.inspect(t)}"`);if(Array.isArray(e))return e.some(i=>V.contains(t,i,n));if(typeof e=="string"){if(Mc(t)||Mc(e))return!1;if(t.includes(e)||t.startsWith("./")&&t.slice(2).includes(e))return!0}return V.isMatch(t,e,{...n,contains:!0})};V.matchKeys=(t,e,n)=>{if(!ms.isObject(t))throw new TypeError("Expected the first argument to be an object");let i=V(Object.keys(t),e,n),s={};for(let r of i)s[r]=t[r];return s};V.some=(t,e,n)=>{let i=[].concat(t);for(let s of[].concat(e)){let r=Me(String(s),n);if(i.some(o=>r(o)))return!0}return!1};V.every=(t,e,n)=>{let i=[].concat(t);for(let s of[].concat(e)){let r=Me(String(s),n);if(!i.every(o=>r(o)))return!1}return!0};V.all=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${Dc.inspect(t)}"`);return[].concat(e).every(i=>Me(i,n)(t))};V.capture=(t,e,n)=>{let i=ms.isWindows(n),r=Me.makeRe(String(t),{...n,capture:!0}).exec(i?ms.toPosixSlashes(e):e);if(r)return r.slice(1).map(o=>o===void 0?"":o)};V.makeRe=(...t)=>Me.makeRe(...t);V.scan=(...t)=>Me.scan(...t);V.parse=(t,e)=>{let n=[];for(let i of[].concat(t||[]))for(let s of Fc(String(i),e))n.push(Me.parse(s,e));return n};V.braces=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return e&&e.nobrace===!0||!Hc(t)?[t]:Fc(t,e)};V.braceExpand=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return V.braces(t,{...e,expand:!0})};V.hasBraces=Hc;Bc.exports=V});var Xc=k(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 Gc=require("path"),dm=Oa(),gs=jt(),Wc="**",fm="\\",hm=/[*?]|^!/,mm=/\[[^[]*]/,gm=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,ym=/[!*+?@]\([^(]*\)/,bm=/,|\.\./,vm=/(?!^)\/{2,}/g;function Vc(t,e={}){return!qc(t,e)}L.isStaticPattern=Vc;function qc(t,e={}){return t===""?!1:!!(e.caseSensitiveMatch===!1||t.includes(fm)||hm.test(t)||mm.test(t)||gm.test(t)||e.extglob!==!1&&ym.test(t)||e.braceExpansion!==!1&&wm(t))}L.isDynamicPattern=qc;function wm(t){let e=t.indexOf("{");if(e===-1)return!1;let n=t.indexOf("}",e+1);if(n===-1)return!1;let i=t.slice(e,n);return bm.test(i)}function _m(t){return Yn(t)?t.slice(1):t}L.convertToPositivePattern=_m;function xm(t){return"!"+t}L.convertToNegativePattern=xm;function Yn(t){return t.startsWith("!")&&t[1]!=="("}L.isNegativePattern=Yn;function Uc(t){return!Yn(t)}L.isPositivePattern=Uc;function Sm(t){return t.filter(Yn)}L.getNegativePatterns=Sm;function Em(t){return t.filter(Uc)}L.getPositivePatterns=Em;function Cm(t){return t.filter(e=>!ys(e))}L.getPatternsInsideCurrentDirectory=Cm;function Pm(t){return t.filter(ys)}L.getPatternsOutsideCurrentDirectory=Pm;function ys(t){return t.startsWith("..")||t.startsWith("./..")}L.isPatternRelatedToParentDirectory=ys;function Am(t){return dm(t,{flipBackslashes:!1})}L.getBaseDirectory=Am;function Rm(t){return t.includes(Wc)}L.hasGlobStar=Rm;function zc(t){return t.endsWith("/"+Wc)}L.endsWithSlashGlobStar=zc;function km(t){let e=Gc.basename(t);return zc(t)||Vc(e)}L.isAffectDepthOfReadingPattern=km;function $m(t){return t.reduce((e,n)=>e.concat(Kc(n)),[])}L.expandPatternsWithBraceExpansion=$m;function Kc(t){let e=gs.braces(t,{expand:!0,nodupes:!0,keepEscaping:!0});return e.sort((n,i)=>n.length-i.length),e.filter(n=>n!=="")}L.expandBraceExpansion=Kc;function Tm(t,e){let{parts:n}=gs.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=Tm;function Jc(t,e){return gs.makeRe(t,e)}L.makeRe=Jc;function Om(t,e){return t.map(n=>Jc(n,e))}L.convertPatternsToRe=Om;function Lm(t,e){return e.some(n=>n.test(t))}L.matchAny=Lm;function Im(t){return t.replace(vm,"/")}L.removeDuplicateSlashes=Im;function jm(t){let e=[],n=[];for(let i of t)Yc(i)?e.push(i):n.push(i);return[e,n]}L.partitionAbsoluteAndRelative=jm;function Yc(t){return Gc.isAbsolute(t)}L.isAbsolute=Yc});var tl=k((MS,el)=>{"use strict";var Nm=require("stream"),Qc=Nm.PassThrough,Mm=Array.prototype.slice;el.exports=Dm;function Dm(){let t=[],e=Mm.call(arguments),n=!1,i=e[e.length-1];i&&!Array.isArray(i)&&i.pipe==null?e.pop():i={};let s=i.end!==!1,r=i.pipeError===!0;i.objectMode==null&&(i.objectMode=!0),i.highWaterMark==null&&(i.highWaterMark=64*1024);let o=Qc(i);function a(){for(let p=0,u=arguments.length;p<u;p++)t.push(Zc(arguments[p],i));return c(),this}function c(){if(n)return;n=!0;let p=t.shift();if(!p){process.nextTick(l);return}Array.isArray(p)||(p=[p]);let u=p.length+1;function d(){--u>0||(n=!1,c())}function f(h){function m(){h.removeListener("merge2UnpipeEnd",m),h.removeListener("end",m),r&&h.removeListener("error",b),d()}function b(y){o.emit("error",y)}if(h._readableState.endEmitted)return d();h.on("merge2UnpipeEnd",m),h.on("end",m),r&&h.on("error",b),h.pipe(o,{end:!1}),h.resume()}for(let h=0;h<p.length;h++)f(p[h]);d()}function l(){n=!1,o.emit("queueDrain"),s&&o.end()}return o.setMaxListeners(0),o.add=a,o.on("unpipe",function(p){p.emit("merge2UnpipeEnd")}),e.length&&a.apply(null,e),o}function Zc(t,e){if(Array.isArray(t))for(let n=0,i=t.length;n<i;n++)t[n]=Zc(t[n],e);else{if(!t._readableState&&t.pipe&&(t=t.pipe(Qc(e))),!t._readableState||!t.pause||!t.pipe)throw new Error("Only readable stream can be merged.");t.pause()}return t}});var il=k(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.merge=void 0;var Fm=tl();function Hm(t){let e=Fm(t);return t.forEach(n=>{n.once("error",i=>e.emit("error",i))}),e.once("close",()=>nl(t)),e.once("end",()=>nl(t)),e}Xn.merge=Hm;function nl(t){t.forEach(e=>e.emit("close"))}});var sl=k(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.isEmpty=Nt.isString=void 0;function Bm(t){return typeof t=="string"}Nt.isString=Bm;function Gm(t){return t===""}Nt.isEmpty=Gm});var qe=k(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.string=ne.stream=ne.pattern=ne.path=ne.fs=ne.errno=ne.array=void 0;var Wm=va();ne.array=Wm;var Vm=wa();ne.errno=Vm;var qm=_a();ne.fs=qm;var Um=Ca();ne.path=Um;var zm=Xc();ne.pattern=zm;var Km=il();ne.stream=Km;var Jm=sl();ne.string=Jm});var cl=k(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.convertPatternGroupToTask=ie.convertPatternGroupsToTasks=ie.groupPatternsByBaseDirectory=ie.getNegativePatternsAsPositive=ie.getPositivePatterns=ie.convertPatternsToTasks=ie.generate=void 0;var Ae=qe();function Ym(t,e){let n=rl(t,e),i=rl(e.ignore,e),s=ol(n),r=al(n,i),o=s.filter(p=>Ae.pattern.isStaticPattern(p,e)),a=s.filter(p=>Ae.pattern.isDynamicPattern(p,e)),c=bs(o,r,!1),l=bs(a,r,!0);return c.concat(l)}ie.generate=Ym;function rl(t,e){let n=t;return e.braceExpansion&&(n=Ae.pattern.expandPatternsWithBraceExpansion(n)),e.baseNameMatch&&(n=n.map(i=>i.includes("/")?i:`**/${i}`)),n.map(i=>Ae.pattern.removeDuplicateSlashes(i))}function bs(t,e,n){let i=[],s=Ae.pattern.getPatternsOutsideCurrentDirectory(t),r=Ae.pattern.getPatternsInsideCurrentDirectory(t),o=vs(s),a=vs(r);return i.push(...ws(o,e,n)),"."in a?i.push(_s(".",r,e,n)):i.push(...ws(a,e,n)),i}ie.convertPatternsToTasks=bs;function ol(t){return Ae.pattern.getPositivePatterns(t)}ie.getPositivePatterns=ol;function al(t,e){return Ae.pattern.getNegativePatterns(t).concat(e).map(Ae.pattern.convertToPositivePattern)}ie.getNegativePatternsAsPositive=al;function vs(t){let e={};return t.reduce((n,i)=>{let s=Ae.pattern.getBaseDirectory(i);return s in n?n[s].push(i):n[s]=[i],n},e)}ie.groupPatternsByBaseDirectory=vs;function ws(t,e,n){return Object.keys(t).map(i=>_s(i,t[i],e,n))}ie.convertPatternGroupsToTasks=ws;function _s(t,e,n,i){return{dynamic:i,positive:e,negative:n,base:t,patterns:[].concat(e,n.map(Ae.pattern.convertToNegativePattern))}}ie.convertPatternGroupToTask=_s});var ul=k(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.read=void 0;function Xm(t,e,n){e.fs.lstat(t,(i,s)=>{if(i!==null){ll(n,i);return}if(!s.isSymbolicLink()||!e.followSymbolicLink){xs(n,s);return}e.fs.stat(t,(r,o)=>{if(r!==null){if(e.throwErrorOnBrokenSymbolicLink){ll(n,r);return}xs(n,s);return}e.markSymbolicLink&&(o.isSymbolicLink=()=>!0),xs(n,o)})})}Qn.read=Xm;function ll(t,e){t(e)}function xs(t,e){t(null,e)}});var pl=k(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.read=void 0;function Qm(t,e){let n=e.fs.lstatSync(t);if(!n.isSymbolicLink()||!e.followSymbolicLink)return n;try{let i=e.fs.statSync(t);return e.markSymbolicLink&&(i.isSymbolicLink=()=>!0),i}catch(i){if(!e.throwErrorOnBrokenSymbolicLink)return n;throw i}}Zn.read=Qm});var dl=k(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.createFileSystemAdapter=Xe.FILE_SYSTEM_ADAPTER=void 0;var ei=require("fs");Xe.FILE_SYSTEM_ADAPTER={lstat:ei.lstat,stat:ei.stat,lstatSync:ei.lstatSync,statSync:ei.statSync};function Zm(t){return t===void 0?Xe.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},Xe.FILE_SYSTEM_ADAPTER),t)}Xe.createFileSystemAdapter=Zm});var fl=k(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var eg=dl(),Ss=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=eg.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}};Es.default=Ss});var mt=k(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.statSync=Qe.stat=Qe.Settings=void 0;var hl=ul(),tg=pl(),Cs=fl();Qe.Settings=Cs.default;function ng(t,e,n){if(typeof e=="function"){hl.read(t,Ps(),e);return}hl.read(t,Ps(e),n)}Qe.stat=ng;function ig(t,e){let n=Ps(e);return tg.read(t,n)}Qe.statSync=ig;function Ps(t={}){return t instanceof Cs.default?t:new Cs.default(t)}});var yl=k((zS,gl)=>{var ml;gl.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:global):t=>(ml||(ml=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var vl=k((KS,bl)=>{bl.exports=rg;var sg=yl();function rg(t,e){let n,i,s,r=!0;Array.isArray(t)?(n=[],i=t.length):(s=Object.keys(t),n={},i=s.length);function o(c){function l(){e&&e(c,n),e=null}r?sg(l):l()}function a(c,l,p){n[c]=p,(--i===0||l)&&o(l)}i?s?s.forEach(function(c){t[c](function(l,p){a(c,l,p)})}):t.forEach(function(c,l){c(function(p,u){a(l,p,u)})}):o(null),r=!1}});var As=k(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var ti=process.versions.node.split(".");if(ti[0]===void 0||ti[1]===void 0)throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var wl=Number.parseInt(ti[0],10),og=Number.parseInt(ti[1],10),_l=10,ag=10,cg=wl>_l,lg=wl===_l&&og>=ag;ni.IS_SUPPORT_READDIR_WITH_FILE_TYPES=cg||lg});var xl=k(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.createDirentFromStats=void 0;var Rs=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 ug(t,e){return new Rs(t,e)}ii.createDirentFromStats=ug});var ks=k(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.fs=void 0;var pg=xl();si.fs=pg});var $s=k(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.joinPathSegments=void 0;function dg(t,e,n){return t.endsWith(n)?t+e:t+n+e}ri.joinPathSegments=dg});var Rl=k(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.readdir=Ze.readdirWithFileTypes=Ze.read=void 0;var fg=mt(),Sl=vl(),hg=As(),El=ks(),Cl=$s();function mg(t,e,n){if(!e.stats&&hg.IS_SUPPORT_READDIR_WITH_FILE_TYPES){Pl(t,e,n);return}Al(t,e,n)}Ze.read=mg;function Pl(t,e,n){e.fs.readdir(t,{withFileTypes:!0},(i,s)=>{if(i!==null){oi(n,i);return}let r=s.map(a=>({dirent:a,name:a.name,path:Cl.joinPathSegments(t,a.name,e.pathSegmentSeparator)}));if(!e.followSymbolicLinks){Ts(n,r);return}let o=r.map(a=>gg(a,e));Sl(o,(a,c)=>{if(a!==null){oi(n,a);return}Ts(n,c)})})}Ze.readdirWithFileTypes=Pl;function gg(t,e){return n=>{if(!t.dirent.isSymbolicLink()){n(null,t);return}e.fs.stat(t.path,(i,s)=>{if(i!==null){if(e.throwErrorOnBrokenSymbolicLink){n(i);return}n(null,t);return}t.dirent=El.fs.createDirentFromStats(t.name,s),n(null,t)})}}function Al(t,e,n){e.fs.readdir(t,(i,s)=>{if(i!==null){oi(n,i);return}let r=s.map(o=>{let a=Cl.joinPathSegments(t,o,e.pathSegmentSeparator);return c=>{fg.stat(a,e.fsStatSettings,(l,p)=>{if(l!==null){c(l);return}let u={name:o,path:a,dirent:El.fs.createDirentFromStats(o,p)};e.stats&&(u.stats=p),c(null,u)})}});Sl(r,(o,a)=>{if(o!==null){oi(n,o);return}Ts(n,a)})})}Ze.readdir=Al;function oi(t,e){t(e)}function Ts(t,e){t(null,e)}});var Ll=k(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.readdir=et.readdirWithFileTypes=et.read=void 0;var yg=mt(),bg=As(),kl=ks(),$l=$s();function vg(t,e){return!e.stats&&bg.IS_SUPPORT_READDIR_WITH_FILE_TYPES?Tl(t,e):Ol(t,e)}et.read=vg;function Tl(t,e){return e.fs.readdirSync(t,{withFileTypes:!0}).map(i=>{let s={dirent:i,name:i.name,path:$l.joinPathSegments(t,i.name,e.pathSegmentSeparator)};if(s.dirent.isSymbolicLink()&&e.followSymbolicLinks)try{let r=e.fs.statSync(s.path);s.dirent=kl.fs.createDirentFromStats(s.name,r)}catch(r){if(e.throwErrorOnBrokenSymbolicLink)throw r}return s})}et.readdirWithFileTypes=Tl;function Ol(t,e){return e.fs.readdirSync(t).map(i=>{let s=$l.joinPathSegments(t,i,e.pathSegmentSeparator),r=yg.statSync(s,e.fsStatSettings),o={name:i,path:s,dirent:kl.fs.createDirentFromStats(i,r)};return e.stats&&(o.stats=r),o})}et.readdir=Ol});var Il=k(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.createFileSystemAdapter=tt.FILE_SYSTEM_ADAPTER=void 0;var Mt=require("fs");tt.FILE_SYSTEM_ADAPTER={lstat:Mt.lstat,stat:Mt.stat,lstatSync:Mt.lstatSync,statSync:Mt.statSync,readdir:Mt.readdir,readdirSync:Mt.readdirSync};function wg(t){return t===void 0?tt.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},tt.FILE_SYSTEM_ADAPTER),t)}tt.createFileSystemAdapter=wg});var jl=k(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});var _g=require("path"),xg=mt(),Sg=Il(),Os=class{constructor(e={}){this._options=e,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=Sg.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,_g.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new xg.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue(e,n){return e??n}};Ls.default=Os});var ai=k(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.Settings=nt.scandirSync=nt.scandir=void 0;var Nl=Rl(),Eg=Ll(),Is=jl();nt.Settings=Is.default;function Cg(t,e,n){if(typeof e=="function"){Nl.read(t,js(),e);return}Nl.read(t,js(e),n)}nt.scandir=Cg;function Pg(t,e){let n=js(e);return Eg.read(t,n)}nt.scandirSync=Pg;function js(t={}){return t instanceof Is.default?t:new Is.default(t)}});var Dl=k((sE,Ml)=>{"use strict";function Ag(t){var e=new t,n=e;function i(){var r=e;return r.next?e=r.next:(e=new t,n=e),r.next=null,r}function s(r){n.next=r,n=r}return{get:i,release:s}}Ml.exports=Ag});var Hl=k((rE,Ns)=>{"use strict";var Rg=Dl();function Fl(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 i=Rg(kg),s=null,r=null,o=0,a=null,c={push:m,drain:he,saturated:he,pause:p,paused:!1,get concurrency(){return n},set concurrency(P){if(!(P>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(n=P,!c.paused)for(;s&&o<n;)o++,y()},running:l,resume:f,idle:h,length:u,getQueue:d,unshift:b,empty:he,kill:v,killAndDrain:g,error:$,abort:S};return c;function l(){return o}function p(){c.paused=!0}function u(){for(var P=s,O=0;P;)P=P.next,O++;return O}function d(){for(var P=s,O=[];P;)O.push(P.value),P=P.next;return O}function f(){if(c.paused){if(c.paused=!1,s===null){o++,y();return}for(;s&&o<n;)o++,y()}}function h(){return o===0&&c.length()===0}function m(P,O){var C=i.get();C.context=t,C.release=y,C.value=P,C.callback=O||he,C.errorHandler=a,o>=n||c.paused?r?(r.next=C,r=C):(s=C,r=C,c.saturated()):(o++,e.call(t,C.value,C.worked))}function b(P,O){var C=i.get();C.context=t,C.release=y,C.value=P,C.callback=O||he,C.errorHandler=a,o>=n||c.paused?s?(C.next=s,s=C):(s=C,r=C,c.saturated()):(o++,e.call(t,C.value,C.worked))}function y(P){P&&i.release(P);var O=s;O&&o<=n?c.paused?o--:(r===s&&(r=null),s=O.next,O.next=null,e.call(t,O.value,O.worked),r===null&&c.empty()):--o===0&&c.drain()}function v(){s=null,r=null,c.drain=he}function g(){s=null,r=null,c.drain(),c.drain=he}function S(){var P=s;for(s=null,r=null;P;){var O=P.next,C=P.callback,I=P.errorHandler,U=P.value,x=P.context;P.value=null,P.callback=he,P.errorHandler=null,I&&I(new Error("abort"),U),C.call(x,new Error("abort")),P.release(P),P=O}c.drain=he}function $(P){a=P}}function he(){}function kg(){this.value=null,this.callback=he,this.next=null,this.release=he,this.context=null,this.errorHandler=null;var t=this;this.worked=function(n,i){var s=t.callback,r=t.errorHandler,o=t.value;t.value=null,t.callback=he,t.errorHandler&&r(n,o),s.call(t.context,n,i),t.release(t)}}function $g(t,e,n){typeof t=="function"&&(n=e,e=t,t=null);function i(p,u){e.call(this,p).then(function(d){u(null,d)},u)}var s=Fl(t,i,n),r=s.push,o=s.unshift;return s.push=a,s.unshift=c,s.drained=l,s;function a(p){var u=new Promise(function(d,f){r(p,function(h,m){if(h){f(h);return}d(m)})});return u.catch(he),u}function c(p){var u=new Promise(function(d,f){o(p,function(h,m){if(h){f(h);return}d(m)})});return u.catch(he),u}function l(){var p=new Promise(function(u){process.nextTick(function(){if(s.idle())u();else{var d=s.drain;s.drain=function(){typeof d=="function"&&d(),u(),s.drain=d}}})});return p}}Ns.exports=Fl;Ns.exports.promise=$g});var ci=k(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.joinPathSegments=De.replacePathSegmentSeparator=De.isAppliedFilter=De.isFatalError=void 0;function Tg(t,e){return t.errorFilter===null?!0:!t.errorFilter(e)}De.isFatalError=Tg;function Og(t,e){return t===null||t(e)}De.isAppliedFilter=Og;function Lg(t,e){return t.split(/[/\\]/).join(e)}De.replacePathSegmentSeparator=Lg;function Ig(t,e,n){return t===""?e:t.endsWith(n)?t+e:t+n+e}De.joinPathSegments=Ig});var Fs=k(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var jg=ci(),Ms=class{constructor(e,n){this._root=e,this._settings=n,this._root=jg.replacePathSegmentSeparator(e,n.pathSegmentSeparator)}};Ds.default=Ms});var Gs=k(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});var Ng=require("events"),Mg=ai(),Dg=Hl(),li=ci(),Fg=Fs(),Hs=class extends Fg.default{constructor(e,n){super(e,n),this._settings=n,this._scandir=Mg.scandir,this._emitter=new Ng.EventEmitter,this._queue=Dg(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 i={directory:e,base:n};this._queue.push(i,s=>{s!==null&&this._handleError(s)})}_worker(e,n){this._scandir(e.directory,this._settings.fsScandirSettings,(i,s)=>{if(i!==null){n(i,void 0);return}for(let r of s)this._handleEntry(r,e.base);n(null,void 0)})}_handleError(e){this._isDestroyed||!li.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 i=e.path;n!==void 0&&(e.path=li.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),li.isAppliedFilter(this._settings.entryFilter,e)&&this._emitEntry(e),e.dirent.isDirectory()&&li.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(i,n===void 0?void 0:e.path)}_emitEntry(e){this._emitter.emit("entry",e)}};Bs.default=Hs});var Bl=k(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});var Hg=Gs(),Ws=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new Hg.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(n=>{Bg(e,n)}),this._reader.onEntry(n=>{this._storage.push(n)}),this._reader.onEnd(()=>{Gg(e,this._storage)}),this._reader.read()}};Vs.default=Ws;function Bg(t,e){t(e)}function Gg(t,e){t(null,e)}});var Gl=k(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var Wg=require("stream"),Vg=Gs(),qs=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new Vg.default(this._root,this._settings),this._stream=new Wg.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}};Us.default=qs});var Wl=k(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var qg=ai(),ui=ci(),Ug=Fs(),zs=class extends Ug.default{constructor(){super(...arguments),this._scandir=qg.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 i=this._scandir(e,this._settings.fsScandirSettings);for(let s of i)this._handleEntry(s,n)}catch(i){this._handleError(i)}}_handleError(e){if(ui.isFatalError(this._settings,e))throw e}_handleEntry(e,n){let i=e.path;n!==void 0&&(e.path=ui.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),ui.isAppliedFilter(this._settings.entryFilter,e)&&this._pushToStorage(e),e.dirent.isDirectory()&&ui.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(i,n===void 0?void 0:e.path)}_pushToStorage(e){this._storage.push(e)}};Ks.default=zs});var Vl=k(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var zg=Wl(),Js=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new zg.default(this._root,this._settings)}read(){return this._reader.read()}};Ys.default=Js});var ql=k(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var Kg=require("path"),Jg=ai(),Xs=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,Kg.sep),this.fsScandirSettings=new Jg.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}};Qs.default=Xs});var di=k(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.Settings=Fe.walkStream=Fe.walkSync=Fe.walk=void 0;var Ul=Bl(),Yg=Gl(),Xg=Vl(),Zs=ql();Fe.Settings=Zs.default;function Qg(t,e,n){if(typeof e=="function"){new Ul.default(t,pi()).read(e);return}new Ul.default(t,pi(e)).read(n)}Fe.walk=Qg;function Zg(t,e){let n=pi(e);return new Xg.default(t,n).read()}Fe.walkSync=Zg;function ey(t,e){let n=pi(e);return new Yg.default(t,n).read()}Fe.walkStream=ey;function pi(t={}){return t instanceof Zs.default?t:new Zs.default(t)}});var fi=k(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});var ty=require("path"),ny=mt(),zl=qe(),er=class{constructor(e){this._settings=e,this._fsStatSettings=new ny.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return ty.resolve(this._settings.cwd,e)}_makeEntry(e,n){let i={name:n,path:n,dirent:zl.fs.createDirentFromStats(n,e)};return this._settings.stats&&(i.stats=e),i}_isFatalError(e){return!zl.errno.isEnoentCodeError(e)&&!this._settings.suppressErrors}};tr.default=er});var sr=k(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});var iy=require("stream"),sy=mt(),ry=di(),oy=fi(),nr=class extends oy.default{constructor(){super(...arguments),this._walkStream=ry.walkStream,this._stat=sy.stat}dynamic(e,n){return this._walkStream(e,n)}static(e,n){let i=e.map(this._getFullEntryPath,this),s=new iy.PassThrough({objectMode:!0});s._write=(r,o,a)=>this._getEntry(i[r],e[r],n).then(c=>{c!==null&&n.entryFilter(c)&&s.push(c),r===i.length-1&&s.end(),a()}).catch(a);for(let r=0;r<i.length;r++)s.write(r);return s}_getEntry(e,n,i){return this._getStat(e).then(s=>this._makeEntry(s,n)).catch(s=>{if(i.errorFilter(s))return null;throw s})}_getStat(e){return new Promise((n,i)=>{this._stat(e,this._fsStatSettings,(s,r)=>s===null?n(r):i(s))})}};ir.default=nr});var Kl=k(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});var ay=di(),cy=fi(),ly=sr(),rr=class extends cy.default{constructor(){super(...arguments),this._walkAsync=ay.walk,this._readerStream=new ly.default(this._settings)}dynamic(e,n){return new Promise((i,s)=>{this._walkAsync(e,n,(r,o)=>{r===null?i(o):s(r)})})}async static(e,n){let i=[],s=this._readerStream.static(e,n);return new Promise((r,o)=>{s.once("error",o),s.on("data",a=>i.push(a)),s.once("end",()=>r(i))})}};or.default=rr});var Jl=k(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});var pn=qe(),ar=class{constructor(e,n,i){this._patterns=e,this._settings=n,this._micromatchOptions=i,this._storage=[],this._fillStorage()}_fillStorage(){for(let e of this._patterns){let n=this._getPatternSegments(e),i=this._splitSegmentsIntoSections(n);this._storage.push({complete:i.length<=1,pattern:e,segments:n,sections:i})}}_getPatternSegments(e){return pn.pattern.getPatternParts(e,this._micromatchOptions).map(i=>pn.pattern.isDynamicPattern(i,this._settings)?{dynamic:!0,pattern:i,patternRe:pn.pattern.makeRe(i,this._micromatchOptions)}:{dynamic:!1,pattern:i})}_splitSegmentsIntoSections(e){return pn.array.splitWhen(e,n=>n.dynamic&&pn.pattern.hasGlobStar(n.pattern))}};cr.default=ar});var Yl=k(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});var uy=Jl(),lr=class extends uy.default{match(e){let n=e.split("/"),i=n.length,s=this._storage.filter(r=>!r.complete||r.segments.length>i);for(let r of s){let o=r.sections[0];if(!r.complete&&i>o.length||n.every((c,l)=>{let p=r.segments[l];return!!(p.dynamic&&p.patternRe.test(c)||!p.dynamic&&p.pattern===c)}))return!0}return!1}};ur.default=lr});var Xl=k(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});var hi=qe(),py=Yl(),pr=class{constructor(e,n){this._settings=e,this._micromatchOptions=n}getFilter(e,n,i){let s=this._getMatcher(n),r=this._getNegativePatternsRe(i);return o=>this._filter(e,o,s,r)}_getMatcher(e){return new py.default(e,this._settings,this._micromatchOptions)}_getNegativePatternsRe(e){let n=e.filter(hi.pattern.isAffectDepthOfReadingPattern);return hi.pattern.convertPatternsToRe(n,this._micromatchOptions)}_filter(e,n,i,s){if(this._isSkippedByDeep(e,n.path)||this._isSkippedSymbolicLink(n))return!1;let r=hi.path.removeLeadingDotSegment(n.path);return this._isSkippedByPositivePatterns(r,i)?!1:this._isSkippedByNegativePatterns(r,s)}_isSkippedByDeep(e,n){return this._settings.deep===1/0?!1:this._getEntryLevel(e,n)>=this._settings.deep}_getEntryLevel(e,n){let i=n.split("/").length;if(e==="")return i;let s=e.split("/").length;return i-s}_isSkippedSymbolicLink(e){return!this._settings.followSymbolicLinks&&e.dirent.isSymbolicLink()}_isSkippedByPositivePatterns(e,n){return!this._settings.baseNameMatch&&!n.match(e)}_isSkippedByNegativePatterns(e,n){return!hi.pattern.matchAny(e,n)}};dr.default=pr});var Ql=k(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});var it=qe(),fr=class{constructor(e,n){this._settings=e,this._micromatchOptions=n,this.index=new Map}getFilter(e,n){let[i,s]=it.pattern.partitionAbsoluteAndRelative(n),r={positive:{all:it.pattern.convertPatternsToRe(e,this._micromatchOptions)},negative:{absolute:it.pattern.convertPatternsToRe(i,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:it.pattern.convertPatternsToRe(s,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return o=>this._filter(o,r)}_filter(e,n){let i=it.path.removeLeadingDotSegment(e.path);if(this._settings.unique&&this._isDuplicateEntry(i)||this._onlyFileFilter(e)||this._onlyDirectoryFilter(e))return!1;let s=this._isMatchToPatternsSet(i,n,e.dirent.isDirectory());return this._settings.unique&&s&&this._createIndexRecord(i),s}_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,i){return!(!this._isMatchToPatterns(e,n.positive.all,i)||this._isMatchToPatterns(e,n.negative.relative,i)||this._isMatchToAbsoluteNegative(e,n.negative.absolute,i))}_isMatchToAbsoluteNegative(e,n,i){if(n.length===0)return!1;let s=it.path.makeAbsolute(this._settings.cwd,e);return this._isMatchToPatterns(s,n,i)}_isMatchToPatterns(e,n,i){if(n.length===0)return!1;let s=it.pattern.matchAny(e,n);return!s&&i?it.pattern.matchAny(e+"/",n):s}};hr.default=fr});var Zl=k(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});var dy=qe(),mr=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return dy.errno.isEnoentCodeError(e)||this._settings.suppressErrors}};gr.default=mr});var tu=k(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});var eu=qe(),yr=class{constructor(e){this._settings=e}getTransformer(){return e=>this._transform(e)}_transform(e){let n=e.path;return this._settings.absolute&&(n=eu.path.makeAbsolute(this._settings.cwd,n),n=eu.path.unixify(n)),this._settings.markDirectories&&e.dirent.isDirectory()&&(n+="/"),this._settings.objectMode?Object.assign(Object.assign({},e),{path:n}):n}};br.default=yr});var mi=k(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});var fy=require("path"),hy=Xl(),my=Ql(),gy=Zl(),yy=tu(),vr=class{constructor(e){this._settings=e,this.errorFilter=new gy.default(this._settings),this.entryFilter=new my.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new hy.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new yy.default(this._settings)}_getRootDirectory(e){return fy.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}}};wr.default=vr});var nu=k(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});var by=Kl(),vy=mi(),_r=class extends vy.default{constructor(){super(...arguments),this._reader=new by.default(this._settings)}async read(e){let n=this._getRootDirectory(e),i=this._getReaderOptions(e);return(await this.api(n,e,i)).map(r=>i.transform(r))}api(e,n,i){return n.dynamic?this._reader.dynamic(e,i):this._reader.static(n.patterns,i)}};xr.default=_r});var iu=k(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});var wy=require("stream"),_y=sr(),xy=mi(),Sr=class extends xy.default{constructor(){super(...arguments),this._reader=new _y.default(this._settings)}read(e){let n=this._getRootDirectory(e),i=this._getReaderOptions(e),s=this.api(n,e,i),r=new wy.Readable({objectMode:!0,read:()=>{}});return s.once("error",o=>r.emit("error",o)).on("data",o=>r.emit("data",i.transform(o))).once("end",()=>r.emit("end")),r.once("close",()=>s.destroy()),r}api(e,n,i){return n.dynamic?this._reader.dynamic(e,i):this._reader.static(n.patterns,i)}};Er.default=Sr});var su=k(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});var Sy=mt(),Ey=di(),Cy=fi(),Cr=class extends Cy.default{constructor(){super(...arguments),this._walkSync=Ey.walkSync,this._statSync=Sy.statSync}dynamic(e,n){return this._walkSync(e,n)}static(e,n){let i=[];for(let s of e){let r=this._getFullEntryPath(s),o=this._getEntry(r,s,n);o===null||!n.entryFilter(o)||i.push(o)}return i}_getEntry(e,n,i){try{let s=this._getStat(e);return this._makeEntry(s,n)}catch(s){if(i.errorFilter(s))return null;throw s}}_getStat(e){return this._statSync(e,this._fsStatSettings)}};Pr.default=Cr});var ru=k(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});var Py=su(),Ay=mi(),Ar=class extends Ay.default{constructor(){super(...arguments),this._reader=new Py.default(this._settings)}read(e){let n=this._getRootDirectory(e),i=this._getReaderOptions(e);return this.api(n,e,i).map(i.transform)}api(e,n,i){return n.dynamic?this._reader.dynamic(e,i):this._reader.static(n.patterns,i)}};Rr.default=Ar});var ou=k(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var Dt=require("fs"),Ry=require("os"),ky=Math.max(Ry.cpus().length,1);Ft.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:Dt.lstat,lstatSync:Dt.lstatSync,stat:Dt.stat,statSync:Dt.statSync,readdir:Dt.readdir,readdirSync:Dt.readdirSync};var kr=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,ky),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({},Ft.DEFAULT_FILE_SYSTEM_ADAPTER),e)}};Ft.default=kr});var gi=k(($E,cu)=>{"use strict";var au=cl(),$y=nu(),Ty=iu(),Oy=ru(),$r=ou(),xe=qe();async function Tr(t,e){Re(t);let n=Or(t,$y.default,e),i=await Promise.all(n);return xe.array.flatten(i)}(function(t){t.glob=t,t.globSync=e,t.globStream=n,t.async=t;function e(l,p){Re(l);let u=Or(l,Oy.default,p);return xe.array.flatten(u)}t.sync=e;function n(l,p){Re(l);let u=Or(l,Ty.default,p);return xe.stream.merge(u)}t.stream=n;function i(l,p){Re(l);let u=[].concat(l),d=new $r.default(p);return au.generate(u,d)}t.generateTasks=i;function s(l,p){Re(l);let u=new $r.default(p);return xe.pattern.isDynamicPattern(l,u)}t.isDynamicPattern=s;function r(l){return Re(l),xe.path.escape(l)}t.escapePath=r;function o(l){return Re(l),xe.path.convertPathToPattern(l)}t.convertPathToPattern=o;let a;(function(l){function p(d){return Re(d),xe.path.escapePosixPath(d)}l.escapePath=p;function u(d){return Re(d),xe.path.convertPosixPathToPattern(d)}l.convertPathToPattern=u})(a=t.posix||(t.posix={}));let c;(function(l){function p(d){return Re(d),xe.path.escapeWindowsPath(d)}l.escapePath=p;function u(d){return Re(d),xe.path.convertWindowsPathToPattern(d)}l.convertPathToPattern=u})(c=t.win32||(t.win32={}))})(Tr||(Tr={}));function Or(t,e,n){let i=[].concat(t),s=new $r.default(n),r=au.generate(i,s),o=new e(s);return r.map(o.read,o)}function Re(t){if(![].concat(t).every(i=>xe.string.isString(i)&&!xe.string.isEmpty(i)))throw new TypeError("Patterns must be a string (non empty) or an array of strings")}cu.exports=Tr});var ca=k((rR,Ox)=>{Ox.exports={name:"@promptci/cli",version:"0.1.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.2.0",commander:"^15.0.0",esbuild:"^0.28.2",typescript:"*",vitest:"^4.1.10"},publishConfig:{access:"public"}}});var Ye=class extends Error{constructor(e,n,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},dt=class extends Ye{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};var nn=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,i)=>{if(!this.argChoices.includes(n))throw new dt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,i):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Dn(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}var ga=require("node:events"),Hn=E(require("node:child_process"),1),je=E(require("node:path"),1),rn=E(require("node:fs"),1),F=E(require("node:process"),1),ya=require("node:util");var da=require("node:util"),sn=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(s=>!s._hidden),i=e._getHelpCommand();return i&&!i._hidden&&n.push(i),this.sortSubcommands&&n.sort((s,r)=>s.name().localeCompare(r.name())),n}compareOptions(e,n){let i=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return i(e).localeCompare(i(n))}visibleOptions(e){let n=e.options.filter(s=>!s.hidden),i=e._getHelpOption();if(i&&!i.hidden){let s=i.short&&e._findOption(i.short),r=i.long&&e._findOption(i.long);!s&&!r?n.push(i):i.long&&!r?n.push(e.createOption(i.long,i.description)):i.short&&!s&&n.push(e.createOption(i.short,i.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let i=e.parent;i;i=i.parent){let s=i.options.filter(r=>!r.hidden);n.push(...s)}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(i=>Dn(i)).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((i,s)=>Math.max(i,this.displayWidth(n.styleSubcommandTerm(n.subcommandTerm(s)))),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((i,s)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(s)))),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((i,s)=>Math.max(i,this.displayWidth(n.styleOptionTerm(n.optionTerm(s)))),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((i,s)=>Math.max(i,this.displayWidth(n.styleArgumentTerm(n.argumentTerm(s)))),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let i="";for(let s=e.parent;s;s=s.parent)i=s.name()+" "+i;return i+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(i=>JSON.stringify(i)).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 i=`(${n.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let i=`(${n.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatItemList(e,n,i){return n.length===0?[]:[i.styleTitle(e),...n,""]}groupItems(e,n,i){let s=new Map;return e.forEach(r=>{let o=i(r);s.has(o)||s.set(o,[])}),n.forEach(r=>{let o=i(r);s.has(o)||s.set(o,[]),s.get(o).push(r)}),s}formatHelp(e,n){let i=n.padWidth(e,n),s=n.helpWidth??80;function r(u,d){return n.formatItem(u,i,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),s),""]));let c=n.visibleArguments(e).map(u=>r(n.styleArgumentTerm(n.argumentTerm(u)),n.styleArgumentDescription(n.argumentDescription(u))));if(o=o.concat(this.formatItemList("Arguments:",c,n)),this.groupItems(e.options,n.visibleOptions(e),u=>u.helpGroupHeading??"Options:").forEach((u,d)=>{let f=u.map(h=>r(n.styleOptionTerm(n.optionTerm(h)),n.styleOptionDescription(n.optionDescription(h))));o=o.concat(this.formatItemList(d,f,n))}),n.showGlobalOptions){let u=n.visibleGlobalOptions(e).map(d=>r(n.styleOptionTerm(n.optionTerm(d)),n.styleOptionDescription(n.optionDescription(d))));o=o.concat(this.formatItemList("Global Options:",u,n))}return this.groupItems(e.commands,n.visibleCommands(e),u=>u.helpGroup()||"Commands:").forEach((u,d)=>{let f=u.map(h=>r(n.styleSubcommandTerm(n.subcommandTerm(h)),n.styleSubcommandDescription(n.subcommandDescription(h))));o=o.concat(this.formatItemList(d,f,n))}),o.join(`
4
+ `)}displayWidth(e){return(0,da.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,i,s){let o=" ".repeat(2);if(!i)return o+e;let a=e.padEnd(n+e.length-s.displayWidth(e)),c=2,p=(this.helpWidth??80)-n-c-2,u;return p<this.minWidthToWrap||s.preformatted(i)?u=i:u=s.boxWrap(i,p).replace(/\n/g,`
5
+ `+" ".repeat(n+c)),o+a+" ".repeat(c)+u.replace(/\n/g,`
6
+ ${o}`)}boxWrap(e,n){if(n<this.minWidthToWrap)return e;let i=e.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,r=[];return i.forEach(o=>{let a=o.match(s);if(a===null){r.push("");return}let c=[a.shift()],l=this.displayWidth(c[0]);a.forEach(p=>{let u=this.displayWidth(p);if(l+u<=n){c.push(p),l+=u;return}r.push(c.join(""));let d=p.trimStart();c=[d],l=this.displayWidth(d)}),r.push(c.join(""))}),r.join(`
7
+ `)}};var $t=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 i=vf(e);this.short=i.shortFlag,this.long=i.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,i)=>{if(!this.argChoices.includes(n))throw new dt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(n,i):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?fa(this.name().replace(/^no-/,"")):fa(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}},Fn=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,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,n){let i=n.attributeName();if(!this.dualOptions.has(i))return!0;let s=this.negativeOptions.get(i).presetArg,r=s!==void 0?s:!1;return n.negate===(r===e)}};function fa(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function vf(t){let e,n,i=/^-[^-]$/,s=/^--[^-]/,r=t.split(/[ |,]+/).concat("guard");if(i.test(r[0])&&(e=r.shift()),s.test(r[0])&&(n=r.shift()),!e&&i.test(r[0])&&(e=r.shift()),!e&&s.test(r[0])&&(e=n,n=r.shift()),r[0].startsWith("-")){let o=r[0],a=`option creation failed due to '${o}' in option flags '${t}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
8
+ - a short flag is a single dash and a single character
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')`):i.test(o)?new Error(`${a}
11
+ - too many short flags`):s.test(o)?new Error(`${a}
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 wf(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let i=0;i<=t.length;i++)n[i]=[i];for(let i=0;i<=e.length;i++)n[0][i]=i;for(let i=1;i<=e.length;i++)for(let s=1;s<=t.length;s++){let r;t[s-1]===e[i-1]?r=0:r=1,n[s][i]=Math.min(n[s-1][i]+1,n[s][i-1]+1,n[s-1][i-1]+r),s>1&&i>1&&t[s-1]===e[i-2]&&t[s-2]===e[i-1]&&(n[s][i]=Math.min(n[s][i],n[s-2][i-2]+1))}return n[t.length][e.length]}function Ki(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 i=[],s=3,r=.4;return e.forEach(o=>{if(o.length<=1)return;let a=wf(t,o),c=Math.max(t.length,o.length);(c-a)/c>r&&(a<s?(s=a,i=[o]):a===s&&i.push(o))}),i.sort((o,a)=>o.localeCompare(a)),n&&(i=i.map(o=>`--${o}`)),i.length>1?`
14
+ (Did you mean one of ${i.join(", ")}?)`:i.length===1?`
15
+ (Did you mean ${i[0]}?)`:""}var Tt=class t extends ga.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=>F.default.stdout.write(n),writeErr:n=>F.default.stderr.write(n),outputError:(n,i)=>i(n),getOutHelpWidth:()=>F.default.stdout.isTTY?F.default.stdout.columns:void 0,getErrHelpWidth:()=>F.default.stderr.isTTY?F.default.stderr.columns:void 0,getOutHasColors:()=>ma()??(F.default.stdout.isTTY&&F.default.stdout.hasColors?.()),getErrHasColors:()=>ma()??(F.default.stderr.isTTY&&F.default.stderr.hasColors?.()),stripColor:n=>(0,ya.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,i){let s=n,r=i;typeof s=="object"&&s!==null&&(r=s,s=null),r=r||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return s&&(c.description(s),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),s?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new sn,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 nn(e,n)}argument(e,n,i,s){let r=this.createArgument(e,n);return typeof i=="function"?r.default(s).argParser(i):r.default(i),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 i=e??"help [command]",[,s,r]=i.match(/([^ ]+) *(.*)/),o=n??"display help for command",a=this.createCommand(s);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 i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
17
+ Expecting one of '${i.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,i){this._exitCallback&&this._exitCallback(new Ye(e,n,i)),F.default.exit(e)}action(e){let n=i=>{let s=this.registeredArguments.length,r=i.slice(0,s);return this._storeOptionsAsProperties?r[s]=this:r[s]=this.opts(),r.push(this),e.apply(this,r)};return this._actionHandler=n,this}createOption(e,n){return new $t(e,n)}_callParseArg(e,n,i,s){try{return e.parseArg(n,i)}catch(r){if(r.code==="commander.invalidArgument"){let o=`${s} ${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 i=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 '${i}'
18
+ - already used by option '${n.flags}'`)}this._initOptionGroup(e),this.options.push(e)}_registerCommand(e){let n=s=>[s.name()].concat(s.aliases()),i=n(e).find(s=>this._findCommand(s));if(i){let s=n(this._findCommand(i)).join("|"),r=n(e).join("|");throw new Error(`cannot add command '${r}' as already have command '${s}'`)}this._initCommandGroup(e),this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),i=e.attributeName();e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let s=(r,o,a)=>{r==null&&e.presetArg!==void 0&&(r=e.presetArg);let c=this.getOptionValue(i);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(i,r,a)};return this.on("option:"+n,r=>{let o=`error: option '${e.flags}' argument '${r}' is invalid.`;s(r,o,"cli")}),e.envVar&&this.on("optionEnv:"+n,r=>{let o=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;s(r,o,"env")}),this}_optionEx(e,n,i,s,r){if(typeof n=="object"&&n instanceof $t)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,i);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(r).argParser(s);else if(s instanceof RegExp){let a=s;s=(c,l)=>{let p=a.exec(c);return p?p[0]:l},o.default(r).argParser(s)}else o.default(s);return this.addOption(o)}option(e,n,i,s){return this._optionEx({},e,n,i,s)}requiredOption(e,n,i,s){return this._optionEx({mandatory:!0},e,n,i,s)}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,i){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(n=i.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){F.default.versions?.electron&&(n.from="electron");let s=F.default.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}e===void 0&&(e=F.default.argv),this.rawArgs=e.slice();let i;switch(n.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":F.default.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=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",i}parse(e,n){this._prepareForParse();let i=this._prepareUserArgs(e,n);return this._parseCommand([],i),this}async parseAsync(e,n){this._prepareForParse();let i=this._prepareUserArgs(e,n);return await this._parseCommand([],i),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,i){if(rn.default.existsSync(e))return;let s=n?`searched for local subcommand relative to directory '${n}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${e}' does not exist
20
+ - if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
21
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${p}`;throw new Error(d)}else if(u.code==="EACCES")throw new Error(`'${r}' not executable`);if(!l)G.exit(1);else{let p=new ks(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});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&&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&&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,o=e.slice();function r(c){return c.length>1&&c[0]==="-"}let a=null;for(;o.length;){let c=o.shift();if(c==="--"){i===s&&i.push(c),i.push(...o);break}if(a&&!r(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,r(c)){let l=this._findOption(c);if(l){if(l.required){let u=o.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;o.length>0&&!r(o[0])&&(u=o.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),o.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(r(c)&&(i=s),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&s.length===0){if(this._findCommand(c)){n.push(c),o.length>0&&s.push(...o);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){n.push(c),o.length>0&&n.push(...o);break}else if(this._defaultCommandName){s.push(c),o.length>0&&s.push(...o);break}}if(this._passThroughOptions){i.push(c),o.length>0&&i.push(...o);break}i.push(c)}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
+ - ${s}`;throw new Error(r)}_executeSubCommand(e,n){n=n.slice();let i=[".js",".ts",".tsx",".mjs",".cjs"];function s(p,u){let d=je.default.resolve(p,u);if(rn.default.existsSync(d))return d;if(i.includes(je.default.extname(u)))return;let f=i.find(h=>rn.default.existsSync(`${d}${h}`));if(f)return`${d}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=e._executableFile||`${this._name}-${e._name}`,o=this._executableDir||"";if(this._scriptPath){let p;try{p=rn.default.realpathSync(this._scriptPath)}catch{p=this._scriptPath}o=je.default.resolve(je.default.dirname(p),o)}if(o){let p=s(o,r);if(!p&&!e._executableFile&&this._scriptPath){let u=je.default.basename(this._scriptPath,je.default.extname(this._scriptPath));u!==this._name&&(p=s(o,`${u}-${e._name}`))}r=p||r}let a=i.includes(je.default.extname(r)),c;F.default.platform!=="win32"?a?(n.unshift(r),n=ha(F.default.execArgv).concat(n),c=Hn.default.spawn(F.default.argv[0],n,{stdio:"inherit"})):c=Hn.default.spawn(r,n,{stdio:"inherit"}):(this._checkForMissingExecutable(r,o,e._name),n.unshift(r),n=ha(F.default.execArgv).concat(n),c=Hn.default.spawn(F.default.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{F.default.on(u,()=>{c.killed===!1&&c.exitCode===null&&c.kill(u)})});let l=this._exitCallback;c.on("close",p=>{p=p??1,l?l(new Ye(p,"commander.executeSubCommandAsync","(close)")):F.default.exit(p)}),c.on("error",p=>{if(p.code==="ENOENT")this._checkForMissingExecutable(r,o,e._name);else if(p.code==="EACCES")throw new Error(`'${r}' not executable`);if(!l)F.default.exit(1);else{let u=new Ye(1,"commander.executeSubCommandAsync","(error)");u.nestedError=p,l(u)}}),this.runningCommand=c}_dispatchSubcommand(e,n,i){let s=this._findCommand(e);s||this.help({error:!0}),s._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,s,"preSubcommand"),r=this._chainOrCall(r,()=>{if(s._executableHandler)this._executeSubCommand(s,n.concat(i));else return s._parseCommand(n,i)}),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=(i,s,r)=>{let o=s;if(s!==null&&i.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,s,r,a)}return o};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((i,s)=>{let r=i.defaultValue;i.variadic?s<this.args.length?(r=this.args.slice(s),i.parseArg&&(r=r.reduce((o,a)=>e(i,a,o),i.defaultValue))):r===void 0&&(r=[]):s<this.args.length&&(r=this.args[s],i.parseArg&&(r=e(i,r,i.defaultValue))),n[s]=r}),this.processedArgs=n}_chainOrCall(e,n){return e?.then&&typeof e.then=="function"?e.then(()=>n()):n()}_chainOrCallHooks(e,n){let i=e,s=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[n]!==void 0).forEach(r=>{r._lifeCycleHooks[n].forEach(o=>{s.push({hookedCommand:r,callback:o})})}),n==="postAction"&&s.reverse(),s.forEach(r=>{i=this._chainOrCall(i,()=>r.callback(r.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,n,i){let s=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(r=>{s=this._chainOrCall(s,()=>r(this,n))}),s}_parseCommand(e,n){let i=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),n=i.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(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){s(),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))s(),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():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),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(i=>{let s=i.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let s=e.find(r=>i.conflictsWith.includes(r.attributeName()));s&&this._conflictingOption(i,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let n=[],i=[],s=n;function r(p){return p.length>1&&p[0]==="-"}let o=p=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(p)?!this._getCommandAndAncestors().some(u=>u.options.map(d=>d.short).some(d=>/^-\d$/.test(d))):!1,a=null,c=null,l=0;for(;l<e.length||c;){let p=c??e[l++];if(c=null,p==="--"){s===i&&s.push(p),s.push(...e.slice(l));break}if(a&&(!r(p)||o(p))){this.emit(`option:${a.name()}`,p);continue}if(a=null,r(p)){let u=this._findOption(p);if(u){if(u.required){let d=e[l++];d===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,d)}else if(u.optional){let d=null;l<e.length&&(!r(e[l])||o(e[l]))&&(d=e[l++]),this.emit(`option:${u.name()}`,d)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(p.length>2&&p[0]==="-"&&p[1]!=="-"){let u=this._findOption(`-${p[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,p.slice(2)):(this.emit(`option:${u.name()}`),c=`-${p.slice(2)}`);continue}}if(/^--[^=]+=/.test(p)){let u=p.indexOf("="),d=this._findOption(p.slice(0,u));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,p.slice(u+1));continue}}if(s===n&&r(p)&&!(this.commands.length===0&&o(p))&&(s=i),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&i.length===0){if(this._findCommand(p)){n.push(p),i.push(...e.slice(l));break}else if(this._getHelpCommand()&&p===this._getHelpCommand().name()){n.push(p,...e.slice(l));break}else if(this._defaultCommandName){i.push(p,...e.slice(l));break}}if(this._passThroughOptions){s.push(p,...e.slice(l));break}s.push(p)}return{operands:n,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},n=this.options.length;for(let i=0;i<n;i++){let s=this.options[i].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,n)=>Object.assign(e,n.opts()),{})}error(e,n){this._outputConfiguration.outputError(`${e}
18
23
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
24
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
20
- `),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 G.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()}`,G.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Dd(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=Er(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",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${s} but got ${e.length}.`;this.error(o,{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=Er(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}
21
- `),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=>Nd(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)}nameFromFilename(e){return this._name=Fe.basename(e,Fe.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp();return n.helpWidth===void 0&&(n.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),n.formatHelp(this,n)}_getHelpContext(e){e=e||{};let n={error:!!e.error},s;return n.error?s=i=>this._outputConfiguration.writeErr(i):s=i=>this._outputConfiguration.writeOut(i),n.write=e.write||s,n.command=this,n}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let s=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let i=this.helpInformation(s);if(n&&(i=n(i),typeof i!="string"&&!Buffer.isBuffer(i)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",s))}helpOption(e,n){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(e,n),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let n=G.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.
22
- 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}
23
- `)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(i=>n.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function kr(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})}Ar.Command=As});var Ir=R(ve=>{var{Argument:$r}=gn(),{Command:Rs}=Rr(),{CommanderError:Fd,InvalidArgumentError:Tr}=Ft(),{Help:Hd}=ws(),{Option:Lr}=Ps();ve.program=new Rs;ve.createCommand=t=>new Rs(t);ve.createOption=(t,e)=>new Lr(t,e);ve.createArgument=(t,e)=>new $r(t,e);ve.Command=Rs;ve.Option=Lr;ve.Argument=$r;ve.Help=Hd;ve.CommanderError=Fd;ve.InvalidArgumentError=Tr;ve.InvalidOptionArgumentError=Tr});var Nr=R(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.splitWhen=bt.flatten=void 0;function Bd(t){return t.reduce((e,n)=>[].concat(e,n),[])}bt.flatten=Bd;function Ud(t,e){let n=[[]],s=0;for(let i of t)e(i)?(s++,n[s]=[]):n[s].push(i);return n}bt.splitWhen=Ud});var Mr=R(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.isEnoentCodeError=void 0;function Vd(t){return t.code==="ENOENT"}yn.isEnoentCodeError=Vd});var Dr=R(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.createDirentFromStats=void 0;var $s=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 Gd(t,e){return new $s(t,e)}bn.createDirentFromStats=Gd});var Ur=R(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.convertPosixPathToPattern=W.convertWindowsPathToPattern=W.convertPathToPattern=W.escapePosixPath=W.escapeWindowsPath=W.escape=W.removeLeadingDotSegment=W.makeAbsolute=W.unixify=void 0;var qd=require("os"),Wd=require("path"),Fr=qd.platform()==="win32",zd=2,Kd=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,Jd=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,Yd=/^\\\\([.?])/,Qd=/\\(?![!()+@[\]{}])/g;function Xd(t){return t.replace(/\\/g,"/")}W.unixify=Xd;function Zd(t,e){return Wd.resolve(t,e)}W.makeAbsolute=Zd;function ef(t){if(t.charAt(0)==="."){let e=t.charAt(1);if(e==="/"||e==="\\")return t.slice(zd)}return t}W.removeLeadingDotSegment=ef;W.escape=Fr?Ts:Ls;function Ts(t){return t.replace(Jd,"\\$2")}W.escapeWindowsPath=Ts;function Ls(t){return t.replace(Kd,"\\$2")}W.escapePosixPath=Ls;W.convertPathToPattern=Fr?Hr:Br;function Hr(t){return Ts(t).replace(Yd,"//$1").replace(Qd,"/")}W.convertWindowsPathToPattern=Hr;function Br(t){return Ls(t)}W.convertPosixPathToPattern=Br});var Gr=R((Tx,Vr)=>{Vr.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 zr=R((Lx,Wr)=>{var tf=Gr(),qr={"{":"}","(":")","[":"]"},nf=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=qr[a];if(c){var l=t.indexOf(c,e);l!==-1&&(e=l+1)}if(t[e]==="!")return!0}else e++}return!1},sf=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=qr[n];if(s){var i=t.indexOf(s,e);i!==-1&&(e=i+1)}if(t[e]==="!")return!0}else e++}return!1};Wr.exports=function(e,n){if(typeof e!="string"||e==="")return!1;if(tf(e))return!0;var s=nf;return n&&n.strict===!1&&(s=sf),s(e)}});var Jr=R((Ix,Kr)=>{"use strict";var of=zr(),rf=require("path").posix.dirname,af=require("os").platform()==="win32",Is="/",cf=/\\/g,lf=/[\{\[].*[\}\]]$/,uf=/(^|[^\\])([\{\[]|\([^\)]+$)/,pf=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Kr.exports=function(e,n){var s=Object.assign({flipBackslashes:!0},n);s.flipBackslashes&&af&&e.indexOf(Is)<0&&(e=e.replace(cf,Is)),lf.test(e)&&(e+=Is),e+="a";do e=rf(e);while(of(e)||uf.test(e));return e.replace(pf,"$1")}});var vn=R(we=>{"use strict";we.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;we.find=(t,e)=>t.nodes.find(n=>n.type===e);we.exceedsLimit=(t,e,n=1,s)=>s===!1||!we.isInteger(t)||!we.isInteger(e)?!1:(Number(e)-Number(t))/Number(n)>=s;we.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)};we.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;we.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;we.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;we.reduce=t=>t.reduce((e,n)=>(n.type==="text"&&e.push(n.value),n.type==="range"&&(n.type="text"),e),[]);we.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 wn=R((jx,Qr)=>{"use strict";var Yr=vn();Qr.exports=(t,e={})=>{let n=(s,i={})=>{let o=e.escapeInvalid&&Yr.isInvalidBrace(i),r=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(o||r)&&Yr.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 Zr=R((Nx,Xr)=>{"use strict";Xr.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var ca=R((Mx,aa)=>{"use strict";var ea=Zr(),ct=(t,e,n)=>{if(ea(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(ea(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(ct.cache.hasOwnProperty(c))return ct.cache[c].result;let l=Math.min(t,e),u=Math.max(t,e);if(Math.abs(l-u)===1){let g=t+"|"+e;return s.capture?`(${g})`:s.wrap===!1?g:`(?:${g})`}let p=ra(t)||ra(e),d={min:t,max:e,a:l,b:u},f=[],h=[];if(p&&(d.isPadded=p,d.maxLen=String(d.max).length),l<0){let g=u<0?Math.abs(u):1;h=ta(g,Math.abs(l),d,s),l=d.a=0}return u>=0&&(f=ta(l,u,d,s)),d.negatives=h,d.positives=f,d.result=df(h,f,s),s.capture===!0?d.result=`(${d.result})`:s.wrap!==!1&&f.length+h.length>1&&(d.result=`(?:${d.result})`),ct.cache[c]=d,d.result};function df(t,e,n){let s=Os(t,e,"-",!1,n)||[],i=Os(e,t,"",!1,n)||[],o=Os(t,e,"-?",!0,n)||[];return s.concat(o).concat(i).join("|")}function ff(t,e){let n=1,s=1,i=sa(t,n),o=new Set([e]);for(;t<=i&&i<=e;)o.add(i),n+=1,i=sa(t,n);for(i=ia(e+1,s)-1;t<i&&i<=e;)o.add(i),s+=1,i=ia(e+1,s)-1;return o=[...o],o.sort(gf),o}function hf(t,e,n){if(t===e)return{pattern:t,count:[],digits:0};let s=mf(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+=yf(c,l,n):r++}return r&&(o+=n.shorthand===!0?"\\d":"[0-9]"),{pattern:o,count:[r],digits:i}}function ta(t,e,n,s){let i=ff(t,e),o=[],r=t,a;for(let c=0;c<i.length;c++){let l=i[c],u=hf(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+oa(a.count),r=l+1;continue}n.isPadded&&(p=bf(l,n,s)),u.string=p+u.pattern+oa(u.count),o.push(u),r=l+1,a=u}return o}function Os(t,e,n,s,i){let o=[];for(let r of t){let{string:a}=r;!s&&!na(e,"string",a)&&o.push(n+a),s&&na(e,"string",a)&&o.push(n+a)}return o}function mf(t,e){let n=[];for(let s=0;s<t.length;s++)n.push([t[s],e[s]]);return n}function gf(t,e){return t>e?1:e>t?-1:0}function na(t,e,n){return t.some(s=>s[e]===n)}function sa(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function ia(t,e){return t-t%Math.pow(10,e)}function oa(t){let[e=0,n=""]=t;return n||e>1?`{${e+(n?","+n:"")}}`:""}function yf(t,e,n){return`[${t}${e-t===1?"":"-"}${e}]`}function ra(t){return/^-?(0+)\d/.test(t)}function bf(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}}`}}ct.cache={};ct.clearCache=()=>ct.cache={};aa.exports=ct});var Ms=R((Dx,ma)=>{"use strict";var vf=require("util"),ua=ca(),la=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),wf=t=>e=>t===!0?Number(e):String(e),js=t=>typeof t=="number"||typeof t=="string"&&t!=="",Ht=t=>Number.isInteger(+t),Ns=t=>{let e=`${t}`,n=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++n]==="0";);return n>0},xf=(t,e,n)=>typeof t=="string"||typeof e=="string"?!0:n.stringify===!0,_f=(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},_n=(t,e)=>{let n=t[0]==="-"?"-":"";for(n&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return n?"-"+t:t},Sf=(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=>_n(String(a),n)).join("|")),t.negatives.length&&(o=`-(${s}${t.negatives.map(a=>_n(String(a),n)).join("|")})`),i&&o?r=`${i}|${o}`:r=i||o,e.wrap?`(${s}${r})`:r},pa=(t,e,n,s)=>{if(n)return ua(t,e,{wrap:!1,...s});let i=String.fromCharCode(t);if(t===e)return i;let o=String.fromCharCode(e);return`[${i}-${o}]`},da=(t,e,n)=>{if(Array.isArray(t)){let s=n.wrap===!0,i=n.capture?"":"?:";return s?`(${i}${t.join("|")})`:t.join("|")}return ua(t,e,n)},fa=(...t)=>new RangeError("Invalid range arguments: "+vf.inspect(...t)),ha=(t,e,n)=>{if(n.strictRanges===!0)throw fa([t,e]);return[]},Pf=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},Cf=(t,e,n=1,s={})=>{let i=Number(t),o=Number(e);if(!Number.isInteger(i)||!Number.isInteger(o)){if(s.strictRanges===!0)throw fa([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=Ns(a)||Ns(c)||Ns(l),p=u?Math.max(a.length,c.length,l.length):0,d=u===!1&&xf(t,e,s)===!1,f=s.transform||wf(d);if(s.toRegex&&n===1)return pa(_n(t,p),_n(e,p),!0,s);let h={negatives:[],positives:[]},g=b=>h[b<0?"negatives":"positives"].push(Math.abs(b)),v=[],y=0;for(;r?i>=o:i<=o;)s.toRegex===!0&&n>1?g(i):v.push(_f(f(i,y),p,d)),i=r?i-n:i+n,y++;return s.toRegex===!0?n>1?Sf(h,s,p):da(v,null,{wrap:!1,...s}):v},Ef=(t,e,n=1,s={})=>{if(!Ht(t)&&t.length>1||!Ht(e)&&e.length>1)return ha(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 pa(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?da(u,null,{wrap:!1,options:s}):u},xn=(t,e,n,s={})=>{if(e==null&&js(t))return[t];if(!js(t)||!js(e))return ha(t,e,s);if(typeof n=="function")return xn(t,e,1,{transform:n});if(la(n))return xn(t,e,0,n);let i={...s};return i.capture===!0&&(i.wrap=!0),n=n||i.step||1,Ht(n)?Ht(t)&&Ht(e)?Cf(t,e,n,i):Ef(t,e,Math.max(Math.abs(n),1),i):n!=null&&!la(n)?Pf(n,i):xn(t,e,1,n)};ma.exports=xn});var ba=R((Fx,ya)=>{"use strict";var kf=Ms(),ga=vn(),Af=(t,e={})=>{let n=(s,i={})=>{let o=ga.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=ga.reduce(s.nodes),p=kf(...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)};ya.exports=Af});var xa=R((Hx,wa)=>{"use strict";var Rf=Ms(),va=wn(),vt=vn(),lt=(t="",e="",n=!1)=>{let s=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return n?vt.flatten(e).map(i=>`{${i}}`):e;for(let i of t)if(Array.isArray(i))for(let o of i)s.push(lt(o,e,n));else for(let o of e)n===!0&&typeof o=="string"&&(o=`{${o}}`),s.push(Array.isArray(o)?lt(i,o,n):i+o);return vt.flatten(s)},$f=(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(lt(a.pop(),va(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(lt(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let p=vt.reduce(i.nodes);if(vt.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=Rf(...p,e);d.length===0&&(d=va(i,e)),a.push(lt(a.pop(),d)),i.nodes=[];return}let c=vt.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(lt(a.pop(),l,c));continue}if(d.value&&d.type!=="open"){l.push(lt(l.pop(),d.value));continue}d.nodes&&s(d,i)}return l};return vt.flatten(s(t))};wa.exports=$f});var Sa=R((Bx,_a)=>{"use strict";_a.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:`
24
- `,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 Aa=R((Ux,ka)=>{"use strict";var Tf=wn(),{MAX_LENGTH:Pa,CHAR_BACKSLASH:Ds,CHAR_BACKTICK:Lf,CHAR_COMMA:If,CHAR_DOT:Of,CHAR_LEFT_PARENTHESES:jf,CHAR_RIGHT_PARENTHESES:Nf,CHAR_LEFT_CURLY_BRACE:Mf,CHAR_RIGHT_CURLY_BRACE:Df,CHAR_LEFT_SQUARE_BRACKET:Ca,CHAR_RIGHT_SQUARE_BRACKET:Ea,CHAR_DOUBLE_QUOTE:Ff,CHAR_SINGLE_QUOTE:Hf,CHAR_NO_BREAK_SPACE:Bf,CHAR_ZERO_WIDTH_NOBREAK_SPACE:Uf}=Sa(),Vf=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let n=e||{},s=typeof n.maxLength=="number"?Math.min(Pa,n.maxLength):Pa;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,f=()=>t[u++],h=g=>{if(g.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&g.type==="text"){a.value+=g.value;return}return r.nodes.push(g),g.parent=r,g.prev=a,a=g,g};for(h({type:"bos"});u<l;)if(r=o[o.length-1],d=f(),!(d===Uf||d===Bf)){if(d===Ds){h({type:"text",value:(e.keepEscaping?d:"")+f()});continue}if(d===Ea){h({type:"text",value:"\\"+d});continue}if(d===Ca){c++;let g;for(;u<l&&(g=f());){if(d+=g,g===Ca){c++;continue}if(g===Ds){d+=f();continue}if(g===Ea&&(c--,c===0))break}h({type:"text",value:d});continue}if(d===jf){r=h({type:"paren",nodes:[]}),o.push(r),h({type:"text",value:d});continue}if(d===Nf){if(r.type!=="paren"){h({type:"text",value:d});continue}r=o.pop(),h({type:"text",value:d}),r=o[o.length-1];continue}if(d===Ff||d===Hf||d===Lf){let g=d,v;for(e.keepQuotes!==!0&&(d="");u<l&&(v=f());){if(v===Ds){d+=v+f();continue}if(v===g){e.keepQuotes===!0&&(d+=v);break}d+=v}h({type:"text",value:d});continue}if(d===Mf){p++;let v={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||r.dollar===!0,depth:p,commas:0,ranges:0,nodes:[]};r=h(v),o.push(r),h({type:"open",value:d});continue}if(d===Df){if(r.type!=="brace"){h({type:"text",value:d});continue}let g="close";r=o.pop(),r.close=!0,h({type:g,value:d}),p--,r=o[o.length-1];continue}if(d===If&&p>0){if(r.ranges>0){r.ranges=0;let g=r.nodes.shift();r.nodes=[g,{type:"text",value:Tf(r)}]}h({type:"comma",value:d}),r.commas++;continue}if(d===Of&&p>0&&r.commas===0){let g=r.nodes;if(p===0||g.length===0){h({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"){g.pop();let v=g[g.length-1];v.value+=a.value+d,a=v,r.ranges--;continue}h({type:"dot",value:d});continue}h({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 g=o[o.length-1],v=g.nodes.indexOf(r);g.nodes.splice(v,1,...r.nodes)}while(o.length>0);return h({type:"eos"}),i};ka.exports=Vf});var Ta=R((Vx,$a)=>{"use strict";var Ra=wn(),Gf=ba(),qf=xa(),Wf=Aa(),he=(t,e={})=>{let n=[];if(Array.isArray(t))for(let s of t){let i=he.create(s,e);Array.isArray(i)?n.push(...i):n.push(i)}else n=[].concat(he.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(n=[...new Set(n)]),n};he.parse=(t,e={})=>Wf(t,e);he.stringify=(t,e={})=>Ra(typeof t=="string"?he.parse(t,e):t,e);he.compile=(t,e={})=>(typeof t=="string"&&(t=he.parse(t,e)),Gf(t,e));he.expand=(t,e={})=>{typeof t=="string"&&(t=he.parse(t,e));let n=qf(t,e);return e.noempty===!0&&(n=n.filter(Boolean)),e.nodupes===!0&&(n=[...new Set(n)]),n};he.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?he.compile(t,e):he.expand(t,e);$a.exports=he});var Bt=R((Gx,Na)=>{"use strict";var zf=require("path"),Ie="\\\\/",La=`[^${Ie}]`,Kf=0,He="\\.",Jf="\\+",Yf="\\?",Sn="\\/",Qf="(?=.)",Ia="[^/]",Fs=`(?:${Sn}|$)`,Oa=`(?:^|${Sn})`,Hs=`${He}{1,2}${Fs}`,Xf=`(?!${He})`,Zf=`(?!${Oa}${Hs})`,eh=`(?!${He}{0,1}${Fs})`,th=`(?!${Hs})`,nh=`[^.${Sn}]`,sh=`${Ia}*?`,ja={DOT_LITERAL:He,PLUS_LITERAL:Jf,QMARK_LITERAL:Yf,SLASH_LITERAL:Sn,ONE_CHAR:Qf,QMARK:Ia,END_ANCHOR:Fs,DOTS_SLASH:Hs,NO_DOT:Xf,NO_DOTS:Zf,NO_DOT_SLASH:eh,NO_DOTS_SLASH:th,QMARK_NO_DOT:nh,STAR:sh,START_ANCHOR:Oa},ih={...ja,SLASH_LITERAL:`[${Ie}]`,QMARK:La,STAR:`${La}*?`,DOTS_SLASH:`${He}{1,2}(?:[${Ie}]|$)`,NO_DOT:`(?!${He})`,NO_DOTS:`(?!(?:^|[${Ie}])${He}{1,2}(?:[${Ie}]|$))`,NO_DOT_SLASH:`(?!${He}{0,1}(?:[${Ie}]|$))`,NO_DOTS_SLASH:`(?!${He}{1,2}(?:[${Ie}]|$))`,QMARK_NO_DOT:`[^.${Ie}]`,START_ANCHOR:`(?:^|[${Ie}])`,END_ANCHOR:`(?:[${Ie}]|$)`},oh={__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"};Na.exports={DEFAULT_MAX_EXTGLOB_RECURSION:Kf,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:oh,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:zf.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?ih:ja}}});var Ut=R(ce=>{"use strict";var rh=require("path"),ah=process.platform==="win32",{REGEX_BACKSLASH:ch,REGEX_REMOVE_BACKSLASH:lh,REGEX_SPECIAL_CHARS:uh,REGEX_SPECIAL_CHARS_GLOBAL:ph}=Bt();ce.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);ce.hasRegexChars=t=>uh.test(t);ce.isRegexChar=t=>t.length===1&&ce.hasRegexChars(t);ce.escapeRegex=t=>t.replace(ph,"\\$1");ce.toPosixSlashes=t=>t.replace(ch,"/");ce.removeBackslashes=t=>t.replace(lh,e=>e==="\\"?"":e);ce.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};ce.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:ah===!0||rh.sep==="\\";ce.escapeLast=(t,e,n)=>{let s=t.lastIndexOf(e,n);return s===-1?t:t[s-1]==="\\"?ce.escapeLast(t,e,s-1):`${t.slice(0,s)}\\${t.slice(s)}`};ce.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};ce.wrapOutput=(t,e={},n={})=>{let s=n.contains?"":"^",i=n.contains?"":"$",o=`${s}(?:${t})${i}`;return e.negated===!0&&(o=`(?:^(?!${o}).*$)`),o}});var Ga=R((Wx,Va)=>{"use strict";var Ma=Ut(),{CHAR_ASTERISK:Bs,CHAR_AT:dh,CHAR_BACKWARD_SLASH:Vt,CHAR_COMMA:fh,CHAR_DOT:Us,CHAR_EXCLAMATION_MARK:Vs,CHAR_FORWARD_SLASH:Ua,CHAR_LEFT_CURLY_BRACE:Gs,CHAR_LEFT_PARENTHESES:qs,CHAR_LEFT_SQUARE_BRACKET:hh,CHAR_PLUS:mh,CHAR_QUESTION_MARK:Da,CHAR_RIGHT_CURLY_BRACE:gh,CHAR_RIGHT_PARENTHESES:Fa,CHAR_RIGHT_SQUARE_BRACKET:yh}=Bt(),Ha=t=>t===Ua||t===Vt,Ba=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},bh=(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,f=!1,h=!1,g=!1,v=!1,y=!1,b=!1,m=!1,x=!1,k=!1,C=0,A,_,L={value:"",depth:0,isGlob:!1},D=()=>l>=s,w=()=>c.charCodeAt(l+1),N=()=>(A=_,c.charCodeAt(++l));for(;l<s;){_=N();let se;if(_===Vt){b=L.backslashes=!0,_=N(),_===Gs&&(y=!0);continue}if(y===!0||_===Gs){for(C++;D()!==!0&&(_=N());){if(_===Vt){b=L.backslashes=!0,N();continue}if(_===Gs){C++;continue}if(y!==!0&&_===Us&&(_=N())===Us){if(d=L.isBrace=!0,h=L.isGlob=!0,k=!0,i===!0)continue;break}if(y!==!0&&_===fh){if(d=L.isBrace=!0,h=L.isGlob=!0,k=!0,i===!0)continue;break}if(_===gh&&(C--,C===0)){y=!1,d=L.isBrace=!0,k=!0;break}}if(i===!0)continue;break}if(_===Ua){if(o.push(l),r.push(L),L={value:"",depth:0,isGlob:!1},k===!0)continue;if(A===Us&&l===u+1){u+=2;continue}p=l+1;continue}if(n.noext!==!0&&(_===mh||_===dh||_===Bs||_===Da||_===Vs)===!0&&w()===qs){if(h=L.isGlob=!0,g=L.isExtglob=!0,k=!0,_===Vs&&l===u&&(x=!0),i===!0){for(;D()!==!0&&(_=N());){if(_===Vt){b=L.backslashes=!0,_=N();continue}if(_===Fa){h=L.isGlob=!0,k=!0;break}}continue}break}if(_===Bs){if(A===Bs&&(v=L.isGlobstar=!0),h=L.isGlob=!0,k=!0,i===!0)continue;break}if(_===Da){if(h=L.isGlob=!0,k=!0,i===!0)continue;break}if(_===hh){for(;D()!==!0&&(se=N());){if(se===Vt){b=L.backslashes=!0,N();continue}if(se===yh){f=L.isBracket=!0,h=L.isGlob=!0,k=!0;break}}if(i===!0)continue;break}if(n.nonegate!==!0&&_===Vs&&l===u){m=L.negated=!0,u++;continue}if(n.noparen!==!0&&_===qs){if(h=L.isGlob=!0,i===!0){for(;D()!==!0&&(_=N());){if(_===qs){b=L.backslashes=!0,_=N();continue}if(_===Fa){k=!0;break}}continue}break}if(h===!0){if(k=!0,i===!0)continue;break}}n.noext===!0&&(g=!1,h=!1);let F=c,We="",S="";u>0&&(We=c.slice(0,u),c=c.slice(u),p-=u),F&&h===!0&&p>0?(F=c.slice(0,p),S=c.slice(p)):h===!0?(F="",S=c):F=c,F&&F!==""&&F!=="/"&&F!==c&&Ha(F.charCodeAt(F.length-1))&&(F=F.slice(0,-1)),n.unescape===!0&&(S&&(S=Ma.removeBackslashes(S)),F&&b===!0&&(F=Ma.removeBackslashes(F)));let P={prefix:We,input:t,start:u,base:F,glob:S,isBrace:d,isBracket:f,isGlob:h,isExtglob:g,isGlobstar:v,negated:m,negatedExtglob:x};if(n.tokens===!0&&(P.maxDepth=0,Ha(_)||r.push(L),P.tokens=r),n.parts===!0||n.tokens===!0){let se;for(let M=0;M<o.length;M++){let Re=se?se+1:u,$e=o[M],fe=t.slice(Re,$e);n.tokens&&(M===0&&u!==0?(r[M].isPrefix=!0,r[M].value=We):r[M].value=fe,Ba(r[M]),P.maxDepth+=r[M].depth),(M!==0||fe!=="")&&a.push(fe),se=$e}if(se&&se+1<t.length){let M=t.slice(se+1);a.push(M),n.tokens&&(r[r.length-1].value=M,Ba(r[r.length-1]),P.maxDepth+=r[r.length-1].depth)}P.slashes=o,P.parts=a}return P};Va.exports=bh});var Ja=R((zx,Ka)=>{"use strict";var Gt=Bt(),Z=Ut(),{MAX_LENGTH:Pn,POSIX_REGEX_SOURCE:vh,REGEX_NON_SPECIAL_CHARS:wh,REGEX_SPECIAL_CHARS_BACKREF:xh,REPLACEMENTS:qa}=Gt,_h=(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=>Z.escapeRegex(i)).join("..")}return n},wt=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,Wa=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},Sh=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},za=t=>{let e=t.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=!0);if(Sh(e))return e.replace(/\\(.)/g,"$1")},Ph=t=>{let e=t.map(za).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},Ws=(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}}}}},Ch=t=>{let e=0,n=[];for(;e<t.length;){let i=Ws(t.slice(e),!1);if(!i||i.type!=="*")return;let o=Wa(i.body).map(a=>a.trim());if(o.length!==1)return;let r=za(o[0]);if(!r||r.length!==1)return;n.push(r),e+=i.end+1}return n.length<1?void 0:`${n.length===1?Z.escapeRegex(n[0]):`[${n.map(i=>Z.escapeRegex(i)).join("")}]`}*`},Eh=t=>{let e=0,n=t.trim(),s=Ws(n);for(;s;)e++,n=s.body.trim(),s=Ws(n);return e},kh=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Gt.DEFAULT_MAX_EXTGLOB_RECURSION,s=Wa(t).map(i=>i.trim());if(s.length>1&&(s.some(i=>i==="")||s.some(i=>/^[*?]+$/.test(i))||Ph(s)))return{risky:!0};for(let i of s){let o=Ch(i);if(o)return{risky:!0,safeOutput:o};if(Eh(i)>n)return{risky:!0}}return{risky:!1}},zs=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=qa[t]||t;let n={...e},s=typeof n.maxLength=="number"?Math.min(Pn,n.maxLength):Pn,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=Z.isWindows(e),l=Gt.globChars(c),u=Gt.extglobChars(l),{DOT_LITERAL:p,PLUS_LITERAL:d,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:g,NO_DOT:v,NO_DOT_SLASH:y,NO_DOTS_SLASH:b,QMARK:m,QMARK_NO_DOT:x,STAR:k,START_ANCHOR:C}=l,A=T=>`(${a}(?:(?!${C}${T.dot?g:p}).)*?)`,_=n.dot?"":v,L=n.dot?m:x,D=n.bash===!0?A(n):k;n.capture&&(D=`(${D})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let w={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=Z.removePrefix(t,w),i=t.length;let N=[],F=[],We=[],S=o,P,se=()=>w.index===i-1,M=w.peek=(T=1)=>t[w.index+T],Re=w.advance=()=>t[++w.index]||"",$e=()=>t.slice(w.index+1),fe=(T="",V=0)=>{w.consumed+=T,w.index+=V},dn=T=>{w.output+=T.output!=null?T.output:T.value,fe(T.value)},bd=()=>{let T=1;for(;M()==="!"&&(M(2)!=="("||M(3)==="?");)Re(),w.start++,T++;return T%2===0?!1:(w.negated=!0,w.start++,!0)},fn=T=>{w[T]++,We.push(T)},ze=T=>{w[T]--,We.pop()},j=T=>{if(S.type==="globstar"){let V=w.braces>0&&(T.type==="comma"||T.type==="brace"),$=T.extglob===!0||N.length&&(T.type==="pipe"||T.type==="paren");T.type!=="slash"&&T.type!=="paren"&&!V&&!$&&(w.output=w.output.slice(0,-S.output.length),S.type="star",S.value="*",S.output=D,w.output+=S.output)}if(N.length&&T.type!=="paren"&&(N[N.length-1].inner+=T.value),(T.value||T.output)&&dn(T),S&&S.type==="text"&&T.type==="text"){S.value+=T.value,S.output=(S.output||"")+T.value;return}T.prev=S,r.push(T),S=T},hn=(T,V)=>{let $={...u[V],conditions:1,inner:""};$.prev=S,$.parens=w.parens,$.output=w.output,$.startIndex=w.index,$.tokensIndex=r.length;let O=(n.capture?"(":"")+$.open;fn("parens"),j({type:T,value:V,output:w.output?"":h}),j({type:"paren",extglob:!0,value:Re(),output:O}),N.push($)},vd=T=>{let V=t.slice(T.startIndex,w.index+1),$=t.slice(T.startIndex+2,w.index),O=kh($,n);if((T.type==="plus"||T.type==="star")&&O.risky){let H=O.safeOutput?(T.output?"":h)+(n.capture?`(${O.safeOutput})`:O.safeOutput):void 0,Te=r[T.tokensIndex];Te.type="text",Te.value=V,Te.output=H||Z.escapeRegex(V);for(let Le=T.tokensIndex+1;Le<r.length;Le++)r[Le].value="",r[Le].output="",delete r[Le].suffix;w.output=T.output+Te.output,w.backtrack=!0,j({type:"paren",extglob:!0,value:P,output:""}),ze("parens");return}let B=T.close+(n.capture?")":""),z;if(T.type==="negate"){let H=D;if(T.inner&&T.inner.length>1&&T.inner.includes("/")&&(H=A(n)),(H!==D||se()||/^\)+$/.test($e()))&&(B=T.close=`)$))${H}`),T.inner.includes("*")&&(z=$e())&&/^\.[^\\/.]+$/.test(z)){let Te=zs(z,{...e,fastpaths:!1}).output;B=T.close=`)${Te})${H})`}T.prev.type==="bos"&&(w.negatedExtglob=!0)}j({type:"paren",extglob:!0,value:P,output:B}),ze("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let T=!1,V=t.replace(xh,($,O,B,z,H,Te)=>z==="\\"?(T=!0,$):z==="?"?O?O+z+(H?m.repeat(H.length):""):Te===0?L+(H?m.repeat(H.length):""):m.repeat(B.length):z==="."?p.repeat(B.length):z==="*"?O?O+z+(H?D:""):D:O?$:`\\${$}`);return T===!0&&(n.unescape===!0?V=V.replace(/\\/g,""):V=V.replace(/\\+/g,$=>$.length%2===0?"\\\\":$?"\\":"")),V===t&&n.contains===!0?(w.output=t,w):(w.output=Z.wrapOutput(V,w,e),w)}for(;!se();){if(P=Re(),P==="\0")continue;if(P==="\\"){let $=M();if($==="/"&&n.bash!==!0||$==="."||$===";")continue;if(!$){P+="\\",j({type:"text",value:P});continue}let O=/^\\+/.exec($e()),B=0;if(O&&O[0].length>2&&(B=O[0].length,w.index+=B,B%2!==0&&(P+="\\")),n.unescape===!0?P=Re():P+=Re(),w.brackets===0){j({type:"text",value:P});continue}}if(w.brackets>0&&(P!=="]"||S.value==="["||S.value==="[^")){if(n.posix!==!1&&P===":"){let $=S.value.slice(1);if($.includes("[")&&(S.posix=!0,$.includes(":"))){let O=S.value.lastIndexOf("["),B=S.value.slice(0,O),z=S.value.slice(O+2),H=vh[z];if(H){S.value=B+H,w.backtrack=!0,Re(),!o.output&&r.indexOf(S)===1&&(o.output=h);continue}}}(P==="["&&M()!==":"||P==="-"&&M()==="]")&&(P=`\\${P}`),P==="]"&&(S.value==="["||S.value==="[^")&&(P=`\\${P}`),n.posix===!0&&P==="!"&&S.value==="["&&(P="^"),S.value+=P,dn({value:P});continue}if(w.quotes===1&&P!=='"'){P=Z.escapeRegex(P),S.value+=P,dn({value:P});continue}if(P==='"'){w.quotes=w.quotes===1?0:1,n.keepQuotes===!0&&j({type:"text",value:P});continue}if(P==="("){fn("parens"),j({type:"paren",value:P});continue}if(P===")"){if(w.parens===0&&n.strictBrackets===!0)throw new SyntaxError(wt("opening","("));let $=N[N.length-1];if($&&w.parens===$.parens+1){vd(N.pop());continue}j({type:"paren",value:P,output:w.parens?")":"\\)"}),ze("parens");continue}if(P==="["){if(n.nobracket===!0||!$e().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(wt("closing","]"));P=`\\${P}`}else fn("brackets");j({type:"bracket",value:P});continue}if(P==="]"){if(n.nobracket===!0||S&&S.type==="bracket"&&S.value.length===1){j({type:"text",value:P,output:`\\${P}`});continue}if(w.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(wt("opening","["));j({type:"text",value:P,output:`\\${P}`});continue}ze("brackets");let $=S.value.slice(1);if(S.posix!==!0&&$[0]==="^"&&!$.includes("/")&&(P=`/${P}`),S.value+=P,dn({value:P}),n.literalBrackets===!1||Z.hasRegexChars($))continue;let O=Z.escapeRegex(S.value);if(w.output=w.output.slice(0,-S.value.length),n.literalBrackets===!0){w.output+=O,S.value=O;continue}S.value=`(${a}${O}|${S.value})`,w.output+=S.value;continue}if(P==="{"&&n.nobrace!==!0){fn("braces");let $={type:"brace",value:P,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};F.push($),j($);continue}if(P==="}"){let $=F[F.length-1];if(n.nobrace===!0||!$){j({type:"text",value:P,output:P});continue}let O=")";if($.dots===!0){let B=r.slice(),z=[];for(let H=B.length-1;H>=0&&(r.pop(),B[H].type!=="brace");H--)B[H].type!=="dots"&&z.unshift(B[H].value);O=_h(z,n),w.backtrack=!0}if($.comma!==!0&&$.dots!==!0){let B=w.output.slice(0,$.outputIndex),z=w.tokens.slice($.tokensIndex);$.value=$.output="\\{",P=O="\\}",w.output=B;for(let H of z)w.output+=H.output||H.value}j({type:"brace",value:P,output:O}),ze("braces"),F.pop();continue}if(P==="|"){N.length>0&&N[N.length-1].conditions++,j({type:"text",value:P});continue}if(P===","){let $=P,O=F[F.length-1];O&&We[We.length-1]==="braces"&&(O.comma=!0,$="|"),j({type:"comma",value:P,output:$});continue}if(P==="/"){if(S.type==="dot"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",r.pop(),S=o;continue}j({type:"slash",value:P,output:f});continue}if(P==="."){if(w.braces>0&&S.type==="dot"){S.value==="."&&(S.output=p);let $=F[F.length-1];S.type="dots",S.output+=P,S.value+=P,$.dots=!0;continue}if(w.braces+w.parens===0&&S.type!=="bos"&&S.type!=="slash"){j({type:"text",value:P,output:p});continue}j({type:"dot",value:P,output:p});continue}if(P==="?"){if(!(S&&S.value==="(")&&n.noextglob!==!0&&M()==="("&&M(2)!=="?"){hn("qmark",P);continue}if(S&&S.type==="paren"){let O=M(),B=P;if(O==="<"&&!Z.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(S.value==="("&&!/[!=<:]/.test(O)||O==="<"&&!/<([!=]|\w+>)/.test($e()))&&(B=`\\${P}`),j({type:"text",value:P,output:B});continue}if(n.dot!==!0&&(S.type==="slash"||S.type==="bos")){j({type:"qmark",value:P,output:x});continue}j({type:"qmark",value:P,output:m});continue}if(P==="!"){if(n.noextglob!==!0&&M()==="("&&(M(2)!=="?"||!/[!=<:]/.test(M(3)))){hn("negate",P);continue}if(n.nonegate!==!0&&w.index===0){bd();continue}}if(P==="+"){if(n.noextglob!==!0&&M()==="("&&M(2)!=="?"){hn("plus",P);continue}if(S&&S.value==="("||n.regex===!1){j({type:"plus",value:P,output:d});continue}if(S&&(S.type==="bracket"||S.type==="paren"||S.type==="brace")||w.parens>0){j({type:"plus",value:P});continue}j({type:"plus",value:d});continue}if(P==="@"){if(n.noextglob!==!0&&M()==="("&&M(2)!=="?"){j({type:"at",extglob:!0,value:P,output:""});continue}j({type:"text",value:P});continue}if(P!=="*"){(P==="$"||P==="^")&&(P=`\\${P}`);let $=wh.exec($e());$&&(P+=$[0],w.index+=$[0].length),j({type:"text",value:P});continue}if(S&&(S.type==="globstar"||S.star===!0)){S.type="star",S.star=!0,S.value+=P,S.output=D,w.backtrack=!0,w.globstar=!0,fe(P);continue}let T=$e();if(n.noextglob!==!0&&/^\([^?]/.test(T)){hn("star",P);continue}if(S.type==="star"){if(n.noglobstar===!0){fe(P);continue}let $=S.prev,O=$.prev,B=$.type==="slash"||$.type==="bos",z=O&&(O.type==="star"||O.type==="globstar");if(n.bash===!0&&(!B||T[0]&&T[0]!=="/")){j({type:"star",value:P,output:""});continue}let H=w.braces>0&&($.type==="comma"||$.type==="brace"),Te=N.length&&($.type==="pipe"||$.type==="paren");if(!B&&$.type!=="paren"&&!H&&!Te){j({type:"star",value:P,output:""});continue}for(;T.slice(0,3)==="/**";){let Le=t[w.index+4];if(Le&&Le!=="/")break;T=T.slice(3),fe("/**",3)}if($.type==="bos"&&se()){S.type="globstar",S.value+=P,S.output=A(n),w.output=S.output,w.globstar=!0,fe(P);continue}if($.type==="slash"&&$.prev.type!=="bos"&&!z&&se()){w.output=w.output.slice(0,-($.output+S.output).length),$.output=`(?:${$.output}`,S.type="globstar",S.output=A(n)+(n.strictSlashes?")":"|$)"),S.value+=P,w.globstar=!0,w.output+=$.output+S.output,fe(P);continue}if($.type==="slash"&&$.prev.type!=="bos"&&T[0]==="/"){let Le=T[1]!==void 0?"|$":"";w.output=w.output.slice(0,-($.output+S.output).length),$.output=`(?:${$.output}`,S.type="globstar",S.output=`${A(n)}${f}|${f}${Le})`,S.value+=P,w.output+=$.output+S.output,w.globstar=!0,fe(P+Re()),j({type:"slash",value:"/",output:""});continue}if($.type==="bos"&&T[0]==="/"){S.type="globstar",S.value+=P,S.output=`(?:^|${f}|${A(n)}${f})`,w.output=S.output,w.globstar=!0,fe(P+Re()),j({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-S.output.length),S.type="globstar",S.output=A(n),S.value+=P,w.output+=S.output,w.globstar=!0,fe(P);continue}let V={type:"star",value:P,output:D};if(n.bash===!0){V.output=".*?",(S.type==="bos"||S.type==="slash")&&(V.output=_+V.output),j(V);continue}if(S&&(S.type==="bracket"||S.type==="paren")&&n.regex===!0){V.output=P,j(V);continue}(w.index===w.start||S.type==="slash"||S.type==="dot")&&(S.type==="dot"?(w.output+=y,S.output+=y):n.dot===!0?(w.output+=b,S.output+=b):(w.output+=_,S.output+=_),M()!=="*"&&(w.output+=h,S.output+=h)),j(V)}for(;w.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(wt("closing","]"));w.output=Z.escapeLast(w.output,"["),ze("brackets")}for(;w.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(wt("closing",")"));w.output=Z.escapeLast(w.output,"("),ze("parens")}for(;w.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(wt("closing","}"));w.output=Z.escapeLast(w.output,"{"),ze("braces")}if(n.strictSlashes!==!0&&(S.type==="star"||S.type==="bracket")&&j({type:"maybe_slash",value:"",output:`${f}?`}),w.backtrack===!0){w.output="";for(let T of w.tokens)w.output+=T.output!=null?T.output:T.value,T.suffix&&(w.output+=T.suffix)}return w};zs.fastpaths=(t,e)=>{let n={...e},s=typeof n.maxLength=="number"?Math.min(Pn,n.maxLength):Pn,i=t.length;if(i>s)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${s}`);t=qa[t]||t;let o=Z.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:f,START_ANCHOR:h}=Gt.globChars(o),g=n.dot?p:u,v=n.dot?d:u,y=n.capture?"":"?:",b={negated:!1,prefix:""},m=n.bash===!0?".*?":f;n.capture&&(m=`(${m})`);let x=_=>_.noglobstar===!0?m:`(${y}(?:(?!${h}${_.dot?l:r}).)*?)`,k=_=>{switch(_){case"*":return`${g}${c}${m}`;case".*":return`${r}${c}${m}`;case"*.*":return`${g}${m}${r}${c}${m}`;case"*/*":return`${g}${m}${a}${c}${v}${m}`;case"**":return g+x(n);case"**/*":return`(?:${g}${x(n)}${a})?${v}${c}${m}`;case"**/*.*":return`(?:${g}${x(n)}${a})?${v}${m}${r}${c}${m}`;case"**/.*":return`(?:${g}${x(n)}${a})?${r}${c}${m}`;default:{let L=/^(.*?)\.(\w+)$/.exec(_);if(!L)return;let D=k(L[1]);return D?D+r+L[2]:void 0}}},C=Z.removePrefix(t,b),A=k(C);return A&&n.strictSlashes!==!0&&(A+=`${a}?`),A};Ka.exports=zs});var Qa=R((Kx,Ya)=>{"use strict";var Ah=require("path"),Rh=Ga(),Ks=Ja(),Js=Ut(),$h=Bt(),Th=t=>t&&typeof t=="object"&&!Array.isArray(t),q=(t,e,n=!1)=>{if(Array.isArray(t)){let u=t.map(d=>q(d,e,n));return d=>{for(let f of u){let h=f(d);if(h)return h}return!1}}let s=Th(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=Js.isWindows(e),r=s?q.compileRe(t,e):q.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=q(i.ignore,u,n)}let l=(u,p=!1)=>{let{isMatch:d,match:f,output:h}=q.test(u,r,e,{glob:t,posix:o}),g={glob:t,state:a,regex:r,posix:o,input:u,output:h,match:f,isMatch:d};return typeof i.onResult=="function"&&i.onResult(g),d===!1?(g.isMatch=!1,p?g:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(g),g.isMatch=!1,p?g:!1):(typeof i.onMatch=="function"&&i.onMatch(g),p?g:!0)};return n&&(l.state=a),l};q.test=(t,e,n,{glob:s,posix:i}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let o=n||{},r=o.format||(i?Js.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=q.matchBase(t,e,n,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};q.matchBase=(t,e,n,s=Js.isWindows(n))=>(e instanceof RegExp?e:q.makeRe(e,n)).test(Ah.basename(t));q.isMatch=(t,e,n)=>q(e,n)(t);q.parse=(t,e)=>Array.isArray(t)?t.map(n=>q.parse(n,e)):Ks(t,{...e,fastpaths:!1});q.scan=(t,e)=>Rh(t,e);q.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=q.toRegex(a,e);return s===!0&&(c.state=t),c};q.makeRe=(t,e={},n=!1,s=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(i.output=Ks.fastpaths(t,e)),i.output||(i=Ks(t,e)),q.compileRe(i,e,n,s)};q.toRegex=(t,e)=>{try{let n=e||{};return new RegExp(t,n.flags||(n.nocase?"i":""))}catch(n){if(e&&e.debug===!0)throw n;return/$^/}};q.constants=$h;Ya.exports=q});var Za=R((Jx,Xa)=>{"use strict";Xa.exports=Qa()});var oc=R((Yx,ic)=>{"use strict";var tc=require("util"),nc=Ta(),Oe=Za(),Ys=Ut(),ec=t=>t===""||t==="./",sc=t=>{let e=t.indexOf("{");return e>-1&&t.indexOf("}",e)>-1},U=(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=Oe(String(e[u]),{...n,onResult:a},!0),d=p.state.negated||p.state.negatedExtglob;d&&r++;for(let f of t){let h=p(f,!0);(d?!h.isMatch:h.isMatch)&&(d?s.add(h.output):(s.delete(h.output),i.add(h.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};U.match=U;U.matcher=(t,e)=>Oe(t,e);U.isMatch=(t,e,n)=>Oe(e,n)(t);U.any=U.isMatch;U.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(U(t,e,{...n,onResult:o}));for(let a of i)r.has(a)||s.add(a);return[...s]};U.contains=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${tc.inspect(t)}"`);if(Array.isArray(e))return e.some(s=>U.contains(t,s,n));if(typeof e=="string"){if(ec(t)||ec(e))return!1;if(t.includes(e)||t.startsWith("./")&&t.slice(2).includes(e))return!0}return U.isMatch(t,e,{...n,contains:!0})};U.matchKeys=(t,e,n)=>{if(!Ys.isObject(t))throw new TypeError("Expected the first argument to be an object");let s=U(Object.keys(t),e,n),i={};for(let o of s)i[o]=t[o];return i};U.some=(t,e,n)=>{let s=[].concat(t);for(let i of[].concat(e)){let o=Oe(String(i),n);if(s.some(r=>o(r)))return!0}return!1};U.every=(t,e,n)=>{let s=[].concat(t);for(let i of[].concat(e)){let o=Oe(String(i),n);if(!s.every(r=>o(r)))return!1}return!0};U.all=(t,e,n)=>{if(typeof t!="string")throw new TypeError(`Expected a string: "${tc.inspect(t)}"`);return[].concat(e).every(s=>Oe(s,n)(t))};U.capture=(t,e,n)=>{let s=Ys.isWindows(n),o=Oe.makeRe(String(t),{...n,capture:!0}).exec(s?Ys.toPosixSlashes(e):e);if(o)return o.slice(1).map(r=>r===void 0?"":r)};U.makeRe=(...t)=>Oe.makeRe(...t);U.scan=(...t)=>Oe.scan(...t);U.parse=(t,e)=>{let n=[];for(let s of[].concat(t||[]))for(let i of nc(String(s),e))n.push(Oe.parse(i,e));return n};U.braces=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return e&&e.nobrace===!0||!sc(t)?[t]:nc(t,e)};U.braceExpand=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");return U.braces(t,{...e,expand:!0})};U.hasBraces=sc;ic.exports=U});var mc=R(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.isAbsolute=I.partitionAbsoluteAndRelative=I.removeDuplicateSlashes=I.matchAny=I.convertPatternsToRe=I.makeRe=I.getPatternParts=I.expandBraceExpansion=I.expandPatternsWithBraceExpansion=I.isAffectDepthOfReadingPattern=I.endsWithSlashGlobStar=I.hasGlobStar=I.getBaseDirectory=I.isPatternRelatedToParentDirectory=I.getPatternsOutsideCurrentDirectory=I.getPatternsInsideCurrentDirectory=I.getPositivePatterns=I.getNegativePatterns=I.isPositivePattern=I.isNegativePattern=I.convertToNegativePattern=I.convertToPositivePattern=I.isDynamicPattern=I.isStaticPattern=void 0;var rc=require("path"),Lh=Jr(),Qs=oc(),ac="**",Ih="\\",Oh=/[*?]|^!/,jh=/\[[^[]*]/,Nh=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,Mh=/[!*+?@]\([^(]*\)/,Dh=/,|\.\./,Fh=/(?!^)\/{2,}/g;function cc(t,e={}){return!lc(t,e)}I.isStaticPattern=cc;function lc(t,e={}){return t===""?!1:!!(e.caseSensitiveMatch===!1||t.includes(Ih)||Oh.test(t)||jh.test(t)||Nh.test(t)||e.extglob!==!1&&Mh.test(t)||e.braceExpansion!==!1&&Hh(t))}I.isDynamicPattern=lc;function Hh(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 Dh.test(s)}function Bh(t){return Cn(t)?t.slice(1):t}I.convertToPositivePattern=Bh;function Uh(t){return"!"+t}I.convertToNegativePattern=Uh;function Cn(t){return t.startsWith("!")&&t[1]!=="("}I.isNegativePattern=Cn;function uc(t){return!Cn(t)}I.isPositivePattern=uc;function Vh(t){return t.filter(Cn)}I.getNegativePatterns=Vh;function Gh(t){return t.filter(uc)}I.getPositivePatterns=Gh;function qh(t){return t.filter(e=>!Xs(e))}I.getPatternsInsideCurrentDirectory=qh;function Wh(t){return t.filter(Xs)}I.getPatternsOutsideCurrentDirectory=Wh;function Xs(t){return t.startsWith("..")||t.startsWith("./..")}I.isPatternRelatedToParentDirectory=Xs;function zh(t){return Lh(t,{flipBackslashes:!1})}I.getBaseDirectory=zh;function Kh(t){return t.includes(ac)}I.hasGlobStar=Kh;function pc(t){return t.endsWith("/"+ac)}I.endsWithSlashGlobStar=pc;function Jh(t){let e=rc.basename(t);return pc(t)||cc(e)}I.isAffectDepthOfReadingPattern=Jh;function Yh(t){return t.reduce((e,n)=>e.concat(dc(n)),[])}I.expandPatternsWithBraceExpansion=Yh;function dc(t){let e=Qs.braces(t,{expand:!0,nodupes:!0,keepEscaping:!0});return e.sort((n,s)=>n.length-s.length),e.filter(n=>n!=="")}I.expandBraceExpansion=dc;function Qh(t,e){let{parts:n}=Qs.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}I.getPatternParts=Qh;function fc(t,e){return Qs.makeRe(t,e)}I.makeRe=fc;function Xh(t,e){return t.map(n=>fc(n,e))}I.convertPatternsToRe=Xh;function Zh(t,e){return e.some(n=>n.test(t))}I.matchAny=Zh;function em(t){return t.replace(Fh,"/")}I.removeDuplicateSlashes=em;function tm(t){let e=[],n=[];for(let s of t)hc(s)?e.push(s):n.push(s);return[e,n]}I.partitionAbsoluteAndRelative=tm;function hc(t){return rc.isAbsolute(t)}I.isAbsolute=hc});var vc=R((Xx,bc)=>{"use strict";var nm=require("stream"),gc=nm.PassThrough,sm=Array.prototype.slice;bc.exports=im;function im(){let t=[],e=sm.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=gc(s);function a(){for(let u=0,p=arguments.length;u<p;u++)t.push(yc(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 f(h){function g(){h.removeListener("merge2UnpipeEnd",g),h.removeListener("end",g),o&&h.removeListener("error",v),d()}function v(y){r.emit("error",y)}if(h._readableState.endEmitted)return d();h.on("merge2UnpipeEnd",g),h.on("end",g),o&&h.on("error",v),h.pipe(r,{end:!1}),h.resume()}for(let h=0;h<u.length;h++)f(u[h]);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 yc(t,e){if(Array.isArray(t))for(let n=0,s=t.length;n<s;n++)t[n]=yc(t[n],e);else{if(!t._readableState&&t.pipe&&(t=t.pipe(gc(e))),!t._readableState||!t.pause||!t.pipe)throw new Error("Only readable stream can be merged.");t.pause()}return t}});var xc=R(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.merge=void 0;var om=vc();function rm(t){let e=om(t);return t.forEach(n=>{n.once("error",s=>e.emit("error",s))}),e.once("close",()=>wc(t)),e.once("end",()=>wc(t)),e}En.merge=rm;function wc(t){t.forEach(e=>e.emit("close"))}});var _c=R(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.isEmpty=xt.isString=void 0;function am(t){return typeof t=="string"}xt.isString=am;function cm(t){return t===""}xt.isEmpty=cm});var Be=R(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.string=ee.stream=ee.pattern=ee.path=ee.fs=ee.errno=ee.array=void 0;var lm=Nr();ee.array=lm;var um=Mr();ee.errno=um;var pm=Dr();ee.fs=pm;var dm=Ur();ee.path=dm;var fm=mc();ee.pattern=fm;var hm=xc();ee.stream=hm;var mm=_c();ee.string=mm});var Ec=R(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 Pe=Be();function gm(t,e){let n=Sc(t,e),s=Sc(e.ignore,e),i=Pc(n),o=Cc(n,s),r=i.filter(u=>Pe.pattern.isStaticPattern(u,e)),a=i.filter(u=>Pe.pattern.isDynamicPattern(u,e)),c=Zs(r,o,!1),l=Zs(a,o,!0);return c.concat(l)}te.generate=gm;function Sc(t,e){let n=t;return e.braceExpansion&&(n=Pe.pattern.expandPatternsWithBraceExpansion(n)),e.baseNameMatch&&(n=n.map(s=>s.includes("/")?s:`**/${s}`)),n.map(s=>Pe.pattern.removeDuplicateSlashes(s))}function Zs(t,e,n){let s=[],i=Pe.pattern.getPatternsOutsideCurrentDirectory(t),o=Pe.pattern.getPatternsInsideCurrentDirectory(t),r=ei(i),a=ei(o);return s.push(...ti(r,e,n)),"."in a?s.push(ni(".",o,e,n)):s.push(...ti(a,e,n)),s}te.convertPatternsToTasks=Zs;function Pc(t){return Pe.pattern.getPositivePatterns(t)}te.getPositivePatterns=Pc;function Cc(t,e){return Pe.pattern.getNegativePatterns(t).concat(e).map(Pe.pattern.convertToPositivePattern)}te.getNegativePatternsAsPositive=Cc;function ei(t){let e={};return t.reduce((n,s)=>{let i=Pe.pattern.getBaseDirectory(s);return i in n?n[i].push(s):n[i]=[s],n},e)}te.groupPatternsByBaseDirectory=ei;function ti(t,e,n){return Object.keys(t).map(s=>ni(s,t[s],e,n))}te.convertPatternGroupsToTasks=ti;function ni(t,e,n,s){return{dynamic:s,positive:e,negative:n,base:t,patterns:[].concat(e,n.map(Pe.pattern.convertToNegativePattern))}}te.convertPatternGroupToTask=ni});var Ac=R(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.read=void 0;function ym(t,e,n){e.fs.lstat(t,(s,i)=>{if(s!==null){kc(n,s);return}if(!i.isSymbolicLink()||!e.followSymbolicLink){si(n,i);return}e.fs.stat(t,(o,r)=>{if(o!==null){if(e.throwErrorOnBrokenSymbolicLink){kc(n,o);return}si(n,i);return}e.markSymbolicLink&&(r.isSymbolicLink=()=>!0),si(n,r)})})}kn.read=ym;function kc(t,e){t(e)}function si(t,e){t(null,e)}});var Rc=R(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.read=void 0;function bm(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}}An.read=bm});var $c=R(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.createFileSystemAdapter=Ke.FILE_SYSTEM_ADAPTER=void 0;var Rn=require("fs");Ke.FILE_SYSTEM_ADAPTER={lstat:Rn.lstat,stat:Rn.stat,lstatSync:Rn.lstatSync,statSync:Rn.statSync};function vm(t){return t===void 0?Ke.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},Ke.FILE_SYSTEM_ADAPTER),t)}Ke.createFileSystemAdapter=vm});var Tc=R(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});var wm=$c(),ii=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=wm.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}};oi.default=ii});var ut=R(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.statSync=Je.stat=Je.Settings=void 0;var Lc=Ac(),xm=Rc(),ri=Tc();Je.Settings=ri.default;function _m(t,e,n){if(typeof e=="function"){Lc.read(t,ai(),e);return}Lc.read(t,ai(e),n)}Je.stat=_m;function Sm(t,e){let n=ai(e);return xm.read(t,n)}Je.statSync=Sm;function ai(t={}){return t instanceof ri.default?t:new ri.default(t)}});var jc=R((c_,Oc)=>{var Ic;Oc.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:global):t=>(Ic||(Ic=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var Mc=R((l_,Nc)=>{Nc.exports=Cm;var Pm=jc();function Cm(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?Pm(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 ci=R(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var $n=process.versions.node.split(".");if($n[0]===void 0||$n[1]===void 0)throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var Dc=Number.parseInt($n[0],10),Em=Number.parseInt($n[1],10),Fc=10,km=10,Am=Dc>Fc,Rm=Dc===Fc&&Em>=km;Tn.IS_SUPPORT_READDIR_WITH_FILE_TYPES=Am||Rm});var Hc=R(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.createDirentFromStats=void 0;var li=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 $m(t,e){return new li(t,e)}Ln.createDirentFromStats=$m});var ui=R(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.fs=void 0;var Tm=Hc();In.fs=Tm});var pi=R(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.joinPathSegments=void 0;function Lm(t,e,n){return t.endsWith(n)?t+e:t+n+e}On.joinPathSegments=Lm});var Wc=R(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.readdir=Ye.readdirWithFileTypes=Ye.read=void 0;var Im=ut(),Bc=Mc(),Om=ci(),Uc=ui(),Vc=pi();function jm(t,e,n){if(!e.stats&&Om.IS_SUPPORT_READDIR_WITH_FILE_TYPES){Gc(t,e,n);return}qc(t,e,n)}Ye.read=jm;function Gc(t,e,n){e.fs.readdir(t,{withFileTypes:!0},(s,i)=>{if(s!==null){jn(n,s);return}let o=i.map(a=>({dirent:a,name:a.name,path:Vc.joinPathSegments(t,a.name,e.pathSegmentSeparator)}));if(!e.followSymbolicLinks){di(n,o);return}let r=o.map(a=>Nm(a,e));Bc(r,(a,c)=>{if(a!==null){jn(n,a);return}di(n,c)})})}Ye.readdirWithFileTypes=Gc;function Nm(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=Uc.fs.createDirentFromStats(t.name,i),n(null,t)})}}function qc(t,e,n){e.fs.readdir(t,(s,i)=>{if(s!==null){jn(n,s);return}let o=i.map(r=>{let a=Vc.joinPathSegments(t,r,e.pathSegmentSeparator);return c=>{Im.stat(a,e.fsStatSettings,(l,u)=>{if(l!==null){c(l);return}let p={name:r,path:a,dirent:Uc.fs.createDirentFromStats(r,u)};e.stats&&(p.stats=u),c(null,p)})}});Bc(o,(r,a)=>{if(r!==null){jn(n,r);return}di(n,a)})})}Ye.readdir=qc;function jn(t,e){t(e)}function di(t,e){t(null,e)}});var Qc=R(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.readdir=Qe.readdirWithFileTypes=Qe.read=void 0;var Mm=ut(),Dm=ci(),zc=ui(),Kc=pi();function Fm(t,e){return!e.stats&&Dm.IS_SUPPORT_READDIR_WITH_FILE_TYPES?Jc(t,e):Yc(t,e)}Qe.read=Fm;function Jc(t,e){return e.fs.readdirSync(t,{withFileTypes:!0}).map(s=>{let i={dirent:s,name:s.name,path:Kc.joinPathSegments(t,s.name,e.pathSegmentSeparator)};if(i.dirent.isSymbolicLink()&&e.followSymbolicLinks)try{let o=e.fs.statSync(i.path);i.dirent=zc.fs.createDirentFromStats(i.name,o)}catch(o){if(e.throwErrorOnBrokenSymbolicLink)throw o}return i})}Qe.readdirWithFileTypes=Jc;function Yc(t,e){return e.fs.readdirSync(t).map(s=>{let i=Kc.joinPathSegments(t,s,e.pathSegmentSeparator),o=Mm.statSync(i,e.fsStatSettings),r={name:s,path:i,dirent:zc.fs.createDirentFromStats(s,o)};return e.stats&&(r.stats=o),r})}Qe.readdir=Yc});var Xc=R(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.createFileSystemAdapter=Xe.FILE_SYSTEM_ADAPTER=void 0;var _t=require("fs");Xe.FILE_SYSTEM_ADAPTER={lstat:_t.lstat,stat:_t.stat,lstatSync:_t.lstatSync,statSync:_t.statSync,readdir:_t.readdir,readdirSync:_t.readdirSync};function Hm(t){return t===void 0?Xe.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},Xe.FILE_SYSTEM_ADAPTER),t)}Xe.createFileSystemAdapter=Hm});var Zc=R(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});var Bm=require("path"),Um=ut(),Vm=Xc(),fi=class{constructor(e={}){this._options=e,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=Vm.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,Bm.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new Um.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue(e,n){return e??n}};hi.default=fi});var Nn=R(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.Settings=Ze.scandirSync=Ze.scandir=void 0;var el=Wc(),Gm=Qc(),mi=Zc();Ze.Settings=mi.default;function qm(t,e,n){if(typeof e=="function"){el.read(t,gi(),e);return}el.read(t,gi(e),n)}Ze.scandir=qm;function Wm(t,e){let n=gi(e);return Gm.read(t,n)}Ze.scandirSync=Wm;function gi(t={}){return t instanceof mi.default?t:new mi.default(t)}});var nl=R((v_,tl)=>{"use strict";function zm(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}}tl.exports=zm});var il=R((w_,yi)=>{"use strict";var Km=nl();function sl(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=Km(Jm),i=null,o=null,r=0,a=null,c={push:g,drain:le,saturated:le,pause:u,paused:!1,get concurrency(){return n},set concurrency(C){if(!(C>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(n=C,!c.paused)for(;i&&r<n;)r++,y()},running:l,resume:f,idle:h,length:p,getQueue:d,unshift:v,empty:le,kill:b,killAndDrain:m,error:k,abort:x};return c;function l(){return r}function u(){c.paused=!0}function p(){for(var C=i,A=0;C;)C=C.next,A++;return A}function d(){for(var C=i,A=[];C;)A.push(C.value),C=C.next;return A}function f(){if(c.paused){if(c.paused=!1,i===null){r++,y();return}for(;i&&r<n;)r++,y()}}function h(){return r===0&&c.length()===0}function g(C,A){var _=s.get();_.context=t,_.release=y,_.value=C,_.callback=A||le,_.errorHandler=a,r>=n||c.paused?o?(o.next=_,o=_):(i=_,o=_,c.saturated()):(r++,e.call(t,_.value,_.worked))}function v(C,A){var _=s.get();_.context=t,_.release=y,_.value=C,_.callback=A||le,_.errorHandler=a,r>=n||c.paused?i?(_.next=i,i=_):(i=_,o=_,c.saturated()):(r++,e.call(t,_.value,_.worked))}function y(C){C&&s.release(C);var A=i;A&&r<=n?c.paused?r--:(o===i&&(o=null),i=A.next,A.next=null,e.call(t,A.value,A.worked),o===null&&c.empty()):--r===0&&c.drain()}function b(){i=null,o=null,c.drain=le}function m(){i=null,o=null,c.drain(),c.drain=le}function x(){var C=i;for(i=null,o=null;C;){var A=C.next,_=C.callback,L=C.errorHandler,D=C.value,w=C.context;C.value=null,C.callback=le,C.errorHandler=null,L&&L(new Error("abort"),D),_.call(w,new Error("abort")),C.release(C),C=A}c.drain=le}function k(C){a=C}}function le(){}function Jm(){this.value=null,this.callback=le,this.next=null,this.release=le,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=le,t.errorHandler&&o(n,r),i.call(t.context,n,s),t.release(t)}}function Ym(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=sl(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,f){o(u,function(h,g){if(h){f(h);return}d(g)})});return p.catch(le),p}function c(u){var p=new Promise(function(d,f){r(u,function(h,g){if(h){f(h);return}d(g)})});return p.catch(le),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}}yi.exports=sl;yi.exports.promise=Ym});var Mn=R(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.joinPathSegments=je.replacePathSegmentSeparator=je.isAppliedFilter=je.isFatalError=void 0;function Qm(t,e){return t.errorFilter===null?!0:!t.errorFilter(e)}je.isFatalError=Qm;function Xm(t,e){return t===null||t(e)}je.isAppliedFilter=Xm;function Zm(t,e){return t.split(/[/\\]/).join(e)}je.replacePathSegmentSeparator=Zm;function eg(t,e,n){return t===""?e:t.endsWith(n)?t+e:t+n+e}je.joinPathSegments=eg});var wi=R(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});var tg=Mn(),bi=class{constructor(e,n){this._root=e,this._settings=n,this._root=tg.replacePathSegmentSeparator(e,n.pathSegmentSeparator)}};vi.default=bi});var Si=R(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});var ng=require("events"),sg=Nn(),ig=il(),Dn=Mn(),og=wi(),xi=class extends og.default{constructor(e,n){super(e,n),this._settings=n,this._scandir=sg.scandir,this._emitter=new ng.EventEmitter,this._queue=ig(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||!Dn.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=Dn.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),Dn.isAppliedFilter(this._settings.entryFilter,e)&&this._emitEntry(e),e.dirent.isDirectory()&&Dn.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(s,n===void 0?void 0:e.path)}_emitEntry(e){this._emitter.emit("entry",e)}};_i.default=xi});var ol=R(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});var rg=Si(),Pi=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new rg.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(n=>{ag(e,n)}),this._reader.onEntry(n=>{this._storage.push(n)}),this._reader.onEnd(()=>{cg(e,this._storage)}),this._reader.read()}};Ci.default=Pi;function ag(t,e){t(e)}function cg(t,e){t(null,e)}});var rl=R(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});var lg=require("stream"),ug=Si(),Ei=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new ug.default(this._root,this._settings),this._stream=new lg.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}};ki.default=Ei});var al=R(Ri=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});var pg=Nn(),Fn=Mn(),dg=wi(),Ai=class extends dg.default{constructor(){super(...arguments),this._scandir=pg.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(Fn.isFatalError(this._settings,e))throw e}_handleEntry(e,n){let s=e.path;n!==void 0&&(e.path=Fn.joinPathSegments(n,e.name,this._settings.pathSegmentSeparator)),Fn.isAppliedFilter(this._settings.entryFilter,e)&&this._pushToStorage(e),e.dirent.isDirectory()&&Fn.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(s,n===void 0?void 0:e.path)}_pushToStorage(e){this._storage.push(e)}};Ri.default=Ai});var cl=R(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});var fg=al(),$i=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new fg.default(this._root,this._settings)}read(){return this._reader.read()}};Ti.default=$i});var ll=R(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});var hg=require("path"),mg=Nn(),Li=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,hg.sep),this.fsScandirSettings=new mg.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}};Ii.default=Li});var Bn=R(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.Settings=Ne.walkStream=Ne.walkSync=Ne.walk=void 0;var ul=ol(),gg=rl(),yg=cl(),Oi=ll();Ne.Settings=Oi.default;function bg(t,e,n){if(typeof e=="function"){new ul.default(t,Hn()).read(e);return}new ul.default(t,Hn(e)).read(n)}Ne.walk=bg;function vg(t,e){let n=Hn(e);return new yg.default(t,n).read()}Ne.walkSync=vg;function wg(t,e){let n=Hn(e);return new gg.default(t,n).read()}Ne.walkStream=wg;function Hn(t={}){return t instanceof Oi.default?t:new Oi.default(t)}});var Un=R(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});var xg=require("path"),_g=ut(),pl=Be(),ji=class{constructor(e){this._settings=e,this._fsStatSettings=new _g.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return xg.resolve(this._settings.cwd,e)}_makeEntry(e,n){let s={name:n,path:n,dirent:pl.fs.createDirentFromStats(n,e)};return this._settings.stats&&(s.stats=e),s}_isFatalError(e){return!pl.errno.isEnoentCodeError(e)&&!this._settings.suppressErrors}};Ni.default=ji});var Fi=R(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});var Sg=require("stream"),Pg=ut(),Cg=Bn(),Eg=Un(),Mi=class extends Eg.default{constructor(){super(...arguments),this._walkStream=Cg.walkStream,this._stat=Pg.stat}dynamic(e,n){return this._walkStream(e,n)}static(e,n){let s=e.map(this._getFullEntryPath,this),i=new Sg.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))})}};Di.default=Mi});var dl=R(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});var kg=Bn(),Ag=Un(),Rg=Fi(),Hi=class extends Ag.default{constructor(){super(...arguments),this._walkAsync=kg.walk,this._readerStream=new Rg.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))})}};Bi.default=Hi});var fl=R(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});var qt=Be(),Ui=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 qt.pattern.getPatternParts(e,this._micromatchOptions).map(s=>qt.pattern.isDynamicPattern(s,this._settings)?{dynamic:!0,pattern:s,patternRe:qt.pattern.makeRe(s,this._micromatchOptions)}:{dynamic:!1,pattern:s})}_splitSegmentsIntoSections(e){return qt.array.splitWhen(e,n=>n.dynamic&&qt.pattern.hasGlobStar(n.pattern))}};Vi.default=Ui});var hl=R(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});var $g=fl(),Gi=class extends $g.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}};qi.default=Gi});var ml=R(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});var Vn=Be(),Tg=hl(),Wi=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 Tg.default(e,this._settings,this._micromatchOptions)}_getNegativePatternsRe(e){let n=e.filter(Vn.pattern.isAffectDepthOfReadingPattern);return Vn.pattern.convertPatternsToRe(n,this._micromatchOptions)}_filter(e,n,s,i){if(this._isSkippedByDeep(e,n.path)||this._isSkippedSymbolicLink(n))return!1;let o=Vn.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!Vn.pattern.matchAny(e,n)}};zi.default=Wi});var gl=R(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});var et=Be(),Ki=class{constructor(e,n){this._settings=e,this._micromatchOptions=n,this.index=new Map}getFilter(e,n){let[s,i]=et.pattern.partitionAbsoluteAndRelative(n),o={positive:{all:et.pattern.convertPatternsToRe(e,this._micromatchOptions)},negative:{absolute:et.pattern.convertPatternsToRe(s,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:et.pattern.convertPatternsToRe(i,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return r=>this._filter(r,o)}_filter(e,n){let s=et.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=et.path.makeAbsolute(this._settings.cwd,e);return this._isMatchToPatterns(i,n,s)}_isMatchToPatterns(e,n,s){if(n.length===0)return!1;let i=et.pattern.matchAny(e,n);return!i&&s?et.pattern.matchAny(e+"/",n):i}};Ji.default=Ki});var yl=R(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});var Lg=Be(),Yi=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return Lg.errno.isEnoentCodeError(e)||this._settings.suppressErrors}};Qi.default=Yi});var vl=R(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});var bl=Be(),Xi=class{constructor(e){this._settings=e}getTransformer(){return e=>this._transform(e)}_transform(e){let n=e.path;return this._settings.absolute&&(n=bl.path.makeAbsolute(this._settings.cwd,n),n=bl.path.unixify(n)),this._settings.markDirectories&&e.dirent.isDirectory()&&(n+="/"),this._settings.objectMode?Object.assign(Object.assign({},e),{path:n}):n}};Zi.default=Xi});var Gn=R(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});var Ig=require("path"),Og=ml(),jg=gl(),Ng=yl(),Mg=vl(),eo=class{constructor(e){this._settings=e,this.errorFilter=new Ng.default(this._settings),this.entryFilter=new jg.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new Og.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new Mg.default(this._settings)}_getRootDirectory(e){return Ig.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}}};to.default=eo});var wl=R(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});var Dg=dl(),Fg=Gn(),no=class extends Fg.default{constructor(){super(...arguments),this._reader=new Dg.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)}};so.default=no});var xl=R(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});var Hg=require("stream"),Bg=Fi(),Ug=Gn(),io=class extends Ug.default{constructor(){super(...arguments),this._reader=new Bg.default(this._settings)}read(e){let n=this._getRootDirectory(e),s=this._getReaderOptions(e),i=this.api(n,e,s),o=new Hg.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)}};oo.default=io});var _l=R(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});var Vg=ut(),Gg=Bn(),qg=Un(),ro=class extends qg.default{constructor(){super(...arguments),this._walkSync=Gg.walkSync,this._statSync=Vg.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)}};ao.default=ro});var Sl=R(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});var Wg=_l(),zg=Gn(),co=class extends zg.default{constructor(){super(...arguments),this._reader=new Wg.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)}};lo.default=co});var Pl=R(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var St=require("fs"),Kg=require("os"),Jg=Math.max(Kg.cpus().length,1);Pt.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:St.lstat,lstatSync:St.lstatSync,stat:St.stat,statSync:St.statSync,readdir:St.readdir,readdirSync:St.readdirSync};var uo=class{constructor(e={}){this._options=e,this.absolute=this._getValue(this._options.absolute,!1),this.baseNameMatch=this._getValue(this._options.baseNameMatch,!1),this.braceExpansion=this._getValue(this._options.braceExpansion,!0),this.caseSensitiveMatch=this._getValue(this._options.caseSensitiveMatch,!0),this.concurrency=this._getValue(this._options.concurrency,Jg),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({},Pt.DEFAULT_FILE_SYSTEM_ADAPTER),e)}};Pt.default=uo});var mo=R((q_,El)=>{"use strict";var Cl=Ec(),Yg=wl(),Qg=xl(),Xg=Sl(),po=Pl(),xe=Be();async function fo(t,e){Ce(t);let n=ho(t,Yg.default,e),s=await Promise.all(n);return xe.array.flatten(s)}(function(t){t.glob=t,t.globSync=e,t.globStream=n,t.async=t;function e(l,u){Ce(l);let p=ho(l,Xg.default,u);return xe.array.flatten(p)}t.sync=e;function n(l,u){Ce(l);let p=ho(l,Qg.default,u);return xe.stream.merge(p)}t.stream=n;function s(l,u){Ce(l);let p=[].concat(l),d=new po.default(u);return Cl.generate(p,d)}t.generateTasks=s;function i(l,u){Ce(l);let p=new po.default(u);return xe.pattern.isDynamicPattern(l,p)}t.isDynamicPattern=i;function o(l){return Ce(l),xe.path.escape(l)}t.escapePath=o;function r(l){return Ce(l),xe.path.convertPathToPattern(l)}t.convertPathToPattern=r;let a;(function(l){function u(d){return Ce(d),xe.path.escapePosixPath(d)}l.escapePath=u;function p(d){return Ce(d),xe.path.convertPosixPathToPattern(d)}l.convertPathToPattern=p})(a=t.posix||(t.posix={}));let c;(function(l){function u(d){return Ce(d),xe.path.escapeWindowsPath(d)}l.escapePath=u;function p(d){return Ce(d),xe.path.convertWindowsPathToPattern(d)}l.convertPathToPattern=p})(c=t.win32||(t.win32={}))})(fo||(fo={}));function ho(t,e,n){let s=[].concat(t),i=new po.default(n),o=Cl.generate(s,i),r=new e(i);return o.map(r.read,r)}function Ce(t){if(![].concat(t).every(s=>xe.string.isString(s)&&!xe.string.isEmpty(s)))throw new TypeError("Patterns must be a string (non empty) or an array of strings")}El.exports=fo});var Or=E(Ir(),1),{program:gx,createCommand:yx,createArgument:bx,createOption:vx,CommanderError:wx,InvalidArgumentError:xx,InvalidOptionArgumentError:_x,Command:jr,Argument:Sx,Option:Px,Help:Cx}=Or.default;var st=E(require("node:fs/promises"),1),Ge=E(require("node:path"),1);var kl=E(mo(),1),qn=E(require("node:fs/promises"),1),Ue=E(require("node:path"),1),Zg=["CLAUDE.md","AGENTS.md",".cursorrules",".windsurfrules",".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"],ey=[".git","node_modules","Library","Temp","bin","obj","dist","build","worktrees",".worktrees"],ty=500*1024,ny=512;function sy(t){let e=Ue.basename(t),n=t.replace(/\\/g,"/");return e==="AGENTS.md"?"agents":e===".cursorrules"||n.includes("/.cursor/rules/")?"cursor":e==="copilot-instructions.md"||n.includes("/.github/instructions/")?"copilot":e==="CLAUDE.md"||n.includes("/.claude/")?"claude":e==="README.md"?"readme":n.includes("/docs/")&&e.endsWith(".md")?"docs":(n.includes("/ai/")||n.includes("/prompts/"))&&e.endsWith(".md")?"prompt":"unknown"}function iy(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}function Al(t){let e=t.split(`
25
+ `),this.outputHelp({error:!0}));let i=n||{},s=i.exitCode||1,r=i.code||"commander.error";this._exit(s,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in F.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()}`,F.default.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Fn(this.options),n=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&n(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,i.implied[s],"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 i=o=>{let a=o.attributeName(),c=this.getOptionValue(a),l=this.options.find(u=>u.negate&&a===u.attributeName()),p=this.options.find(u=>!u.negate&&a===u.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:p||o},s=o=>{let a=i(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},r=`error: ${s(e)} cannot be used with ${s(n)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],r=this;do{let o=r.createHelp().visibleOptions(r).filter(a=>a.long).map(a=>a.long);s=s.concat(o),r=r.parent}while(r&&!r._enablePositionalOptions);n=Ki(e,s)}let i=`error: unknown option '${e}'${n}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,i=n===1?"":"s",s=e.length,r=this.parent?` for '${this.name()}'`:"",o=e.join(", "),a=`error: too many arguments${r}. Expected ${n} argument${i} but got ${s}: ${o}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(r=>{s.push(r.name()),r.alias()&&s.push(r.alias())}),n=Ki(e,s)}let i=`error: unknown command '${e}'${n}`;this.error(i,{code:"commander.unknownCommand"})}version(e,n,i){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",i=i||"output the version number";let s=this.createOption(n,i);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.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 i=this.parent?._findCommand(e);if(i){let s=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}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(i=>Dn(i));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=je.default.basename(e,je.default.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp(),i=this._getOutputContext(e);n.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let s=n.formatHelp(this,n);return i.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(e){e=e||{};let n=!!e.error,i,s,r;return n?(i=a=>this._outputConfiguration.writeErr(a),s=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),s=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:n,write:a=>(s||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:s,helpWidth:r}}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let i=this._getOutputContext(e),s={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let r=this.helpInformation({error:i.error});if(n&&(r=n(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",s))}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(F.default.exitCode??0);n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
27
+ Expecting one of '${i.join("', '")}'`);let s=`${e}Help`;return this.on(s,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(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ha(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,i="127.0.0.1",s="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])?s=r[3]:i=r[3]):(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=r[1],i=r[3],s=r[4]),n&&s!=="0"?`${n}=${i}:${parseInt(s)+1}`:e})}function ma(){if(F.default.env.NO_COLOR||F.default.env.FORCE_COLOR==="0"||F.default.env.FORCE_COLOR==="false")return!1;if(F.default.env.FORCE_COLOR||F.default.env.CLICOLOR_FORCE!==void 0)return!0}var lS=new Tt;var lt=E(require("node:fs/promises"),1),Ke=E(require("node:path"),1);var _f=new Set(["skill","agent"]);function ba(t){return _f.has(t)}var Bn=["auto","typescript","nextjs","unity","dotnet","python","go","rust","unknown"];var fu=E(gi(),1),yi=E(require("node:fs/promises"),1),Lr=E(require("node:path"),1);var Ly=/^ {0,3}([`~]{3,})\s*([^\s`]*)/,Iy=/^ {0,3}([`~]{3,})\s*$/,lu=/(`+)([^`]+)\1/g;function st(t){let e=t.split(`
29
+ `),n=[],i=!1,s=null,r=0,o="",a=-1;for(let c=0;c<e.length;c++){let l=e[c]??"",p=c+1;if(!i){let d=Ly.exec(l);if(d){i=!0,s=d[1][0]??null,r=d[1].length,o=(d[2]??"").toLowerCase(),a=n.length,n.push({text:l,lineNumber:p,kind:"open",inFence:!0,lang:o,closed:!0});continue}n.push({text:l,lineNumber:p,kind:"text",inFence:!1,lang:"",closed:!0});continue}let u=Iy.exec(l);if(u&&u[1][0]===s&&u[1].length>=r){n.push({text:l,lineNumber:p,kind:"close",inFence:!0,lang:o,closed:!0}),i=!1,s=null,r=0,o="",a=-1;continue}n.push({text:l,lineNumber:p,kind:"content",inFence:!0,lang:o,closed:!0})}if(i&&a>=0)for(let c=a;c<n.length;c++)n[c].closed=!1;return n}function dn(t){let e=[],n=null;for(let i of st(t)){if(i.kind==="open"){n={lang:i.lang,closed:i.closed,openLine:i.lineNumber,contentStartLine:i.lineNumber+1,lines:[]},e.push(n);continue}if(i.kind==="content"&&n){n.lines.push(i.text);continue}i.kind==="close"&&(n=null)}return e}function ke(t,e={}){let n=st(t).filter(i=>!i.inFence).map(i=>i.text).join(`
30
+ `);return e.stripInlineCode?n.replace(/`[^`\n]+`/g,""):n}function uu(t){return st(t).map(e=>e.inFence?"":e.text).join(`
31
+ `)}function pu(t,e={}){let n=e.closedOnly??!0;return dn(t).filter(i=>n?i.closed:!0).map(i=>i.lines.join(`
32
+ `)).join(`
33
+ `)}function du(t){let e=new Array(t.length).fill(!1),n=0;for(let i of st(t)){if(i.inFence)e.fill(!0,n,n+i.text.length);else{let s,r=new RegExp(lu.source,lu.flags);for(;(s=r.exec(i.text))!==null;)e.fill(!0,n+s.index,n+s.index+s[0].length)}n+=i.text.length+1}return e}var be=E(require("node:path"),1);function He(t,e){let n=be.resolve(t),i=be.resolve(e),s=be.relative(n,i);return s===""||s!==".."&&!s.startsWith(`..${be.sep}`)&&!be.isAbsolute(s)}function gt(t,e){try{let n=be.resolve(t),i=be.isAbsolute(e)?be.resolve(e):be.resolve(n,e);return He(n,i)?i:null}catch{return null}}var jy=["CLAUDE.md","AGENTS.md",".cursorrules",".windsurfrules",".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"],Ny=[".git","node_modules","Library","Temp","bin","obj","dist","build","worktrees",".worktrees"],Ir=500*1024,jr=512;function My(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.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 Dy(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}function hu(t){let e=t.split(`
25
34
  `);return t.length>0&&t.endsWith(`
26
- `)&&e.pop(),e}function oy(t,e){let n=Al(t),s=[],i,o=1,r=[],a=p=>{let d=r.join(`
27
- `),f=i!==void 0?iy(i):`${e}:0`;s.push({id:f,filePath:e,heading:i,startLine:o,endLine:p,text:d,normalizedText:d.toLowerCase().trim()})},c=!1,l=null,u=0;for(let p=0;p<n.length;p++){let d=p+1,f=n[p]??"";if(c){let g=/^ {0,3}([`~]{3,})\s*$/.exec(f);if(g&&g[1][0]===l&&g[1].length>=u){c=!1,l=null,u=0,r.push(f);continue}r.push(f);continue}else{let g=/^ {0,3}([`~]{3,})/.exec(f);if(g){c=!0,l=g[1][0]??null,u=g[1].length,r.push(f);continue}}let h=/^ {0,3}(#{1,3})\s+(.+)/.exec(f);h?((r.length>0||i!==void 0)&&a(d-1),i=h[2].trim(),o=d,r=[f]):r.push(f)}return(r.length>0||i!==void 0)&&a(n.length),s}function ry(t){let e=Math.min(t.length,ny);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}async function Wt(t){let e=Ue.resolve(t.repoPath),n=t.include&&t.include.length>0?t.include:Zg,s=[...ey.map(r=>`**/${r}/**`),...t.exclude??[]],i;try{i=await(0,kl.default)(n,{cwd:e,ignore:s,dot:!0,absolute:!1,followSymbolicLinks:!1})}catch{return[]}let o=[];for(let r of i){let a=Ue.resolve(e,r),c=Ue.relative(e,a);if(!(c.startsWith("..")||Ue.isAbsolute(c)))try{let l=await qn.stat(a);if(!l.isFile()||l.size>ty)continue;let u=await qn.readFile(a);if(ry(u))continue;let p=u.toString("utf-8"),d=oy(p,a),f=Al(p).length,h=p.length;o.push({path:a,fileType:sy(a),content:p,sections:d,lineCount:f,charCount:h,estimatedTokens:Math.round(h/4)})}catch{}}return o.sort((r,a)=>r.path.localeCompare(a.path)),o}var Wn=E(require("node:fs/promises"),1),ne=E(require("node:path"),1),yo=E(mo(),1);async function Me(t){try{return await Wn.access(t),!0}catch{return!1}}async function go(t){try{return(await Wn.stat(t)).isDirectory()}catch{return!1}}async function zt(t){let e=ne.resolve(t);if((await(0,yo.default)("next.config.*",{cwd:e,dot:!1,followSymbolicLinks:!1,deep:1})).length>0)return"nextjs";let s=await Me(ne.join(e,"package.json"));if(s){let g=await go(ne.join(e,"app")),v=await go(ne.join(e,"pages"));if(g||v)return"nextjs"}let i=await Me(ne.join(e,"tsconfig.json"));if(s||i)return"typescript";let o=await go(ne.join(e,"Assets")),r=await Me(ne.join(e,"ProjectSettings","ProjectVersion.txt"));if(o&&r)return"unity";if((await(0,yo.default)(["*.sln","*.csproj"],{cwd:e,dot:!1,followSymbolicLinks:!1,deep:1})).length>0)return"dotnet";let c=await Me(ne.join(e,"pyproject.toml")),l=await Me(ne.join(e,"requirements.txt")),u=await Me(ne.join(e,"Pipfile")),p=await Me(ne.join(e,"environment.yml")),d=await Me(ne.join(e,"setup.py"));return c||l||u||p||d?"python":await Me(ne.join(e,"go.mod"))?"go":await Me(ne.join(e,"Cargo.toml"))?"rust":"unknown"}function bo(t){let e=t.map(n=>n.content).join(`
28
- `);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":/\btypescript\b|\btsconfig\b|\btsc\s|\bpnpm\b|\bnpm\s+run\b|\bvitest\b|\bjest\b/i.test(e)?"typescript":/\bdotnet\b|\.sln\b|\.csproj\b|\bxunit\b|\bnunit\b|\bmstest\b/i.test(e)?"dotnet":/\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 Tl=E(require("node:crypto"),1),zn=150,ay=80,cy=10,ly=.8,uy=.6,py=.6,Rl=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 Ll(t){return t.toLowerCase().replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+\.\s+/gm,"").replace(/\s+/g," ").trim()}function vo(t){let e=t.match(/\b\w+\b/g)??[];return new Set(e)}function dy(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 fy(t){return t.length<=200?t:`${t.slice(0,200)}\u2026`}function wo(t){if(!t)return!1;let e=t.toLowerCase().trim();if(Rl.has(e))return!0;for(let n of Rl)if(e.startsWith(n))return!0;return!1}function $l(t){return t?.toLowerCase().replace(/\s+/g," ").trim()??""}function hy(t,e){let n=$l(t.heading),s=$l(e.heading);return n.length>0&&n===s}function Kt(t,e){if(!t.has(e))return e;let n=Kt(t,t.get(e));return t.set(e,n),n}function my(t,e,n){let s=Kt(t,e),i=Kt(t,n);s!==i&&t.set(s,i)}function xo(t){let e=[...t].sort().join("|");return`duplicate-${Tl.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function _o(t){let e=[];for(let u of t)for(let p of u.sections){let d=Ll(p.text);d.length<ay||vo(d).size<cy||e.push({...p,normalizedText:d})}let n=new Map,s=new Map,i=[];for(let u=0;u<e.length;u++)for(let p=u+1;p<e.length;p++){let d=e[u],f=e[p];if(d.filePath===f.filePath&&d.startLine===f.startLine)continue;let h=`${d.filePath}:${d.startLine}`,g=`${f.filePath}:${f.startLine}`,v=d.normalizedText,y=f.normalizedText,b=null,m=0;if(wo(d.heading)||wo(f.heading))continue;let x=d.filePath===f.filePath;if(v===y){if(!x&&(v.length<zn||y.length<zn)&&!hy(d,f))continue;b="high",m=.95}else{if(!x&&(v.length<zn||y.length<zn))continue;let k=x?py:ly,C=dy(vo(v),vo(y));C>=k?(b="warning",m=x?.8:.75):!x&&C>=uy&&(b="info",m=.5)}b!==null&&(s.set(h,d),s.set(g,f),my(n,h,g),i.push({keyA:h,keyB:g,severity:b,confidence:m}))}let o=new Map;for(let u of s.keys()){let p=Kt(n,u);o.has(p)||o.set(p,[]),o.get(p).push(u)}let r={info:0,warning:1,high:2,critical:3},a=new Map,c=new Map;for(let u of i){let p=Kt(n,u.keyA),d=a.get(p);(!d||r[u.severity]>r[d])&&(a.set(p,u.severity),c.set(p,u.confidence))}let l=[];for(let[u,p]of o){if(p.length<2)continue;let d=p.map(C=>s.get(C)),f=a.get(u)??"warning",h=c.get(u)??.75,g=[...new Set(d.map(C=>C.filePath))],v=[...new Set(d.map(C=>C.heading??"(untitled)"))],y=v.length===1?v[0]:v.slice(0,2).join(" / "),b=g.length,m=b>2?`Possible duplicate: ${y} (${b} files)`:`Possible duplicate: ${y}`,x=d.slice(1).reduce((C,A)=>C+Math.round(A.text.length/4),0),k=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:xo(p),severity:f,category:"duplicate",title:m,summary:k,filePaths:g,locations:d.map(C=>({filePath:C.filePath,startLine:C.startLine,endLine:C.endLine})),evidence:[fy(d[0].normalizedText),`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.`,confidence:h})}return l}function So(t){let e=[];for(let n of t){let s=new Map;for(let r of n.sections){if(!r.heading||wo(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=>`${n.path}:${p.startLine}`),l=xo(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 h=[c,l].sort().join("|");if(o.has(h))continue;o.add(h);let g=s.get(c),v=s.get(l),y=[...g,...v].sort((m,x)=>m.startLine-x.startLine),b=y.map(m=>`${n.path}:${m.startLine}`);e.push({id:xo(b),severity:"warning",category:"duplicate",title:`Overlapping section headings in one file: "${g[0].heading}" / "${v[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(m=>({filePath:n.path,startLine:m.startLine,endLine:m.endLine})),evidence:[`"${g[0].heading}" at line ${g[0].startLine}`,`"${v[0].heading}" at line ${v[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 Jn=E(require("node:crypto"),1),Po=E(require("node:path"),1),gy=1,Bl=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"]),yy=new Set(["for","when","if","unless","except"]),by=new Set(["it","them","they","we","code","sure","careful","good","clean","simple","easy","proper","consistent","clear","correct","possible","necessary","appropriate"]),Ul=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 Il(t,e,n=3,s=!1){let i=t.slice(e).replace(/^\s+/,"");if(s){let a=/^([a-zA-Z]+)\s+/.exec(i);a&&Ul.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&&(Bl.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 Jt=[{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 vy(t,e,n,s){let i=t.slice(e).replace(/^\s+/,"");if(s){let l=/^([a-zA-Z]+)\s+/.exec(i);l&&Ul.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 yy.has(c)}function Kn(t){return t.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim()}function Ol(t){if(!t||t.length<2)return!0;let e=t.split(" ").filter(Boolean);return e.length===0?!0:e.every(n=>by.has(n))}function wy(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 jl(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&&!Bl.has(c)&&(r.unshift(c),r.length>=n))break}return r.join(" ")}function xy(t){let e=t.text.split(`
29
- `).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 Nl(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 _y(t){let e=[],n=xy({...t,text:Eo(t.text)});for(let s=0;s<Jt.length;s++){let i=Jt[s];for(let o of n){let r=i.skipLeadingVerb??!1,a=i.extractSubjectBefore??!1,c=Nl(i.negativePattern,o),l=o;for(let p of c){let d=p.index+p.text.length,f=a,h=Kn(f?jl(o,p.index,4):Il(o,d,3,r));if(h.length>=2&&!Ol(h)){let g=!f&&vy(o,d,h,r);e.push({section:t,pairIndex:s,polarity:"negative",subject:h,matchedLine:o,hasQualifier:g})}l=l.slice(0,p.index)+" ".repeat(p.text.length)+l.slice(d)}let u=Nl(i.positivePattern,l);for(let p of u){let d=a||(i.extractPositiveSubjectBefore??!1),f=Kn(d?jl(o,p.index,4):Il(o,p.index+p.text.length,3,r));f.length>=2&&!Ol(f)&&e.push({section:t,pairIndex:s,polarity:"positive",subject:f,matchedLine:o})}}}return e}function Ml(t,e,n,s,i,o){let r=[`${t}:${e}`,`${n}:${s}`].sort(),a=`${r[0]}|${r[1]}|${i}|${o}`;return`conflict-${Jn.createHash("sha1").update(a).digest("hex").slice(0,12)}`}function Co(t){let e=[];for(let a of t)for(let c of a.sections)c.text.trim().length>=gy&&e.push(c);let n=[];for(let a of e)n.push(..._y(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,f=p.subject===d.subject?1:wy(p.subject,d.subject),h;if(p.subject===d.subject){let k=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)),C=Jt[l.pairIndex];h=d.hasQualifier&&/\balways\b/i.test(p.matchedLine)&&C.label.includes("always")?.5:d.hasQualifier?.35:k?.5:.8}else if(f>=.5){let x=Jt[l.pairIndex],k=p.subject.split(" ").filter(Boolean),C=d.subject.split(" ").filter(Boolean);if(k.length<2||C.length<2){if(!x.allowSingleTokenMatch)continue;let A=k.length<=C.length?k[0]:C[0];if(!(k.length>C.length?p.subject:d.subject).startsWith(A))continue}h=d.hasQualifier?.3:.5}else continue;if(h<.4)continue;let g=Ml(p.section.filePath,p.section.startLine,d.section.filePath,d.section.startLine,l.pairIndex,p.subject);if(i.has(g))continue;i.add(g);let v=h>=.7?"high":"warning",y=Jt[l.pairIndex],b=p.subject.length<=d.subject.length?p.subject:d.subject,m=Array.from(new Set([p.section.filePath,d.section.filePath]));s.push({id:g,severity:v,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:m,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:h})}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 h=u.subject.split(" ").filter(Boolean).length,g=p.subject.split(" ").filter(Boolean).length;if(h<2||g<2)continue}if(p.hasQualifier)continue;let d=Ml(u.section.filePath,u.section.startLine,p.section.filePath,p.section.startLine,-1,a);if(i.has(d))continue;i.add(d);let f=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:f,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 Sy=[{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 Py(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 Cy(t){let e=new Map;for(let{re:n,name:s,normalize:i}of Sy){let o=new RegExp(n.source,n.flags),r;for(;(r=o.exec(t))!==null;){if(Py(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 Eo(t){let e=t.split(`
30
- `),n=[],s=!1,i=null,o=0;for(let r of e)if(s){let a=/^ {0,3}([`~]{3,})\s*$/.exec(r);a&&a[1][0]===i&&a[1].length>=o&&(s=!1,i=null,o=0)}else{let a=/^ {0,3}([`~]{3,})/.exec(r);if(a){s=!0,i=a[1][0]??null,o=a[1].length;continue}n.push(r)}return n.join(`
31
- `)}function Ey(t,e){let n=`version-conflict:${t}:${[...e].sort().join("|")}`;return`version-conflict-${Jn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function ko(t){if(t.length<2)return[];let e=t.map(o=>({file:o,versions:Cy(Eo(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(f=>r.get(f)).every(f=>f.every(h=>h===c[0])))continue;let p=Ey(o,a),d=a.map(f=>`${o} ${f} referenced in: ${r.get(f).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(f=>({filePath:f})),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 ky(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ay={"kebab-case":["kebab-case","kebab case","kebabcase"],camelcase:["camelcase","camel case","camel-case"],pascalcase:["pascalcase","pascal case","pascal-case"]};function Dl(t){let e=Ay[t.toLowerCase()]??[t];return new RegExp(`\\b(?:${e.map(ky).join("|")})\\b`,"i")}var Ry=[{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"}],Fl=/\b(?:use|prefer|always|must|should|follow|rely\s+on|stick\s+to|require)\b/i;function Hl(t,e){let n=t.split(`
32
- `).map(s=>s.trim());for(let s=0;s<n.length;s++){let i=n[s];if(e.test(i)&&Fl.test(i))return!0;let o=n[s+1];if(i&&o){let r=`${i} ${o}`;if(e.test(r)&&Fl.test(r))return!0}}return!1}function Ao(t){if(t.length<2)return[];let e=[],n=new Set,s=new Map(t.map(o=>[o.path,Eo(o.content)])),i=o=>s.get(o.path)??o.content;for(let o of Ry){let r=Dl(o.termA),a=Dl(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 f=c.some(b=>Hl(i(b),r)),h=l.some(b=>Hl(i(b),a));if(!f&&!h)continue;let g=[o.termA.toLowerCase(),o.termB.toLowerCase()].sort().join("|");if(n.has(g))continue;n.add(g);let v=[...new Set([...c,...l].map(b=>b.path))],y=`competing-tech-${Jn.createHash("sha1").update(g).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:v,locations:v.map(b=>({filePath:b})),evidence:[`"${o.termA}" referenced in: ${c.map(b=>Po.basename(b.path)).join(", ")}`,`"${o.termB}" referenced in: ${l.map(b=>Po.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 $o=E(require("node:fs"),1),ue=E(require("node:path"),1),Xl=E(require("node:crypto"),1),Vl=/\[(?:[^\]]*)\]\(([^)]+)\)/g,Gl=/\[(?:[^\]]|\]\([^)]*\))*\]\(([^)]+)\)/g,ql=/^[ \t]{0,3}\[[^\]]+\]:\s*(\S+)/gm,Wl=/(?<!\w)@((?:\.{1,2}\/)?[\w./\\-]+\.(?:md|ts|js|mjs|cjs|tsx|jsx|json|yml|yaml|toml|txt|sh|py|cs|go|rs))/g,zl=/`([^\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,Kl=/^[ \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,Jl="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",$y=new RegExp(`^(?:#{1,4}\\s+.*\\b(?:${Jl})\\b|\\*\\*[^*\\n]*\\b(?:${Jl})\\b[^*\\n]*\\*\\*\\s*)`,"im"),Ty=/\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 Yl(t){return dt(t).replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase()}var Ly=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 Ct(t){return/^https?:\/\/|^mailto:|^#|^data:/.test(t.trimStart())}function Ql(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 Iy=/^(foo|bar|baz|qux|quux|example|sample|placeholder|stub|demo|test|your[-_]?file|my[-_]?file|filename|file[-_]?name)(\.\w+)?$/i,Oy=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"]),jy=/^(ComponentName|MyComponent|YourComponent|WidgetName|FeatureName|ModuleName|ServiceName|ModelName|EntityName|ResourceName|DomainName|ControllerName|ScreenName|PageName)(?:\.\w+)*$/i;function Ny(t){if(/<[A-Za-z][A-Za-z0-9_-]*>/.test(t)||/\{[A-Za-z][A-Za-z0-9_-]*\}/.test(t)||t.split("/").includes("..."))return!0;let e=ue.basename(dt(t)),n=ue.dirname(dt(t)),s=n!=="."&&n!==""&&n!==".\\"&&n!=="./";return!!(!s&&Iy.test(e)||jy.test(e)||!s&&Oy.has(e.toLowerCase())||/camelCase|CamelCase|PascalCase|pascalCase|kebab[-_]?[Cc]ase|snake_?[Cc]ase/.test(e))}var My=[/(?:^|[/\\])\.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 Dy(t){let e=t.replace(/\\/g,"/");return My.some(n=>n.test(e))}function Ro(t){let e=ue.extname(t.split("#")[0]??"").toLowerCase();return Ly.has(e)}function dt(t){return t.split("#")[0].split("?")[0].trim()}function Fy(t){try{return $o.existsSync(t)}catch{return!1}}var Hy=new Set([".go",".cs",".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".sh",".java",".kt",".swift"]),By=new Set([".go",".rs",".cs",".java",".kt",".swift",".ts",".tsx"]),Uy=/(?:^|[/\\])(?:legacy|old|deprecated|archive|archived)(?:[/\\]|[-_.])/i,Vy=new Set(["readme","claude","agents","cursor","copilot","docs","prompt","unknown"]),Gy=.45;function qy(t){try{return $o.existsSync(ue.dirname(t))}catch{return!1}}function Wy(t){let e=`dead-ref:${t}`;return`dead-ref-${Xl.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function zy(t){let e=[0];for(let n=0;n<t.length;n++)t[n]===`
33
- `&&e.push(n+1);return e}function pt(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 Ky=/\.(?:md|png|jpg|jpeg|gif|svg|webp|pdf)$/i;function Jy(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 Zl(t,e,n){let s=[],i=[],o=n;for(let r of t){let a=o;o+=r.length+1;let c=Jy(r);if(!c)continue;let l=c.entry;if(/\/$/.test(l)){let h=`${[...i].reverse().find(g=>g.indent<c.indent||g.indent===c.indent&&g.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(!Ky.test(l))continue;let p=[...i].reverse().find(f=>f.indent<c.indent||f.indent===c.indent&&f.plain),d=/[/\\]/.test(l)?l:`${p?.path??""}${l}`;s.push({ref:d,evidence:r.trim(),line:pt(e,a)})}return s}function Yy(t,e){let n=[],s=/^```[^\n]*\n([\s\S]*?)^```/gm,i;for(;(i=s.exec(t))!==null;){let o=i[1]??"",r=t.indexOf(`
34
- `,i.index),a=r===-1?i.index:r+1,c=o.split(`
35
- `);n.push(...Zl(c,e,a))}return n}function Qy(t,e){return Zl(t.split(`
36
- `),e,0)}function Xy(t,e={}){let n=[],s=zy(t),i,o=new RegExp(Vl.source,Vl.flags);for(;(i=o.exec(t))!==null;){if(i.index>=2&&t[i.index-2]==="["&&t[i.index-1]==="!")continue;let p=i[1]??"",d=dt(Ql(p));d&&!Ct(d)&&Ro(d)&&n.push({ref:d,evidence:`[...](${p})`,line:pt(s,i.index)})}let r=new RegExp(Gl.source,Gl.flags);for(;(i=r.exec(t))!==null;){if(!i[0].slice(0,i[0].lastIndexOf("](")).includes("]("))continue;let d=i[1]??"",f=dt(Ql(d));f&&!Ct(f)&&Ro(f)&&n.push({ref:f,evidence:`[...](${d})`,line:pt(s,i.index)})}let a=new RegExp(ql.source,ql.flags);for(;(i=a.exec(t))!==null;){let p=i[1]??"",d=dt(p);d&&!Ct(d)&&Ro(d)&&n.push({ref:d,evidence:i[0].trim(),line:pt(s,i.index)})}let c=new RegExp(Wl.source,Wl.flags);for(;(i=c.exec(t))!==null;){let p=i[1]??"";p&&!Ct(p)&&n.push({ref:p,evidence:`@${p}`,line:pt(s,i.index)})}let l=new RegExp(zl.source,zl.flags);for(;(i=l.exec(t))!==null;){let p=i[1]??"";if(p&&!Ct(p)&&!p.includes("*")&&!p.includes("?")){if(e.skipSourceBackticks){let d=ue.extname(p).toLowerCase();if(By.has(d)&&!Uy.test(p))continue}n.push({ref:p,evidence:`\`${p}\``,line:pt(s,i.index)})}}if($y.test(t)){let p=new RegExp(Kl.source,Kl.flags);for(;(i=p.exec(t))!==null;){let d=i[1]??"";d&&!Ct(d)&&n.push({ref:d,evidence:i[0].trim(),line:pt(s,i.index)})}n.push(...Qy(t,s));for(let d of Yy(t,s))n.push(d)}let u=t.split(`
37
- `);return n.filter(({ref:p,line:d})=>{let f=u[d-1]??"",h=Ty.exec(f);if(!h)return!0;let g=Yl(h[1]??"");if(!g)return!0;let v=Yl(p);return!(v===g||v.endsWith(`/${g}`)||g.endsWith(`/${v}`))})}function To(t,e){let n=new Map;for(let o of t){let r=ue.dirname(o.path),a=Xy(o.content,{skipSourceBackticks:Vy.has(o.fileType)});for(let{ref:c,evidence:l,line:u}of a){if(Ny(c)||Dy(c))continue;let p=[ue.resolve(r,c),ue.resolve(e,c)];if(p.some(Fy))continue;let d=ue.extname(c.split("#")[0]??"").toLowerCase(),f=Hy.has(d),h=p.some(qy),g=f&&h?.5:.85,v=c.toLowerCase().replace(/\\/g,"/"),y=`Reference: ${l}`;n.has(v)||n.set(v,{displayRef:c,filePaths:new Set,fileLines:new Map,evidenceLines:[],minConfidence:g});let b=n.get(v);b.filePaths.add(o.path);let m=b.fileLines.get(o.path);(m===void 0||u<m)&&b.fileLines.set(o.path,u),b.evidenceLines.includes(y)||b.evidenceLines.push(y),b.minConfidence=Math.min(b.minConfidence,g)}}let s=[],i=Gy;for(let[o,{displayRef:r,filePaths:a,fileLines:c,evidenceLines:l,minConfidence:u}]of n){if(u<i)continue;let p=[...a];s.push({id:Wy(o),severity:"warning",category:"structure",title:`Broken file reference: ${ue.basename(dt(r))}`,summary:`This instruction file references "${r}" which does not appear to exist. The file may have been renamed, moved, or deleted.`,filePaths:p,locations:p.map(d=>{let f=c.get(d);return f!==void 0?{filePath:d,startLine:f}:{filePath:d}}),evidence:l,recommendation:"Verify the path is correct relative to the instruction file location, or remove the reference if the file no longer exists.",confidence:u})}return s}var tt=E(require("node:crypto"),1),Ve=E(require("node:path"),1),Et=[{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:"info",confidence:.7,fixRecipe:"If tests or commands fail, report the failure honestly. Never claim success when checks are skipped or error."},{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:"info",confidence:.7,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:"info",confidence:.65,fixRecipe:"Prefer focused, minimal diffs. Do not rewrite or refactor code unrelated to the current task."},{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."}],Zy=/\bdo\s+not\s+(edit|modify|change)\b/im,eb=/<!--\s*auto[- ]?generated|auto[- ]?generated|<!--\s*generated\s*(?:by\s+\w+)?|this\s+file\s+is\s+generated|generated\s+by\s+\w+/i,tb=/<\/?claude:[\w-]+|<instructions-for-claude[\s>]/i,eu=/(?:follow|use|see|refer\s+to|canonical\s+(?:source|instructions?)|pointer\s+to)\s+[`'"*]*(?:\.?\/)?(?:\.github\/)?(?:AGENTS|CLAUDE)\.md\b/i;function nb(t){return`agent-practice-${tt.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function sb(t){return`do-not-edit-${tt.createHash("sha1").update(`do-not-edit:${t}`).digest("hex").slice(0,12)}`}function ib(t){return`per-file-behavior-${tt.createHash("sha1").update(`per-file-behavior:${t}`).digest("hex").slice(0,12)}`}function Yt(t,e){return e.some(n=>n.test(t))}function ob(t,e){let n=1;for(let s=0;s<e&&s<t.length;s++)t[s]===`
38
- `&&n++;return n}function Yn(t){return t.split(`
35
+ `)&&e.pop(),e}function bi(t,e){let n=hu(t),i=[],s,r=1,o=[],a=l=>{let p=o.join(`
36
+ `),u=s!==void 0?Dy(s):`${e}:0`;i.push({id:u,filePath:e,heading:s,startLine:r,endLine:l,text:p,normalizedText:p.toLowerCase().trim()})},c=st(t);for(let l=0;l<n.length;l++){let p=l+1,u=n[l]??"";if(c[l]?.inFence){o.push(u);continue}let d=/^ {0,3}(#{1,3})\s+(.+)/.exec(u);d?((o.length>0||s!==void 0)&&a(p-1),s=d[2].trim(),r=p,o=[u]):o.push(u)}return(o.length>0||s!==void 0)&&a(n.length),i}function Nr(t){let e=Math.min(t.length,jr);for(let n=0;n<e;n++)if(t[n]===0)return!0;return!1}async function fn(t){let e=Lr.resolve(t.repoPath),n=t.include&&t.include.length>0?t.include:jy,i=[...Ny.map(o=>`**/${o}/**`),...t.exclude??[]],s;try{s=await(0,fu.default)(n,{cwd:e,ignore:i,dot:!0,absolute:!1,followSymbolicLinks:!1})}catch{return[]}let r=[];for(let o of s){let a=Lr.resolve(e,o);if(He(e,a))try{let c=await yi.stat(a);if(!c.isFile()||c.size>Ir)continue;let l=await yi.readFile(a);if(Nr(l))continue;let p=l.toString("utf-8"),u=bi(p,a),d=hu(p).length,f=p.length;r.push({path:a,fileType:My(o),content:p,sections:u,lineCount:d,charCount:f,estimatedTokens:Math.round(f/4)})}catch{}}return r.sort((o,a)=>o.path.localeCompare(a.path)),r}var vi=E(require("node:fs/promises"),1),se=E(require("node:path"),1),Dr=E(gi(),1);async function Be(t){try{return await vi.access(t),!0}catch{return!1}}async function Mr(t){try{return(await vi.stat(t)).isDirectory()}catch{return!1}}async function hn(t){let e=se.resolve(t);if((await(0,Dr.default)("next.config.*",{cwd:e,dot:!1,followSymbolicLinks:!1,deep:1})).length>0)return"nextjs";let i=await Be(se.join(e,"package.json"));if(i){let m=await Mr(se.join(e,"app")),b=await Mr(se.join(e,"pages"));if(m||b)return"nextjs"}let s=await Mr(se.join(e,"Assets")),r=await Be(se.join(e,"ProjectSettings","ProjectVersion.txt"));if(s&&r)return"unity";if((await(0,Dr.default)(["*.sln","*.csproj"],{cwd:e,dot:!1,followSymbolicLinks:!1,deep:1})).length>0)return"dotnet";let a=await Be(se.join(e,"tsconfig.json"));if(i||a)return"typescript";let c=await Be(se.join(e,"pyproject.toml")),l=await Be(se.join(e,"requirements.txt")),p=await Be(se.join(e,"Pipfile")),u=await Be(se.join(e,"environment.yml")),d=await Be(se.join(e,"setup.py"));return c||l||p||u||d?"python":await Be(se.join(e,"go.mod"))?"go":await Be(se.join(e,"Cargo.toml"))?"rust":"unknown"}function Fr(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 yu=E(require("node:crypto"),1);function J(t,e=120){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e)}\u2026`}function Fy(t,e,n=120){let s=new RegExp(e.source,e.flags.replace("g","")).exec(t);return s?J(s[0],n):void 0}function Ht(t,e,n,i=120){let s=Fy(t,e,i);return s?`${n}: "${s}"`:n}var wi=150,Hy=80,By=10,Gy=.8,Wy=.6,Vy=.6,mu=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 bu(t){return t.toLowerCase().replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+\.\s+/gm,"").replace(/\s+/g," ").trim()}function Hr(t){let e=t.match(/\b\w+\b/g)??[];return new Set(e)}function qy(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 i of t)e.has(i)&&n++;return n/(t.size+e.size-n)}function Br(t){if(!t)return!1;let e=t.toLowerCase().trim();if(mu.has(e))return!0;for(let n of mu)if(e.startsWith(n))return!0;return!1}function gu(t){return t?.toLowerCase().replace(/\s+/g," ").trim()??""}function Uy(t,e){let n=gu(t.heading),i=gu(e.heading);return n.length>0&&n===i}function mn(t,e){if(!t.has(e))return e;let n=mn(t,t.get(e));return t.set(e,n),n}function zy(t,e,n){let i=mn(t,e),s=mn(t,n);i!==s&&t.set(i,s)}function Gr(t){let e=[...t].sort().join("|");return`duplicate-${yu.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function Wr(t){let e=[];for(let p of t)for(let u of p.sections){let d=bu(u.text);d.length<Hy||Hr(d).size<By||e.push({...u,normalizedText:d})}let n=new Map,i=new Map,s=[];for(let p=0;p<e.length;p++)for(let u=p+1;u<e.length;u++){let d=e[p],f=e[u];if(d.filePath===f.filePath&&d.startLine===f.startLine)continue;let h=`${d.filePath}:${d.startLine}`,m=`${f.filePath}:${f.startLine}`,b=d.normalizedText,y=f.normalizedText,v=null,g=0;if(Br(d.heading)||Br(f.heading))continue;let S=d.filePath===f.filePath;if(b===y){if(!S&&(b.length<wi||y.length<wi)&&!Uy(d,f))continue;v="high",g=.95}else{if(!S&&(b.length<wi||y.length<wi))continue;let $=S?Vy:Gy,P=qy(Hr(b),Hr(y));P>=$?(v="warning",g=S?.8:.75):!S&&P>=Wy&&(v="info",g=.5)}v!==null&&(i.set(h,d),i.set(m,f),zy(n,h,m),s.push({keyA:h,keyB:m,severity:v,confidence:g}))}let r=new Map;for(let p of i.keys()){let u=mn(n,p);r.has(u)||r.set(u,[]),r.get(u).push(p)}let o={info:0,warning:1,high:2,critical:3},a=new Map,c=new Map;for(let p of s){let u=mn(n,p.keyA),d=a.get(u);(!d||o[p.severity]>o[d])&&(a.set(u,p.severity),c.set(u,p.confidence))}let l=[];for(let[p,u]of r){if(u.length<2)continue;let d=u.map(P=>i.get(P)),f=a.get(p)??"warning",h=c.get(p)??.75,m=[...new Set(d.map(P=>P.filePath))],b=[...new Set(d.map(P=>P.heading??"(untitled)"))],y=b.length===1?b[0]:b.slice(0,2).join(" / "),v=m.length,g=v>2?`Possible duplicate: ${y} (${v} files)`:`Possible duplicate: ${y}`,S=d.slice(1).reduce((P,O)=>P+Math.round(O.text.length/4),0),$=v>2?`This section appears highly similar in ${v} files. Consider consolidating into one canonical location.`:"These sections appear highly similar. Consider consolidating them into one canonical location.";l.push({id:Gr(u),severity:f,category:"duplicate",title:g,summary:$,filePaths:m,locations:d.map(P=>({filePath:P.filePath,startLine:P.startLine,endLine:P.endLine})),evidence:[J(d[0].normalizedText,200),`Duplicated size: ~${S} tokens`],recommendation:`Consolidate these sections into one canonical location (e.g. AGENTS.md) and use forwarding pointers to save ~${S} tokens per session. If both are intentional, add a comment clarifying the distinction.`,autoApplySafe:v>=2,confidence:h})}return l}function Vr(t){let e=[];for(let n of t){let i=new Map;for(let o of n.sections){if(!o.heading||Br(o.heading))continue;let a=o.heading.toLowerCase().replace(/^#+\s*/,"").replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim();a.length<3||(i.has(a)||i.set(a,[]),i.get(a).push(o))}for(let[,o]of i){if(o.length<2||new Set(o.map(u=>{let d=/^(#{1,6})\s/.exec(u.text);return d?d[1].length:0})).size>1)continue;let c=o.map(u=>`${n.path}:${u.startLine}`),l=Gr(c),p=o[0].heading??"(untitled)";e.push({id:l,severity:"warning",category:"duplicate",title:`Duplicate section heading in one file: "${p}"`,summary:`The heading "${p}" 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(u=>({filePath:n.path,startLine:u.startLine,endLine:u.endLine})),evidence:[`Heading "${p}" found at lines: ${o.map(u=>u.startLine).join(", ")}`],recommendation:"Merge the duplicate sections into one, or rename one if the distinction is intentional.",confidence:.85})}let s=[...i.keys()],r=new Set;for(let o=0;o<s.length;o++)for(let a=o+1;a<s.length;a++){let c=s[o],l=s[a],p=c.length<=l.length?c:l,u=c.length<=l.length?l:c;if(p.length<4||!u.startsWith(p))continue;let d=u.slice(p.length);if(!/^\s/.test(d)||!d.trimStart())continue;let h=[c,l].sort().join("|");if(r.has(h))continue;r.add(h);let m=i.get(c),b=i.get(l),y=[...m,...b].sort((g,S)=>g.startLine-S.startLine),v=y.map(g=>`${n.path}:${g.startLine}`);e.push({id:Gr(v),severity:"warning",category:"duplicate",title:`Overlapping section headings in one file: "${m[0].heading}" / "${b[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(g=>({filePath:n.path,startLine:g.startLine,endLine:g.endLine})),evidence:[`"${m[0].heading}" at line ${m[0].startLine}`,`"${b[0].heading}" at line ${b[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 xi=E(require("node:crypto"),1),qr=E(require("node:path"),1);var Ky=1,Au=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"]),Jy=new Set(["for","when","if","unless","except"]),Yy=new Set(["it","them","they","we","code","sure","careful","good","clean","simple","easy","proper","consistent","clear","correct","possible","necessary","appropriate"]),Ru=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 vu(t,e,n=3,i=!1){let s=t.slice(e).replace(/^\s+/,"");if(i){let a=/^([a-zA-Z]+)\s+/.exec(s);a&&Ru.has(a[1].toLowerCase())&&(s=s.slice(a[0].length))}let r=[],o=s.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&&(Au.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 gn=[{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 Xy(t,e,n,i){let s=t.slice(e).replace(/^\s+/,"");if(i){let l=/^([a-zA-Z]+)\s+/.exec(s);l&&Ru.has(l[1].toLowerCase())&&(s=s.slice(l[0].length))}let r=s.replace(/[—–].*$/,"").replace(/\s*\(.*$/,"").replace(/[,;:.].*$/,"").trim(),o=n.split(" ").filter(Boolean),a=r;for(let l of o){let p=a.toLowerCase().indexOf(l);if(p<0)return!1;a=a.slice(p+l.length).trimStart()}a=a.replace(/^[^a-zA-Z]+/,"");let c=/^([a-zA-Z]+)/.exec(a)?.[1]?.toLowerCase()??"";return Jy.has(c)}function _i(t){return t.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim()}function wu(t){if(!t||t.length<2)return!0;let e=t.split(" ").filter(Boolean);return e.length===0?!0:e.every(n=>Yy.has(n))}function Qy(t,e){let n=new Set(t.split(" ").filter(Boolean)),i=new Set(e.split(" ").filter(Boolean));if(n.size===0||i.size===0)return 0;let s=0;for(let o of n)i.has(o)&&s++;let r=n.size+i.size-s;return s/r}function _u(t,e,n=4){let i=t.slice(0,e).trimEnd();if(!i)return"";let s=0;for(let a=i.length-1;a>=0;a--)if(/[,;.]/.test(i[a])){s=a+1;break}let r=i.slice(s).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&&!Au.has(c)&&(o.unshift(c),o.length>=n))break}return o.join(" ")}function Zy(t){let e=t.text.split(`
38
+ `).map(s=>s.trim()),n=[],i="";for(let s of e){let r=/^ {0,3}#{1,6}\s/.test(s),o=/^(?:[-*+]\s+|\d+[.)]\s+)/.test(s);if(!s||s.startsWith("|")||r){i&&(n.push(i),i=""),r&&n.push(s);continue}o&&i&&(n.push(i),i=""),i=i?`${i} ${s}`:s,/[.!?:;]$/.test(s)&&(n.push(i),i="")}return i&&n.push(i),n}function xu(t,e){let n=t.flags.includes("g")?t.flags:`${t.flags}g`,i=new RegExp(t.source,n),s=[],r;for(;(r=i.exec(e))!==null;)s.push({index:r.index,text:r[0]}),r[0].length===0&&i.lastIndex++;return s}function eb(t){let e=[],n=Zy({...t,text:ke(t.text)});for(let i=0;i<gn.length;i++){let s=gn[i];for(let r of n){let o=s.skipLeadingVerb??!1,a=s.extractSubjectBefore??!1,c=xu(s.negativePattern,r),l=r;for(let u of c){let d=u.index+u.text.length,f=a,h=_i(f?_u(r,u.index,4):vu(r,d,3,o));if(h.length>=2&&!wu(h)){let m=!f&&Xy(r,d,h,o);e.push({section:t,pairIndex:i,polarity:"negative",subject:h,matchedLine:r,hasQualifier:m})}l=l.slice(0,u.index)+" ".repeat(u.text.length)+l.slice(d)}let p=xu(s.positivePattern,l);for(let u of p){let d=a||(s.extractPositiveSubjectBefore??!1),f=_i(d?_u(r,u.index,4):vu(r,u.index+u.text.length,3,o));f.length>=2&&!wu(f)&&e.push({section:t,pairIndex:i,polarity:"positive",subject:f,matchedLine:r})}}}return e}function Su(t,e,n,i,s,r){let o=[`${t}:${e}`,`${n}:${i}`].sort(),a=`${o[0]}|${o[1]}|${s}|${r}`;return`conflict-${xi.createHash("sha1").update(a).digest("hex").slice(0,12)}`}function Ur(t){let e=[];for(let a of t)for(let c of a.sections)c.text.trim().length>=Ky&&e.push(c);let n=[];for(let a of e)n.push(...eb(a));let i=[],s=new Set;for(let a=0;a<n.length;a++)for(let c=a+1;c<n.length;c++){let l=n[a],p=n[c];if(l.pairIndex!==p.pairIndex||l.polarity===p.polarity)continue;let u=l.polarity==="positive"?l:p,d=l.polarity==="negative"?l:p,f=u.subject===d.subject?1:Qy(u.subject,d.subject),h;if(u.subject===d.subject){let $=u.subject.split(" ").filter(Boolean).length===1&&(new RegExp(`\`${u.subject}\\.[a-z]`,"i").test(u.matchedLine)||new RegExp(`\`${d.subject}\\.[a-z]`,"i").test(d.matchedLine)),P=gn[l.pairIndex];h=d.hasQualifier&&/\balways\b/i.test(u.matchedLine)&&P.label.includes("always")?.5:d.hasQualifier?.35:$?.5:.8}else if(f>=.5){let S=gn[l.pairIndex],$=u.subject.split(" ").filter(Boolean),P=d.subject.split(" ").filter(Boolean);if($.length<2||P.length<2){if(!S.allowSingleTokenMatch)continue;let O=$.length<=P.length?$[0]:P[0];if(!($.length>P.length?u.subject:d.subject).startsWith(O))continue}h=d.hasQualifier?.3:.5}else continue;if(h<.4)continue;let m=Su(u.section.filePath,u.section.startLine,d.section.filePath,d.section.startLine,l.pairIndex,u.subject);if(s.has(m))continue;s.add(m);let b=h>=.7?"high":"warning",y=gn[l.pairIndex],v=u.subject.length<=d.subject.length?u.subject:d.subject,g=Array.from(new Set([u.section.filePath,d.section.filePath]));i.push({id:m,severity:b,category:"conflict",title:`Possible conflicting instruction: ${v}`,summary:`Possible conflict \u2014 review these together. A "${y.label}" directive pattern was found pointing in opposite directions for the subject "${v}".`,filePaths:g,locations:[{filePath:u.section.filePath,startLine:u.section.startLine,endLine:u.section.endLine},{filePath:d.section.filePath,startLine:d.section.startLine,endLine:d.section.endLine}],evidence:[u.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 p of c)for(let u of l){if(p.pairIndex===u.pairIndex||p.section.filePath===u.section.filePath&&p.section.startLine===u.section.startLine)continue;{let h=p.subject.split(" ").filter(Boolean).length,m=u.subject.split(" ").filter(Boolean).length;if(h<2||m<2)continue}if(u.hasQualifier)continue;let d=Su(p.section.filePath,p.section.startLine,u.section.filePath,u.section.startLine,-1,a);if(s.has(d))continue;s.add(d);let f=Array.from(new Set([p.section.filePath,u.section.filePath]));i.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:f,locations:[{filePath:p.section.filePath,startLine:p.section.startLine,endLine:p.section.endLine},{filePath:u.section.filePath,startLine:u.section.startLine,endLine:u.section.endLine}],evidence:[p.matchedLine,u.matchedLine],recommendation:"Review these instructions together and consolidate into one clear directive.",confidence:.5})}}return i}var tb=[{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 nb(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 ib(t){let e=new Map;for(let{re:n,name:i,normalize:s}of tb){let r=new RegExp(n.source,n.flags),o;for(;(o=r.exec(t))!==null;){if(nb(t,o.index))continue;let a=s(o[1]);e.has(i)||e.set(i,new Set),e.get(i).add(a)}}return e}function sb(t,e){let n=`version-conflict:${t}:${[...e].sort().join("|")}`;return`version-conflict-${xi.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function zr(t){if(t.length<2)return[];let e=t.map(r=>({file:r,versions:ib(ke(r.content))})),n=new Map;for(let{file:r,versions:o}of e)for(let[a,c]of o){n.has(a)||n.set(a,new Map);let l=n.get(a);for(let p of c)l.has(p)||l.set(p,[]),l.get(p).push(r.path)}let i=[],s=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(f=>o.get(f)).every(f=>f.every(h=>h===c[0])))continue;let u=sb(r,a),d=a.map(f=>`${r} ${f} referenced in: ${o.get(f).map(s).join(", ")}`);i.push({id:u,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(f=>({filePath:f})),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 i}function rb(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ob={"kebab-case":["kebab-case","kebab case","kebabcase"],camelcase:["camelcase","camel case","camel-case"],pascalcase:["pascalcase","pascal case","pascal-case"]};function Eu(t){let e=ob[t.toLowerCase()]??[t];return new RegExp(`\\b(?:${e.map(rb).join("|")})\\b`,"i")}var ab=[{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"}],Cu=/\b(?:use|prefer|always|must|should|follow|rely\s+on|stick\s+to|require)\b/i;function Pu(t,e){let n=t.split(`
39
+ `).map(i=>i.trim());for(let i=0;i<n.length;i++){let s=n[i];if(e.test(s)&&Cu.test(s))return!0;let r=n[i+1];if(s&&r){let o=`${s} ${r}`;if(e.test(o)&&Cu.test(o))return!0}}return!1}function Kr(t){if(t.length<2)return[];let e=[],n=new Set,i=new Map(t.map(r=>[r.path,ke(r.content)])),s=r=>i.get(r.path)??r.content;for(let r of ab){let o=Eu(r.termA),a=Eu(r.termB),c=t.filter(v=>o.test(s(v))),l=t.filter(v=>a.test(s(v)));if(c.length===0||l.length===0)continue;let p=new Set(c.map(v=>v.path)),u=new Set(l.map(v=>v.path));if([...p].every(v=>u.has(v))&&[...u].every(v=>p.has(v)))continue;let f=c.some(v=>Pu(s(v),o)),h=l.some(v=>Pu(s(v),a));if(!f&&!h)continue;let m=[r.termA.toLowerCase(),r.termB.toLowerCase()].sort().join("|");if(n.has(m))continue;n.add(m);let b=[...new Set([...c,...l].map(v=>v.path))],y=`competing-tech-${xi.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:b,locations:b.map(v=>({filePath:v})),evidence:[`"${r.termA}" referenced in: ${c.map(v=>qr.basename(v.path)).join(", ")}`,`"${r.termB}" referenced in: ${l.map(v=>qr.basename(v.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 Yr=E(require("node:fs"),1),me=E(require("node:path"),1),Du=E(require("node:crypto"),1);var ku=/\[(?:[^\]]*)\]\(([^)]+)\)/g,$u=/\[(?:[^\]]|\]\([^)]*\))*\]\(([^)]+)\)/g,Tu=/^[ \t]{0,3}\[[^\]]+\]:\s*(\S+)/gm,Ou=/(?<!\w)@((?:\.{1,2}\/)?[\w./\\-]+\.(?:md|ts|js|mjs|cjs|tsx|jsx|json|yml|yaml|toml|txt|sh|py|cs|go|rs))/g,Lu=/`([^\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,Iu=/^[ \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,ju="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",cb=new RegExp(`^(?:#{1,4}\\s+.*\\b(?:${ju})\\b|\\*\\*[^*\\n]*\\b(?:${ju})\\b[^*\\n]*\\*\\*\\s*)`,"im"),lb=/\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 Nu(t){return bt(t).replace(/\\/g,"/").replace(/^\.\//,"").toLowerCase()}var ub=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 Bt(t){return/^https?:\/\/|^mailto:|^#|^data:/.test(t.trimStart())}function Mu(t){let e=t.trim(),n=/^<([^>]+)>(?:\s+(?:"[^"]*"|'[^']*'))?\s*$/.exec(e);if(n)return n[1];let i=/^(\S+)\s+(?:"[^"]*"|'[^']*')\s*$/.exec(e);return i?i[1]:e}var pb=/^(foo|bar|baz|qux|quux|example|sample|placeholder|stub|demo|test|your[-_]?file|my[-_]?file|filename|file[-_]?name)(\.\w+)?$/i,db=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"]),fb=/^(ComponentName|MyComponent|YourComponent|WidgetName|FeatureName|ModuleName|ServiceName|ModelName|EntityName|ResourceName|DomainName|ControllerName|ScreenName|PageName)(?:\.\w+)*$/i;function hb(t){if(/<[A-Za-z][A-Za-z0-9_-]*>/.test(t)||/\{[A-Za-z][A-Za-z0-9_-]*\}/.test(t)||t.split("/").includes("..."))return!0;let e=me.basename(bt(t)),n=me.dirname(bt(t)),i=n!=="."&&n!==""&&n!==".\\"&&n!=="./";return!!(!i&&pb.test(e)||fb.test(e)||!i&&db.has(e.toLowerCase())||/camelCase|CamelCase|PascalCase|pascalCase|kebab[-_]?[Cc]ase|snake_?[Cc]ase/.test(e))}var mb=[/(?:^|[/\\])\.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 gb(t){let e=t.replace(/\\/g,"/");return mb.some(n=>n.test(e))}function Jr(t){let e=me.extname(t.split("#")[0]??"").toLowerCase();return ub.has(e)}function bt(t){return t.split("#")[0].split("?")[0].trim()}function yb(t){try{return Yr.existsSync(t)}catch{return!1}}var bb=new Set([".go",".cs",".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".sh",".java",".kt",".swift"]),vb=new Set([".go",".rs",".cs",".java",".kt",".swift",".ts",".tsx"]),wb=/(?:^|[/\\])(?:legacy|old|deprecated|archive|archived)(?:[/\\]|[-_.])/i,_b=new Set(["readme","claude","agents","cursor","windsurf","copilot","docs","prompt","unknown"]),xb=.45;function Sb(t){try{return Yr.existsSync(me.dirname(t))}catch{return!1}}function Eb(t){let e=`dead-ref:${t}`;return`dead-ref-${Du.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function Cb(t){let e=[0];for(let n=0;n<t.length;n++)t[n]===`
40
+ `&&e.push(n+1);return e}function yt(t,e){let n=0,i=t.length-1;for(;n<i;){let s=n+i+1>>1;t[s]<=e?n=s:i=s-1}return n+1}var Pb=/\.(?:md|png|jpg|jpeg|gif|svg|webp|pdf)$/i;function Ab(t){let e=t.replace(/\s*#.*$/,""),i=(e.match(/^[ \t│|]*/)?.[0]??"").replace(/[│|]/g," ").length,s=e.trim();if(!s)return null;let r=/^(?:[│|]\s*)*(?:[├└][-─\s]+|[|+`][-─]+\s*)(.+)$/.exec(s),o=(r?r[1]:s)?.trim()??"";return!o||!r&&/\s/.test(o)?null:{entry:o,indent:i,hasConnector:!!r}}function Fu(t,e,n){let i=[],s=[],r=n;for(let o of t){let a=r;r+=o.length+1;let c=Ab(o);if(!c)continue;let l=c.entry;if(/\/$/.test(l)){let h=`${[...s].reverse().find(m=>m.indent<c.indent||m.indent===c.indent&&m.plain)?.path??""}${l}`;for(;s.length>0&&s[s.length-1].indent>=c.indent;)s.pop();s.push({indent:c.indent,path:h,plain:!c.hasConnector});continue}if(!Pb.test(l))continue;let u=[...s].reverse().find(f=>f.indent<c.indent||f.indent===c.indent&&f.plain),d=/[/\\]/.test(l)?l:`${u?.path??""}${l}`;i.push({ref:d,evidence:o.trim(),line:yt(e,a)})}return i}function Rb(t,e){let n=[];for(let i of dn(t)){if(!i.closed)continue;let s=e[i.contentStartLine-1]??t.length;n.push(...Fu(i.lines,e,s))}return n}function kb(t,e){return Fu(t.split(`
41
+ `),e,0)}function $b(t,e={}){let n=[],i=Cb(t),s,r=new RegExp(ku.source,ku.flags);for(;(s=r.exec(t))!==null;){if(s.index>=2&&t[s.index-2]==="["&&t[s.index-1]==="!")continue;let u=s[1]??"",d=bt(Mu(u));d&&!Bt(d)&&Jr(d)&&n.push({ref:d,evidence:`[...](${u})`,line:yt(i,s.index)})}let o=new RegExp($u.source,$u.flags);for(;(s=o.exec(t))!==null;){if(!s[0].slice(0,s[0].lastIndexOf("](")).includes("]("))continue;let d=s[1]??"",f=bt(Mu(d));f&&!Bt(f)&&Jr(f)&&n.push({ref:f,evidence:`[...](${d})`,line:yt(i,s.index)})}let a=new RegExp(Tu.source,Tu.flags);for(;(s=a.exec(t))!==null;){let u=s[1]??"",d=bt(u);d&&!Bt(d)&&Jr(d)&&n.push({ref:d,evidence:s[0].trim(),line:yt(i,s.index)})}let c=new RegExp(Ou.source,Ou.flags);for(;(s=c.exec(t))!==null;){let u=s[1]??"";u&&!Bt(u)&&n.push({ref:u,evidence:`@${u}`,line:yt(i,s.index)})}let l=new RegExp(Lu.source,Lu.flags);for(;(s=l.exec(t))!==null;){let u=s[1]??"";if(u&&!Bt(u)&&!u.includes("*")&&!u.includes("?")){if(e.skipSourceBackticks){let d=me.extname(u).toLowerCase();if(vb.has(d)&&!wb.test(u))continue}n.push({ref:u,evidence:`\`${u}\``,line:yt(i,s.index)})}}if(cb.test(t)){let u=new RegExp(Iu.source,Iu.flags);for(;(s=u.exec(t))!==null;){let d=s[1]??"";d&&!Bt(d)&&n.push({ref:d,evidence:s[0].trim(),line:yt(i,s.index)})}n.push(...kb(t,i));for(let d of Rb(t,i))n.push(d)}let p=t.split(`
42
+ `);return n.filter(({ref:u,line:d})=>{let f=p[d-1]??"",h=lb.exec(f);if(!h)return!0;let m=Nu(h[1]??"");if(!m)return!0;let b=Nu(u);return!(b===m||b.endsWith(`/${m}`)||m.endsWith(`/${b}`))})}function Xr(t,e){let n=new Map;for(let r of t){let o=me.dirname(r.path),a=$b(r.content,{skipSourceBackticks:_b.has(r.fileType)});for(let{ref:c,evidence:l,line:p}of a){if(hb(c)||gb(c))continue;let u=[me.resolve(o,c),me.resolve(e,c)];if(u.some(yb))continue;let d=me.extname(c.split("#")[0]??"").toLowerCase(),f=bb.has(d),h=u.some(Sb),m=f&&h?.5:.85,b=c.toLowerCase().replace(/\\/g,"/"),y=`Reference: ${l}`;n.has(b)||n.set(b,{displayRef:c,filePaths:new Set,fileLines:new Map,evidenceLines:[],minConfidence:m});let v=n.get(b);v.filePaths.add(r.path);let g=v.fileLines.get(r.path);(g===void 0||p<g)&&v.fileLines.set(r.path,p),v.evidenceLines.includes(y)||v.evidenceLines.push(y),v.minConfidence=Math.min(v.minConfidence,m)}}let i=[],s=xb;for(let[r,{displayRef:o,filePaths:a,fileLines:c,evidenceLines:l,minConfidence:p}]of n){if(p<s)continue;let u=[...a];i.push({id:Eb(r),severity:"warning",category:"structure",title:`Broken file reference: ${me.basename(bt(o))}`,summary:`This instruction file references "${o}" which does not appear to exist. The file may have been renamed, moved, or deleted.`,filePaths:u,locations:u.map(d=>{let f=c.get(d);return f!==void 0?{filePath:d,startLine:f}:{filePath:d}}),evidence:l,recommendation:"Verify the path is correct relative to the instruction file location, or remove the reference if the file no longer exists.",confidence:p})}return i}var rt=E(require("node:crypto"),1),$e=E(require("node:path"),1);var Gt=[{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."}],Tb=/\bdo\s+not\s+(edit|modify|change)\b/im,Ob=/<!--\s*auto[- ]?generated|auto[- ]?generated|<!--\s*generated\s*(?:by\s+\w+)?|this\s+file\s+is\s+generated|generated\s+by\s+\w+/i,Lb=/<\/?claude:[\w-]+|<instructions-for-claude[\s>]/i,Hu=/(?:follow|use|see|refer\s+to|canonical\s+(?:source|instructions?)|pointer\s+to)\s+[`'"*]*(?:\.?\/)?(?:\.github\/)?(?:AGENTS|CLAUDE)\.md\b/i;function Ib(t){return`agent-practice-${rt.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function jb(t){return`do-not-edit-${rt.createHash("sha1").update(`do-not-edit:${t}`).digest("hex").slice(0,12)}`}function Nb(t){return`per-file-behavior-${rt.createHash("sha1").update(`per-file-behavior:${t}`).digest("hex").slice(0,12)}`}function yn(t,e){return e.some(n=>n.test(t))}function Mb(t,e){let n=1;for(let i=0;i<e&&i<t.length;i++)t[i]===`
43
+ `&&n++;return n}function Si(t){return t.split(`
39
44
  `).filter(e=>!/^\s*(?:[-*+]|\d+\.)\s+/.test(e)||!/\[[ x?]\]/.test(e)).join(`
40
- `)}function rb(t){let e=t.split(`
41
- `),n=[],s=!1,i=null,o=0;for(let r of e)if(s){let a=/^ {0,3}([`~]{3,})\s*$/.exec(r);a&&a[1][0]===i&&a[1].length>=o&&(s=!1,i=null,o=0)}else{let a=/^ {0,3}([`~]{3,})/.exec(r);if(a){s=!0,i=a[1][0]??null,o=a[1].length;continue}n.push(r)}return n.join(`
42
- `)}function Lo(t){return t.replace(/\\/g,"/").toLowerCase()}function Qn(t){let e=Lo(t.path);return t.fileType==="copilot"||e===".github/copilot-instructions.md"||e.endsWith("/.github/copilot-instructions.md")||e.includes("/.github/instructions/")}function ab(t){let e=Lo(t.path),n=Ve.basename(t.path).toLowerCase();return t.fileType==="cursor"||n===".cursorrules"||e.includes("/.cursor/rules/")}function cb(t){let e=Lo(t.path),n=Ve.basename(t.path).toLowerCase();return t.fileType==="claude"||n==="claude.md"||e.includes("/.claude/")}function tu(t){if(ab(t))return{label:"Cursor rules file",agent:"Cursor agents"};if(cb(t))return{label:"CLAUDE.md",agent:"Claude"};if(Qn(t))return{label:".github/copilot-instructions.md",agent:"GitHub Copilot"}}function nu(t){let e=t.content.split(/\r?\n/).slice(0,12).join(`
43
- `);return eu.test(e)?!0:t.lineCount<20&&eu.test(t.content)}function Io(t){if(t.length===0)return[];let e=[],n=t.map(p=>p.content).join(`
44
- `),s=Yn(n),i=t.map(p=>p.path);for(let p of Et){let d=p.id==="no-verification-loop"?s:n;Yt(d,p.patterns)||e.push({id:nb(p.id),severity:p.severity,category:"agent_practices",title:p.title,summary:p.summary,filePaths:i,locations:[],evidence:[`Pattern not found across ${t.length} instruction file(s).`],recommendation:p.recommendation,fixRecipe:p.fixRecipe,confidence:p.confidence})}let o=[...Et.find(p=>p.id==="no-verification-loop").patterns,...Et.find(p=>p.id==="no-honesty-policy").patterns,...Et.find(p=>p.id==="no-scope-control").patterns,...Et.find(p=>p.id==="no-read-before-edit").patterns],r=p=>Yt(Yn(p.content),o),a=new Set;for(let p of t){let d=tu(p);if(!d||r(p)||nu(p))continue;let f=t.find(h=>h!==p&&r(h));f&&(a.add(p.path),e.push({id:ib(p.path),severity:"warning",category:"agent_practices",title:`No behavioral guidance in ${d.label}`,summary:`The ${d.label} contains no agent behavioral rules (verification loop, honesty policy, scope control, read-before-edit). ${d.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 ${Ve.basename(p.path)}.`,`Some behavioral guidance appears in ${Ve.basename(f.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 ${d.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 Et){let d=t.find(f=>Yt(Yn(f.content),p.patterns));if(d)for(let f of t){if(f===d)continue;let h=tu(f);if(!h||nu(f)||a.has(f.path))continue;if(!Yt(Yn(f.content),p.patterns)){let v=p.title.toLowerCase().replace("no ","").replace(" instruction",""),y=tt.createHash("sha1").update(`behavior-gap:${f.path}:${p.id}`).digest("hex").slice(0,12);e.push({id:`per-file-behavioral-gap-${y}`,severity:"warning",category:"agent_practices",title:`Missing critical guidance "${p.title.replace("No ","").replace(" instruction","")}" in ${h.label}`,summary:`The ${h.label} lacks the critical behavioral guidance regarding "${v}" which is defined in ${Ve.basename(d.path)}. Since ${h.agent} reads ${h.label}, they will miss this rule.`,filePaths:[f.path,d.path],locations:[{filePath:f.path}],evidence:[`Guidance pattern not found in ${Ve.basename(f.path)}.`,`Guidance defined in ${Ve.basename(d.path)}.`],recommendation:`Add the missing guidance to ${h.label} (e.g., "${p.recommendation.replace("Add a rule such as: ","").replace(/"/g,"")}") or use a forwarding pointer (e.g., "Follow ${Ve.basename(d.path)}").`,fixRecipe:p.fixRecipe,confidence:.8})}}}let c=/^#{1,4}\s+(?:agent\s+behavior|ai\s+behavior|agent\s+rules|behavior\s+rules|agent\s+instructions)\b/im,l=p=>`copilot-agent-behavior-${tt.createHash("sha1").update(`copilot-agent-behavior:${p}`).digest("hex").slice(0,12)}`;if((()=>{let p=t.filter(Qn);return p.length===0||!p.some(r)?!1:!t.filter(h=>!Qn(h)&&h.fileType!=="readme"&&h.fileType!=="docs").some(r)})()){let p=t.find(Qn);e.push({id:l(p.path),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"&&c.test(p.content)&&Yt(p.content,o)&&(e.some(d=>d.id===l(p.path))||e.push({id:l(p.path),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 d=p.content.slice(0,500),f=Zy.exec(d),h=!!f,g=eb.test(d),v=f?ob(p.content,f.index):1;if(h&&!g)e.push({id:sb(p.path),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:v,endLine:v}],evidence:[f[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(h&&g&&p.lineCount>5){let b=m=>`auto-gen-header-${tt.createHash("sha1").update(`auto-gen-header:${m}`).digest("hex").slice(0,12)}`;e.push({id:b(p.path),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:v,endLine:v}],evidence:[f[0].trim()],recommendation:"Remove the auto-generated header. If this file is genuinely generated, add a clear generator comment that names the tool and the source template so the origin is unambiguous.",confidence:.75})}let y=rb(p.content).replace(/`[^`\n]+`/g,"");if(p.fileType!=="claude"&&p.fileType!=="readme"&&tb.test(y)){let b=x=>`claude-xml-tag-${tt.createHash("sha1").update(`claude-xml-tag:${x}`).digest("hex").slice(0,12)}`,m=/<\/?claude:[\w-]+/i.exec(y)?.[0]??"<claude:...>";e.push({id:b(p.path),severity:"warning",category:"structure",title:"Claude-specific XML tag in non-Claude instruction file",summary:`This file contains a Claude-specific XML tag (${m}) 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:[p.path],locations:[{filePath:p.path}],evidence:[`Found: ${m} in ${p.fileType} 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})}}return e}var lu=E(require("node:crypto"),1),lb=["duplicate","conflict","context_bloat","missing_context","stale_instruction","vague_guidance","structure","command_validity","agent_practices","security"],su=new Set([...lb,"all"]),iu=/<!--\s*promptci-ignore:\s*(\S+)([\s\S]*?)-->/g,ou=/<!--\s*promptci-ignore-start:\s*(\S+)([\s\S]*?)-->/g,ru=/<!--\s*promptci-ignore-end\s*-->/g;function Qt(t,e){return t.slice(0,e).split(`
45
- `).length}function ub(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 au(t){let e=/reason:\s*(.+?)(?:\n|$)/i.exec(t);return e?e[1].trim():null}function cu(t,e){return su.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: ${[...su].join(", ")}.`}}function pb(t,e,n){let s=`suppression-invalid:${t}:${e}:${n}`;return`suppression-invalid-${lu.createHash("sha1").update(s).digest("hex").slice(0,12)}`}function db(t){let e=t.split(`
46
- `),n=[],s=!1,i=null,o=0;for(let r of e)if(s){let a=/^ {0,3}([`~]{3,})\s*$/.exec(r);a&&a[1][0]===i&&a[1].length>=o&&(s=!1,i=null,o=0),n.push("")}else{let a=/^ {0,3}([`~]{3,})/.exec(r);if(a){s=!0,i=a[1][0]??null,o=a[1].length,n.push("");continue}n.push(r)}return n.join(`
47
- `)}function fb(t){let{content:e,path:n,sections:s,lineCount:i}=t,o=[],r=db(e),a=new RegExp(iu.source,iu.flags),c;for(;(c=a.exec(r))!==null;){let h=c[1]?.trim()??"",g=c[2]??"",v=au(g),y=Qt(r,c.index),b=Qt(r,c.index+c[0].length),m=ub(y,b,s,i,e),{valid:x,message:k}=cu(h,v);o.push({filePath:n,category:x?h:"all",reason:v??"",startLine:y,endLine:m,valid:x,validationMessage:k})}let l=[],u=new RegExp(ou.source,ou.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:au(c[2]??"")});let p=new RegExp(ru.source,ru.flags);for(;(c=p.exec(r))!==null;)l.push({kind:"end",offset:c.index,endOffset:c.index+c[0].length});l.sort((h,g)=>h.offset-g.offset);let d=h=>{o.push({filePath:n,category:"all",reason:"",startLine:Qt(r,h.offset),endLine:i,valid:!1,validationMessage:"promptci-ignore-start has no matching promptci-ignore-end marker."})},f=null;for(let h of l){if(h.kind==="start"){f&&d(f),f=h;continue}if(!f)continue;let g=Qt(r,f.offset),v=Qt(r,h.endOffset),{valid:y,message:b}=cu(f.category??"",f.reason??null);o.push({filePath:n,category:y?f.category:"all",reason:f.reason??"",startLine:g,endLine:v,valid:y,validationMessage:b}),f=null}return f&&d(f),o}function Oo(t){return t.flatMap(fb)}function jo(t){return t.filter(e=>!e.valid).map(e=>({id:pb(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
48
- reason: This section documents examples. -->`,confidence:1}))}function No(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 Mo={critical:18,high:10,warning:4,info:1},hb={structure:30,stale_instruction:15,duplicate:20,vague_guidance:10};function Do(t){let e=100,n=new Map;for(let s of t){let i=(Mo[s.severity]??0)*s.confidence,o=hb[s.category];if(o!==void 0){let r=n.get(s.category)??0,a=Math.max(0,o-r),c=Math.min(i,a);n.set(s.category,r+c),e-=c}else e-=i}return Math.round(Math.max(0,Math.min(100,e)))}var uu={high:3,medium:2,low:1};function pu(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 Fo(t){let e=[...t].sort((i,o)=>{let r=(Mo[o.severity]??0)-(Mo[i.severity]??0);if(r!==0)return r;let a=o.confidence-i.confidence;if(a!==0)return a;let c=uu[pu(o)]-uu[pu(i)];if(c!==0)return c;let l=o.filePaths.length-i.filePaths.length;if(l!==0)return l;let u=i.category.localeCompare(o.category);return u!==0?u: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 Y=E(require("node:fs/promises"),1),K=E(require("node:path"),1),gu=E(require("node:crypto"),1);var Xn=E(require("node:path"),1),du=require("node:fs");function fu(t){let{filesScanned:e,repoPath:n}=t,s=y=>{let b=Xn.relative(n,y);return b&&!b.startsWith("..")?b:y};if(e.reduce((y,b)=>y+b.estimatedTokens,0)<500&&t.issues.length===0)return"";let o=[];for(let y of e)for(let b of y.sections){let m=(b.heading||"").toLowerCase(),x=b.normalizedText,k="unknown",C="",A="";m.includes("changelog")||m.includes("history")||m.includes("roadmap")||m.includes("screenshot")||m.includes("mockup")||m.includes("past plan")||m.includes("yesterday")||m.includes("todo")||m.includes("status")||m.includes("task")||m.includes("notes")||x.includes("todo")&&(m.includes("todo")||m.includes("done"))?(k="archive",A="Contains historical, stale, or roadmap content that is not relevant to ongoing AI tasks."):m.includes("deploy")||m.includes("vercel")||m.includes("ci/cd")||m.includes("release")?(k="on-demand",C="docs/ai/deployment.md",A="Contains deployment steps, environments, or release workflows which are only needed during releases."):m.includes("nextjs")||m.includes("next.js")||m.includes("react")||m.includes("remix")||m.includes("frontend")||m.includes("dashboard")?(k="on-demand",C="docs/ai/nextjs.md",A="Contains framework-specific UI/Next.js conventions that are only needed when editing web dashboard code."):m.includes("supabase")||m.includes("database")||m.includes("prisma")||m.includes("migration")||m.includes("sql")||m.includes("schema")?(k="on-demand",C="docs/ai/supabase.md",A="Contains database setup or migration steps which are only needed when schema or API boundary changes occur."):m.includes("architecture")||m.includes("design")||m.includes("structure")||m.includes("components")?(k="on-demand",C="docs/ai/architecture.md",A="Contains repository structure or module descriptions that are only needed when creating new components."):m.includes("troubleshoot")||m.includes("debug")||m.includes("error")||m.includes("issue")?(k="on-demand",C="docs/ai/troubleshooting.md",A="Contains error codes or troubleshooting procedures only needed when debugging failures."):b.text.includes("```")&&b.text.length>1500?(k="on-demand",C="docs/ai/examples.md",A="Contains long code snippets or examples that bloat always-loaded context."):(m.includes("identity")||m.includes("about")||m.includes("purpose")||m.includes("boundary")||m.includes("non-goal")||m.includes("verification")||m.includes("build")||m.includes("test")||m.includes("lint")||m.includes("typecheck")||m.includes("safety")||m.includes("security")||m.includes("secret")||m.includes("credential")||m.includes("auth")||m.includes("read-before-edit")||m.includes("scope-control")||m.includes("honesty")||m.includes("plan-first"))&&(k="always-load",A="Contains core setup, boundary constraints, verification commands, or critical developer practices."),k!=="unknown"&&o.push({file:y,section:b,classification:k,suggestedFile:C,reason:A})}let r=[];r.push("## Context Architecture & Retrieval Map"),r.push(""),r.push("> [!NOTE]"),r.push("> Split large instruction files to keep canonical instructions under the token budget. Move detailed instructions to on-demand documents and link them."),r.push("");let a=o.filter(y=>y.classification==="on-demand"),c=o.filter(y=>y.classification==="archive");if(a.length>0||c.length>0){r.push("### Suggested Context Splits"),r.push(""),r.push("| Section / File | Current Size | Classification | Recommendation |"),r.push("|---|---|---|---|");for(let y of[...a,...c]){let b=`\`${s(y.file.path)}\` (Heading: *${y.section.heading||"None"}*)`,m=`~${Math.round(y.section.text.length/4)} tokens`,x=y.classification==="archive"?"Archive/Remove":`On-Demand (\`${y.suggestedFile}\`)`;r.push(`| ${b} | ${m} | **${x}** | ${y.reason} |`)}r.push("")}r.push("### Suggested Canonical AGENTS.md Layout"),r.push("To minimize token consumption, structure your canonical rules as follows:"),r.push("```markdown"),r.push("# PromptCI - Agent Instructions"),r.push(""),r.push("## Identity & Boundaries"),r.push("- Describe core project limits, tech stack, and non-goals here."),r.push(""),r.push("## Verification Loop"),r.push("- List exact commands: e.g. `pnpm lint`, `pnpm typecheck`, `pnpm test`."),r.push(""),r.push("## References (On-Demand)"),r.push("- For deployment details, read [deployment.md](file:///docs/ai/deployment.md)."),r.push("- For DB schema, read [supabase.md](file:///docs/ai/supabase.md)."),r.push("```"),r.push("");let l=o.filter(y=>{let b=y.section.text,m=b.split(`
49
- `),x=m.some(C=>/^\s*\d+\.\s+[A-Z]/i.test(C)),k=m.some(C=>/^\s*[-*]\s+(Run|Do|Verify|Build|Compile|Deploy|Release|Upgrade|Test|Check|Commit|Push)\b/i.test(C));return b.length>1e3&&(x||k)});if(l.length>0){r.push("## Skills Readiness & Extraction Recommendations"),r.push(""),r.push("The following sections describe multi-step procedural workflows. These are excellent candidates to move out of instruction files into reusable local playbooks or skills to save persistent context tokens:"),r.push("");for(let y of l){let b=y.section.heading||"Workflow",m=`custom-playbook-${y.section.id}`,x=`When executing specialized tasks related to ${b}`,k=b.toLowerCase();k.includes("deploy")||k.includes("release")?(m="deployment-runbook",x="Before running a deployment, release, or publishing builds"):k.includes("supabase")||k.includes("migration")||k.includes("database")?(m="supabase-migration-workflow",x="When writing or executing database migrations, DDL, or database client code"):(k.includes("test")||k.includes("ci"))&&(m="test-and-ci-checklist",x="When verifying build health or running the automated test matrix"),r.push(`### Skill Candidate: \`${m}\``),r.push(`- **Trigger Condition:** ${x}`),r.push(`- **Source Section:** \`${s(y.file.path)}\` (Section: *${b}*)`),r.push(`- **Savings Potential:** ~${Math.round(y.section.text.length/4)} tokens per session`),r.push(`- **Action:** Extract the procedural checklist into a file like \`docs/skills/${m}.md\` and add a single trigger rule in AGENTS.md.`),r.push("")}}let u=[];for(let y of o){let b=Math.round(y.section.text.length/4);if(b<100)continue;let m=1,x="Archive or remove";y.classification==="archive"?(m=2,x="Remove completely or move to archive/"):y.classification==="on-demand"?(m=1.5,x=`Extract to on-demand doc (\`${y.suggestedFile}\`)`):y.classification==="always-load"&&(m=.5,x="Trim details or move examples out");let k=y.section.text.toLowerCase();if(k.includes("verification")||k.includes("honesty")||k.includes("read-before-edit")||k.includes("scope-control")||k.includes("security")||k.includes("safety")||k.includes("plan-first")){if(y.classification==="always-load")continue;m*=.5}(/\b(?:last\s+updated|generated\s+at|timestamp|current\s+branch|active\s+task|health\s+score)\b/i.test(y.section.text)||/\b(?:202\d-\d{2}-\d{2}|[0-2]?\d:[0-5]\d:[0-5]\d)\b/.test(y.section.text))&&(m+=.5),y.section.text.includes("```")&&y.section.text.length>2e3&&(m+=.5),t.issues.some(L=>L.category==="duplicate"&&L.filePaths.includes(y.file.path))&&(m+=.5),u.push({name:`\`${s(y.file.path)}\` (Section: *${y.section.heading||"None"}*)`,tokens:b,savingsPotential:b*m,reason:y.reason,action:x})}let p=u.sort((y,b)=>b.savingsPotential-y.savingsPotential).slice(0,3);p.length>0&&(r.push("## Context ROI Ranking (Cleanup Opportunities)"),r.push(""),r.push("Prioritized list of instruction sections to clean up, refactor, or extract to maximize token savings:"),r.push(""),r.push("| Rank | Section / File | Token Size | Savings Potential | Suggested Action | Why? |"),r.push("|---|---|---|---|---|---|"),p.forEach((y,b)=>{let m=b+1;r.push(`| ${m} | ${y.name} | ~${y.tokens} | High | ${y.action} | ${y.reason} |`)}),r.push(""));let d=t.repoPath&&((0,du.existsSync)(Xn.join(t.repoPath,"supabase"))||e.some(y=>y.path.endsWith("package.json")&&y.content.includes("@supabase/supabase-js"))),f=e.some(y=>y.path.includes("packages/cli")||y.path.includes("apps/cli")),h=e.some(y=>y.path.includes("packages/web")||y.path.includes("apps/web")),g=e.some(y=>/next/i.test(y.content)),v=[];if(d&&v.push({name:"`supabase-auth-and-upload`",source:"Supabase schema and client config rules",whenToLoad:"When altering database schemas, migrations, security triggers, or upload APIs.",savings:"Avoids loading database structures for standard frontend/backend edits."}),f&&v.push({name:"`cli-command-workflow`",source:"CLI entrypoints and argument parsers instructions",whenToLoad:"When changing CLI flags, command syntax, or command handlers.",savings:"Keeps command parsing logic out of web dashboard and core development runs."}),(h||g)&&v.push({name:"`web-dashboard-development`",source:"Next.js components, page routes, and middleware rules",whenToLoad:"When building UI dashboard layouts, state management, or styling components.",savings:"Keeps CSS and layout instructions out of core engines and CLI builds."}),o.some(y=>y.classification==="on-demand"&&y.suggestedFile==="docs/ai/deployment.md")&&v.push({name:"`deployment-and-ci`",source:"Vercel, CI/CD, and release commands checklists",whenToLoad:"When debugging GitHub Actions workflows or preparing production releases.",savings:"Keeps long validation check scripts out of the standard iteration loop."}),v.length>0){r.push("## Suggested Context Packs"),r.push(""),r.push("Consider defining task-specific context bundles so agents only load rules relevant to their active focus area:"),r.push(""),r.push("| Pack Name | Source Sections | When to Load | Token Benefit |"),r.push("|---|---|---|---|");for(let y of v)r.push(`| ${y.name} | ${y.source} | ${y.whenToLoad} | ${y.savings} |`);r.push("")}return r.join(`
50
- `)}var mb={critical:"CRITICAL",high:"HIGH",warning:"WARNING",info:"INFO"},yu={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},hu={critical:0,high:1,warning:2,info:3};function Ho(t,e){let n=K.relative(e,t);return!n||n.startsWith("..")?t:n}function gb(t,e){if(!t.filePaths||t.filePaths.length===0)return t.id??"";let n=t.id?.replace(/-[^-]+$/,"")??"",s=t.filePaths.map(o=>{let r=o.replace(/\\/g,"/");return e&&K.isAbsolute(o)?Ho(o,e).replace(/\\/g,"/"):r}).sort();return`trend-${gu.createHash("sha1").update(JSON.stringify({category:t.category??"",severity:t.severity??"",idFamily:n,title:t.title??"",filePaths:s})).digest("hex").slice(0,12)}`}function mu(t,e){let n=new Set,s=[];for(let i of t){if(i.id){if(n.has(i.id))continue;n.add(i.id)}s.push(gb(i,e))}return s}function yb(t){let e=Math.round(t/10),n=10-e;return"\u2588".repeat(e)+"\u2591".repeat(n)}function bb(t){return t>=90?"Healthy":t>=70?"Fair":t>=50?"Needs attention":"Critical issues found"}function vb(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 wb(t){return[...t].sort((e,n)=>{let s=hu[e.severity]-hu[n.severity];if(s!==0)return s;let i=n.confidence-e.confidence;return i!==0?i:e.id.localeCompare(n.id)})}function xb(t,e=100){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e)}\u2026`}function _b(t,e,n){let s=yu[t.severity],i=mb[t.severity],o=[];if(o.push(`### ${e}. ${s} [${i}] ${t.title}`),o.push(""),o.push(`${t.summary}`),o.push(""),t.filePaths.length>0){for(let a of t.filePaths)o.push(`**File:** \`${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:** \`${n(a.filePath)}\` ${c}`)}o.push("")}if(t.evidence.length>0){o.push("**Evidence:**");for(let a of t.evidence)o.push(`- ${xb(a)}`);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(`
51
- `)}function bu(t){let e=[],{healthScore:n,topFixes:s,issues:i,projectType:o,repoPath:r,generatedAt:a,filesScanned:c}=t,l=f=>Ho(f,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.length}`),t.metrics&&e.push(`**Estimated instruction tokens:** ${t.metrics.estimatedInstructionTokens}`),e.push(""),e.push("## Health Score"),e.push(""),e.push("```"),e.push(`${yb(n)} ${n}/100 ${bb(n)}`),e.push("```"),e.push("");let u=vb(i);if(i.length>0){let f=[];for(let h of["critical","high","warning","info"]){let g=u.get(h).length;g>0&&f.push(`${yu[h]} ${g} ${h}`)}e.push(f.join(" \xB7 ")),e.push("")}if(e.push("## Trend"),e.push(""),t.trend){let f=t.trend;f.previousScanDate&&e.push(`- **Previous scan:** ${f.previousScanDate}`);let h=f.scoreDelta>0?`+${f.scoreDelta}`:`${f.scoreDelta}`;e.push(`- **Score change:** ${h}`),e.push(`- **New issues:** ${f.newIssuesCount}`),e.push(`- **Resolved issues:** ${f.resolvedIssuesCount}`);let g=Object.keys(f.categoryDeltas);if(g.length>0){e.push("- **Category changes:**");for(let v of g){let y=f.categoryDeltas[v],b=y>0?`+${y}`:`${y}`;e.push(` - ${v}: ${b}`)}}f.streak>0&&e.push(`- **Streak:** ${f.streak} scan(s) without high/critical issues`)}else e.push("First scan \u2014 no trend data available yet.");e.push(""),s.length>0&&(e.push("## Top Fixes"),e.push(""),s.forEach((f,h)=>{e.push(`**${h+1}. ${f.title}**`),e.push(""),e.push(`${f.reason}`),e.push(""),e.push(`*Action:* ${f.suggestedAction}`),e.push("")})),i.length===0?(e.push("## Issues"),e.push(""),e.push("No issues found. Instruction files look good!"),e.push("")):(e.push("## Issues"),e.push(""),wb(i).forEach((h,g)=>{e.push(_b(h,g+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 f of p){let h=f.filePaths[0]?l(f.filePaths[0]):"(unknown)",g=f.locations.find(y=>y.startLine!==void 0),v=g?` L${g.startLine}${g.endLine?`\u2013${g.endLine}`:""}`:"";e.push(`- **${f.category}** in \`${h}\`${v}`)}e.push("")}if(c.length>0){e.push("## Files Scanned"),e.push("");for(let f of c)e.push(`- \`${l(f.path)}\` (${f.fileType}, ${f.lineCount} lines, ~${f.estimatedTokens} tokens)`);e.push("")}let d=fu(t);return d&&(e.push(d),e.push("")),e.push("---"),e.push("> Findings are heuristic. Review each item before acting. This report identifies patterns \u2014 it does not auto-fix."),e.push(""),e.push("*Generated by [PromptCI](https://github.com/SeriousGeese/PromptCI)*"),e.join(`
52
- `)}function Zn(t,e=!0){let n=i=>Ho(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),fileType:i.fileType,lineCount:i.lineCount,charCount:i.charCount,estimatedTokens:i.estimatedTokens})),...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 Bo(t){return K.join(t,".promptci","history","index.json")}async function Uo(t){let e=Bo(t);try{let n=await Y.readFile(e,"utf8"),s=JSON.parse(n);if(Array.isArray(s))return s}catch{}return[]}async function vu(t,e,n){let s;try{s=await Y.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=K.join(t,".promptci","history",r);await Y.mkdir(a,{recursive:!0});let c=K.join(".promptci","history",r,"report.md"),l=K.join(".promptci","history",r,"report.json"),u=K.join(t,c),p=K.join(t,l);try{await Y.copyFile(e,u)}catch{await Y.writeFile(u,s,"utf8")}await Y.copyFile(n,p);let d=Array.isArray(i.issues)?i.issues:[],f={critical:0,high:0,warning:0,info:0};for(let y of d){let b=y.severity;b in f&&f[b]++}let h={generatedAt:o,healthScore:typeof i.healthScore=="number"?i.healthScore:0,issueCount:f,archiveMdPath:c,archiveJsonPath:l},g=await Uo(t);g.push(h);let v=Bo(t);return await Y.mkdir(K.dirname(v),{recursive:!0}),await Y.writeFile(v,JSON.stringify(g,null,2),"utf8"),h}async function es(t,e={}){let n=K.join(t.repoPath,".promptci"),s=e.mdPath??K.join(n,"latest.md"),i=e.jsonPath??K.join(n,"report.json");await Y.mkdir(K.dirname(s),{recursive:!0}),await Y.mkdir(K.dirname(i),{recursive:!0});let o=await Sb(i),r=await Uo(t.repoPath),a=await Pb(t,o,r);a&&(t.trend=a);let l=e.archive!==!1&&!e.mdPath&&!e.jsonPath?await vu(t.repoPath,s,i):null,u=bu(t),p=Zn(t);return await Promise.all([Y.writeFile(s,u,"utf8"),Y.writeFile(i,p,"utf8")]),{mdPath:s,jsonPath:i,archivedEntry:l}}async function Sb(t){try{let e=await Y.readFile(t,"utf8");return JSON.parse(e)}catch{return null}}async function Pb(t,e,n){if(!e)return null;try{let s=t.issues||[],i=Array.isArray(e.issues)?e.issues:[],o=new Set(mu(s,t.repoPath)),r=new Set(mu(i)),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(x=>x.category===y).length,m=i.filter(x=>x.category===y).length;u[y]=b-m}let p=["critical","high","warning","info"],d={};for(let y of p){let b=s.filter(x=>x.severity===y).length,m=i.filter(x=>x.severity===y).length;d[y]=b-m}let f=s.filter(y=>y.severity==="high"||y.severity==="critical").length,h=0;if(f===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 m=n[b];if(m&&(m.issueCount.high??0)===0&&(m.issueCount.critical??0)===0)h++;else break}}let g=typeof e.generatedAt=="string"?e.generatedAt:void 0,v=typeof e.healthScore=="number"?e.healthScore:0;return{previousScanDate:g,scoreDelta:t.healthScore-v,newIssuesCount:a.length,resolvedIssuesCount:c.length,severityDeltas:d,categoryDeltas:u,newIssueIds:a,resolvedIssueIds:c,streak:h}}catch{return null}}var wu=E(require("node:crypto"),1),xu=E(require("node:fs"),1),_u=E(require("node:path"),1);function ts(t){return`manifest-${wu.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function Cb(t,e,n){if(!(/\[tool\.poetry\]/.test(e)||/build-backend\s*=\s*["'][^"']*poetry[^"']*["']/i.test(e)))return null;let i=_u.join(n,"requirements.txt");if(xu.existsSync(i))return null;let o=/pip\s+install\s+-r\s+requirements\.txt/i,r=t.filter(a=>o.test(a.content));return r.length===0?null:{id:ts("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(a=>a.path),locations:r.map(a=>({filePath:a.path})),evidence:["`pip install -r requirements.txt` found in instruction file(s)","pyproject.toml declares Poetry as the build system","requirements.txt does not exist in the repo"],recommendation:"Update the instruction files to use Poetry commands instead: `poetry install` (or `uv sync` if the project has migrated to uv). Remove the `pip install -r requirements.txt` reference.",confidence:.9}}function Eb(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(qo(c.content,l.index)||!(p<s||p===s&&d<i))continue;let h=`${p}.${d}`,g=`${s}.${i}`,v=`${c.path}:${h}`;r.has(v)||(r.add(v),o.push({id:ts(`python-version:${c.path}:${h}`),severity:"high",category:"stale_instruction",title:`Python version mismatch: instruction says ${h}, pyproject.toml requires \u2265${g}`,summary:`An instruction file refers to Python ${h}, but pyproject.toml declares \`python = "^${g}"\` (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${g}`],recommendation:`Update the instruction file to reference Python ${g} (or remove the version claim and rely on pyproject.toml as the authoritative source).`,confidence:.85}))}}return o}var kb=["pandas","numpy","sqlalchemy","fastapi","django","flask","pydantic"];function Ab(t){return t==="sqlalchemy"?"SQLAlchemy":t==="fastapi"?"FastAPI":t[0].toUpperCase()+t.slice(1)}function Go(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vo(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 Rb(t){let e=new Map;for(let n of kb){let s=Go(n),o=new RegExp(`^\\s*${s}\\s*=\\s*["']([^"']+)["']`,"im").exec(t);if(o){let c=Vo(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=Vo(a[1]);if(c!==null){e.set(n,c);break}}}return e}function $b(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 Tb(t,e){let n=Rb(e);if(n.size===0)return[];let s=[],i=new Set;for(let[o,r]of n){let a=Ab(o),c=new RegExp(`\\b${Go(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(!$b(l.content,u.index))continue;let d=parseInt(u[1],10);if(d>=r)continue;let f=u[2]?`${d}.${u[2]}`:`${d}.x`,h=`${l.path}:${o}:${f}`;i.has(h)||(i.add(h),s.push({id:ts(`library-version:${l.path}:${o}:${f}`),severity:"high",category:"stale_instruction",title:`${a} version mismatch: instruction says ${f}, pyproject.toml uses ${r}.x`,summary:`An instruction file refers to ${a} ${f}, 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} ${f}"; 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 Lb=["react","next","typescript","vite","vitest","jest"],Ib={react:"React",next:"Next.js",typescript:"TypeScript",vite:"Vite",vitest:"Vitest",jest:"Jest"};function Ob(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 Lb){let c=r[a];if(typeof c!="string")continue;let l=Vo(c);l!==null&&s.set(a,l)}}return s}function jb(t,e){let n=Ob(e);if(n.size===0)return[];let s=[],i=new Set;for(let[o,r]of n){let a=Ib[o],c=new RegExp(`\\b${Go(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(!Nb(l.content,u.index))continue;let d=parseInt(u[1],10);if(d>=r)continue;let f=u[2]?`${d}.${u[2]}`:`${d}.x`,h=`${l.path}:${o}:${f}`;i.has(h)||(i.add(h),s.push({id:ts(`js-library-version:${l.path}:${o}:${f}`),severity:"high",category:"stale_instruction",title:`${a} version mismatch: instruction says ${f}, package.json uses ${r}.x`,summary:`An instruction file refers to ${a} ${f}, 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} ${f}"; 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 Nb(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 qo(t,e){let n=t.lastIndexOf(`
53
- `,e-1)+1,s=t.indexOf(`
54
- `,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 Mb(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(r=>r.name!==s),o=[];for(let r 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(r.content))!==null;){let p=r.content.lastIndexOf(`
55
- `,l.index-1)+1,d=r.content.indexOf(`
56
- `,l.index),f=r.content.slice(p,d===-1?void 0:d);if(!(s==="pnpm"&&/\bnpm\s+(?:install|i)\s+-g\s+pnpm\b/i.test(f))&&!qo(r.content,l.index)){u=!0;break}}if(u){o.push(r);break}}return o.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:o.map(r=>r.path),locations:o.map(r=>({filePath:r.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 Db(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\s+)?([a-z0-9][a-z0-9:_-]*)\b/gi,r=new Set,a=new Set(["install","add","remove","init","test","start","stop","restart","exec","dlx","i","help","run","ci","audit","update","outdated","publish","create","link","why","workspace","workspaces","store","ls","list","pack","unlink","uninstall","up","prune","package","packages","project","repo","repository"]),c=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"]);for(let l of n){let u,p=new RegExp(o.source,o.flags);for(;(u=p.exec(l.content))!==null;){let d=u[1];if(!d.startsWith("-")&&!a.has(d)&&!c.has(d.toLowerCase())&&!s.has(d)){let f=`${l.path}:${d}`;if(r.has(f))continue;r.add(f),i.push({id:`manifest-missing-script:${l.path}:${d}`,severity:"warning",category:"stale_instruction",title:`Reference to missing script: "${d}"`,summary:`Instructions tell the agent to run \`${d}\`, but this script is not defined in package.json. The agent might attempt to run a command that fails.`,filePaths:[l.path],locations:[{filePath:l.path}],evidence:[`Found reference to \`${d}\` in ${l.path}`],recommendation:"Verify if the script name is correct or add the missing script to package.json.",confidence:.7})}}}return i}function Fb(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(!qo(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:${c.path}:${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 Hb(t,e,n){let s=t.lastIndexOf(`
45
+ `)}function Ei(t){return t.fileType==="copilot"||$e.basename(t.path).toLowerCase()==="copilot-instructions.md"}function Db(t){return t.fileType==="cursor"||$e.basename(t.path).toLowerCase()===".cursorrules"}function Fb(t){return t.fileType==="windsurf"||$e.basename(t.path).toLowerCase()===".windsurfrules"}function Hb(t){return t.fileType==="claude"||$e.basename(t.path).toLowerCase()==="claude.md"}function Bu(t){if(Db(t))return{label:"Cursor rules file",agent:"Cursor agents"};if(Fb(t))return{label:".windsurfrules",agent:"Windsurf agents"};if(Hb(t))return{label:"CLAUDE.md",agent:"Claude"};if(Ei(t))return{label:".github/copilot-instructions.md",agent:"GitHub Copilot"}}function Gu(t){let e=t.content.split(/\r?\n/).slice(0,12).join(`
46
+ `);return Hu.test(e)?!0:t.lineCount<20&&Hu.test(t.content)}function Qr(t){if(t.length===0)return[];let e=[],n=t.map(u=>u.content).join(`
47
+ `),i=Si(n),s=t.map(u=>u.path);for(let u of Gt){let d=u.id==="no-verification-loop"?i:n;yn(d,u.patterns)||e.push({id:Ib(u.id),severity:u.severity,category:"agent_practices",title:u.title,summary:u.summary,filePaths:s,locations:[],evidence:[`Pattern not found across ${t.length} instruction file(s).`],recommendation:u.recommendation,fixRecipe:u.fixRecipe,confidence:u.confidence})}let r=[...Gt.find(u=>u.id==="no-verification-loop").patterns,...Gt.find(u=>u.id==="no-honesty-policy").patterns,...Gt.find(u=>u.id==="no-scope-control").patterns,...Gt.find(u=>u.id==="no-read-before-edit").patterns],o=u=>yn(Si(u.content),r),a=new Set;for(let u of t){let d=Bu(u);if(!d||o(u)||Gu(u))continue;let f=t.find(h=>h!==u&&o(h));f&&(a.add(u.path),e.push({id:Nb(u.path),severity:"warning",category:"agent_practices",title:`No behavioral guidance in ${d.label}`,summary:`The ${d.label} contains no agent behavioral rules (verification loop, honesty policy, scope control, read-before-edit). ${d.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:[u.path],locations:[{filePath:u.path}],evidence:[`No behavioral patterns found in ${$e.basename(u.path)}.`,`Some behavioral guidance appears in ${$e.basename(f.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 ${d.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 u of Gt){let d=t.find(f=>yn(Si(f.content),u.patterns));if(d)for(let f of t){if(f===d)continue;let h=Bu(f);if(!h||Gu(f)||a.has(f.path))continue;if(!yn(Si(f.content),u.patterns)){let b=u.title.toLowerCase().replace("no ","").replace(" instruction",""),y=rt.createHash("sha1").update(`behavior-gap:${f.path}:${u.id}`).digest("hex").slice(0,12);e.push({id:`per-file-behavioral-gap-${y}`,severity:"warning",category:"agent_practices",title:`Missing critical guidance "${u.title.replace("No ","").replace(" instruction","")}" in ${h.label}`,summary:`The ${h.label} lacks the critical behavioral guidance regarding "${b}" which is defined in ${$e.basename(d.path)}. Since ${h.agent} reads ${h.label}, they will miss this rule.`,filePaths:[f.path,d.path],locations:[{filePath:f.path}],evidence:[`Guidance pattern not found in ${$e.basename(f.path)}.`,`Guidance defined in ${$e.basename(d.path)}.`],recommendation:`Add the missing guidance to ${h.label} (e.g., "${u.recommendation.replace("Add a rule such as: ","").replace(/"/g,"")}") or use a forwarding pointer (e.g., "Follow ${$e.basename(d.path)}").`,fixRecipe:u.fixRecipe,confidence:.8})}}}let c=/^#{1,4}\s+(?:agent\s+behavior|ai\s+behavior|agent\s+rules|behavior\s+rules|agent\s+instructions)\b/im,l=u=>`copilot-agent-behavior-${rt.createHash("sha1").update(`copilot-agent-behavior:${u}`).digest("hex").slice(0,12)}`;if((()=>{let u=t.filter(Ei);return u.length===0||!u.some(o)?!1:!t.filter(h=>!Ei(h)&&h.fileType!=="readme"&&h.fileType!=="docs").some(o)})()){let u=t.find(Ei);e.push({id:l(u.path),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:[u.path],locations:[{filePath:u.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 u of t)u.fileType==="copilot"&&c.test(u.content)&&yn(u.content,r)&&(e.some(d=>d.id===l(u.path))||e.push({id:l(u.path),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:[u.path],locations:[{filePath:u.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 u of t){let d=u.content.slice(0,500),f=Tb.exec(d),h=!!f,m=Ob.test(d),b=f?Mb(u.content,f.index):1;if(h&&!m)e.push({id:jb(u.path),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:[u.path],locations:[{filePath:u.path,startLine:b,endLine:b}],evidence:[f[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(h&&m&&u.lineCount>5){let v=g=>`auto-gen-header-${rt.createHash("sha1").update(`auto-gen-header:${g}`).digest("hex").slice(0,12)}`;e.push({id:v(u.path),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 ${u.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:[u.path],locations:[{filePath:u.path,startLine:b,endLine:b}],evidence:[f[0].trim()],recommendation:"Remove the auto-generated header. If this file is genuinely generated, add a clear generator comment that names the tool and the source template so the origin is unambiguous.",confidence:.75})}let y=ke(u.content).replace(/`[^`\n]+`/g,"");if(u.fileType!=="claude"&&u.fileType!=="readme"&&Lb.test(y)){let v=S=>`claude-xml-tag-${rt.createHash("sha1").update(`claude-xml-tag:${S}`).digest("hex").slice(0,12)}`,g=/<\/?claude:[\w-]+/i.exec(y)?.[0]??"<claude:...>";e.push({id:v(u.path),severity:"warning",category:"structure",title:"Claude-specific XML tag in non-Claude instruction file",summary:`This file contains a Claude-specific XML tag (${g}) 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:[u.path],locations:[{filePath:u.path}],evidence:[`Found: ${g} in ${u.fileType} 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})}}return e}var Ju=E(require("node:crypto"),1);var Bb=["duplicate","conflict","context_bloat","missing_context","stale_instruction","vague_guidance","structure","command_validity","agent_practices","ai_config","security","custom"],Wu=new Set([...Bb,"all"]),Vu=/<!--\s*promptci-ignore:\s*(\S+)([\s\S]*?)-->/g,qu=/<!--\s*promptci-ignore-start:\s*(\S+)([\s\S]*?)-->/g,Uu=/<!--\s*promptci-ignore-end\s*-->/g;function bn(t,e){return t.slice(0,e).split(`
48
+ `).length}function Gb(t,e,n,i,s){let r=s.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],p=r.slice(e,Math.max(e,c?.startLine?c.startLine-1:e)).every(u=>u.trim()==="");return c&&c.startLine>e&&p?c.endLine:a.endLine}}for(let o of n)if(o.startLine>t)return o.endLine;return i}function zu(t){let e=/reason:\s*(.+?)(?:\r?\n|$)/i.exec(t);return e?e[1].trim():null}function Ku(t,e){return Wu.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: ${[...Wu].join(", ")}.`}}function Wb(t,e,n){let i=`suppression-invalid:${t}:${e}:${n}`;return`suppression-invalid-${Ju.createHash("sha1").update(i).digest("hex").slice(0,12)}`}function Vb(t){let{content:e,path:n,sections:i,lineCount:s}=t,r=[],o=uu(e),a=new RegExp(Vu.source,Vu.flags),c;for(;(c=a.exec(o))!==null;){let h=c[1]?.trim()??"",m=c[2]??"",b=zu(m),y=bn(o,c.index),v=bn(o,c.index+c[0].length),g=Gb(y,v,i,s,e),{valid:S,message:$}=Ku(h,b);r.push({filePath:n,category:S?h:"all",reason:b??"",startLine:y,endLine:g,valid:S,validationMessage:$})}let l=[],p=new RegExp(qu.source,qu.flags);for(;(c=p.exec(o))!==null;)l.push({kind:"start",offset:c.index,endOffset:c.index+c[0].length,category:c[1]?.trim()??"",reason:zu(c[2]??"")});let u=new RegExp(Uu.source,Uu.flags);for(;(c=u.exec(o))!==null;)l.push({kind:"end",offset:c.index,endOffset:c.index+c[0].length});l.sort((h,m)=>h.offset-m.offset);let d=h=>{r.push({filePath:n,category:"all",reason:"",startLine:bn(o,h.offset),endLine:s,valid:!1,validationMessage:"promptci-ignore-start has no matching promptci-ignore-end marker."})},f=null;for(let h of l){if(h.kind==="start"){f&&d(f),f=h;continue}if(!f)continue;let m=bn(o,f.offset),b=bn(o,h.endOffset),{valid:y,message:v}=Ku(f.category??"",f.reason??null);r.push({filePath:n,category:y?f.category:"all",reason:f.reason??"",startLine:m,endLine:b,valid:y,validationMessage:v}),f=null}return f&&d(f),r}function Zr(t){return t.flatMap(Vb)}function eo(t){return t.filter(e=>!e.valid).map(e=>({id:Wb(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 to(t,e){let n=e.filter(r=>r.valid),i=[],s=[];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(u=>{if(u.filePath!==a.filePath)return!1;if(u.startLine===void 0)return!0;let d=u.endLine??u.startLine;return u.startLine<=a.endLine&&d>=a.startLine}))return!0;let l=new Set(r.filePaths);return!!(!r.locations.some(u=>l.has(u.filePath))&&r.filePaths.includes(a.filePath))}return r.filePaths.includes(a.filePath)})?s.push(r):i.push(r);return{active:i,suppressed:s}}var no={critical:18,high:10,warning:4,info:1},qb={structure:30,stale_instruction:15,duplicate:20,vague_guidance:10,ai_config:25};function io(t){let e=100,n=new Map;for(let i of t){let s=(no[i.severity]??0)*i.confidence,r=qb[i.category];if(r!==void 0){let o=n.get(i.category)??0,a=Math.max(0,r-o),c=Math.min(s,a);n.set(i.category,o+c),e-=c}else e-=s}return Math.round(Math.max(0,Math.min(100,e)))}var Yu={high:3,medium:2,low:1};function Xu(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 so(t){let e=[...t].sort((s,r)=>{let o=(no[r.severity]??0)-(no[s.severity]??0);if(o!==0)return o;let a=r.confidence-s.confidence;if(a!==0)return a;let c=Yu[Xu(r)]-Yu[Xu(s)];if(c!==0)return c;let l=r.filePaths.length-s.filePaths.length;if(l!==0)return l;let p=s.category.localeCompare(r.category);return p!==0?p:s.id.localeCompare(r.id)}),n=[],i=new Set;for(let s of e){if(n.length>=3)break;i.has(s.category)||(i.add(s.category),n.push({title:s.title,reason:s.summary,suggestedAction:s.recommendation}))}return n}var Z=E(require("node:fs/promises"),1),re=E(require("node:path"),1);var Zu=E(require("node:crypto"),1),wt=E(require("node:path"),1),Ub={info:0,warning:1,high:2,critical:3};function Qu(t){return Ub[t]??-1}function vt(t){return t.replace(/\\/g,"/")}function ep(t,e){if(!e)return t;try{let s=wt.relative(e,t);if(s&&!s.startsWith("..")&&!wt.isAbsolute(s))return vt(s)}catch{}let n=vt(t),i=[vt(e).replace(/\/+$/,""),vt(wt.resolve(e)).replace(/\/+$/,"")];for(let s of i){if(n===s)return".";if(n.startsWith(`${s}/`))return n.slice(s.length+1)}return n}function zb(t,e){if(!e)return t;let n=vt(t);return[vt(e).replace(/\/+$/,""),vt(wt.resolve(e)).replace(/\/+$/,"")].reduce((s,r)=>s.replaceAll(r,"<repo>"),n)}function vn(t,e){let n=t.filePaths.map(r=>ep(r,e)).sort(),i=t.evidence.map(r=>zb(r,e)).sort(),s=[t.category,t.title,...n,...i].join("|");return Zu.createHash("sha256").update(s).digest("hex")}function Wt(t,e){return t.map(n=>({id:n.id,category:n.category,title:n.title,filePaths:n.filePaths.map(i=>ep(i,e)).sort(),severity:n.severity,fingerprint:vn(n,e)})).sort((n,i)=>n.fingerprint.localeCompare(i.fingerprint))}function ro(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 i=n;if(typeof i.fingerprint!="string")throw new Error(`Baseline entry at index ${e} is missing a "fingerprint" string field.`);if(typeof i.category!="string")throw new Error(`Baseline entry at index ${e} is missing a "category" string field.`)}}function Vt(t,e,n){let i=new Map;for(let o of e)i.set(o.fingerprint,o.severity??"info");let s=[],r=[];for(let o of t){let a=vn(o,n),c=i.get(a);c===void 0||Qu(o.severity)>Qu(c)?s.push(o):r.push(o)}return{newIssues:s,baselinedIssues:r}}var Kb={critical:"CRITICAL",high:"HIGH",warning:"WARNING",info:"INFO"},oo={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},tp={critical:0,high:1,warning:2,info:3},Jb={critical:"Critical",high:"High",warning:"Warning",info:"Info"},Yb="ai-setup",Xb={critical:"issues-critical",high:"issues-high",warning:"issues-warning",info:"issues-info"},Qb=50;function Zb(t){let e=[],n=ip(t.filter(r=>r.category==="ai_config"));n.length>0&&e.push({anchor:Yb,heading:`\u{1F916} AI Setup (${n.length})`,issues:n});let i=t.filter(r=>r.category!=="ai_config"),s=op(i);for(let r of["critical","high","warning","info"]){let o=ip(s.get(r));o.length!==0&&e.push({anchor:Xb[r],heading:`${oo[r]} ${Jb[r]} (${o.length})`,issues:o})}return e}function sp(t,e){let n=re.relative(e,t);return!n||n.startsWith("..")?t:n}function ev(t,e){return vn({category:t.category??"",title:t.title??"",filePaths:t.filePaths??[],evidence:t.evidence??[]},e)}function np(t,e){return t.map(n=>ev(n,e))}function tv(t){let e=Math.round(t/10),n=10-e;return"\u2588".repeat(e)+"\u2591".repeat(n)}function rp(t){return t>=90?"Healthy":t>=70?"Fair":t>=50?"Needs attention":"Critical issues found"}function op(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 ip(t){return[...t].sort((e,n)=>{let i=tp[e.severity]-tp[n.severity];if(i!==0)return i;let s=n.confidence-e.confidence;return s!==0?s:e.id.localeCompare(n.id)})}function nv(t,e,n){let i=oo[t.severity],s=Kb[t.severity],r=[];if(r.push(`#### ${e}. ${i} [${s}] ${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:** \`${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:** \`${n(a.filePath)}\` ${c}`)}r.push("")}if(t.evidence.length>0){r.push("**Evidence:**");for(let a of t.evidence)r.push(`- ${J(a,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 ap(t){let e=[],{healthScore:n,topFixes:i,issues:s,projectType:r,repoPath:o,generatedAt:a,filesScanned:c}=t,l=d=>sp(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.length}`),t.metrics&&(e.push(`**Estimated instruction tokens:** ${t.metrics.estimatedInstructionTokens} (always-loaded)`),t.metrics.estimatedOnDemandTokens&&e.push(`**On-demand skill/agent tokens:** ${t.metrics.estimatedOnDemandTokens} across ${t.metrics.onDemandFileCount} file(s) \u2014 loaded only when invoked, not counted above`)),e.push(""),e.push("## Health Score"),e.push(""),e.push("```"),e.push(`${tv(n)} ${n}/100 ${rp(n)}`),e.push("```"),e.push("");let p=op(s);if(s.length>0){let d=[];for(let f of["critical","high","warning","info"]){let h=p.get(f).length;h>0&&d.push(`${oo[f]} ${h} ${f}`)}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 f=d.scoreDelta>0?`+${d.scoreDelta}`:`${d.scoreDelta}`;e.push(`- **Score change:** ${f}`),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 b=d.categoryDeltas[m],y=b>0?`+${b}`:`${b}`;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(""),i.length>0&&(e.push("## Top Fixes"),e.push(""),i.forEach((d,f)=>{e.push(`**${f+1}. ${d.title}**`),e.push(""),e.push(`${d.reason}`),e.push(""),e.push(`*Action:* ${d.suggestedAction}`),e.push("")})),s.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=Zb(s);e.push(`**Jump to:** ${d.map(f=>`[${f.heading}](#${f.anchor})`).join(" \xB7 ")}`),e.push("");for(let f of d)e.push(`<a id="${f.anchor}"></a>`),e.push(""),e.push(`### ${f.heading}`),e.push(""),f.issues.forEach((h,m)=>{e.push(nv(h,m+1,l)),e.push(""),e.push("---"),e.push("")})}let u=t.suppressedIssues;if(u&&u.length>0){e.push(`## Suppressed (${u.length})`),e.push(""),e.push(`The following ${u.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 u){let f=d.filePaths[0]?l(d.filePaths[0]):"(unknown)",h=d.locations.find(b=>b.startLine!==void 0),m=h?` L${h.startLine}${h.endLine?`\u2013${h.endLine}`:""}`:"";e.push(`- **${d.category}** in \`${f}\`${m}`)}e.push("")}if(c.length>0){e.push("## Files Scanned"),e.push("");let d=c.slice(0,Qb);for(let h of d)e.push(`- \`${l(h.path)}\` (${h.fileType}, ${h.lineCount} lines, ~${h.estimatedTokens} tokens)`);let f=c.length-d.length;f>0&&e.push(`- \u2026and ${f} 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 Ci(t,e=!0){let n=s=>sp(s,t.repoPath),i={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(s=>({...s,filePaths:s.filePaths.map(n),locations:s.locations.map(r=>({...r,filePath:n(r.filePath)}))})),filesScanned:t.filesScanned.map(s=>({path:n(s.path),fileType:s.fileType,lineCount:s.lineCount,charCount:s.charCount,estimatedTokens:s.estimatedTokens})),...t.suppressedIssues&&t.suppressedIssues.length>0?{suppressedIssues:t.suppressedIssues.map(s=>({...s,filePaths:s.filePaths.map(n),locations:s.locations.map(r=>({...r,filePath:n(r.filePath)}))}))}:{}};return e?JSON.stringify(i,null,2):JSON.stringify(i)}function ao(t){return re.join(t,".promptci","history","index.json")}async function co(t){let e=ao(t);try{let n=await Z.readFile(e,"utf8"),i=JSON.parse(n);if(Array.isArray(i))return i}catch{}return[]}async function cp(t,e,n){let i;try{i=await Z.readFile(n,"utf8")}catch{return null}let s;try{s=JSON.parse(i)}catch{return null}let r=typeof s.generatedAt=="string"?s.generatedAt:new Date().toISOString(),o=r.replace(/[:.]/g,"-").replace(/Z$/,"Z"),a=re.join(t,".promptci","history",o);await Z.mkdir(a,{recursive:!0});let c=re.join(".promptci","history",o,"report.md"),l=re.join(".promptci","history",o,"report.json"),p=re.join(t,c),u=re.join(t,l);try{await Z.copyFile(e,p)}catch{await Z.writeFile(p,i,"utf8")}await Z.copyFile(n,u);let d=Array.isArray(s.issues)?s.issues:[],f={critical:0,high:0,warning:0,info:0};for(let v of d){let g=v.severity;g in f&&f[g]++}let h={generatedAt:r,healthScore:typeof s.healthScore=="number"?s.healthScore:0,issueCount:f,archiveMdPath:c,archiveJsonPath:l},m=await co(t);m.push(h);let b=ao(t);await Z.mkdir(re.dirname(b),{recursive:!0});let y=`${b}.tmp`;return await Z.writeFile(y,JSON.stringify(m,null,2),"utf8"),await Z.rename(y,b),h}async function Pi(t,e={}){let n=re.join(t.repoPath,".promptci"),i=e.mdPath??re.join(n,"latest.md"),s=e.jsonPath??re.join(n,"report.json");await Z.mkdir(re.dirname(i),{recursive:!0}),await Z.mkdir(re.dirname(s),{recursive:!0});let r=await iv(s),o=await co(t.repoPath),a=await sv(t,r,o);a&&(t.trend=a);let l=e.archive!==!1&&!e.mdPath&&!e.jsonPath?await cp(t.repoPath,i,s):null,p=ap(t),u=Ci(t);return await Promise.all([Z.writeFile(i,p,"utf8"),Z.writeFile(s,u,"utf8")]),{mdPath:i,jsonPath:s,archivedEntry:l}}async function iv(t){try{let e=await Z.readFile(t,"utf8");return JSON.parse(e)}catch{return null}}async function sv(t,e,n){if(!e)return null;try{let i=t.issues||[],s=Array.isArray(e.issues)?e.issues:[],r=new Set(np(i,t.repoPath)),o=new Set(np(s,t.repoPath)),a=[...r].filter(y=>!o.has(y)),c=[...o].filter(y=>!r.has(y)),l=new Set([...i.map(y=>y.category),...s.map(y=>y.category)].filter(y=>typeof y=="string")),p={};for(let y of l){if(!y)continue;let v=i.filter(S=>S.category===y).length,g=s.filter(S=>S.category===y).length;p[y]=v-g}let u=["critical","high","warning","info"],d={};for(let y of u){let v=i.filter(S=>S.severity===y).length,g=s.filter(S=>S.severity===y).length;d[y]=v-g}let f=i.filter(y=>y.severity==="high"||y.severity==="critical").length,h=0;if(f===0&&(h=1,s.filter(v=>v.severity==="high"||v.severity==="critical").length===0)){h++;for(let v=n.length-1;v>=0;v--){let g=n[v];if(g&&(g.issueCount.high??0)===0&&(g.issueCount.critical??0)===0)h++;else break}}let m=typeof e.generatedAt=="string"?e.generatedAt:void 0,b=typeof e.healthScore=="number"?e.healthScore:0;return{previousScanDate:m,scoreDelta:t.healthScore-b,newIssuesCount:a.length,resolvedIssuesCount:c.length,severityDeltas:d,categoryDeltas:p,newIssueIds:a,resolvedIssueIds:c,streak:h}}catch{return null}}var lp=E(require("node:crypto"),1),up=E(require("node:fs"),1),pp=E(require("node:path"),1);function Ai(t){return`manifest-${lp.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function rv(t,e,n){if(!(/\[tool\.poetry\]/.test(e)||/build-backend\s*=\s*["'][^"']*poetry[^"']*["']/i.test(e)))return null;let s=pp.join(n,"requirements.txt");if(up.existsSync(s))return null;let r=/pip\s+install\s+-r\s+requirements\.txt/i,o=t.filter(a=>r.test(a.content));return o.length===0?null:{id:Ai("pip-vs-poetry"),severity:"high",category:"conflict",title:"Tooling mismatch: instruction uses pip but project uses Poetry",summary:"Instruction files tell the agent to run `pip install -r requirements.txt`, but this project uses Poetry as its build system (pyproject.toml with [tool.poetry]) and has no requirements.txt. Running this command would fail immediately.",filePaths:o.map(a=>a.path),locations:o.map(a=>({filePath:a.path})),evidence:["`pip install -r requirements.txt` found in instruction file(s)","pyproject.toml declares Poetry as the build system","requirements.txt does not exist in the repo"],recommendation:"Update the instruction files to use Poetry commands instead: `poetry install` (or `uv sync` if the project has migrated to uv). Remove the `pip install -r requirements.txt` reference.",confidence:.9}}function ov(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 i=parseInt(n[1],10),s=parseInt(n[2],10),r=[],o=new Set,a=/\bPython\s+(\d+)\.(\d+)\b/gi;for(let c of t){let l,p=new RegExp(a.source,a.flags);for(;(l=p.exec(c.content))!==null;){let u=parseInt(l[1],10),d=parseInt(l[2],10);if(po(c.content,l.index)||!(u<i||u===i&&d<s))continue;let h=`${u}.${d}`,m=`${i}.${s}`,b=`${c.path}:${h}`;o.has(b)||(o.add(b),r.push({id:Ai(`python-version:${c.path}:${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 av=["pandas","numpy","sqlalchemy","fastapi","django","flask","pydantic"];function cv(t){return t==="sqlalchemy"?"SQLAlchemy":t==="fastapi"?"FastAPI":t[0].toUpperCase()+t.slice(1)}function uo(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lo(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 lv(t){let e=new Map;for(let n of av){let i=uo(n),r=new RegExp(`^\\s*${i}\\s*=\\s*["']([^"']+)["']`,"im").exec(t);if(r){let c=lo(r[1]);if(c!==null){e.set(n,c);continue}}let o=new RegExp(`["']${i}(?:\\[[^\\]]+\\])?\\s*([~^=<>!]{1,2}\\s*\\d+(?:\\.\\d+)?)`,"gim"),a;for(;(a=o.exec(t))!==null;){let c=lo(a[1]);if(c!==null){e.set(n,c);break}}}return e}function uv(t,e){let n=Math.max(0,e-80),i=Math.min(t.length,e+120),s=t.slice(n,i);return/\b(target|support|supports|compatibility|compatible|avoid|maintain|maintains)\b/i.test(s)}function pv(t,e){let n=lv(e);if(n.size===0)return[];let i=[],s=new Set;for(let[r,o]of n){let a=cv(r),c=new RegExp(`\\b${uo(a)}\\s+(?:v(?:ersion)?\\s*)?(\\d+)(?:\\.(\\d+|x))?\\b`,"gi");for(let l of t){let p,u=new RegExp(c.source,c.flags);for(;(p=u.exec(l.content))!==null;){if(!uv(l.content,p.index))continue;let d=parseInt(p[1],10);if(d>=o)continue;let f=p[2]?`${d}.${p[2]}`:`${d}.x`,h=`${l.path}:${r}:${f}`;s.has(h)||(s.add(h),i.push({id:Ai(`library-version:${l.path}:${r}:${f}`),severity:"high",category:"stale_instruction",title:`${a} version mismatch: instruction says ${f}, pyproject.toml uses ${o}.x`,summary:`An instruction file refers to ${a} ${f}, 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} ${f}"; 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 i}var dv=["react","next","typescript","vite","vitest","jest"],fv={react:"React",next:"Next.js",typescript:"TypeScript",vite:"Vite",vitest:"Vitest",jest:"Jest"};function hv(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,i=new Map,s=[n.dependencies,n.devDependencies,n.peerDependencies];for(let r of s){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r;for(let a of dv){let c=o[a];if(typeof c!="string")continue;let l=lo(c);l!==null&&i.set(a,l)}}return i}function mv(t,e){let n=hv(e);if(n.size===0)return[];let i=[],s=new Set;for(let[r,o]of n){let a=fv[r],c=new RegExp(`\\b${uo(a)}\\s+(?:v(?:ersion)?\\s*)?(\\d+)(?:\\.(\\d+|x))?\\b`,"gi");for(let l of t){let p,u=new RegExp(c.source,c.flags);for(;(p=u.exec(l.content))!==null;){if(!gv(l.content,p.index))continue;let d=parseInt(p[1],10);if(d>=o)continue;let f=p[2]?`${d}.${p[2]}`:`${d}.x`,h=`${l.path}:${r}:${f}`;s.has(h)||(s.add(h),i.push({id:Ai(`js-library-version:${l.path}:${r}:${f}`),severity:"high",category:"stale_instruction",title:`${a} version mismatch: instruction says ${f}, package.json uses ${o}.x`,summary:`An instruction file refers to ${a} ${f}, 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} ${f}"; 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 i}function gv(t,e){let n=Math.max(0,e-100),i=Math.min(t.length,e+140),s=t.slice(n,i);return/\b(use|using|target|support|supports|compatibility|compatible|avoid|maintain|migration|migrate|features?|apis?)\b/i.test(s)}function po(t,e){let n=t.lastIndexOf(`
57
52
  `,e-1)+1,i=t.indexOf(`
58
- `,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 Bb(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(!Hb(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 Wo(t){let{files:e,manifests:n,repoRoot:s}=t,i=[];n.packageJson&&(i.push(...jb(e,n.packageJson)),i.push(...Db(t)),i.push(...Fb(t)),i.push(...Bb(t)));let o=Mb(t);if(o&&i.push(o),n.pyproject){let r=Cb(e,n.pyproject,s);r&&i.push(r),i.push(...Eb(e,n.pyproject)),i.push(...Tb(e,n.pyproject))}return i}var ft=E(require("node:fs/promises"),1),me=E(require("node:path"),1);var Ub=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","bun.lock"];function Vb(){return{packageManagerName:"unknown",scripts:{},dependencies:{},devDependencies:{},peerDependencies:{},lockfiles:[]}}function zo(t,e){let n=me.resolve(t),s=me.resolve(n,e),i=me.relative(n,s);if(i.startsWith("..")||me.isAbsolute(i))throw new Error(`Path escapes repo root: ${e}`);return s}async function Su(t,e){try{return await ft.readFile(zo(t,e),"utf-8")}catch{return}}async function Gb(t,e){let n=[];for(let s of e)try{(await ft.stat(zo(t,s))).isFile()&&n.push(s)}catch{}return n}function Pu(t){return t?t.startsWith("pnpm@")?"pnpm":t.startsWith("npm@")?"npm":t.startsWith("yarn@")?"yarn":t.startsWith("bun@")?"bun":"unknown":"unknown"}function ns(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 ss(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 Cu(t,e){let n=Vb();if(n.raw=t,n.lockfiles=e,!t)return n.packageManagerName=ns(e),n;let s;try{s=JSON.parse(t)}catch{return n.packageManagerName=ns(e),n}if(typeof s!="object"||s===null||Array.isArray(s))return n.packageManagerName=ns(e),n;let i=s;if(n.packageManager=typeof i.packageManager=="string"?i.packageManager:void 0,n.packageManagerName=Pu(n.packageManager)!=="unknown"?Pu(n.packageManager):ns(e),n.scripts=ss(i.scripts),n.dependencies=ss(i.dependencies),n.devDependencies=ss(i.devDependencies),n.peerDependencies=ss(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 qb(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(`
59
- `).trim();u&&s.push({filePath:t,command:u,line:i+1})}return s}async function Wb(t){let e=zo(t,me.join(".github","workflows")),n;try{n=await ft.readdir(e,{withFileTypes:!0})}catch{return{files:[],commands:[]}}let s=n.filter(o=>o.isFile()&&/\.(ya?ml)$/i.test(o.name)).map(o=>me.join(e,o.name)).sort(),i=[];for(let o of s){let r=me.relative(t,o),a=await ft.readFile(o,"utf-8");i.push(...qb(r,a))}return{files:s.map(o=>me.relative(t,o)),commands:i}}function zb(t){return{estimatedInstructionTokens:t.reduce((e,n)=>e+n.estimatedTokens,0),instructionFileCount:t.length,largestInstructionFiles:[...t].sort((e,n)=>n.estimatedTokens-e.estimatedTokens).slice(0,5).map(e=>({path:e.path,estimatedTokens:e.estimatedTokens}))}}async function Xt(t){let e=me.resolve(t.repoPath),n=await Wt({...t,repoPath:e}),s=t.projectType&&t.projectType!=="auto"?t.projectType:await zt(e);s==="unknown"&&(s=bo(n));let[i,o,r,a]=await Promise.all([Su(e,"package.json"),Su(e,"pyproject.toml"),Gb(e,Ub),Wb(e)]),c={};return i&&(c.packageJson=i),o&&(c.pyproject=o),{repoRoot:e,files:n,projectType:s,manifests:c,packageJson:Cu(i,r),workflows:a,metrics:zb(n),contextBudget:t.contextBudget,fileContextBudget:t.fileContextBudget}}var Ko=E(require("node:crypto"),1),kt=E(require("node:path"),1),Eu=[/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];function ku(t){if(t.length===0)return[];let e=[],n=[];for(let r of t)Eu.some(a=>a.test(r.content))&&n.push(r);function s(r){let a=Ko.createHash("sha1").update(r).digest("hex").slice(0,12);return`canonical-${r}-${a}`}n.length>1&&e.push({id:s("ambiguous-authority"),severity:"warning",category:"structure",title:"Ambiguous authority: multiple files claim to be canonical",summary:`Multiple files (${n.map(r=>kt.basename(r.path)).join(", ")}) claim to be the "canonical" or "authoritative" source of truth. This leads to confusion about which instructions take precedence.`,filePaths:n.map(r=>r.path),locations:n.map(r=>({filePath:r.path})),evidence:n.map(r=>{let a;for(let l of Eu){let u=l.exec(r.content);if(u){a=u[0];break}}let c=(a??"").replace(/\s+/g," ").trim();return`${kt.basename(r.path)}: "${c}"`}),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(r=>kt.basename(r.path).toLowerCase()==="agents.md")||n[0];if(o){let r=a=>{let c=a.split(`
53
+ `,e),s=t.slice(n,i===-1?void 0:i);return/\b(?:do\s+not|don'?t|avoid|never|instead\s+of|not\s+use|refrain\s+from)\b/i.test(s)}function yv(t){let{packageJson:e,files:n}=t,i=e.packageManagerName;if(i==="unknown")return null;let s=[{name:"npm",label:"npm"},{name:"pnpm",label:"pnpm"},{name:"yarn",label:"Yarn"},{name:"bun",label:"Bun"}].filter(o=>o.name!==i),r=[];for(let o of n)for(let a of s){let c=new RegExp(`\\b${a.name}\\s+(?:install|add|run|exec|dlx|i)\\b`,"gi"),l,p=!1;for(;(l=c.exec(o.content))!==null;){let u=o.content.lastIndexOf(`
54
+ `,l.index-1)+1,d=o.content.indexOf(`
55
+ `,l.index),f=o.content.slice(u,d===-1?void 0:d);if(!(i==="pnpm"&&/\bnpm\s+(?:install|i)\s+-g\s+pnpm\b/i.test(f))&&!po(o.content,l.index)){p=!0;break}}if(p){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 ${i}`,summary:`Instruction files refer to other package managers, but this project appears to use ${i} (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 ${i}`,"Instruction files mention other package managers in command-like contexts"],recommendation:`Update instruction files to consistently use ${i} commands.`,fixRecipe:`This repo uses ${i}. Use \`${i} install\`, \`${i} test\`, and \`${i} build\`; do not substitute npm/yarn commands.`,confidence:.8}}function bv(t){let{packageJson:e,files:n}=t,i=new Set(Object.keys(e.scripts));if(i.size===0)return[];let s=[],r=/\b(?:npm|yarn|pnpm|bun)\s+(run\s+)?([a-z0-9][a-z0-9:_-]*)\b/gi,o=new Set,a=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"]),c=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"]);for(let l of n){let p=du(l.content),u,d=new RegExp(r.source,r.flags);for(;(u=d.exec(l.content))!==null;){let f=u[1]!==void 0,h=u[2];if(!h.startsWith("-")&&!/^[0-9]/.test(h)&&!(!f&&!p[u.index])&&!a.has(h)&&!c.has(h.toLowerCase())&&!i.has(h)){let m=`${l.path}:${h}`;if(o.has(m))continue;o.add(m),s.push({id:`manifest-missing-script:${l.path}:${h}`,severity:"warning",category:"stale_instruction",title:`Reference to missing script: "${h}"`,summary:`Instructions tell the agent to run \`${h}\`, but this script is not defined in package.json. The agent might attempt to run a command that fails.`,filePaths:[l.path],locations:[{filePath:l.path}],evidence:[`Found reference to \`${h}\` in ${l.path}`],recommendation:"Verify if the script name is correct or add the missing script to package.json.",confidence:.7})}}}return s}function vv(t){let{packageJson:e,files:n}=t;if(!e.enginesNode)return[];let i=/>=\s*(\d+)/.exec(e.enginesNode)||/\^\s*(\d+)/.exec(e.enginesNode);if(!i)return[];let s=parseInt(i[1],10),r=[],o=new Set,a=/\bNode(?:\.js)?\s*(?:v)?(\d+)\b/gi;for(let c of n){let l,p=new RegExp(a.source,a.flags);for(;(l=p.exec(c.content))!==null;){let u=parseInt(l[1],10);if(!po(c.content,l.index)&&u<s){let d=`${c.path}:${u}`;if(o.has(d))continue;o.add(d),r.push({id:`manifest-node-version-mismatch:${c.path}:${u}`,severity:"warning",category:"stale_instruction",title:`Node.js version mismatch: instruction says ${u}, project requires \u2265${s}`,summary:`Instructions mention Node.js ${u}, but package.json specifies a minimum version of ${s} in \`engines.node\`.`,filePaths:[c.path],locations:[{filePath:c.path}],evidence:[`Instruction says Node ${u}; engines.node says ${e.enginesNode}`],recommendation:`Update instructions to reflect the minimum supported Node.js version (${s}).`,confidence:.8})}}}return r}function wv(t,e,n){let i=t.lastIndexOf(`
56
+ `,e-1)+1,s=t.indexOf(`
57
+ `,e),r=t.slice(i,s===-1?void 0:s);return!!(/\b(?:do\s+not|don'?t|avoid|never|refrain\s+from|not\s+use)\b/i.test(r.slice(0,e-i+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 _v(t){let{packageJson:e,files:n}=t,i={...e.dependencies,...e.devDependencies},s=[],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(!i[o.package]){let a=o.alternatives.find(c=>i[c]);if(a){let c=new RegExp(`\\b${o.name}\\b`,"gi"),l=n.filter(p=>{let u,d=new RegExp(c.source,c.flags);for(;(u=d.exec(p.content))!==null;)if(!wv(p.content,u.index,o.name))return!0;return!1});l.length>0&&s.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(p=>p.path),locations:l.map(p=>({filePath:p.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 s}function fo(t){let{files:e,manifests:n,repoRoot:i}=t,s=[];n.packageJson&&(s.push(...mv(e,n.packageJson)),s.push(...bv(t)),s.push(...vv(t)),s.push(..._v(t)));let r=yv(t);if(r&&s.push(r),n.pyproject){let o=rv(e,n.pyproject,i);o&&s.push(o),s.push(...ov(e,n.pyproject)),s.push(...pv(e,n.pyproject))}return s}var St=E(require("node:fs/promises"),1),ct=E(require("node:path"),1);var Te=E(require("node:fs"),1),fp=E(require("node:path"),1),hp=E(require("node:crypto"),1),mp=E(gi(),1),gp=E(jt(),1);function _t(t){return t.replace(/\\/g,"/")}function Ut(t,e){let n=gt(t,e);if(!n)return!1;try{return Te.statSync(n).isFile()}catch{return!1}}function Se(t,e){let n=gt(t,e);if(n)try{return Te.readFileSync(n,"utf8")}catch{return}}var yp=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/worktrees/**","**/.worktrees/**"];function zt(t,e,n=yp){let i;try{i=mp.default.sync(e,{cwd:t,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,ignore:n})}catch{return[]}return i.map(_t).sort()}var qt={skills:[".claude/**/SKILL.md"],agents:[".claude/agents/**/*.md"],settings:[".claude/settings.json",".claude/settings.local.json"],mcp:[".mcp.json"],cursorRules:[".cursor/rules/**/*.mdc"],copilotInstructions:[".github/instructions/**/*.md"]};function xv(t,e){let n=gt(t,e);if(!n)return!1;try{let i=Te.statSync(n);if(!i.isFile()||i.size>Ir)return!1;let s=Te.openSync(n,"r");try{let r=Buffer.alloc(Math.min(i.size,jr)),o=Te.readSync(s,r,0,r.length,0);return!Nr(r.subarray(0,o))}finally{Te.closeSync(s)}}catch{return!1}}function ho(t,e={}){let n=[...yp,...e.exclude??[]],i=e.include&&e.include.length>0?e.include:void 0,s=r=>{let o=zt(t,[...r],n);return i&&(o=(0,gp.default)(o,i,{dot:!0}).sort()),o.filter(a=>xv(t,a))};return{skills:s(qt.skills),agents:s(qt.agents),settings:s(qt.settings),mcp:s(qt.mcp),cursorRules:s(qt.cursorRules),copilotInstructions:s(qt.copilotInstructions)}}function ce(t){return hp.createHash("sha1").update(t).digest("hex").slice(0,12)}function Ee(t,e){let n=i=>fp.resolve(t,i);return e.map(i=>({...i,filePaths:i.filePaths.map(n),locations:i.locations.map(s=>({...s,filePath:n(s.filePath)}))}))}var wn=/\.(sh|bash|zsh|js|mjs|cjs|ts|py|rb|ps1)$/i;function ot(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 Sv(t){return t.charCodeAt(0)===65279?t.slice(1):t}var dp=/^(?:---|\.\.\.)[ \t]*$/;function bp(t){let e="",n="";for(let i=0;i<t.length;i++){let s=t[i];if(e)s===e&&(e="");else if((s==='"'||s==="'")&&(n===""||/[\s[{(,]/.test(n)))e=s;else if(s==="#"&&(n===""||/\s/.test(n)))return t.slice(0,i).trimEnd();n=s}return t}function vp(t){let e=[],n="",i=0,s="";for(let r of t){if(s){n+=r,r===s&&(s="");continue}if((r==='"'||r==="'")&&n.trim()===""){s=r,n+=r;continue}if(r==="["||r==="{"||r==="("){i++,n+=r;continue}if(r==="]"||r==="}"||r===")"){i>0&&i--,n+=r;continue}if(r===","&&i===0){e.push(n),n="";continue}n+=r}return e.push(n),e.map(r=>mo(r.trim())).filter(r=>r!=="")}function mo(t){return t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))?t.slice(1,-1):t}function Ev(t){let e=bp(t).trim();if(e==="")return null;let n=mo(e);if(n!==e)return n;if(e.startsWith("[")&&e.endsWith("]")){let i=e.slice(1,-1).trim();return i===""?[]:vp(i)}return e==="true"?!0:e==="false"?!1:e==="null"||e==="~"?null:/^-?\d+(\.\d+)?$/.test(e)?Number(e):e}function Ue(t){let n=Sv(t).split(/\r?\n/),i={present:!1,closed:!1,data:{},keyLines:{},fenceEndLine:-1,bodyStartLine:1,errors:[]};if(n.length===0||n[0].trim()!=="---")return i;i.present=!0;let s=null,r=null,o=!1,a=[],c=()=>{if(r===null)return;let p=o?a.join(" "):a.join(`
58
+ `);i.data[r]=p.trim(),r=null,a=[]},l=1;for(;l<n.length;l++){let p=n[l],u=p.trim();if(r!==null){if(dp.test(p)){c(),i.closed=!0,i.fenceEndLine=l+1,i.bodyStartLine=l+2;break}if(u===""||/^\s/.test(p)){a.push(u);continue}c()}if(dp.test(p)){i.closed=!0,i.fenceEndLine=l+1,i.bodyStartLine=l+2;break}if(u===""||u.startsWith("#"))continue;let d=/^(\s*)-\s+(.*)$/.exec(p);if(d&&s){let v=i.data[s],g=mo(bp(d[2]).trim());g!==""&&(Array.isArray(v)?v.push(g):i.data[s]=[g]);continue}let f=/^(\s*)([^:\s][^:]*):\s?(.*)$/.exec(p);if(!f){i.errors.push(`Unparseable frontmatter line ${l+1}: ${u.slice(0,60)}`);continue}let h=f[1].length,m=f[2].trim(),b=f[3];if(h>0){i.errors.push(`Nested frontmatter key "${m}" on line ${l+1} is not supported`);continue}Object.prototype.hasOwnProperty.call(i.data,m)?i.errors.push(`Duplicate frontmatter key "${m}" (line ${l+1})`):i.keyLines[m]=l+1;let y=b.trim();if(y==="|"||y==="|-"||y==="|+"||y===">"||y===">-"||y===">+"){r=m,o=y.startsWith(">"),a=[],s=null;continue}if(y===""){i.data[m]=null,s=m;continue}i.data[m]=Ev(b),s=null}return r!==null&&c(),i.closed||(i.bodyStartLine=n.length+1),i}function Kt(t){return t==null?[]:Array.isArray(t)?t.map(e=>String(e).trim()).filter(Boolean):typeof t=="string"?t.split(`
59
+ `).flatMap(e=>vp(e)):[String(t)]}function D(t){return{severity:"warning",category:"ai_config",confidence:.8,...t}}function at(t,e,n,i){let s=(o,a)=>`ai-config-${i.idPrefix}-${o}-${ce(a)}`;if(!n.present)return[D({id:s("no-frontmatter",t),severity:i.noFrontmatterSeverity??"high",title:i.noFrontmatterTitle??`${i.noun} is missing YAML frontmatter`,summary:`${t} has no \`---\` frontmatter block. ${i.why}`,filePaths:[t],locations:[{filePath:t,startLine:1,endLine:1}],evidence:[`First line: ${e.split(/\r?\n/)[0]?.slice(0,60)??"(empty)"}`],recommendation:i.recommendation,confidence:i.noFrontmatterConfidence??.85})];let r=[];n.closed||r.push(D({id:s("unterminated",t),severity:"high",title:`${i.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(D({id:s("fm-error",`${t}|${o}`),title:a?`${i.noun} frontmatter has an unsupported key "${a}"`:`${i.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 go={"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},_n=Object.keys(go),wp={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"},Cv=4,Pv=.03,Av=.35;function _p(t){return Math.round(t/1e3)*1e3}function Jt(t){let e=t.trim().toLowerCase();if(Object.prototype.hasOwnProperty.call(go,e))return e;if(Object.prototype.hasOwnProperty.call(wp,e))return wp[e]}function xp(t){let e=go[t],n=_p(e*Pv*Cv),i=_p(n*Av);return{contextWindowTokens:e,contextBudget:n,fileContextBudget:i}}function yo(t){let e=Jt(t);return e?xp(e):void 0}var Cp=E(require("node:crypto"),1),Pp=E(require("node:fs/promises"),1),xt=E(require("node:path"),1),Ap=E(jt(),1);var vo=xt.join(".promptci","custom-rules.json"),bo=["forbiddenPattern","absentPattern","requiredSection","crossFileConflict"],Sp=["info","warning","high","critical"],Rv=/^[gimsuy]*$/,le=class extends Error{constructor(e){super(`Invalid ${vo}: ${e}`),this.name="CustomRulesError"}};function xn(t,e,n){let i=t[e];if(typeof i!="string"||i.trim()==="")throw new le(`${n} is missing a non-empty string "${e}".`);return i}function kv(t,e,n){if(!Array.isArray(t)||!t.every(i=>typeof i=="string"))throw new le(`${n}: "${e}" must be an array of strings.`);return t}function $v(t,e,n){if(e!==void 0&&!Rv.test(e))throw new le(`${n}: "flags" may only contain regex flags (gimsuy).`);try{new RegExp(t,e)}catch(i){throw new le(`${n}: "pattern" is not a valid regular expression: ${i instanceof Error?i.message:String(i)}`)}}function Rp(t){let e;if(Array.isArray(t))e=t;else if(t&&typeof t=="object"&&"rules"in t)e=t.rules;else throw new le('top level must be an object with a "rules" array (or a bare array of rules).');if(!Array.isArray(e))throw new le('"rules" must be an array.');let n=[],i=new Set;for(let s=0;s<e.length;s++){let r=e[s],o=`rule at index ${s}`;if(typeof r!="object"||r===null||Array.isArray(r))throw new le(`${o} must be an object.`);let a=r,c=xn(a,"id",o),l=`rule "${c}"`;if(i.has(c))throw new le(`${l}: duplicate rule id (ids must be unique).`);i.add(c);let p=xn(a,"type",l);if(!bo.includes(p))throw new le(`${l}: "type" must be one of ${bo.join(", ")} (got "${p}").`);let u=xn(a,"message",l),d="warning";if("severity"in a){if(typeof a.severity!="string"||!Sp.includes(a.severity))throw new le(`${l}: "severity" must be one of ${Sp.join(", ")}.`);d=a.severity}let f={id:c,type:p,message:u,severity:d};if("files"in a&&(f.files=kv(a.files,"files",l)),"flags"in a){if(typeof a.flags!="string")throw new le(`${l}: "flags" must be a string.`);f.flags=a.flags}p==="requiredSection"?f.heading=xn(a,"heading",l):(f.pattern=xn(a,"pattern",l),$v(f.pattern,f.flags,l)),n.push(f)}return n}async function wo(t){let e=xt.join(t,vo),n;try{n=await Pp.readFile(e,"utf-8")}catch(s){if(s.code==="ENOENT")return[];throw s}let i;try{i=JSON.parse(n)}catch{throw new le("file is not valid JSON.")}return Rp(i)}function Tv(t){return Cp.createHash("sha1").update(t).digest("hex").slice(0,12)}function kp(t,e){let n=1;for(let i=0;i<e&&i<t.length;i++)t[i]===`
60
+ `&&n++;return n}function Ov(t,e,n){return!e.files||e.files.length===0?t:t.filter(i=>{let s=xt.relative(n,i.path).replace(/\\/g,"/");return Ap.default.isMatch(s,e.files,{dot:!0})})}function _o(t){return new RegExp(t.pattern,t.flags)}function Ri(t){return{severity:t.severity,category:"custom",confidence:1,tags:["custom-rule"]}}function Lv(t,e){let n=[];for(let i of t){let s=_o(e).exec(i.content);if(!s)continue;let r=kp(i.content,s.index);n.push({id:`custom:${e.id}:${Tv(i.path)}`,...Ri(e),title:e.message,summary:`Custom rule "${e.id}": a forbidden pattern was found in this file.`,filePaths:[i.path],locations:[{filePath:i.path,startLine:r,endLine:r}],evidence:[`Matched text: "${J(s[0],120)}" (line ${r})`],recommendation:`Remove or revise the flagged content to satisfy custom rule "${e.id}".`})}return n}function Iv(t,e){return t.some(i=>_o(e).test(i.content))?[]:[{id:`custom:${e.id}`,...Ri(e),title:e.message,summary:`Custom rule "${e.id}": a required pattern is absent from all checked instruction files.`,filePaths:t.map(i=>i.path),locations:t.map(i=>({filePath:i.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 Ep(t){return t.toLowerCase().replace(/^#+\s*/,"").replace(/\s+/g," ").trim()}function jv(t,e){let n=Ep(e.heading);return t.some(s=>s.sections.some(r=>r.heading!==void 0&&Ep(r.heading).includes(n)))?[]:[{id:`custom:${e.id}`,...Ri(e),title:e.message,summary:`Custom rule "${e.id}": a required section heading ("${e.heading}") is missing from all checked files.`,filePaths:t.map(s=>s.path),locations:t.map(s=>({filePath:s.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 Nv(t,e){let n=new Map;for(let o of t){let a=_o(e).exec(o.content);if(!a)continue;let c=(a[1]??a[0]).trim(),l=kp(o.content,a.index),p=n.get(c)??[];p.push({filePath:o.path,line:l}),n.set(c,p)}if(n.size<2)return[];let i=[...new Set([...n.values()].flat().map(o=>o.filePath))],s=[...n.values()].flat().map(o=>({filePath:o.filePath,startLine:o.line,endLine:o.line})),r=[...n.entries()].map(([o,a])=>`"${J(o,60)}" in ${a.map(c=>xt.basename(c.filePath)).join(", ")}`);return[{id:`custom:${e.id}`,...Ri(e),title:e.message,summary:`Custom rule "${e.id}": the tracked value differs across files (${n.size} distinct values).`,filePaths:i,locations:s,evidence:r,recommendation:`Reconcile the conflicting values so custom rule "${e.id}" sees a single consistent value.`}]}function xo(t,e,n){let i=[];for(let s of e){let r=Ov(t,s,n);switch(s.type){case"forbiddenPattern":i.push(...Lv(r,s));break;case"absentPattern":i.push(...Iv(r,s));break;case"requiredSection":i.push(...jv(r,s));break;case"crossFileConflict":i.push(...Nv(r,s));break}}return i}var Mv=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","bun.lock"];function Dv(){return{packageManagerName:"unknown",scripts:{},dependencies:{},devDependencies:{},peerDependencies:{},lockfiles:[]}}function Eo(t,e){let n=gt(t,e);if(n===null)throw new Error(`Path escapes repo root: ${e}`);return n}async function So(t,e){try{return await St.readFile(Eo(t,e),"utf-8")}catch{return}}async function Fv(t,e){let n=[];for(let i of e)try{(await St.stat(Eo(t,i))).isFile()&&n.push(i)}catch{}return n}function $p(t){return t?t.startsWith("pnpm@")?"pnpm":t.startsWith("npm@")?"npm":t.startsWith("yarn@")?"yarn":t.startsWith("bun@")?"bun":"unknown":"unknown"}function ki(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 $i(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[n,i]of Object.entries(t))typeof i=="string"&&(e[n]=i);return e}function Tp(t,e){let n=Dv();if(n.raw=t,n.lockfiles=e,!t)return n.packageManagerName=ki(e),n;let i;try{i=JSON.parse(t)}catch{return n.packageManagerName=ki(e),n}if(typeof i!="object"||i===null||Array.isArray(i))return n.packageManagerName=ki(e),n;let s=i;if(n.packageManager=typeof s.packageManager=="string"?s.packageManager:void 0,n.packageManagerName=$p(n.packageManager)!=="unknown"?$p(n.packageManager):ki(e),n.scripts=$i(s.scripts),n.dependencies=$i(s.dependencies),n.devDependencies=$i(s.devDependencies),n.peerDependencies=$i(s.peerDependencies),typeof s.engines=="object"&&s.engines!==null&&!Array.isArray(s.engines)){let r=s.engines;n.enginesNode=typeof r.node=="string"?r.node:void 0}return n}function Hv(t,e){let n=e.split(/\r?\n/),i=[];for(let s=0;s<n.length;s++){let r=n[s],o=/^(\s*)(?:-\s*)?run:\s*(.*)$/.exec(r);if(!o)continue;let a=o[1].length,c=o[2].trim();if(c&&!/^[|>][+-]?$/.test(c)){i.push({filePath:t,command:c,line:s+1});continue}let l=[];for(let u=s+1;u<n.length;u++){let d=n[u];if(d.trim()===""){l.push("");continue}if((d.match(/^\s*/)?.[0].length??0)<=a)break;l.push(d.trim())}let p=l.filter(Boolean).join(`
61
+ `).trim();p&&i.push({filePath:t,command:p,line:s+1})}return i}async function Bv(t){let e=Eo(t,ct.join(".github","workflows")),n;try{n=await St.readdir(e,{withFileTypes:!0})}catch{return{files:[],commands:[]}}let i=n.filter(r=>r.isFile()&&/\.(ya?ml)$/i.test(r.name)).map(r=>ct.join(e,r.name)).sort(),s=[];for(let r of i){let o=ct.relative(t,r),a=await St.readFile(r,"utf-8");s.push(...Hv(o,a))}return{files:i.map(r=>ct.relative(t,r)),commands:s}}function Gv(t,e){let n={estimatedInstructionTokens:t.reduce((i,s)=>i+s.estimatedTokens,0),instructionFileCount:t.length,largestInstructionFiles:[...t].sort((i,s)=>s.estimatedTokens-i.estimatedTokens).slice(0,5).map(i=>({path:i.path,estimatedTokens:i.estimatedTokens}))};return e.length>0&&(n.onDemandFileCount=e.length,n.estimatedOnDemandTokens=e.reduce((i,s)=>i+s.estimatedTokens,0)),n}async function Sn(t){let e=ct.resolve(t.repoPath),n=await fn({...t,repoPath:e}),i=[],s=[];for(let h of n)(ba(h.fileType)?s:i).push(h);let r=t.projectType&&t.projectType!=="auto"?t.projectType:await hn(e);r==="unknown"&&(r=Fr(i));let[o,a,c,l,p,u]=await Promise.all([So(e,"package.json"),So(e,"pyproject.toml"),So(e,"requirements.txt"),Fv(e,Mv),Bv(e),wo(e)]),d={};o&&(d.packageJson=o),a&&(d.pyproject=a),c!==void 0&&(d.requirements=c);let f=t.targetModel?yo(t.targetModel):void 0;return{repoRoot:e,files:i,projectType:r,manifests:d,packageJson:Tp(o,l),workflows:p,aiConfig:ho(e,t),metrics:Gv(i,s),contextBudget:t.contextBudget??f?.contextBudget,fileContextBudget:t.fileContextBudget??f?.fileContextBudget,vagueGuidanceSeverity:t.vagueGuidanceSeverity,onDemandFiles:s,customRules:u}}var Co=E(require("node:crypto"),1),Yt=E(require("node:path"),1);var Op=[/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];function Lp(t){if(t.length===0)return[];let e=[],n=[];for(let o of t)Op.some(a=>a.test(o.content))&&n.push(o);function i(o){let a=Co.createHash("sha1").update(o).digest("hex").slice(0,12);return`canonical-${o}-${a}`}n.length>1&&e.push({id:i("ambiguous-authority"),severity:"warning",category:"structure",title:"Ambiguous authority: multiple files claim to be canonical",summary:`Multiple files (${n.map(o=>Yt.basename(o.path)).join(", ")}) claim to be the "canonical" or "authoritative" source of truth. This leads to confusion about which instructions take precedence.`,filePaths:n.map(o=>o.path),locations:n.map(o=>({filePath:o.path})),evidence:n.map(o=>{let a;for(let c of Op){let l=c.exec(o.content);if(l){a=l[0];break}}return`${Yt.basename(o.path)}: "${J(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(o=>Yt.basename(o.path).toLowerCase()==="agents.md")||n[0];if(r){let o=a=>{let c=a.split(`
60
62
  `);return c.length>0&&c[0].trim().startsWith("#")?c.slice(1).join(`
61
- `).trim():a.trim()};for(let a of t){if(a===o)continue;let c=kt.basename(a.path).toLowerCase(),l=a.path.replace(/\\/g,"/").toLowerCase();if((c==="claude.md"||c===".cursorrules"||l.includes("/.claude/")||l.includes("/.cursor/rules/")||l.includes("/.github/copilot-instructions.md")||l.includes("/.github/instructions/"))&&a.lineCount>50){for(let p of a.sections)if(p.endLine-p.startLine>50&&o.sections.some(f=>{let h=r(f.text).toLowerCase().replace(/\s+/g," ").trim(),g=r(p.text).toLowerCase().replace(/\s+/g," ").trim();return h===g||h.length>500&&h.slice(0,500)===g.slice(0,500)})){let f=Ko.createHash("sha1").update(`canonical-owner:behavior-duplication:${a.path}`).digest("hex").slice(0,12),h=kt.basename(o.path),g=Math.round(p.text.length/4);e.push({id:`behavior-duplication-${f}`,severity:"info",category:"duplicate",title:"Large duplicated behavior in tool-specific file",summary:`The ${c} contains a large section (> 50 lines) that appears to be duplicated from ${h}. This can lead to instruction drift.`,filePaths:[a.path,o.path],locations:[{filePath:a.path,startLine:p.startLine,endLine:p.endLine}],evidence:[`Section "${p.heading??"Untitled"}" is near-identical to one in ${h}`,`Duplicate size: ~${g} tokens`],recommendation:`Consider moving shared rules to ${h} and using a forwarding pointer (e.g., "Follow ${h}") to save ~${g} tokens per session.`,confidence:.8});break}}}}return e}var Au=E(require("node:crypto"),1);function Jo(t){return`ci-align-${Au.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function Yo(t){return t.split(/&&|\n/).map(e=>e.trim()).filter(Boolean)}function Kb(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 Jb(t){let e=[];for(let n of Yo(t)){let s=Kb(n);s&&!e.includes(s)&&e.push(s)}return e}var Yb={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 Qb(t,e){let n=Yb[t];return e.some(s=>n.test(s.content))}function Xb(t){let e=/\b(pnpm|npm|yarn|bun)\b/.exec(t.toLowerCase());return e?e[1]:null}function Zb(t){let e=new Set;for(let n of t)for(let s of Yo(n.command)){let i=Xb(s);i&&e.add(i)}return e}var Ru=new Set(["install","i","add","remove","uninstall","init","help","test","start","stop","restart","exec","dlx","run","workspace","workspaces"]),$u=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 ev(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 Ru.has(n)||$u.has(n)?null:n}function tv(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 Jb(o.command))s.has(r)||s.set(r,[]),s.get(r).push(o);let i=[];for(let[o,r]of s.entries()){if(Qb(o,n))continue;let a=[...new Set(r.map(c=>c.filePath))];i.push({id:Jo(`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 nv(t){let{workflows:e,files:n,packageJson:s}=t;if(e.files.length===0)return[];let i=Zb(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(`
62
- `,u.index-1)+1,f=a.content.indexOf(`
63
- `,u.index),h=a.content.slice(d,f===-1?void 0:f);if(!/\b(?:do\s+not|don'?t|avoid|never|not\s+use|refrain)\b/i.test(h)){p=!0;break}}p&&r.push({id:Jo(`pm-mismatch-ci:${a.path}:${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 sv(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 Yo(l.command)){let p=ev(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(!(Ru.has(d)||$u.has(d))&&!o.has(d)&&!r.has(d)){let f=`${l.path}:${d}`;if(a.has(f))continue;a.add(f),c.push({id:Jo(`orphan-script:${l.path}:${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 Tu(t){return t.workflows.files.length===0?[]:[...tv(t),...nv(t),...sv(t)]}var Qo=E(require("node:fs"),1),Xo=E(require("node:path"),1),Lu=E(require("node:crypto"),1);function iv(t){return`prod-bound-${Lu.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function ov(t,e){return e.some(n=>Qo.existsSync(Xo.join(t,n)))}var rv=[{name:"Web App",fsPaths:["apps/web","next.config.ts","next.config.js","next.config.mjs","next.config.cjs"],depPrefixes:["next"],contradictoryPatterns:[/\b(?:do\s+not|don'?t)\s+add\s+(?:a\s+)?web\s+app\b/i,/\bno\s+web\s+app\s+(?:exists?\s+)?yet\b/i,/\bno\s+web\s+app\b(?!\s+(?:logic|code|component|route|page|specific))/i,/\bweb\s+app\s+(?:pending|not\s+(?:yet\s+)?(?:built|implemented|created))\b/i],severity:"high",title:"Possible stale boundary: instruction appears to deny a web app that exists",evidenceLabel:"web app (apps/web or next.config.*)",recommendation:"Update the instruction file to reflect that the web app is now present. Replace the stale non-goal statement with current guidance about the web app."},{name:"Supabase",fsPaths:["supabase/migrations","supabase"],depPrefixes:["@supabase/"],contradictoryPatterns:[/\bno\s+supabase\b/i,/\bsupabase\s+(?:pending|not\s+(?:yet\s+)?(?:set\s+up|configured|added|integrated))\b/i,/\bno\s+(?:supabase\s+)?(?:database|db)\s+yet\b/i],severity:"high",title:"Possible stale boundary: instruction appears to deny Supabase that is configured",evidenceLabel:"Supabase (supabase/ directory or @supabase/* dependency)",recommendation:"Update the instruction file to reflect that Supabase is now configured. Replace the stale non-goal statement with current guidance about the database."},{name:"Database",fsPaths:["supabase/migrations","drizzle","prisma","prisma/schema.prisma"],depPrefixes:["drizzle-orm","prisma","@prisma/"],contradictoryPatterns:[/\bno\s+database\b/i,/\bdatabase\s+pending\b/i,/\bno\s+db\b/i,/\bwithout\s+a\s+database\b/i],severity:"high",title:"Possible stale boundary: instruction appears to deny a database that exists",evidenceLabel:"database schema/migrations (supabase/migrations, drizzle, or prisma)",recommendation:"Update the instruction file to reflect the current database setup. Replace the stale non-goal statement with current guidance about data access."},{name:"Dashboard",fsPaths:["apps/web/src/app/dashboard","apps/web/src/app/(dashboard)","apps/web/src/app/api/upload/route.ts","src/app/dashboard","src/app/(dashboard)","app/dashboard","app/(dashboard)","src/pages/dashboard","pages/dashboard"],contradictoryPatterns:[/\bdashboard\s+(?:pending|not\s+(?:yet\s+)?(?:built|implemented|created|started))\b/i,/\bno\s+dashboard\b/i,/\bdashboard\s+does\s+not\s+exist\b/i],severity:"warning",title:"Possible stale boundary: instruction appears to deny a dashboard that exists",evidenceLabel:"dashboard routes (apps/web/src/app/dashboard or upload API route)",recommendation:"Update the instruction file to reflect that the dashboard is now implemented."},{name:"Upload API",fsPaths:["apps/web/src/app/api/upload/route.ts","apps/web/src/app/api/upload","src/app/api/upload/route.ts","src/app/api/upload","app/api/upload/route.ts","app/api/upload","pages/api/upload.ts"],contradictoryPatterns:[/\bupload\s+not\s+(?:yet\s+)?implemented\b/i,/\bno\s+upload\s+(?:route|api|endpoint)\b/i,/\bupload\s+(?:api|route|endpoint)\s+(?:pending|does\s+not\s+exist)\b/i],severity:"warning",title:"Possible stale boundary: instruction appears to deny an upload API that exists",evidenceLabel:"upload API route (apps/web/src/app/api/upload/route.ts)",recommendation:"Update the instruction file to reflect that the upload API is implemented. Document what data is uploaded and any relevant security guidance."},{name:"Playwright/E2E",fsPaths:["playwright.config.ts","playwright.config.js","playwright.config.mjs","playwright.config.cjs"],depPrefixes:["@playwright/test"],contradictoryPatterns:[/\bno\s+(?:e2e|end.to.end)\s+tests?\b/i,/\bno\s+playwright\b/i,/\bplaywright\s+(?:pending|not\s+(?:yet\s+)?(?:set\s+up|configured|added))\b/i],severity:"warning",title:"Possible stale boundary: instruction appears to deny E2E tests that are configured",evidenceLabel:"Playwright config (playwright.config.*)",recommendation:"Update the instruction file to include E2E testing guidance. Document how to run Playwright tests and any relevant setup steps."},{name:"GitHub OAuth",fsPaths:["apps/web/src/app/auth","apps/web/src/app/api/auth","apps/web/src/app/(auth)","src/app/auth","src/app/api/auth","src/app/(auth)","app/auth","app/api/auth","app/(auth)","pages/api/auth"],contradictoryPatterns:[/\bno\s+(?:github\s+)?(?:oauth|auth(?:entication)?)\b(?!\s+(?:is\s+)?(?:required|needed|necessary)\b)/i,/\bauth(?:entication)?\s+(?:pending|not\s+(?:yet\s+)?(?:built|implemented|added))\b/i,/\bno\s+login\b(?!\s+(?:is\s+)?(?:required|needed|necessary)\b)/i],severity:"warning",title:"Possible stale boundary: instruction appears to deny auth that is implemented",evidenceLabel:"auth routes (apps/web/src/app/auth or apps/web/src/app/api/auth)",recommendation:"Update the instruction file to reflect that authentication is now implemented."}];function av(t,e){if(ov(e.repoRoot,t.fsPaths))return!0;if(t.depPrefixes&&t.depPrefixes.length>0){let n={...e.packageJson.dependencies,...e.packageJson.devDependencies};return t.depPrefixes.some(s=>Object.keys(n).some(i=>i===s||i.startsWith(s)))}return!1}function cv(t){let e=t.split(`
64
- `),n=[],s=!1,i=null,o=0;for(let r of e)if(s){let a=/^ {0,3}([`~]{3,})\s*$/.exec(r);a&&a[1][0]===i&&a[1].length>=o&&(s=!1,i=null,o=0)}else{let a=/^ {0,3}([`~]{3,})/.exec(r);if(a){s=!0,i=a[1][0]??null,o=a[1].length;continue}n.push(r)}return n.join(`
65
- `).replace(/`[^`\n]+`/g,"")}function lv(t,e){for(let n of e){let i=new RegExp(n.source,n.flags.replace("g","")).exec(t);if(i)return{pattern:n,matched:i[0]}}}function Iu(t){let e=[],{repoRoot:n,files:s}=t;for(let i of rv){if(!av(i,t))continue;let o=i.fsPaths.filter(a=>Qo.existsSync(Xo.join(n,a))),r=o.length>0?o:[i.evidenceLabel];for(let a of s){let c=lv(cv(a.content),i.contradictoryPatterns);c&&e.push({id:iv(`${i.name}:${a.path}`),severity:i.severity,category:"stale_instruction",title:i.title,summary:`The instruction file appears to contain a stale product-boundary statement that contradicts ${i.evidenceLabel} found in the repository. The phrase "${c.matched}" may no longer reflect the current state of the project.`,filePaths:[a.path],locations:[{filePath:a.path}],evidence:[`Contradictory phrase found: "${c.matched}"`,`Repository evidence: ${r.join(", ")}`],recommendation:i.recommendation,confidence:.85})}}return e}var At=E(require("node:fs"),1),_e=E(require("node:path"),1),Du=E(require("node:crypto"),1);function uv(t,e){return`cmd-validity-${Du.createHash("sha1").update(`${t}|${e}`).digest("hex").slice(0,12)}`}function is(t,e){try{let n=_e.resolve(t,e);return At.existsSync(n)}catch{return!1}}function Fu(t){try{let e=At.readFileSync(t,"utf8"),n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return null;let s=typeof n.scripts=="object"&&n.scripts!==null&&!Array.isArray(n.scripts)?Object.fromEntries(Object.entries(n.scripts).filter(i=>typeof i[1]=="string")):{};return{name:typeof n.name=="string"?n.name:void 0,scripts:s}}catch{return null}}function Ou(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 pv(t){if(t)return t.replace(/^['"]|['"]$/g,"").replace(/^\.\.\./,"").replace(/\.\.\.$/,"").replace(/^!/,"").trim()}function dv(t,e){let n=new Set,s=e.replace(/\\/g,"/");(s.startsWith(".")||s.includes("/"))&&n.add(_e.join(t,s,"package.json"));for(let i of["apps","packages","libs"]){let o=_e.join(t,i);try{for(let r of At.readdirSync(o,{withFileTypes:!0}))r.isDirectory()&&n.add(_e.join(o,r.name,"package.json"))}catch{}}return[...n]}function ju(t,e,n){let s=pv(e);if(!s)return!1;for(let i of dv(t.repoRoot,s)){let o=Fu(i);if(!o)continue;let r=_e.dirname(i).replace(/\\/g,"/"),a=_e.relative(t.repoRoot,r).replace(/\\/g,"/");if((o.name===s||a===s||a.endsWith(`/${s}`))&&o.scripts[n])return!0}return!1}function Zo(t){return!t||t.startsWith("-")?!1:t.includes("/")||t.includes("\\")||/\.[a-z]{1,5}$/i.test(t)}var fv=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"]),hv=new Set(["install","i","ci","uninstall","remove","update","outdated","audit","start","stop","restart","test","it","init","create","publish","link","unlink","pack","exec","run"]),mv=new Set(["install","add","remove","upgrade","outdated","audit","init","create","publish","link","unlink","why","pack","run"]);function Nu(t,e){if(t===null)return null;let n=e.replace(/^['"]|['"]$/g,"").trim();if(!n||n.startsWith("/")||n.startsWith("~")||/^[a-zA-Z]:[\\/]/.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 Mu(t){return t.split(/&&|\|\||;|\n/).map(e=>e.trim()).filter(Boolean)}function gv(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 yv=new Set(["bash","sh","shell","powershell","pwsh","zsh","command-line","cmd"]);function bv(t){let e=[],n=t.split(/\r?\n/),s=!1,i=!1,o=null,r=0,a=-1,c=[];for(let l=0;l<n.length;l++){let u=n[l];if(s){let p=/^ {0,3}([`~]{3,})\s*$/.exec(u);if(p&&p[1][0]===o&&p[1].length>=r){if(s=!1,i)for(let d=0;d<c.length;d++){let h=c[d].trim();if(h.startsWith("#"))continue;let g=h.replace(/^\$\s*/,"");if(!g)continue;let v=".";for(let y of Mu(g)){let b=/^cd\s+(.+)$/.exec(y);b&&(v=Nu(v,b[1].trim())),e.push({text:y,line:a+d+1,cwd:v})}}i=!1,o=null,r=0;continue}i&&c.push(u);continue}else{let p=/^ {0,3}([`~]{3,})\s*([a-zA-Z0-9_-]*)/.exec(u);if(p){s=!0,o=p[1][0]??null,r=p[1].length;let d=(p[2]??"").toLowerCase();i=d===""||yv.has(d),a=l+1,c=[];continue}}for(let p of u.matchAll(/`([^`]+)`/g)){let d=p[1].trim(),f=".";for(let h of Mu(d)){let g=/^cd\s+(.+)$/.exec(h);g&&(f=Nu(f,g[1].trim())),gv(h)&&e.push({text:h,line:l+1,cwd:f})}}for(let p of u.matchAll(/\brun\s+(pnpm|npm|yarn|bun|node|tsx|ts-node|bash|python|dotnet|docker)\s+(.+?)(?=[.!?](?:\s|$)|[,;!]|$)/gi)){let d=(p[2]??"").trim().replace(/[.!?]+$/,""),f=`${p[1]} ${d}`.trim();e.push({text:f,line:l+1})}}return e}var vv=/[<{]|\.{3,}|your-file|your-script|example|placeholder/i,wv=new Set(["--filter","-F","--cwd","-C","--loader","--require","-r"]);function xv(t,e){return t==="pnpm"&&e==="-r"?!1:wv.has(e)}function os(t){let e=1,n=t[0]??"";for(;e<t.length;){let s=t[e];if(!s.startsWith("-"))break;e++,xv(n,s)&&t[e]&&!t[e].startsWith("-")&&e++}return e}function er(t,e,n,s,i,o){if(e===null)return null;let r=s.includes("/")?s.split("/").map(u=>u.trim()).filter(Boolean):[s],a=e!=="."&&e!=="",c=a?Fu(_e.join(t.repoRoot,e,"package.json")):null;if(a&&!c)return null;let l=Object.keys(t.packageJson.scripts).length>0;if(!c&&!l)return null;for(let u of r)if(!i.has(u)){if(c){if(c.scripts[u]||ju(t,Ou(n),u))continue;return`${o} script "${u}" does not appear in ${e}/package.json scripts`}if(!ju(t,Ou(n),u)&&!t.packageJson.scripts[u])return`${o} script "${u}" does not appear in package.json scripts`}return null}function _v(t,e,n="."){if(vv.test(t))return null;let s=t.trim().split(/\s+/);if(s.length===0)return null;let i=s[0],o=n===null?null:n!=="."&&n!==""?_e.join(e.repoRoot,n):e.repoRoot;if(i==="pnpm"){let a=os(s),c=s[a];if(!c)return null;let l=c==="run"?s[a+1]:c;return l?er(e,n,s,l,fv,"pnpm"):null}if(i==="npm"){let a=os(s);if(s[a]==="run"&&s[a+1])return er(e,n,s,s[a+1],hv,"npm")}if(i==="yarn"){let a=os(s),c=s[a];if(!c)return null;let l=c==="run"?s[a+1]:c==="workspace"?s[a+2]:c;return l?er(e,n,s,l,mv,"yarn"):null}if(o&&["node","tsx","ts-node","bash","sh","python","python3"].includes(i)&&s[1]){let a=s[os(s)];if(a&&Zo(a)&&!is(o,a))return`File "${a}" referenced by "${i}" does not appear to exist in the repository`}if(o&&(i.startsWith("./")||i.startsWith("../"))&&!is(o,i))return`Script "${i}" does not appear to exist in the repository`;if(o&&i==="docker"&&s[1]==="compose"&&s.includes("-f")){let a=s.indexOf("-f"),c=s[a+1];if(c&&Zo(c)&&!is(o,c))return`Docker Compose file "${c}" does not appear to exist in the repository`}if(o&&i==="dotnet"&&s[1]==="test"&&s[2]){let a=s[2];if(Zo(a)){if(!is(o,a))return`dotnet test target "${a}" does not appear to exist`;if(!/\.(sln|csproj|fsproj)$/.test(a))return`dotnet test target "${a}" should be a .sln, .csproj, or .fsproj file`}}return null}function Hu(t){let e=[],n=new Set;for(let s of t.files){let i=bv(s.content);for(let o of i){let r=_v(o.text,t,o.cwd??".");if(!r)continue;let a=`${s.path}|${o.text}`;n.has(a)||(n.add(a),e.push({id:uv(s.path,o.text),severity:"warning",category:"command_validity",title:`Possible reference to missing command or file: \`${o.text.split(/\s+/).slice(0,3).join(" ")}\``,summary:r,filePaths:[s.path],locations:[{filePath:s.path,startLine:o.line,endLine:o.line}],evidence:[`Command: \`${o.text}\``,`In file: ${s.path}`],recommendation:"Verify the command. If the script was renamed, update the instruction file. If it is an illustrative example, wrap it in a placeholder like <script-name> to suppress this finding.",confidence:.8}))}}return e}var Uu=E(require("node:crypto"),1),Sv={fileWarning:8e3,fileHigh:2e4,totalWarning:3e4,totalHigh:6e4,copilotLineWarning:1e3,readmeFileWarning:15e3,readmeFileHigh:3e4};function tr(t){return`context-bloat-file-${Uu.createHash("sha1").update(t).digest("hex").slice(0,12)}`}var Bu="context-bloat-total";function Pv(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 Vu(t,e){let n=Pv(Sv,e),s=[];for(let a of t){let{charCount:c,estimatedTokens:l,path:u,fileType:p}=a,d=p==="readme"?n.readmeFileWarning:n.fileWarning,f=p==="readme"?n.readmeFileHigh:n.fileHigh;c>=f?s.push({id:tr(u),severity:"high",category:"context_bloat",title:"Instruction file is very large",summary:`File is ${c.toLocaleString()} chars, above high threshold (${f.toLocaleString()}).`,filePaths:[u],locations:[{filePath:u}],evidence:[`charCount: ${c.toLocaleString()}`,`estimatedTokens: ~${l.toLocaleString()}`],recommendation:"Consider splitting this file.",confidence:1}):c>=d&&s.push({id:tr(u),severity:"warning",category:"context_bloat",title:"Instruction file may be too large",summary:`File is ${c.toLocaleString()} chars, above warning threshold (${d.toLocaleString()}).`,filePaths:[u],locations:[{filePath:u}],evidence:[`charCount: ${c.toLocaleString()}`,`estimatedTokens: ~${l.toLocaleString()}`],recommendation:"Consider trimming this file.",confidence:1})}for(let a of t)a.fileType==="copilot"&&a.lineCount>n.copilotLineWarning&&s.push({id:tr(a.path+":copilot-lines"),severity:"warning",category:"context_bloat",title:"Copilot instructions file exceeds recommended line limit",summary:`File is ${a.lineCount.toLocaleString()} lines. GitHub recommends keeping Copilot instruction files under ${n.copilotLineWarning.toLocaleString()} lines \u2014 longer files may be truncated, degrading response quality.`,filePaths:[a.path],locations:[{filePath:a.path}],evidence:[`lineCount: ${a.lineCount.toLocaleString()}`,`threshold: ${n.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 i=t.reduce((a,c)=>a+c.charCount,0),o=t.reduce((a,c)=>a+c.estimatedTokens,0),r=t.map(a=>a.path);return i>=n.totalHigh?s.push({id:Bu,severity:"high",category:"context_bloat",title:"Total instruction context is very large",summary:`Total is ${i.toLocaleString()} chars, above high threshold (${n.totalHigh.toLocaleString()}).`,filePaths:r,locations:r.map(a=>({filePath:a})),evidence:[`totalCharCount: ${i.toLocaleString()}`,`totalEstimatedTokens: ~${o.toLocaleString()}`],recommendation:"Aim to keep total context under 30k characters.",confidence:1}):i>=n.totalWarning&&s.push({id:Bu,severity:"warning",category:"context_bloat",title:"Total instruction context may be too large",summary:`Total is ${i.toLocaleString()} chars, above warning threshold (${n.totalWarning.toLocaleString()}).`,filePaths:r,locations:r.map(a=>({filePath:a})),evidence:[`totalCharCount: ${i.toLocaleString()}`,`totalEstimatedTokens: ~${o.toLocaleString()}`],recommendation:"Consider trimming instruction files.",confidence:1}),s}var qu=E(require("node:crypto"),1),Cv=8e3,Ev=2500,kv=.5,Av=1e3;function Gu(t){return`context-cost-${qu.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function Wu(t){let e=[],n=t.metrics.estimatedInstructionTokens;n>Cv&&e.push({id:"context-cost-total-token-budget",severity:"warning",category:"context_bloat",title:"Instruction context may exceed a practical token budget",summary:`Scanned instruction context is approximately ${n} tokens. This may increase AI cost and make persistent context harder for agents to use.`,filePaths:t.files.map(s=>s.path),locations:[],evidence:[`Estimated instruction tokens: ${n}`],recommendation:"Consider moving rarely needed examples, historical notes, and detailed runbooks into linked on-demand docs.",confidence:.8,tags:["cost","context"]});for(let s of t.files)s.estimatedTokens<=Ev||e.push({id:Gu(`large-file:${s.path}`),severity:"info",category:"context_bloat",title:`Large always-scanned instruction file: ${s.path.split(/[\\/]/).pop()??s.path}`,summary:`This file is approximately ${s.estimatedTokens} tokens. Large instruction files are often worth splitting into short always-loaded rules plus topic-specific reference docs.`,filePaths:[s.path],locations:[{filePath:s.path}],evidence:[`${s.path}: ~${s.estimatedTokens} tokens`],recommendation:"Keep critical rules in the instruction file and move deep examples or runbooks to linked docs.",confidence:.75,tags:["cost","context"]});if(n>0){let s=t.files.find(i=>i.fileType==="readme");s&&s.estimatedTokens>=Av&&s.estimatedTokens/n>=kv&&e.push({id:Gu(`readme-dominates:${s.path}`),severity:"info",category:"context_bloat",title:"README dominates scanned instruction context",summary:`README content accounts for about ${Math.round(s.estimatedTokens/n*100)}% of scanned instruction tokens. That may be appropriate, but AI-specific guidance is usually cheaper in a smaller canonical file.`,filePaths:[s.path],locations:[{filePath:s.path}],evidence:[`README: ~${s.estimatedTokens} of ~${n} scanned tokens`],recommendation:"Consider keeping AI rules in AGENTS.md and leaving README as project documentation linked only when relevant.",confidence:.65,tags:["cost","context"]})}return e}var Ku=E(require("node:crypto"),1),Rv={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 ht(t){return`missing-context-${Ku.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function $v(t,e){let n=e.toLowerCase();return/[^a-z0-9]/.test(n)?t.includes(n):new RegExp(`\\b${n}\\b`).test(t)}function Tv(t){let e=t.split(`
66
- `),n=[],s=!1,i=null,o=0,r=[];for(let a of e){if(!s){let l=/^ {0,3}([`~]{3,})/.exec(a);l&&(s=!0,i=l[1][0]??null,o=l[1].length,r=[]);continue}let c=/^ {0,3}([`~]{3,})\s*$/.exec(a);if(c&&c[1][0]===i&&c[1].length>=o){s=!1,n.push(r.join(`
67
- `)),i=null,o=0;continue}r.push(a)}return n.join(`
68
- `)}var Lv=[/(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/],Iv=[/`(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],Ov=[/\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 jv(t){let e=t.map(i=>i.content).join(`
69
- `),n=Tv(e);return Lv.some(i=>i.test(n))||Iv.some(i=>i.test(e))?null:{id:ht("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 Nv=[/\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],Mv=[/\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 Dv(t){let e=t.map(i=>i.content).join(`
70
- `);return!Nv.some(i=>i.test(e))||Mv.some(i=>i.test(e))?null:{id:ht("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 Fv(t){let e=t.map(s=>s.content).join(`
71
- `);return Ov.some(s=>s.test(e))?null:{id:ht("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 Hv=[/\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],Bv=[/\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 Uv(t){let e=t.map(i=>i.content).join(`
72
- `);return!Hv.some(i=>i.test(e))||Bv.some(i=>i.test(e))?null:{id:ht("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 zu=/\b([A-Z][A-Z0-9_]{3,})\b/g,Vv=[/\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],Gv=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 qv(t){let e=t.map(a=>a.content).join(`
73
- `);if(Vv.some(a=>a.test(e)))return null;let s=new Set,i,o=new RegExp(zu.source,zu.flags);for(;(i=o.exec(e))!==null;){let a=i[1];!Gv.has(a)&&a.includes("_")&&s.add(a)}if(s.size<3)return null;let r=[...s].slice(0,4).join(", ");return{id:ht("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 Wv=[{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 zv(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 Wv)!r.some(f=>l.some(h=>h.test(f.content)))||o.some(f=>l.some(h=>h.test(f.content)))||a.push({id:ht(`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 Ju(t,e){let n=[],s=jv(t);s&&n.push(s);let i=Fv(t);i&&n.push(i);let o=Dv(t);o&&n.push(o);let r=Uv(t);r&&n.push(r);let a=qv(t);if(a&&n.push(a),n.push(...zv(t)),e==="auto"||e==="unknown")return n;let c=Rv[e];if(!c)return n;let l=t.map(p=>p.content.toLowerCase()).join(`
74
- `);if(c.keywords.filter(p=>$v(l,p)).length<c.minimumPresent){let p=c.keywords.slice(0,3).join(", ");n.push({id:ht(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 Xu=E(require("node:crypto"),1),Kv=/(?<![/-])\b(2019|2020|2021|2022|2023|2024|2025)\b(?![/-])/g,Jv=/\b(?:history|changelog|change\s*log|release\s+notes?|releases?|versions?|what.?s\s+new|for\s+reference)\b/i,Yv=/\b(TODO\s*:?\s*remove|remove\s+later|temporary\s+fix|workaround)\b/gi,Yu=/<!--(?:(?!-->)[\s\S])*?\b(TODO|FIXME|WORKAROUND|HACK|NOTE)\b(?:(?!-->)[\s\S])*?\(\s*(\d{4})[-–\d]/gi,Qv=/deprecated[\w\s,.()\\\-:`]{0,60}(v?\d+[\w.]+|react|next\.?js|angular|vue|webpack|babel|unity|jest|mocha)/gi,Xv=[{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 Zv(t,e){let n=`${t.filePath}:${t.startLine}:${e}`;return`stale-${Xu.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function nr(t,e=120){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e)}\u2026`}function sr(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 ew(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 tw(t){let e=[],n,s=new RegExp(Yu.source,Yu.flags);for(;(n=s.exec(t))!==null;)Number(n[2])<=2025&&e.push(n[0]);return e}function nw(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 Qu(t,e=!0){let n=t.split(`
75
- `),s=[],i=!1,o=null,r=0;for(let c of n)if(i){let l=/^ {0,3}([`~]{3,})\s*$/.exec(c);l&&l[1][0]===o&&l[1].length>=r&&(i=!1,o=null,r=0)}else{let l=/^ {0,3}([`~]{3,})/.exec(c);if(l){i=!0,o=l[1][0]??null,r=l[1].length;continue}s.push(c)}let a=s.join(`
76
- `);return e?a.replace(/`[^`\n]+`/g,""):a}function Zu(t){let e=[],n=new Set;for(let s of t)for(let i of s.sections){if(i.heading&&Jv.test(i.heading))continue;let o=i.text,r=Qu(o),a=Qu(o,!1),c=[],l=0,u=`${s.path}:${i.startLine}`,p=sr(r,Kv);p.length>0&&(c.push(`Year reference(s) that may be outdated: ${[...new Set(p)].join(", ")}`),l=Math.max(l,.6));let d=sr(a,Yv);d.length>0&&(c.push(`Cleanup keyword(s): ${[...new Set(d.map(g=>g.trim()))].join(", ")}`),l=Math.max(l,.6));let f=sr(a,Qv);f.length>0&&(c.push(`"deprecated" near version/tool: ${nr(f[0]??"",80)}`),l=Math.max(l,.7));for(let{re:g,label:v}of Xv){let b=ew(r,g).filter(({index:m})=>!nw(r,m));b.length>0&&(c.push(`Old version reference: ${v} ("${b[0].match}")`),l=Math.max(l,.7))}let h=tw(a);h.length>0&&(c.push(`Dated ${h[0].match(/TODO|FIXME|WORKAROUND|HACK|NOTE/i)?.[0]??"TODO"} marker in HTML comment: ${nr(h[0]??"",80)}`),l=Math.max(l,.65)),c.length!==0&&(n.has(u)||(n.add(u),e.push({id:Zv(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: "${nr(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.",confidence:l})))}return e}var tp=E(require("node:crypto"),1),sw=["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"],ep=120;function iw(t){let e=new Set;for(let n of t)e.add(n),n.includes("-")&&e.add(n.replace(/-/g," "));return[...e]}var np=iw(sw);function ow(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var rw=new Map(np.map(t=>[t,new RegExp(`\\b${ow(t)}\\b`)]));function aw(t){let e=t.split(`
77
- `),n=[],s=!1,i=null,o=0;for(let r of e)if(s){let a=/^ {0,3}([`~]{3,})\s*$/.exec(r);a&&a[1][0]===i&&a[1].length>=o&&(s=!1,i=null,o=0)}else{let a=/^ {0,3}([`~]{3,})/.exec(r);if(a){s=!0,i=a[1][0]??null,o=a[1].length;continue}n.push(r)}return n.join(`
78
- `).replace(/`[^`\n]+`/g,"")}function cw(t,e){let n=t.split(`
79
- `).map(i=>i.trim()),s=[];for(let i=0;i<n.length;i++){let o=n[i];o&&e.test(o.toLowerCase())&&o.length<=ep&&s.push(o);let r=n[i+1];if(o&&r){let a=`${o} ${r}`;e.test(a.toLowerCase())&&a.length<=ep&&s.push(a)}}return s}function lw(t){let e=`${t.filePath}:${t.startLine}:vague`;return`vague-${tp.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function sp(t){let e=[],n=new Set;for(let s of t)for(let i of s.sections){let o=`${s.path}:${i.startLine}`;if(n.has(o))continue;let r=aw(i.text),a=r.toLowerCase().replace(/\n/g," "),c=[],l=[];for(let p of np){let d=rw.get(p);if(d.test(a))for(let f of cw(r,d))c.includes(p)||c.push(p),l.includes(f)||l.push(f)}if(c.length===0)continue;n.add(o);let u=c.map(p=>`"${p}"`).join(", ");e.push({id:lw(i),severity:"info",category:"vague_guidance",title:"Vague guidance detected",summary:`This section contains guidance that may be too vague to be actionable: ${u}.`,filePaths:[s.path],locations:[{filePath:s.path,startLine:i.startLine,endLine:i.endLine}],evidence:l.slice(0,3).map(p=>`Line: "${p}"`),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:.8})}return e}var cs=E(require("node:crypto"),1),ge=E(require("node:path"),1),Se=E(require("node:fs"),1),rs=[{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."}],uw=[{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 as(t){return`security-pack-${cs.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function pw(t,e){return`destructive-command-${cs.createHash("sha1").update(`destructive-command:${t}:${e}`).digest("hex").slice(0,12)}`}function dw(t){return`security-pack-inspect-reports-first-${cs.createHash("sha1").update(`inspect-reports-first:${t}`).digest("hex").slice(0,12)}`}function Zt(t,e){return e.some(n=>n.test(t))}function ip(t,e){return t.startsWith("!")?!1:t.replace(/^\/+|\/+$/g,"").split("/").includes(e)}function op(t){let{files:e,repoRoot:n}=t;if(e.length===0)return[];let s=[],i=e.map(m=>m.content).join(`
80
- `),o=e.map(m=>m.path);if([".env",".env.example",".env.local",".env.development",".env.production"].some(m=>Se.existsSync(ge.join(n,m)))||t.files.some(m=>/env\s+vars|environment\s+variables/i.test(m.content))){let m=rs.find(x=>x.id==="no-secret-safeguard");Zt(i,m.patterns)||s.push({id:as(m.id),severity:m.severity,category:"security",title:m.title,summary:m.summary,filePaths:o,locations:[],evidence:["Environment variables detected but no safeguard instruction found."],recommendation:m.recommendation,fixRecipe:m.fixRecipe,confidence:m.confidence})}let c={...t.packageJson.dependencies,...t.packageJson.devDependencies,...t.packageJson.peerDependencies};if(Se.existsSync(ge.join(n,"supabase/migrations"))||Object.keys(c).some(m=>m==="@supabase/supabase-js"||m.startsWith("@supabase/"))){let m=rs.find(x=>x.id==="no-supabase-service-role-rule");Zt(i,m.patterns)||s.push({id:as(m.id),severity:m.severity,category:"security",title:m.title,summary:m.summary,filePaths:o,locations:[],evidence:["Supabase detected but no service role safeguard instruction found."],recommendation:m.recommendation,fixRecipe:m.fixRecipe,confidence:m.confidence})}if(t.files.some(m=>{let x=m.path.replace(/\\/g,"/");return x.includes("/api/upload")||x.includes("/uploads/")||/multer|busboy|formidable/i.test(m.content)})){let m=rs.find(x=>x.id==="no-upload-boundary-docs");Zt(i,m.patterns)||s.push({id:as(m.id),severity:m.severity,category:"security",title:m.title,summary:m.summary,filePaths:o,locations:[],evidence:["Upload features detected but no data boundary documentation found."],recommendation:m.recommendation,fixRecipe:m.fixRecipe,confidence:m.confidence})}if(Se.existsSync(ge.join(n,".promptci"))){let m=rs.find(x=>x.id==="no-promptci-report-safeguard");Zt(i,m.patterns)||s.push({id:as(m.id),severity:m.severity,category:"security",title:m.title,summary:m.summary,filePaths:o,locations:[],evidence:[".promptci/ folder detected but no report safeguard instruction found."],recommendation:m.recommendation,fixRecipe:m.fixRecipe,confidence:m.confidence})}for(let m of e)for(let x of uw)if(x.pattern.test(m.content)){let k=[/ask\s+(before|for\s+approval)/i,/confirm\s+before/i,/be\s+careful\s+with/i,/destructive\s+operation/i,/\bdanger(?:ous)?\b/i];Zt(m.content,k)||s.push({id:pw(m.path,x.name),severity:"warning",category:"security",title:`Destructive command "${x.name}" without safety language`,summary:`Instruction file contains a destructive command "${x.name}" but lacks safety language (e.g., "Ask before running").`,filePaths:[m.path],locations:[],evidence:[`Destructive command "${x.name}" found in ${ge.basename(m.path)} without safety language.`],recommendation:`Add safety language such as "Ask for confirmation before running ${x.name}" to ensure destructive operations are not performed accidentally.`,confidence:.7})}let d=ge.join(n,".gitignore"),f="";try{Se.existsSync(d)&&(f=Se.readFileSync(d,"utf8"))}catch{}let h=f.split(/\r?\n/).map(m=>m.trim()).filter(m=>m&&!m.startsWith("#"));h.some(m=>ip(m,".promptci"))||s.push({id:"security-pack-no-promptci-gitignore",severity:"info",category:"security",title:"Missing .promptci/ ignore in .gitignore",summary:"The .promptci/ directory is not ignored in .gitignore, which may lead to committing large generated scan reports to the repository.",filePaths:[".gitignore"],locations:[],evidence:[".promptci/ entry not found in .gitignore"],recommendation:"Add `.promptci/` to your `.gitignore` file to prevent committing generated reports.",fixRecipe:'echo ".promptci/" >> .gitignore',confidence:.9});let y=["coverage","dist","build",".next","bin","obj","temp","tmp","logs"].filter(m=>{let x=ge.join(n,m);try{if(Se.existsSync(x)&&Se.statSync(x).isDirectory())return!h.some(A=>ip(A,m))}catch{}return!1});y.length>0&&s.push({id:"security-pack-unignored-dirs",severity:"warning",category:"context_bloat",title:"Unignored build, output, or coverage directories",summary:`The repository contains directory/directories (${y.join(", ")}) that are commonly generated but not ignored in .gitignore. AI tools may ingest these, inflating token costs.`,filePaths:[".gitignore"],locations:[],evidence:y.map(m=>`Directory "${m}" exists but is not ignored in .gitignore.`),recommendation:`Add generated directories to .gitignore. For example: "${y.map(m=>`${m}/`).join(", ")}"`,fixRecipe:y.map(m=>`echo "${m}/" >> .gitignore`).join(`
81
- `),confidence:.8});let b=!1;try{let m=ge.join(n,".promptci","config.json");if(Se.existsSync(m)){let x=JSON.parse(Se.readFileSync(m,"utf8"));if(Array.isArray(x.include)){let k=["**/*","**/*.md","*","*.*","**"];b=x.include.some(C=>k.includes(C.trim()))}}}catch{}if(b){let m=e.filter(x=>{let k=ge.relative(n,x.path).replace(/\\/g,"/");return k.includes(".promptci/")||k.includes("coverage/")||k.includes(".next/")});m.length>0&&s.push({id:"security-pack-broad-include",severity:"warning",category:"context_bloat",title:"Broad include pattern scanning generated directories",summary:"PromptCI configuration has a broad include pattern that matches generated directories such as .promptci/ or coverage/, causing them to be unnecessarily scanned.",filePaths:[".promptci/config.json"],locations:[],evidence:m.map(x=>`Scanned generated file: ${ge.relative(n,x.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 m of e){let x=[/read\s+.*\.promptci\s+before/i,/inspect\s+.*\.promptci\s+before/i,/check\s+.*\.promptci\s+before/i,/read\s+.*report.*\s+before\s+.*(source|docs|code)/i,/inspect\s+.*report.*\s+before\s+.*(source|docs|code)/i];for(let k of x)if(k.test(m.content)){s.push({id:dw(m.path),severity:"info",category:"context_bloat",title:"Instruction prioritizing generated reports over source docs",summary:`Instruction file "${ge.basename(m.path)}" tells the agent to inspect generated reports before source files, which can cause circular or outdated guidance ingestion.`,filePaths:[m.path],locations:[],evidence:[`Matched pattern: ${k.toString()}`],recommendation:"Recommend linking to latest reports or directing the agent to read source documents first instead of generated reports.",fixRecipe:"Update the instruction to prioritize reading source files and configuration rather than relying on generated reports.",confidence:.7});break}}return s}var ie=E(require("node:path"),1),oe=E(require("node:fs"),1);function rp(t){let e=[],{packageJson:n,repoRoot:s,files:i}=t,o=!!(n.dependencies.next||n.devDependencies.next),r=oe.existsSync(ie.join(s,"next.config.js"))||oe.existsSync(ie.join(s,"next.config.mjs"))||oe.existsSync(ie.join(s,"next.config.ts"))||oe.existsSync(ie.join(s,"apps","web","next.config.js"))||oe.existsSync(ie.join(s,"apps","web","next.config.mjs"))||oe.existsSync(ie.join(s,"apps","web","next.config.ts"));if(!o&&!r)return[];let a=oe.existsSync(ie.join(s,"app"))||oe.existsSync(ie.join(s,"src","app"))||oe.existsSync(ie.join(s,"apps","web","app"))||oe.existsSync(ie.join(s,"apps","web","src","app")),c=oe.existsSync(ie.join(s,"pages"))||oe.existsSync(ie.join(s,"src","pages"))||oe.existsSync(ie.join(s,"apps","web","pages"))||oe.existsSync(ie.join(s,"apps","web","src","pages"));if(a&&(i.some(u=>u.content.toLowerCase().includes("app router")||u.content.toLowerCase().includes("server component")||u.content.toLowerCase().includes("client component"))||e.push({id:"nextjs-missing-app-router-guidance",severity:"warning",category:"structure",title:"Missing Next.js App Router Guidance",summary:"The project uses the App Router, but the instructions do not mention App Router specific rules like Server vs Client components.",filePaths:i.map(u=>u.path),locations:[],evidence:['App directory detected, but no "App Router" or "Server/Client Component" mention in instructions.'],recommendation:"Add guidance for Next.js App Router, specifically regarding Server and Client Component usage.",confidence:.9})),a&&!c){let l=i.filter(u=>u.content.toLowerCase().includes("pages router")||u.content.toLowerCase().includes("getstaticprops")||u.content.toLowerCase().includes("getserversideprops"));l.length>0&&e.push({id:"nextjs-stale-pages-router-guidance",severity:"warning",category:"stale_instruction",title:"Stale Pages Router Guidance",summary:"The project uses the App Router exclusively, but instructions still reference Pages Router concepts like getStaticProps.",filePaths:l.map(u=>u.path),locations:l.map(u=>({filePath:u.path})),evidence:["Pages Router specific terms found in an App Router project."],recommendation:"Remove or update Pages Router specific instructions to align with App Router.",confidence:.8})}return e}var nt=E(require("node:path"),1),Rt=E(require("node:fs"),1);function ap(t){let e=[],{manifests:n,repoRoot:s,files:i}=t,o=!!n.pyproject,r=Rt.existsSync(nt.join(s,"requirements.txt")),a=Rt.existsSync(nt.join(s,"Pipfile")),c=Rt.existsSync(nt.join(s,"environment.yml"));if(!o&&!r&&!a&&!c)return[];(n.pyproject?.includes("pytest")||r&&Rt.readFileSync(nt.join(s,"requirements.txt"),"utf-8").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 u=[],p=[];return a&&u.push("Pipenv (Pipfile)"),a&&p.push(nt.join(s,"Pipfile")),c&&u.push("Conda (environment.yml)"),c&&p.push(nt.join(s,"environment.yml")),o&&n.pyproject?.includes("[tool.poetry]")&&u.push("Poetry (pyproject.toml)"),o&&n.pyproject?.includes("[tool.poetry]")&&p.push(nt.join(s,"pyproject.toml")),u.length>1&&e.push({id:"python-multiple-env-managers",severity:"warning",category:"conflict",title:"Multiple Python Environment Managers",summary:`Multiple environment managers detected: ${u.join(", ")}. This can lead to conflicting instructions.`,filePaths:p.length>0?p:i.map(d=>d.path),locations:[],evidence:[`Detected: ${u.join(", ")}`],recommendation:"Decide on a single environment manager and remove the others, or clearly document when to use each.",confidence:.9}),e}var ir=E(require("node:path"),1),or=E(require("node:fs"),1);function cp(t){let e=[],{repoRoot:n,files:s}=t,i=or.existsSync(ir.join(n,"Assets")),o=or.existsSync(ir.join(n,"ProjectSettings","ProjectVersion.txt")),r=s.map(d=>d.content).join(`
82
- `),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=s.map(d=>d.path);return/monobehaviour\s+(?:lifecycle|guidance|rules?)|\blifecycle\s+(?:method|methods|guidance|rules?)|instantiate\b.*monobehaviour|avoid\b.*update|new\s+monobehaviour|awake\(\)|start\(\)|update\(\)/i.test(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}var lp=E(require("node:path"),1),en=E(require("node:fs"),1);function up(t){let e=[],{repoRoot:n,files:s}=t,i=t.projectType==="dotnet";if(!i)try{i=en.readdirSync(n).some(u=>u.endsWith(".sln")||u.endsWith(".csproj"))}catch{}let o=s.map(u=>u.content).join(`
83
- `),r=/\bdotnet\b|\.sln\b|\.csproj\b|\bxunit\b|\bnunit\b|\bmstest\b/i.test(o);if(!i&&!r)return[];let a=s.map(u=>u.path);/dotnet\s+(build|test|restore|run)/i.test(o)||e.push({id:"dotnet-missing-validation-commands",severity:"warning",category:"structure",title:"Missing .NET Validation Commands",summary:'The project uses .NET, but instructions do not mention dotnet validation commands like "dotnet build" or "dotnet test".',filePaths:a,locations:[],evidence:[".NET detected, but no dotnet build/test commands found in instructions."],recommendation:'Add instructions telling the agent to run "dotnet build" and "dotnet test" to verify changes.',fixRecipe:"Before saying work is complete, run dotnet build && dotnet test to verify changes.",confidence:.85});let l;try{let p=en.readdirSync(n).find(d=>d.endsWith(".csproj"));if(p){let d=en.readFileSync(lp.join(n,p),"utf-8"),f=/<TargetFramework>(.*?)<\/TargetFramework>/.exec(d);f&&(l=f[1]?.trim())}}catch{}if(l){let u=/\b(netcoreapp\d+\.\d+|net5\.0|netcore)\b/i.test(o);/^net(?:[6-9]|[1-9]\d+)\.0/.test(l)&&u&&e.push({id:"dotnet-obsolete-framework-reference",severity:"warning",category:"stale_instruction",title:".NET Obsolete Framework Reference",summary:`The project targets modern .NET (${l}), but instructions still reference obsolete versions like .NET Core 3.1 or .NET 5.0.`,filePaths:a,locations:[],evidence:[`Project targets ${l}; obsolete framework references found in instructions.`],recommendation:`Update instructions to reference the current target framework version (${l}).`,fixRecipe:`Target .NET ${l} as the framework for this project. Do not use legacy .NET Core 3.1 or .NET 5.0 APIs.`,confidence:.8})}return e}var pp=E(require("node:path"),1),dp=E(require("node:fs"),1);function fp(t){let e=[],{repoRoot:n,files:s}=t,i=dp.existsSync(pp.join(n,"go.mod")),o=s.map(l=>l.content).join(`
84
- `),r=/\bgo\.mod\b/i.test(o)||/`[^`\n]*\bgo\s+(?:build|test|run|get|mod)\b[^`\n]*`/i.test(o);if(!i&&!r)return[];let a=s.map(l=>l.path);return/\bgo\s+test\b/i.test(o)||e.push({id:"go-missing-testing-commands",severity:"warning",category:"structure",title:"Missing Go Testing Commands",summary:'Go project detected, but instructions do not mention Go testing commands like "go test ./...".',filePaths:a,locations:[],evidence:['Go detected, but no "go test" command found in instructions.'],recommendation:'Add instructions telling the agent to run "go test ./..." to verify changes.',fixRecipe:"Before saying work is complete, run go test ./... to verify all tests pass.",confidence:.85}),e}var rr=E(require("node:path"),1),ls=E(require("node:fs"),1);function hp(t){let e=[],{repoRoot:n,files:s}=t,i=ls.existsSync(rr.join(n,"Cargo.toml")),o=s.map(u=>u.content).join(`
85
- `),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=ls.readFileSync(rr.join(n,"Cargo.toml"),"utf-8"),p=/^rust-version\s*=\s*["'](.*?)["']/m.exec(u);p&&(l=p[1]?.trim())}catch{}if(l){let u=f=>{let h=/^(\d+)\.(\d+)/.exec(f);return h?`${h[1]}.${h[2]}`:void 0},d=/\bRust\s+(\d+\.\d+(?:\.\d+)?)\b/i.exec(o);if(d){let f=d[1];u(f)!==u(l)&&e.push({id:"rust-version-mismatch",severity:"warning",category:"stale_instruction",title:"Rust Version Mismatch",summary:`Instructions mention Rust version ${f}, but Cargo.toml specifies rust-version = "${l}".`,filePaths:a,locations:[],evidence:[`Cargo.toml requires rust-version = ${l}; instructions mention Rust ${f}`],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 mp(t){let e=[];return e.push(...rp(t)),e.push(...ap(t)),e.push(...cp(t)),e.push(...up(t)),e.push(...fp(t)),e.push(...hp(t)),e}var yp=E(require("node:path"),1),bp=E(require("node:crypto"),1);function tn(t,e){let n=bp.createHash("sha1").update(`prompt-cache-${t}:${e}`).digest("hex").slice(0,12);return`prompt-cache-${t}-${n}`}var fw=[/\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],hw=[/health\s+score\s*:\s*\d+/i,/files\s+scanned\s*:\s*\d+/i,/promptci\s+report/i,/\bgenerated\s+by\s+promptci\b/i,/latest\s+scan\s+results/i,/scan\s+history/i],mw=[/current\s+branch\s*:\s*\S+/i,/git\s+branch\s*:\s*\S+/i,/current\s+task\s*:\s*\S+/i],gp=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i;function vp(t){let e=[],n=t.filter(s=>["claude","agents","cursor","copilot","prompt"].includes(s.fileType));for(let s of n){let i=yp.basename(s.path);for(let c of fw)if(c.test(s.content)){e.push({id:tn("volatile-timestamp",s.path),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:[`Matched pattern: ${c.toString()}`],recommendation:"Move volatile dates to a separate task-specific prompt or scratch file, or remove them from canonical instructions.",fixRecipe:'Remove the "Last updated: <date>" or timestamp line from the file.',confidence:.85});break}for(let c of hw)if(c.test(s.content)){e.push({id:tn("pasted-report",s.path),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:[`Matched pattern: ${c.toString()}`],recommendation:"Link to the generated report file or read it on-demand instead of pasting its contents into canonical instructions.",fixRecipe:"Delete the pasted report summary block and reference the report file path instead.",confidence:.9});break}for(let c of mw)if(c.test(s.content)){e.push({id:tn("volatile-branch-task",s.path),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:[`Matched pattern: ${c.toString()}`],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(gp.test(s.content)){let c=s.content.match(gp)?.[0]??"";e.push({id:tn("local-paths",s.path),severity:"warning",category:"context_bloat",title:"Local machine paths in instructions",summary:`The instruction file "${i}" contains absolute local machine paths ("${c}"). These paths change per environment, preventing prompt caching and causing instruction drift.`,filePaths:[s.path],locations:[],evidence:[`Found absolute local path: ${c}`],recommendation:"Use repository-relative paths instead of absolute local machine paths.",fixRecipe:"Replace absolute local paths with repository-relative paths.",confidence:.8})}let o=s.content.split(/\r?\n/),r=0,a=0;for(let c of o){let l=c.trim();if(l.startsWith("|")&&l.endsWith("|")){if(/^\|[-\s:|]+\|$/.test(l))continue;a++}else a>r&&(r=a),a=0}a>r&&(r=a),r>15&&e.push({id:tn("large-table",s.path),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:[],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 gw=[/\b(?:cheap|cheaper|smaller|cost-aware|routing)\b.*\b(?:model|models|route|routing)\b/i,/\b(?:escalate\s+to|escalation\s+path|stronger\s+model|expensive\s+model)\b/i,/\bgpt-4o-mini\b/i,/\bclaude-3-5-haiku\b|\bhaiku\b/i,/\bgemini-2\.5-flash\b|\bgemini\s+flash\b|\bflash\s+model\b/i,/\bmodel\s+routing\b/i];function wp(t){let{files:e,metrics:n}=t;if(e.length===0)return[];if(n.estimatedInstructionTokens<500)return[];let s=e.map(o=>o.content).join(`
86
- `);return gw.some(o=>o.test(s))?[]:[{id:"cheap-model-routing-missing",severity:"info",category:"agent_practices",title:"Missing model routing guidance",summary:"No model routing guidelines found in instruction files. Using expensive frontier models for simple tasks (like linting or formatting) unnecessarily increases AI costs.",filePaths:e.map(o=>o.path),locations:[],evidence:["No mentions of cheaper models, model routing, or escalation conditions found in instructions."],recommendation:"Add guidelines specifying when to use cheaper/smaller models (e.g. Gemini 2.5 Flash, GPT-4o-mini) versus escalating to stronger models.",fixRecipe:["### Model Routing Guidance","- Use cheaper/smaller models (e.g. Gemini 2.5 Flash, GPT-4o-mini) for: formatting, linting, simple test additions, mechanical renames, and documentation updates.","- Escalate to stronger models (e.g. Gemini 2.5 Pro, Claude 3.5 Sonnet) for: complex multi-file debugging, security-sensitive changes, and core architecture decisions."].join(`
87
- `),confidence:.8}]}var xp=E(require("node:path"),1),_p=E(require("node:crypto"),1);function yw(t){return`cost-verbosity-encouraged-${_p.createHash("sha1").update(`cost-verbosity-encouraged:${t}`).digest("hex").slice(0,12)}`}var bw=[/explain\s+everything\s+in\s+detail/i,/explain\s+in\s+detail/i,/always\s+include\s+full\s+command\s+output/i,/provide\s+exhaustive\s+summaries/i,/print\s+the\s+entire\s+report/i,/include\s+all\s+logs/i,/\b(?:provide|include|write|give)\s+(?:a\s+)?detailed\s+explanation\b/i],vw=[/summarize\s+command/i,/do\s+not\s+paste\s+(?:full\s+)?logs/i,/keep\s+final\s+answers\s+concise/i,/be\s+concise/i,/brief\s+summary/i,/only\s+key\s+failures/i,/use\s+links\s+to\s+generated\s+artifacts/i];function Sp(t){let e=[],n=t.filter(o=>["claude","agents","cursor","copilot","prompt"].includes(o.fileType));if(n.length===0)return[];let s=n.map(o=>o.content).join(`
88
- `);for(let o of n){let r=xp.basename(o.path),a=o.content.split(/\r?\n/);for(let c of a)if(bw.some(u=>u.test(c))&&!/fail|error|debug|crash|when\s+failing/i.test(c)){e.push({id:yw(o.path),severity:"warning",category:"agent_practices",title:"Verbose output behavior encouraged",summary:`The instruction file "${r}" encourages the agent to produce overly verbose outputs or print excessive logs, increasing output-token costs.`,filePaths:[o.path],locations:[],evidence:[`Matched verbose instruction line: "${c.trim()}"`],recommendation:"Encourage concise status updates and final answers to reduce output token cost. Summarize logs and command results instead of pasting them in full.",fixRecipe:'Replace verbosity demands with instructions like: "Be concise and summarize results, linking to files instead of printing them in full."',confidence:.85});break}}return vw.some(o=>o.test(s))||e.push({id:"cost-missing-verbosity-discipline",severity:"info",category:"agent_practices",title:"Missing output verbosity discipline",summary:"No conciseness or verbosity discipline guidelines found in instruction files. Verbose agents write redundant code dumps and explanations, bloating output tokens.",filePaths:n.map(o=>o.path),locations:[],evidence:["No guidelines found encouraging conciseness, log summarization, or artifact linking."],recommendation:"Add guidance to keep answers concise, summarize command output, and link to files instead of pasting large content.",fixRecipe:'Add a section: "Summarize command results. Do not paste full logs unless requested. Keep final answers concise."',confidence:.8}),e}var Q=E(require("node:path"),1),re=E(require("node:fs"),1),Pp=E(require("node:crypto"),1);function ww(t,e){let n=Pp.createHash("sha1").update(`mcp-tooling-expensive:${t}:${e}`).digest("hex").slice(0,12);return`mcp-tooling-expensive-${t.replace(/\s+/g,"-")}-${n}`}var xw=[{pattern:/\bread\s+all\s+(?:docs|documentation)\b/i,name:"read all docs",signal:"docs",title:"Instructions command reading all documentation at once",recommendation:"Recommend using ripgrep (rg) to find relevant docs or linking to docs and asking the agent to open only relevant sections on-demand.",fixRecipe:"Use local search tools (like rg) to find relevant documentation instead of loading all docs at once."},{pattern:/\bload\s+the\s+entire\s+codebase\b/i,name:"load the entire codebase",signal:"any",title:"Instructions command loading the entire codebase",recommendation:"Recommend using search tools (like rg) or file listing tools instead of reading the entire codebase into context.",fixRecipe:"Do not read all files in the codebase. Use ripgrep or file search to locate files of interest."},{pattern:/\balways\s+include\s+all\s+(?:db\s+)?schema\b/i,name:"always include all schema files",signal:"database",title:"Instructions command loading all database schemas",recommendation:"Recommend querying database schemas via a database MCP server or searching for specific schema definitions on-demand.",fixRecipe:"Do not load entire database schemas. Query the specific table structures using local search or schema files on-demand."},{pattern:/\bpaste\s+the\s+full\s+logs\b/i,name:"paste the full logs",signal:"any",title:"Instructions command pasting full logs",recommendation:"Recommend summarizing logs or sharing only key error traces instead of pasting complete logs.",fixRecipe:"Summarize command failures and paste only the relevant error lines rather than full logs."},{pattern:/\bread\s+every\s+file\b/i,name:"read every file",signal:"any",title:"Instructions command reading every source file",recommendation:"Recommend using search tools or targeted file reading tools to find relevant code sections.",fixRecipe:"Use ripgrep to find target code instead of reading every file."}];function Cp(t){let e=[],{repoRoot:n,files:s}=t;if(s.length===0)return[];let i=re.existsSync(Q.join(n,"docs"))||re.existsSync(Q.join(n,"doc")),o={...t.packageJson.dependencies,...t.packageJson.devDependencies},r=Object.keys(o).some(d=>d.startsWith("@supabase/")),a=t.files.some(d=>d.path.endsWith("package.json")&&d.content.includes("@supabase/supabase-js")),c=re.existsSync(Q.join(n,"supabase"))||re.existsSync(Q.join(n,"prisma"))||re.existsSync(Q.join(n,"db"))||r||a,l=re.existsSync(Q.join(n,"packages"))||re.existsSync(Q.join(n,"apps"))||re.existsSync(Q.join(n,"pnpm-workspace.yaml")),u=re.existsSync(Q.join(n,"mcp-config.json"))||re.existsSync(Q.join(n,".cursor","mcp.json"))||re.existsSync(Q.join(n,".claudegpt","mcp.json")),p=re.existsSync(Q.join(n,"schema.graphql"))||re.existsSync(Q.join(n,"openapi.json"))||re.existsSync(Q.join(n,"swagger.json"))||t.files.some(d=>d.path.endsWith("schema.prisma"));for(let d of s){let f=Q.basename(d.path);for(let h of xw)if(h.pattern.test(d.content)){if(h.signal==="docs"&&!i||h.signal==="database"&&!c)continue;let g=h.recommendation,v=h.fixRecipe;h.name==="load the entire codebase"||h.name==="read every file"?l?(g="This monorepo has multiple packages/apps. Reading or loading the entire codebase is extremely expensive. Recommend using file search (like rg), file listing tools, or a workspace MCP server instead.",v="Do not read all files in the codebase. Use ripgrep (rg) or a directory listing MCP to search for relevant files."):u&&(g="Recommend using your configured MCP server tools (like filesystem search) instead of instructing the agent to load or read the entire codebase.",v="Use filesystem search or MCP tools to read files of interest instead of loading the entire codebase."):h.name==="always include all schema files"&&(u?(g="Recommend querying database schemas via your configured database MCP server instead of pasting or loading schema files on-demand.",v="Do not load entire database schemas. Query the specific table structures using your database MCP server tools."):p&&(g="Recommend querying specific schema definitions or APIs on-demand instead of loading all schema files at once.",v="Do not load entire schema files. Use local search or file reads to view only the relevant schema files on-demand.")),e.push({id:ww(h.name,d.path),severity:"warning",category:"context_bloat",title:h.title,summary:`The instruction file "${f}" commands the agent to "${h.name}". This encourages expensive broad context loading instead of using targeted search or MCP tools.`,filePaths:[d.path],locations:[],evidence:[`Matched pattern: ${h.pattern.toString()}`],recommendation:g,fixRecipe:v,confidence:.8})}}return e}var _w=[/\brtk\b/i,/rust\s+token\s+killer/i,/output\s+filter/i,/token[- ]optimized\s+(cli|command|output)/i,/cli\s+proxy/i,/filter.*command.*output/i,/compact.*output/i,/--failures[- ]only/i],Sw=["npm test","npm run test","yarn test","pnpm test","jest","vitest","pytest","cargo test","go test","rspec","git diff","git log","git status","next build","npm run build","tsc","eslint","ruff check","cargo clippy","golangci-lint","docker logs","kubectl logs","gh pr list","gh run list"];function ar(t){let{files:e,metrics:n}=t;if(e.length===0)return[];if(n.estimatedInstructionTokens<500)return[];let s=e.map(a=>a.content).join(`
89
- `);if(_w.some(a=>a.test(s)))return[];let o=Sw.filter(a=>s.toLowerCase().includes(a.toLowerCase())),r=o.length>0?`Noisy commands referenced in instructions: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}.`:"No output-filter signals found across all instruction files.";return[{id:"cli-output-filter-missing",severity:"info",category:"agent_practices",title:"No CLI output filtering guidance",summary:"Instruction files contain no guidance on filtering verbose CLI output before it reaches the LLM context. Commands like `npm test`, `git diff`, and `cargo test` can produce hundreds of boilerplate lines. A CLI proxy such as RTK (Rust Token Killer) intercepts these transparently and reduces token consumption by 60-90% on affected commands.",filePaths:e.map(a=>a.path),locations:[],evidence:[r],recommendation:"Install a CLI output filter (e.g. RTK: github.com/rtk-ai/rtk) and document it in your instruction files. For Claude Code, `rtk init -g` installs a PreToolUse hook that transparently rewrites Bash commands \u2014 no per-command changes needed.",fixRecipe:["## CLI Output Filtering","","Use [RTK](https://github.com/rtk-ai/rtk) to reduce token consumption from verbose commands:","","```bash","brew install rtk # macOS","# or: cargo install --git https://github.com/rtk-ai/rtk","rtk init -g # Claude Code (PreToolUse hook)","rtk init -g --codex # Codex (AGENTS.md)","rtk init --agent antigravity # Antigravity (project-scoped rules)","```","","The hook transparently rewrites `npm test` \u2192 `rtk npm test` (failures only),","`git diff` \u2192 `rtk git diff` (condensed), etc. Run `rtk gain` to see token savings."].join(`
90
- `),confidence:.75,impact:"medium"}]}var cr=E(require("node:path"),1),Ep=[/\bRead\s+tool\b/,/\bGrep\s+tool\b/,/\bGlob\s+tool\b/,/\b[Uu]se\s+Read\b/,/\b[Uu]se\s+Grep\b/,/\b[Uu]se\s+Glob\b/,/\b[Pp]refer\s+Read\b/,/\b[Pp]refer\s+Grep\b/,/\b[Pp]refer\s+Glob\b/,/\bdedicated\s+tools?\b.*\binstead\s+of\s+(cat|grep|find)\b/i,/\b(avoid|instead\s+of|not)\b.*\b(cat|grep|find)\b.*\b(Read|Grep|Glob)\b/,/\b(Read|Grep|Glob)\b.*\b(instead\s+of|not|avoid)\b.*\b(cat|grep|find)\b/i,/built[- ]in\s+tools?\s+(over|instead\s+of|not|vs\.?)\s+(bash|shell|cat|grep|find)/i];function Pw(t){let e=t.path.replace(/\\/g,"/").toLowerCase(),n=cr.basename(t.path).toLowerCase();return t.fileType==="claude"||n==="claude.md"||e.includes("/.claude/")||n==="claude.local.md"}function lr(t){let e=t.filter(Pw);if(e.length===0)return[];let n=e.map(r=>r.content).join(`
91
- `);if(Ep.some(r=>r.test(n)))return[];let i=t.map(r=>r.content).join(`
92
- `);return Ep.some(r=>r.test(i))?[]:[{id:"native-tool-preference-missing",severity:"info",category:"agent_practices",title:"No guidance to prefer built-in tools over Bash equivalents (Claude Code)",summary:"Claude Code's built-in Read, Grep, and Glob tools are faster and more token-efficient than their Bash equivalents (cat/head/tail, grep/rg, find). Instructions that explicitly prefer these tools reduce context noise and bypass the Bash permission prompt entirely. No such guidance was found in Claude-targeted instruction files.",filePaths:e.map(r=>r.path),locations:[],evidence:[`No Read/Grep/Glob preference guidance found in: ${e.map(r=>cr.basename(r.path)).join(", ")}.`],recommendation:"Add a rule to Claude-targeted files instructing agents to prefer Read over cat/head/tail, Grep over grep/rg, and Glob over find when working with local files. Reserve Bash for operations that have no dedicated tool (e.g. git commands, running tests).",fixRecipe:["## Tool Selection (Claude Code)","","Prefer dedicated tools over Bash for file operations \u2014 they are faster, more token-efficient,","and bypass the Bash permission prompt:","","- **File search**: Use `Glob` (not `find` or `ls`)","- **Content search**: Use `Grep` (not `grep` or `rg`)","- **Read files**: Use `Read` (not `cat`/`head`/`tail`)","","Reserve Bash for operations without a dedicated tool: git commands, running builds/tests,","package manager commands, and other shell-only operations."].join(`
93
- `),confidence:.7,impact:"medium"}]}var Cw=[{id:"duplicates",group:"scan",run:t=>_o(t.files)},{id:"duplicate-headings",group:"scan",run:t=>So(t.files)},{id:"conflicts",group:"scan",run:t=>Co(t.files)},{id:"version-conflicts",group:"scan",run:t=>ko(t.files)},{id:"competing-tech-conflicts",group:"scan",run:t=>Ao(t.files)},{id:"context-bloat",group:"scan",run:t=>Vu(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})},{id:"stale-instructions",group:"scan",run:t=>Zu(t.files)},{id:"command-validity",group:"scan",run:t=>Hu(t)},{id:"missing-context",group:"scan",run:t=>Ju(t.files,t.projectType)},{id:"manifest-consistency",group:"scan",run:t=>Wo(t)},{id:"vague-guidance",group:"scan",run:t=>sp(t.files)},{id:"dead-references",group:"scan",run:t=>To(t.files,t.repoRoot)},{id:"agent-practices",group:"scan",run:t=>Io(t.files)},{id:"canonical-owner",group:"scan",run:t=>ku(t.files)},{id:"ci-alignment",group:"scan",run:t=>Tu(t)},{id:"product-boundary",group:"scan",run:t=>Iu(t)},{id:"security-pack",group:"scan",run:t=>op(t)},{id:"framework-packs",group:"scan",run:t=>mp(t)},{id:"prompt-cache-friendliness",group:"scan",run:t=>vp(t.files)},{id:"cheap-model-routing",group:"scan",run:t=>wp(t)},{id:"output-verbosity",group:"scan",run:t=>Sp(t.files)},{id:"mcp-tooling",group:"scan",run:t=>Cp(t)},{id:"cli-output-filter",group:"scan",run:t=>ar(t)},{id:"native-tool-preference",group:"scan",run:t=>lr(t.files)},{id:"context-cost",group:"context",run:Wu}];function nn(t,e){return Cw.filter(n=>n.group===e).flatMap(n=>n.run(t))}async function ur(t){let e=await Xt(t),n=nn(e,"context");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:n}}var Ap=E(require("node:crypto"),1),gt=E(require("node:path"),1),Ew={info:0,warning:1,high:2,critical:3};function kp(t){return Ew[t]??-1}function mt(t){return t.replace(/\\/g,"/")}function Rp(t,e){if(!e)return t;try{let i=gt.relative(e,t);if(i&&!i.startsWith("..")&&!gt.isAbsolute(i))return mt(i)}catch{}let n=mt(t),s=[mt(e).replace(/\/+$/,""),mt(gt.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 kw(t,e){if(!e)return t;let n=mt(t);return[mt(e).replace(/\/+$/,""),mt(gt.resolve(e)).replace(/\/+$/,"")].reduce((i,o)=>i.replaceAll(o,"<repo>"),n)}function pr(t,e){let n=t.filePaths.map(o=>Rp(o,e)).sort(),s=t.evidence.map(o=>kw(o,e)).sort(),i=[t.category,t.title,...n,...s].join("|");return Ap.createHash("sha256").update(i).digest("hex")}function $t(t,e){return t.map(n=>({id:n.id,category:n.category,title:n.title,filePaths:n.filePaths.map(s=>Rp(s,e)).sort(),severity:n.severity,fingerprint:pr(n,e)})).sort((n,s)=>n.fingerprint.localeCompare(s.fingerprint))}function dr(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 Tt(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=pr(r,n),c=s.get(a);c===void 0||kp(r.severity)>kp(c)?i.push(r):o.push(r)}return{newIssues:i,baselinedIssues:o}}async function Ee(t){let e=await Xt(t),n=nn(e,"scan"),s=Oo(e.files),i=[...n,...jo(s)],{active:o,suppressed:r}=No(i,s),a=Do(o),c=Fo(o),l,u;if(t.baseline){let p=Tt(o,t.baseline,e.repoRoot);l=p.newIssues,u=p.baselinedIssues}return{schemaVersion:"0.1",generatedAt:new Date().toISOString(),repoPath:e.repoRoot,projectType:e.projectType,healthScore:a,metrics:e.metrics,filesScanned:e.files,issues:o,topFixes:c,newIssues:l,baselinedIssues:u,suppressedIssues:r.length>0?r:void 0}}var ye=E(require("node:path"),1),sn=E(require("node:fs/promises"),1);function Lt(t,e){let n=ye.resolve(t),s=ye.isAbsolute(e)?ye.resolve(e):ye.resolve(n,e);if(!s.startsWith(n))throw new Error(`Path traversal detected: "${e}" is outside repo root "${n}"`);return s}async function fr(t,e){let n=[];if(t.id==="security-pack-no-promptci-gitignore"){let s=Lt(e,".gitignore"),i="";try{i=await sn.readFile(s,"utf-8")}catch{}if(!i.includes(".promptci/")){let o=i.includes(`\r
94
- `)?`\r
95
- `:`
96
- `,r=i.endsWith(`
97
- `)||i.endsWith("\r")?`.promptci/${o}`:`${o}.promptci/${o}`;n.push({filePath:s,originalContent:i,newContent:i+r})}return n}if(t.id==="security-pack-unignored-dirs"){let s=Lt(e,".gitignore"),i="";try{i=await sn.readFile(s,"utf-8")}catch{}let o="",r=i.includes(`\r
63
+ `).trim():a.trim()};for(let a of t){if(a===r)continue;let c=Yt.basename(a.path).toLowerCase();if((a.fileType==="claude"||a.fileType==="cursor"||a.fileType==="windsurf"||a.fileType==="copilot"||c==="claude.md"||c===".cursorrules"||c===".windsurfrules")&&a.lineCount>50){for(let p of a.sections)if(p.endLine-p.startLine>50&&r.sections.some(d=>{let f=o(d.text).toLowerCase().replace(/\s+/g," ").trim(),h=o(p.text).toLowerCase().replace(/\s+/g," ").trim();return f===h||f.length>500&&f.slice(0,500)===h.slice(0,500)})){let d=Co.createHash("sha1").update(`canonical-owner:behavior-duplication:${a.path}`).digest("hex").slice(0,12),f=Yt.basename(r.path),h=Math.round(p.text.length/4);e.push({id:`behavior-duplication-${d}`,severity:"info",category:"duplicate",title:"Large duplicated behavior in tool-specific file",summary:`The ${c} contains a large section (> 50 lines) that appears to be duplicated from ${f}. This can lead to instruction drift.`,filePaths:[a.path,r.path],locations:[{filePath:a.path,startLine:p.startLine,endLine:p.endLine}],evidence:[`Section "${p.heading??"Untitled"}" is near-identical to one in ${f}`,`Duplicate size: ~${h} tokens`],recommendation:`Consider moving shared rules to ${f} and using a forwarding pointer (e.g., "Follow ${f}") to save ~${h} tokens per session.`,confidence:.8});break}}}}return e}var Ip=E(require("node:crypto"),1);function Po(t){return`ci-align-${Ip.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function Ao(t){return t.split(/&&|\n/).map(e=>e.trim()).filter(Boolean)}function Wv(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 Vv(t){let e=[];for(let n of Ao(t)){let i=Wv(n);i&&!e.includes(i)&&e.push(i)}return e}var qv={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 Uv(t,e){let n=qv[t];return e.some(i=>n.test(i.content))}function zv(t){let e=/\b(pnpm|npm|yarn|bun)\b/.exec(t.toLowerCase());return e?e[1]:null}function Kv(t){let e=new Set;for(let n of t)for(let i of Ao(n.command)){let s=zv(i);s&&e.add(s)}return e}var jp=new Set(["install","i","add","remove","uninstall","init","help","test","start","stop","restart","exec","dlx","run","workspace","workspaces"]),Np=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 Jv(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 jp.has(n)||Np.has(n)?null:n}function Yv(t){let{workflows:e,files:n}=t;if(e.files.length===0)return[];let i=new Map;for(let r of e.commands)for(let o of Vv(r.command))i.has(o)||i.set(o,[]),i.get(o).push(r);let s=[];for(let[r,o]of i.entries()){if(Uv(r,n))continue;let a=[...new Set(o.map(c=>c.filePath))];s.push({id:Po(`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 s}function Xv(t){let{workflows:e,files:n,packageJson:i}=t;if(e.files.length===0)return[];let s=Kv(e.commands);if(s.size===0)return[];let r=i.packageManagerName!=="unknown"?i.packageManagerName:Array.from(s)[0];if(!s.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"),p,u=!1;for(;(p=l.exec(a.content))!==null;){let d=a.content.lastIndexOf(`
64
+ `,p.index-1)+1,f=a.content.indexOf(`
65
+ `,p.index),h=a.content.slice(d,f===-1?void 0:f);if(!/\b(?:do\s+not|don'?t|avoid|never|not\s+use|refrain)\b/i.test(h)){u=!0;break}}u&&o.push({id:Po(`pm-mismatch-ci:${a.path}:${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(s).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 Qv(t){let{workflows:e,files:n,packageJson:i,manifests:s}=t;if(e.files.length===0)return[];if(s.packageJson)return[];let r=new Set(Object.keys(i.scripts)),o=new Set;for(let l of e.commands)for(let p of Ao(l.command)){let u=Jv(p);u&&o.add(u)}let a=new Set,c=[];for(let l of n){let p=/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?([a-z0-9][a-z0-9:_-]*)\b/gi,u;for(;(u=p.exec(l.content))!==null;){let d=u[1].toLowerCase();if(!(jp.has(d)||Np.has(d))&&!r.has(d)&&!o.has(d)){let f=`${l.path}:${d}`;if(a.has(f))continue;a.add(f),c.push({id:Po(`orphan-script:${l.path}:${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 Mp(t){return t.workflows.files.length===0?[]:[...Yv(t),...Xv(t),...Qv(t)]}var Xt=E(require("node:fs"),1),Ce=E(require("node:path"),1),Gp=E(require("node:crypto"),1);function Zv(t,e){return`cmd-validity-${Gp.createHash("sha1").update(`${t}|${e}`).digest("hex").slice(0,12)}`}function Ti(t,e){try{let n=Ce.resolve(t,e);return Xt.existsSync(n)}catch{return!1}}function Wp(t){try{let e=Xt.readFileSync(t,"utf8"),n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return null;let i=typeof n.scripts=="object"&&n.scripts!==null&&!Array.isArray(n.scripts)?Object.fromEntries(Object.entries(n.scripts).filter(s=>typeof s[1]=="string")):{};return{name:typeof n.name=="string"?n.name:void 0,scripts:i}}catch{return null}}function Dp(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 ew(t){if(t)return t.replace(/^['"]|['"]$/g,"").replace(/^\.\.\./,"").replace(/\.\.\.$/,"").replace(/^!/,"").trim()}function tw(t,e){let n=new Set,i=e.replace(/\\/g,"/");(i.startsWith(".")||i.includes("/"))&&n.add(Ce.join(t,i,"package.json"));for(let s of["apps","packages","libs"]){let r=Ce.join(t,s);try{for(let o of Xt.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&n.add(Ce.join(r,o.name,"package.json"))}catch{}}return[...n]}function Fp(t,e,n){let i=ew(e);if(!i)return!1;for(let s of tw(t.repoRoot,i)){let r=Wp(s);if(!r)continue;let o=Ce.dirname(s).replace(/\\/g,"/"),a=Ce.relative(t.repoRoot,o).replace(/\\/g,"/");if((r.name===i||a===i||a.endsWith(`/${i}`))&&r.scripts[n])return!0}return!1}function Ro(t){return!t||t.startsWith("-")?!1:t.includes("/")||t.includes("\\")||/\.[a-z]{1,5}$/i.test(t)}var nw=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"]),iw=new Set(["install","i","ci","uninstall","remove","update","outdated","audit","start","stop","restart","test","it","init","create","publish","link","unlink","pack","exec","run","version"]),sw=new Set(["install","add","remove","upgrade","outdated","audit","init","create","publish","link","unlink","why","pack","run","version"]);function Hp(t,e){if(t===null)return null;let n=e.replace(/^['"]|['"]$/g,"").trim();if(!n||n.startsWith("/")||n.startsWith("~")||/^[a-zA-Z]:[\\/]/.test(n))return null;let i=t==="."?[]:t.split("/");for(let s of n.replace(/\\/g,"/").split("/"))if(!(s===""||s==="."))if(s===".."){if(i.length===0)return null;i.pop()}else i.push(s);return i.length===0?".":i.join("/")}function Bp(t){return t.split(/&&|\|\||;|\n/).map(e=>e.trim()).filter(Boolean)}function rw(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(i=>n===i||n.startsWith("./"))||n.startsWith("./")||n.startsWith("../"))}var ow=new Set(["bash","sh","shell","powershell","pwsh","zsh","command-line","cmd"]);function aw(t){let e=[];for(let n of dn(t)){let i=/^[a-zA-Z0-9_-]*/.exec(n.lang)[0];if(!(!(i===""||ow.has(i))||!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 Bp(a)){let p=/^cd\s+(.+)$/.exec(l);p&&(c=Hp(c,p[1].trim())),e.push({text:l,line:n.contentStartLine+r,cwd:c})}}}for(let n of st(t)){if(n.inFence)continue;let i=n.lineNumber-1,s=n.text.replace(/\r$/,"");for(let r of s.matchAll(/`([^`]+)`/g)){let o=r[1].trim(),a=".";for(let c of Bp(o)){let l=/^cd\s+(.+)$/.exec(c);l&&(a=Hp(a,l[1].trim())),rw(c)&&e.push({text:c,line:i+1,cwd:a})}}for(let r of s.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:i+1})}}return e.sort((n,i)=>n.line-i.line)}var cw=/[<{]|\.{3,}|your-file|your-script|example|placeholder/i,lw=new Set(["--filter","-F","--cwd","-C","--loader","--require","-r"]);function uw(t,e){return t==="pnpm"&&e==="-r"?!1:lw.has(e)}function Oi(t){let e=1,n=t[0]??"";for(;e<t.length;){let i=t[e];if(!i.startsWith("-"))break;e++,uw(n,i)&&t[e]&&!t[e].startsWith("-")&&e++}return e}function ko(t,e,n,i,s,r){if(e===null)return null;let o=i.includes("/")?i.split("/").map(p=>p.trim()).filter(Boolean):[i],a=e!=="."&&e!=="",c=a?Wp(Ce.join(t.repoRoot,e,"package.json")):null;if(a&&!c)return null;let l=Object.keys(t.packageJson.scripts).length>0;if(!c&&!l)return null;for(let p of o)if(!s.has(p)){if(c){if(c.scripts[p]||Fp(t,Dp(n),p))continue;return`${r} script "${p}" does not appear in ${e}/package.json scripts`}if(!Fp(t,Dp(n),p)&&!t.packageJson.scripts[p])return`${r} script "${p}" does not appear in package.json scripts`}return null}function pw(t,e,n="."){if(cw.test(t))return null;let i=t.trim().split(/\s+/);if(i.length===0)return null;let s=i[0],r=n===null?null:n!=="."&&n!==""?Ce.join(e.repoRoot,n):e.repoRoot;if(s==="pnpm"){let a=Oi(i),c=i[a];if(!c)return null;let l=c==="run"?i[a+1]:c;return l?ko(e,n,i,l,nw,"pnpm"):null}if(s==="npm"){let a=Oi(i);if(i[a]==="run"&&i[a+1])return ko(e,n,i,i[a+1],iw,"npm")}if(s==="yarn"){let a=Oi(i),c=i[a];if(!c)return null;let l=c==="run"?i[a+1]:c==="workspace"?i[a+2]:c;return l?ko(e,n,i,l,sw,"yarn"):null}if(r&&["node","tsx","ts-node","bash","sh","python","python3"].includes(s)&&i[1]){let a=i[Oi(i)];if(a&&Ro(a)&&!Ti(r,a))return`File "${a}" referenced by "${s}" does not appear to exist in the repository`}if(r&&(s.startsWith("./")||s.startsWith("../"))&&!Ti(r,s))return`Script "${s}" does not appear to exist in the repository`;if(r&&s==="docker"&&i[1]==="compose"&&i.includes("-f")){let a=i.indexOf("-f"),c=i[a+1];if(c&&Ro(c)&&!Ti(r,c))return`Docker Compose file "${c}" does not appear to exist in the repository`}if(r&&s==="dotnet"&&i[1]==="test"&&i[2]){let a=i[2];if(Ro(a)){if(!Ti(r,a))return`dotnet test target "${a}" does not appear to exist`;if(!/\.(sln|csproj|fsproj)$/.test(a))return`dotnet test target "${a}" should be a .sln, .csproj, or .fsproj file`}}return null}function Vp(t){let e=[],n=new Set;for(let i of t.files){let s=aw(i.content);for(let r of s){let o=pw(r.text,t,r.cwd??".");if(!o)continue;let a=`${i.path}|${r.text}`;n.has(a)||(n.add(a),e.push({id:Zv(i.path,r.text),severity:"warning",category:"command_validity",title:`Possible reference to missing command or file: \`${r.text.split(/\s+/).slice(0,3).join(" ")}\``,summary:o,filePaths:[i.path],locations:[{filePath:i.path,startLine:r.line,endLine:r.line}],evidence:[`Command: \`${r.text}\``,`In file: ${i.path}`],recommendation:"Verify the command. If the script was renamed, update the instruction file. If it is an illustrative example, wrap it in a placeholder like <script-name> to suppress this finding.",confidence:.8}))}}return e}var Up=E(require("node:crypto"),1),dw={fileWarning:8e3,fileHigh:2e4,totalWarning:3e4,totalHigh:6e4,copilotLineWarning:1e3,readmeFileWarning:15e3,readmeFileHigh:3e4,windsurfFileWarning:6e3,windsurfFileHigh:12e3};function Li(t){return`context-bloat-file-${Up.createHash("sha1").update(t).digest("hex").slice(0,12)}`}var qp="context-bloat-total",fw=.5,hw=1e3,En=["cost","context"];function mw(t,e){if(!e)return t;let n={...t};for(let i of Object.keys(e)){let s=e[i];s!==void 0&&(n[i]=s)}return n}function zp(t,e){let n=mw(dw,e),i=[];for(let c of t){let{charCount:l,estimatedTokens:p,path:u,fileType:d}=c,f=n.fileWarning,h=n.fileHigh;d==="readme"?(f=n.readmeFileWarning,h=n.readmeFileHigh):d==="windsurf"&&(f=n.windsurfFileWarning,h=n.windsurfFileHigh);let m=d==="windsurf",b=`Trim the file under ~${n.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.`;l>=h?i.push({id:Li(u),severity:"high",category:"context_bloat",title:m?".windsurfrules is past the Windsurf size limit":"Instruction file is very large",summary:m?`File is ${l.toLocaleString()} chars, past Windsurf's ~${n.windsurfFileHigh.toLocaleString()}-char combined budget \u2014 rules beyond the ~${n.windsurfFileWarning.toLocaleString()}-char limit are silently truncated.`:`File is ${l.toLocaleString()} chars, above high threshold (${h.toLocaleString()}).`,filePaths:[u],locations:[{filePath:u}],evidence:[`charCount: ${l.toLocaleString()}`,`estimatedTokens: ~${p.toLocaleString()}`],recommendation:m?b:"Consider splitting this file.",confidence:1,tags:En}):l>=f&&i.push({id:Li(u),severity:"warning",category:"context_bloat",title:m?".windsurfrules may exceed the Windsurf size limit":"Instruction file may be too large",summary:m?`File is ${l.toLocaleString()} chars, past Windsurf's ~${n.windsurfFileWarning.toLocaleString()}-char truncation limit \u2014 rules beyond it may be silently dropped.`:`File is ${l.toLocaleString()} chars, above warning threshold (${f.toLocaleString()}).`,filePaths:[u],locations:[{filePath:u}],evidence:[`charCount: ${l.toLocaleString()}`,`estimatedTokens: ~${p.toLocaleString()}`],recommendation:m?b:"Consider trimming this file.",confidence:1,tags:En})}for(let c of t)c.fileType==="copilot"&&c.lineCount>n.copilotLineWarning&&i.push({id:Li(c.path+":copilot-lines"),severity:"warning",category:"context_bloat",title:"Copilot instructions file exceeds recommended line limit",summary:`File is ${c.lineCount.toLocaleString()} lines. GitHub recommends keeping Copilot instruction files under ${n.copilotLineWarning.toLocaleString()} lines \u2014 longer files may be truncated, degrading response quality.`,filePaths:[c.path],locations:[{filePath:c.path}],evidence:[`lineCount: ${c.lineCount.toLocaleString()}`,`threshold: ${n.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 s=t.reduce((c,l)=>c+l.charCount,0),r=t.reduce((c,l)=>c+l.estimatedTokens,0),o=t.map(c=>c.path);s>=n.totalHigh?i.push({id:qp,severity:"high",category:"context_bloat",title:"Total instruction context is very large",summary:`Total is ${s.toLocaleString()} chars, above high threshold (${n.totalHigh.toLocaleString()}).`,filePaths:o,locations:o.map(c=>({filePath:c})),evidence:[`totalCharCount: ${s.toLocaleString()}`,`totalEstimatedTokens: ~${r.toLocaleString()}`],recommendation:"Aim to keep total context under 30k characters.",confidence:1,tags:En}):s>=n.totalWarning&&i.push({id:qp,severity:"warning",category:"context_bloat",title:"Total instruction context may be too large",summary:`Total is ${s.toLocaleString()} chars, above warning threshold (${n.totalWarning.toLocaleString()}).`,filePaths:o,locations:o.map(c=>({filePath:c})),evidence:[`totalCharCount: ${s.toLocaleString()}`,`totalEstimatedTokens: ~${r.toLocaleString()}`],recommendation:"Consider trimming instruction files.",confidence:1,tags:En});let a=t.find(c=>c.fileType==="readme");if(r>0&&a&&a.estimatedTokens>=hw&&a.estimatedTokens/r>=fw){let c=Math.round(a.estimatedTokens/r*100);i.push({id:Li(`${a.path}:readme-dominates`),severity:"info",category:"context_bloat",title:"README dominates scanned instruction context",summary:`README content accounts for about ${c}% of scanned instruction tokens. That may be appropriate, but AI-specific guidance is usually cheaper in a smaller canonical file.`,filePaths:[a.path],locations:[{filePath:a.path}],evidence:[`README: ~${a.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:En})}return i}var Jp=E(require("node:crypto"),1);var gw={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 Et(t){return`missing-context-${Jp.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function yw(t,e){let n=e.toLowerCase();return/[^a-z0-9]/.test(n)?t.includes(n):new RegExp(`\\b${n}\\b`).test(t)}var bw=[/(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/],vw=[/`(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],ww=[/\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 _w(t){let e=t.map(s=>s.content).join(`
66
+ `),n=pu(e);return bw.some(s=>s.test(n))||vw.some(s=>s.test(e))?null:{id:Et("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(s=>s.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 xw=[/\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],Sw=[/\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 Ew(t){let e=t.map(s=>s.content).join(`
67
+ `);return!xw.some(s=>s.test(e))||Sw.some(s=>s.test(e))?null:{id:Et("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(s=>s.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 Cw(t){let e=t.map(i=>i.content).join(`
68
+ `);return ww.some(i=>i.test(e))?null:{id:Et("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(i=>i.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 Pw=[/\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],Aw=[/\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 Rw(t){let e=t.map(s=>s.content).join(`
69
+ `);return!Pw.some(s=>s.test(e))||Aw.some(s=>s.test(e))?null:{id:Et("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(s=>s.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 Kp=/\b([A-Z][A-Z0-9_]{3,})\b/g,kw=[/\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],$w=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 Tw(t){let e=t.map(a=>a.content).join(`
70
+ `);if(kw.some(a=>a.test(e)))return null;let i=new Set,s,r=new RegExp(Kp.source,Kp.flags);for(;(s=r.exec(e))!==null;){let a=s[1];!$w.has(a)&&a.includes("_")&&i.add(a)}if(i.size<3)return null;let o=[...i].slice(0,4).join(", ");return{id:Et("missing-env-var-list"),severity:"info",category:"missing_context",title:"Environment variables referenced but no comprehensive list documented",summary:`Instruction files mention ${i.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:[`${i.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 Ow=[{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 Lw(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")},i=c=>c.fileType==="copilot"||e(c).includes("/.github/instructions/"),s=t.find(n);if(!s)return[];let r=t.filter(i),o=t.filter(c=>!r.includes(c));if(o.length===0)return[];let a=[];for(let{label:c,patterns:l,recommendation:p}of Ow)!o.some(f=>l.some(h=>h.test(f.content)))||r.some(f=>l.some(h=>h.test(f.content)))||a.push({id:Et(`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:[s.path],locations:[{filePath:s.path}],evidence:[`"${c}" is documented in other instruction files but absent from Copilot instruction files.`],recommendation:p,confidence:.6});return a}function Yp(t,e){let n=[],i=_w(t);i&&n.push(i);let s=Cw(t);s&&n.push(s);let r=Ew(t);r&&n.push(r);let o=Rw(t);o&&n.push(o);let a=Tw(t);if(a&&n.push(a),n.push(...Lw(t)),e==="auto"||e==="unknown")return n;let c=gw[e];if(!c)return n;let l=t.map(u=>u.content.toLowerCase()).join(`
71
+ `);if(c.keywords.filter(u=>yw(l,u)).length<c.minimumPresent){let u=c.keywords.slice(0,3).join(", ");n.push({id:Et(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: ${u}\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 Zp=E(require("node:crypto"),1);var Iw=7;function ed(t=new Date){return t.getFullYear()}var Xp=0,Ii=null;function jw(){let t=ed();if(Ii&&Xp===t)return Ii;let e=[];for(let n=t-Iw;n<=t-1;n++)e.push(String(n));return Xp=t,Ii=new RegExp(`(?<![/-])\\b(${e.join("|")})\\b(?![/-])`,"g"),Ii}var Nw=/\b(?:history|changelog|change\s*log|release\s+notes?|releases?|versions?|what.?s\s+new|for\s+reference)\b/i,Mw=/\b(TODO\s*:?\s*remove|remove\s+later|temporary\s+fix|workaround)\b/gi,Qp=/<!--(?:(?!-->)[\s\S])*?\b(TODO|FIXME|WORKAROUND|HACK|NOTE)\b(?:(?!-->)[\s\S])*?\(\s*(\d{4})[-–\d]/gi,Dw=/deprecated[\w\s,.()\\\-:`]{0,60}(v?\d+[\w.]+|react|next\.?js|angular|vue|webpack|babel|unity|jest|mocha)/gi,Fw=[{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 Hw(t,e){let n=`${t.filePath}:${t.startLine}:${e}`;return`stale-${Zp.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function $o(t,e){let n=[],i,s=new RegExp(e.source,e.flags);for(;(i=s.exec(t))!==null;)n.push(i[0]);return n}function Bw(t,e){let n=[],i,s=new RegExp(e.source,e.flags);for(;(i=s.exec(t))!==null;)n.push({match:i[0],index:i.index});return n}function Gw(t){let e=[],n,i=new RegExp(Qp.source,Qp.flags);for(;(n=i.exec(t))!==null;)Number(n[2])<ed()&&e.push(n[0]);return e}function Ww(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 td(t){let e=[],n=new Set;for(let i of t)for(let s of i.sections){if(s.heading&&Nw.test(s.heading))continue;let r=s.text,o=ke(r,{stripInlineCode:!0}),a=ke(r),c=[],l=0,p=`${i.path}:${s.startLine}`,u=$o(o,jw());u.length>0&&(c.push(`Year reference(s) that may be outdated: ${[...new Set(u)].join(", ")}`),l=Math.max(l,.6));let d=$o(a,Mw);d.length>0&&(c.push(`Cleanup keyword(s): ${[...new Set(d.map(m=>m.trim()))].join(", ")}`),l=Math.max(l,.6));let f=$o(a,Dw);f.length>0&&(c.push(`"deprecated" near version/tool: ${J(f[0]??"",80)}`),l=Math.max(l,.7));for(let{re:m,label:b}of Fw){let v=Bw(o,m).filter(({index:g})=>!Ww(o,g));v.length>0&&(c.push(`Old version reference: ${b} ("${v[0].match}")`),l=Math.max(l,.7))}let h=Gw(a);h.length>0&&(c.push(`Dated ${h[0].match(/TODO|FIXME|WORKAROUND|HACK|NOTE/i)?.[0]??"TODO"} marker in HTML comment: ${J(h[0]??"",80)}`),l=Math.max(l,.65)),c.length!==0&&(n.has(p)||(n.add(p),e.push({id:Hw(s,"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:[i.path],locations:[{filePath:i.path,startLine:s.startLine,endLine:s.endLine}],evidence:[`Section: "${J(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 id=E(require("node:crypto"),1);var Vw=["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"],nd=120;function qw(t){let e=new Set;for(let n of t)e.add(n),n.includes("-")&&e.add(n.replace(/-/g," "));return[...e]}var sd=qw(Vw),Uw=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 zw(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Kw=new Map(sd.map(t=>[t,new RegExp(`\\b${zw(t)}\\b`)]));function Jw(t,e){let n=t.split(`
72
+ `).map(s=>s.trim()),i=[];for(let s=0;s<n.length;s++){let r=n[s];r&&e.test(r.toLowerCase())&&r.length<=nd&&i.push(r);let o=n[s+1];if(r&&o){let a=`${r} ${o}`;e.test(a.toLowerCase())&&a.length<=nd&&i.push(a)}}return i}function Yw(t){let e=`${t.filePath}:${t.startLine}:vague`;return`vague-${id.createHash("sha1").update(e).digest("hex").slice(0,12)}`}function rd(t,e={}){let n=[],i=new Set;for(let s of t)for(let r of s.sections){let o=`${s.path}:${r.startLine}`;if(i.has(o))continue;let a=ke(r.text,{stripInlineCode:!0}),c=a.toLowerCase().replace(/\n/g," "),l=[],p=[];for(let b of sd){let y=Kw.get(b);if(y.test(c))for(let v of Jw(a,y))l.includes(b)||l.push(b),p.includes(v)||p.push(v)}if(l.length===0)continue;i.add(o);let u=l.map(b=>`"${b}"`).join(", "),d=l.some(b=>Uw.has(b)),f=d?"warning":"info",h=e.severityOverride??f,m=d?.8:.75;n.push({id:Yw(r),severity:h,category:"vague_guidance",title:"Vague guidance detected",summary:`This section contains guidance that may be too vague to be actionable: ${u}.`,filePaths:[s.path],locations:[{filePath:s.path,startLine:r.startLine,endLine:r.endLine}],evidence:p.slice(0,3).map(b=>`Line: "${b}"`),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 Di=E(require("node:crypto"),1),ve=E(require("node:path"),1),Pe=E(require("node:fs"),1);var Cn=["# PromptCI: ignore generated reports, keep the shared baseline, config, and custom rules","**/.promptci/*","!**/.promptci/baseline.json","!**/.promptci/config.json","!**/.promptci/custom-rules.json"],To=`${Cn.join(`
73
+ `)}
74
+ `;function Pn(t){return`${Cn.join(t)}${t}`}var ji=[{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."}],Xw=[{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 Ni(t){return`security-pack-${Di.createHash("sha1").update(t).digest("hex").slice(0,12)}`}function Qw(t,e){return`destructive-command-${Di.createHash("sha1").update(`destructive-command:${t}:${e}`).digest("hex").slice(0,12)}`}function Zw(t){return`security-pack-inspect-reports-first-${Di.createHash("sha1").update(`inspect-reports-first:${t}`).digest("hex").slice(0,12)}`}function An(t,e){return e.some(n=>n.test(t))}function Mi(t,e){return t.startsWith("!")?!1:t.replace(/^\/+|\/+$/g,"").split("/").includes(e)}function od(t){let{files:e,repoRoot:n}=t;if(e.length===0)return[];let i=[],s=e.map(g=>g.content).join(`
75
+ `),r=e.map(g=>g.path);if([".env",".env.example",".env.local",".env.development",".env.production"].some(g=>Pe.existsSync(ve.join(n,g)))||t.files.some(g=>/env\s+vars|environment\s+variables/i.test(g.content))){let g=ji.find(S=>S.id==="no-secret-safeguard");An(s,g.patterns)||i.push({id:Ni(g.id),severity:g.severity,category:"security",title:g.title,summary:g.summary,filePaths:r,locations:[],evidence:["Environment variables detected but no safeguard instruction found."],recommendation:g.recommendation,fixRecipe:g.fixRecipe,confidence:g.confidence})}let c={...t.packageJson.dependencies,...t.packageJson.devDependencies,...t.packageJson.peerDependencies};if(Pe.existsSync(ve.join(n,"supabase/migrations"))||Object.keys(c).some(g=>g==="@supabase/supabase-js"||g.startsWith("@supabase/"))){let g=ji.find(S=>S.id==="no-supabase-service-role-rule");An(s,g.patterns)||i.push({id:Ni(g.id),severity:g.severity,category:"security",title:g.title,summary:g.summary,filePaths:r,locations:[],evidence:["Supabase detected but no service role safeguard instruction found."],recommendation:g.recommendation,fixRecipe:g.fixRecipe,confidence:g.confidence})}if(t.files.some(g=>{let S=g.path.replace(/\\/g,"/");return S.includes("/api/upload")||S.includes("/uploads/")||/multer|busboy|formidable/i.test(g.content)})){let g=ji.find(S=>S.id==="no-upload-boundary-docs");An(s,g.patterns)||i.push({id:Ni(g.id),severity:g.severity,category:"security",title:g.title,summary:g.summary,filePaths:r,locations:[],evidence:["Upload features detected but no data boundary documentation found."],recommendation:g.recommendation,fixRecipe:g.fixRecipe,confidence:g.confidence})}if(Pe.existsSync(ve.join(n,".promptci"))){let g=ji.find(S=>S.id==="no-promptci-report-safeguard");An(s,g.patterns)||i.push({id:Ni(g.id),severity:g.severity,category:"security",title:g.title,summary:g.summary,filePaths:r,locations:[],evidence:[".promptci/ folder detected but no report safeguard instruction found."],recommendation:g.recommendation,fixRecipe:g.fixRecipe,confidence:g.confidence})}for(let g of e)for(let S of Xw)if(S.pattern.test(g.content)){let $=[/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];An(g.content,$)||i.push({id:Qw(g.path,S.name),severity:"warning",category:"security",title:`Destructive command "${S.name}" without safety language`,summary:`Instruction file contains a destructive command "${S.name}" but lacks safety language (e.g., "Ask before running").`,filePaths:[g.path],locations:[],evidence:[`Destructive command "${S.name}" found in ${ve.basename(g.path)} without safety language.`],recommendation:`Add safety language such as "Ask for confirmation before running ${S.name}" to ensure destructive operations are not performed accidentally.`,confidence:.7})}let d=ve.join(n,".gitignore"),f="";try{Pe.existsSync(d)&&(f=Pe.readFileSync(d,"utf8"))}catch{}let h=f.split(/\r?\n/).map(g=>g.trim()).filter(g=>g&&!g.startsWith("#"));h.some(g=>Mi(g,".promptci"))||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"+Cn.map(g=>` ${g}`).join(`
76
+ `)+"\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:To,autoApplySafe:!0,confidence:.9});let y=["coverage","dist","build",".next","bin","obj","temp","tmp","logs"].filter(g=>{let S=ve.join(n,g);try{if(Pe.existsSync(S)&&Pe.statSync(S).isDirectory())return!h.some(O=>Mi(O,g))}catch{}return!1});y.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 (${y.join(", ")}) that are commonly generated but not ignored in .gitignore. AI tools may ingest these, inflating token costs.`,filePaths:[".gitignore"],locations:[],evidence:y.map(g=>`Directory "${g}" exists but is not ignored in .gitignore.`),recommendation:`Add generated directories to .gitignore. For example: "${y.map(g=>`${g}/`).join(", ")}"`,fixRecipe:y.map(g=>`echo "${g}/" >> .gitignore`).join(`
77
+ `),autoApplySafe:!0,confidence:.8});let v=!1;try{let g=ve.join(n,".promptci","config.json");if(Pe.existsSync(g)){let S=JSON.parse(Pe.readFileSync(g,"utf8"));if(Array.isArray(S.include)){let $=["**/*","**/*.md","*","*.*","**"];v=S.include.some(P=>$.includes(P.trim()))}}}catch{}if(v){let g=e.filter(S=>{let $=ve.relative(n,S.path).replace(/\\/g,"/");return $.includes(".promptci/")||$.includes("coverage/")||$.includes(".next/")});g.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:g.map(S=>`Scanned generated file: ${ve.relative(n,S.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 g of e){let S=[{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 $ of S)if($.re.test(g.content)){i.push({id:Zw(g.path),severity:"info",category:"context_bloat",title:"Instruction prioritizing generated reports over source docs",summary:`Instruction file "${ve.basename(g.path)}" tells the agent to inspect generated reports before source files, which can cause circular or outdated guidance ingestion.`,filePaths:[g.path],locations:[],evidence:[Ht(g.content,$.re,$.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}var ue=E(require("node:path"),1),pe=E(require("node:fs"),1);function ad(t){let e=[],{packageJson:n,repoRoot:i,files:s}=t,r=!!(n.dependencies.next||n.devDependencies.next),o=pe.existsSync(ue.join(i,"next.config.js"))||pe.existsSync(ue.join(i,"next.config.mjs"))||pe.existsSync(ue.join(i,"next.config.ts"))||pe.existsSync(ue.join(i,"apps","web","next.config.js"))||pe.existsSync(ue.join(i,"apps","web","next.config.mjs"))||pe.existsSync(ue.join(i,"apps","web","next.config.ts"));if(!r&&!o)return[];let a=pe.existsSync(ue.join(i,"app"))||pe.existsSync(ue.join(i,"src","app"))||pe.existsSync(ue.join(i,"apps","web","app"))||pe.existsSync(ue.join(i,"apps","web","src","app")),c=pe.existsSync(ue.join(i,"pages"))||pe.existsSync(ue.join(i,"src","pages"))||pe.existsSync(ue.join(i,"apps","web","pages"))||pe.existsSync(ue.join(i,"apps","web","src","pages"));if(a&&(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})),a&&!c){let l=s.filter(p=>p.content.toLowerCase().includes("pages router")||p.content.toLowerCase().includes("getstaticprops")||p.content.toLowerCase().includes("getserversideprops"));l.length>0&&e.push({id:"nextjs-stale-pages-router-guidance",severity:"warning",category:"stale_instruction",title:"Stale Pages Router Guidance",summary:"The project uses the App Router exclusively, but instructions still reference Pages Router concepts like getStaticProps.",filePaths:l.map(p=>p.path),locations:l.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 Qt=E(require("node:path"),1),Oo=E(require("node:fs"),1);function cd(t){let e=[],{manifests:n,repoRoot:i,files:s}=t,r=!!n.pyproject,o=n.requirements!==void 0,a=Oo.existsSync(Qt.join(i,"Pipfile")),c=Oo.existsSync(Qt.join(i,"environment.yml"));if(!r&&!o&&!a&&!c)return[];(n.pyproject?.includes("pytest")||n.requirements?.includes("pytest"))&&(s.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:s.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=[],u=[];return a&&p.push("Pipenv (Pipfile)"),a&&u.push(Qt.join(i,"Pipfile")),c&&p.push("Conda (environment.yml)"),c&&u.push(Qt.join(i,"environment.yml")),r&&n.pyproject?.includes("[tool.poetry]")&&p.push("Poetry (pyproject.toml)"),r&&n.pyproject?.includes("[tool.poetry]")&&u.push(Qt.join(i,"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:u.length>0?u:s.map(d=>d.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}var Lo=E(require("node:path"),1),Io=E(require("node:fs"),1);function ld(t){let e=[],{repoRoot:n,files:i}=t,s=Io.existsSync(Lo.join(n,"Assets")),r=Io.existsSync(Lo.join(n,"ProjectSettings","ProjectVersion.txt")),o=i.map(d=>d.content).join(`
78
+ `),a=/\bunity\b.*\b(lts|editor|hub|engine)\b|\bmonobehaviour\b|\bunityengine\b|\bgameobject\b|\bprefab\b|\bscriptableobject\b/i.test(o);if(!(s&&r)&&!a)return[];let c=i.map(d=>d.path);return/monobehaviour\s+(?:lifecycle|guidance|rules?)|\blifecycle\s+(?:method|methods|guidance|rules?)|instantiate\b.*monobehaviour|avoid\b.*update|new\s+monobehaviour|awake\(\)|start\(\)|update\(\)/i.test(o)||e.push({id:"unity-missing-monobehaviour-guidance",severity:"warning",category:"structure",title:"Missing Unity MonoBehaviour Lifecycle Guidance",summary:'Unity project detected, but instructions lack guidelines on MonoBehaviour lifecycle (e.g. not calling "new" on MonoBehaviours, avoiding empty Update methods).',filePaths:c,locations:[],evidence:["Unity detected, but no MonoBehaviour lifecycle rules found in instructions."],recommendation:'Add guidance warning never to use "new" to instantiate MonoBehaviours, and advising on efficient Update() / Awake() / Start() usage.',fixRecipe:'Do not instantiate MonoBehaviours using the "new" keyword; always use GameObject.AddComponent or Object.Instantiate. Avoid leaving empty Awake, Start, or Update methods in scripts as they still incur Unity lifecycle overhead.',confidence:.8}),/\[serializefield\]|serializefield\b|prefab\s+(?:safety|workflow|guidance|rules?)|meta\s+file/i.test(o)||e.push({id:"unity-missing-serialization-guidance",severity:"warning",category:"structure",title:"Missing Unity Serialization and Prefab Safety Guidance",summary:"Unity project detected, but instructions lack safety rules for Prefabs and [SerializeField] parameters.",filePaths:c,locations:[],evidence:["Unity detected, but no SerializeField or prefab rules found in instructions."],recommendation:"Add rules for using [SerializeField] for private variables to expose them in the inspector, and avoiding editing .meta files manually.",fixRecipe:"Use [SerializeField] to expose private fields in the Unity Inspector instead of making them public. Never manually edit or delete .meta files; let the Unity Editor manage them to prevent serialization breakages.",confidence:.8}),/play\s+mode|test\s+runner|unity\s+test/i.test(o)||e.push({id:"unity-missing-test-guidance",severity:"info",category:"structure",title:"Missing Unity Play Mode and Test Runner Guidance",summary:"Unity project detected, but instructions do not guide agents to test changes in Play Mode or Unity Test Runner.",filePaths:c,locations:[],evidence:["Unity detected, but no Play Mode/Test Runner verification found in instructions."],recommendation:"Add instructions telling agents to run tests using Unity Test Runner or test changes in Play Mode.",fixRecipe:"Verify gameplay and UI changes by testing in the Unity Editor Play Mode or running Unity Test Runner (Window > General > Test Runner).",confidence:.75}),e}var ud=E(require("node:path"),1),Rn=E(require("node:fs"),1);function pd(t){let e=[],{repoRoot:n,files:i}=t,s=t.projectType==="dotnet";if(!s)try{s=Rn.readdirSync(n).some(p=>p.endsWith(".sln")||p.endsWith(".csproj"))}catch{}let r=i.map(p=>p.content).join(`
79
+ `),o=/\bdotnet\b|\.sln\b|\.csproj\b|\bxunit\b|\bnunit\b|\bmstest\b/i.test(r);if(!s&&!o)return[];let a=i.map(p=>p.path);/dotnet\s+(build|test|restore|run)/i.test(r)||e.push({id:"dotnet-missing-validation-commands",severity:"warning",category:"structure",title:"Missing .NET Validation Commands",summary:'The project uses .NET, but instructions do not mention dotnet validation commands like "dotnet build" or "dotnet test".',filePaths:a,locations:[],evidence:[".NET detected, but no dotnet build/test commands found in instructions."],recommendation:'Add instructions telling the agent to run "dotnet build" and "dotnet test" to verify changes.',fixRecipe:"Before saying work is complete, run dotnet build && dotnet test to verify changes.",confidence:.85});let l;try{let u=Rn.readdirSync(n).find(d=>d.endsWith(".csproj"));if(u){let d=Rn.readFileSync(ud.join(n,u),"utf-8"),f=/<TargetFramework>(.*?)<\/TargetFramework>/.exec(d);f&&(l=f[1]?.trim())}}catch{}if(l){let p=/\b(netcoreapp\d+\.\d+|net5\.0|netcore)\b/i.test(r);/^net(?:[6-9]|[1-9]\d+)\.0/.test(l)&&p&&e.push({id:"dotnet-obsolete-framework-reference",severity:"warning",category:"stale_instruction",title:".NET Obsolete Framework Reference",summary:`The project targets modern .NET (${l}), but instructions still reference obsolete versions like .NET Core 3.1 or .NET 5.0.`,filePaths:a,locations:[],evidence:[`Project targets ${l}; obsolete framework references found in instructions.`],recommendation:`Update instructions to reference the current target framework version (${l}).`,fixRecipe:`Target .NET ${l} as the framework for this project. Do not use legacy .NET Core 3.1 or .NET 5.0 APIs.`,confidence:.8})}return e}var dd=E(require("node:path"),1),fd=E(require("node:fs"),1);function hd(t){let e=[],{repoRoot:n,files:i}=t,s=fd.existsSync(dd.join(n,"go.mod")),r=i.map(l=>l.content).join(`
80
+ `),o=/\bgo\.mod\b/i.test(r)||/`[^`\n]*\bgo\s+(?:build|test|run|get|mod)\b[^`\n]*`/i.test(r);if(!s&&!o)return[];let a=i.map(l=>l.path);return/\bgo\s+test\b/i.test(r)||e.push({id:"go-missing-testing-commands",severity:"warning",category:"structure",title:"Missing Go Testing Commands",summary:'Go project detected, but instructions do not mention Go testing commands like "go test ./...".',filePaths:a,locations:[],evidence:['Go detected, but no "go test" command found in instructions.'],recommendation:'Add instructions telling the agent to run "go test ./..." to verify changes.',fixRecipe:"Before saying work is complete, run go test ./... to verify all tests pass.",confidence:.85}),e}var jo=E(require("node:path"),1),Fi=E(require("node:fs"),1);function md(t){let e=[],{repoRoot:n,files:i}=t,s=Fi.existsSync(jo.join(n,"Cargo.toml")),r=i.map(p=>p.content).join(`
81
+ `),o=/\bcargo\.toml\b|\bcargo\s+(build|test|run|clippy|fmt)\b/i.test(r);if(!s&&!o)return[];let a=i.map(p=>p.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(s)try{let p=Fi.readFileSync(jo.join(n,"Cargo.toml"),"utf-8"),u=/^rust-version\s*=\s*["'](.*?)["']/m.exec(p);u&&(l=u[1]?.trim())}catch{}if(l){let p=f=>{let h=/^(\d+)\.(\d+)/.exec(f);return h?`${h[1]}.${h[2]}`:void 0},d=/\bRust\s+(\d+\.\d+(?:\.\d+)?)\b/i.exec(r);if(d){let f=d[1];p(f)!==p(l)&&e.push({id:"rust-version-mismatch",severity:"warning",category:"stale_instruction",title:"Rust Version Mismatch",summary:`Instructions mention Rust version ${f}, but Cargo.toml specifies rust-version = "${l}".`,filePaths:a,locations:[],evidence:[`Cargo.toml requires rust-version = ${l}; instructions mention Rust ${f}`],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 gd(t){let e=[];return e.push(...ad(t)),e.push(...cd(t)),e.push(...ld(t)),e.push(...pd(t)),e.push(...hd(t)),e.push(...md(t)),e}var bd=E(require("node:path"),1),vd=E(require("node:crypto"),1);function kn(t,e){let n=vd.createHash("sha1").update(`prompt-cache-${t}:${e}`).digest("hex").slice(0,12);return`prompt-cache-${t}-${n}`}var e_=[{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"}],t_=[{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'}],n_=[{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"}],yd=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i;function wd(t){let e=[],n=t.filter(i=>["claude","agents","cursor","windsurf","copilot","prompt"].includes(i.fileType));for(let i of n){let s=bd.basename(i.path);for(let c of e_)if(c.re.test(i.content)){e.push({id:kn("volatile-timestamp",i.path),severity:"warning",category:"context_bloat",title:"Volatile timestamp in instruction file",summary:`The instruction file "${s}" contains a volatile date or timestamp. Frequently changing dates in persistent instruction files invalidate prompt caches.`,filePaths:[i.path],locations:[],evidence:[Ht(i.content,c.re,c.label)],recommendation:"Move volatile dates to a separate task-specific prompt or scratch file, or remove them from canonical instructions.",fixRecipe:'Remove the "Last updated: <date>" or timestamp line from the file.',confidence:.85});break}for(let c of t_)if(c.re.test(i.content)){e.push({id:kn("pasted-report",i.path),severity:"warning",category:"context_bloat",title:"Pasted scan report or summary in instructions",summary:`The instruction file "${s}" contains pasted scan results or reports. Committing generated reports into canonical instruction files breaks prompt caching and bloats context.`,filePaths:[i.path],locations:[],evidence:[Ht(i.content,c.re,c.label)],recommendation:"Link to the generated report file or read it on-demand instead of pasting its contents into canonical instructions.",fixRecipe:"Delete the pasted report summary block and reference the report file path instead.",confidence:.9});break}for(let c of n_)if(c.re.test(i.content)){e.push({id:kn("volatile-branch-task",i.path),severity:"warning",category:"context_bloat",title:"Volatile branch or task status in instructions",summary:`The instruction file "${s}" contains active git branch or task details. Frequently updated task status or branch names break prompt caching.`,filePaths:[i.path],locations:[],evidence:[Ht(i.content,c.re,c.label)],recommendation:"Move branch-specific notes and active task details to git commit messages, PR descriptions, or a temporary scratch file.",fixRecipe:"Remove active branch and task notes from the persistent instructions.",confidence:.85});break}if(yd.test(i.content)){let c=i.content.match(yd)?.[0]??"";e.push({id:kn("local-paths",i.path),severity:"warning",category:"context_bloat",title:"Local machine paths in instructions",summary:`The instruction file "${s}" contains absolute local machine paths ("${c}"). These paths change per environment, preventing prompt caching and causing instruction drift.`,filePaths:[i.path],locations:[],evidence:[`Found absolute local path: ${c}`],recommendation:"Use repository-relative paths instead of absolute local machine paths.",fixRecipe:"Replace absolute local paths with repository-relative paths.",confidence:.8})}let r=i.content.split(/\r?\n/),o=0,a=0;for(let c of r){let l=c.trim();if(l.startsWith("|")&&l.endsWith("|")){if(/^\|[-\s:|]+\|$/.test(l))continue;a++}else a>o&&(o=a),a=0}a>o&&(o=a),o>15&&e.push({id:kn("large-table",i.path),severity:"warning",category:"context_bloat",title:"Large table in instruction file",summary:`The instruction file "${s}" contains a large Markdown table (${o} rows). Large tables bloat prompt context and reduce caching friendliness.`,filePaths:[i.path],locations:[],evidence:[`Markdown table with ${o} rows found in ${s}.`],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 No=E(require("node:path"),1);var _d=12,i_={idPrefix:"skill",noun:"Skill",why:"A skill needs `name` and `description` frontmatter or it will not load.",recommendation:"Add a frontmatter block with `name` and `description` at the top of the SKILL.md file."};function Zt(t,e,n=""){return`ai-config-skill-${t}-${ce(`${e}|${n}`)}`}function s_(t){return t.toLowerCase().replace(/[`*_~]/g,"").replace(/[^a-z0-9]+/g," ").trim()}function r_(t){if(!t)return!1;let e=t.trim();if(/^(https?:|mailto:|#|\/\/)/i.test(e)||e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)||/[<>{}*?|"\s]/.test(e)||e.includes(".."))return!1;let n=e.split("#")[0],i=n.includes("/"),s=/\.[a-z0-9]{1,6}$/i.test(n);return i&&s}function o_(t){let e=[],n=new Set,i=(r,o)=>{if(!r_(r))return;let a=r.split("#")[0];n.has(a)||(n.add(a),e.push({ref:a,line:o}))},s=t.split(/\r?\n/);for(let r=0;r<s.length;r++){let o=s[r];for(let a of o.matchAll(/\[[^\]]*\]\(([^)]+)\)/g))i(a[1].split(/\s+/)[0].replace(/^<|>$/g,""),r+1);for(let a of o.matchAll(/`([^`]+)`/g))i(a[1].trim(),r+1)}return e}function Mo(t){let e=[],n=[];for(let i of t.aiConfig.skills){let s=Se(t.repoRoot,i);if(s===void 0)continue;let r=_t(No.dirname(i)).split("/").pop()??"",o=Ue(s);if(e.push(...at(i,s,o,i_)),!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?a!==r&&r&&e.push(D({id:Zt("name-dir-mismatch",i),title:"Skill `name` does not match its directory",summary:`${i}: frontmatter \`name: ${a}\` does not match the skill directory \`${r}/\`. Claude resolves skills by directory name.`,filePaths:[i],locations:[{filePath:i,startLine:o.keyLines.name??1,endLine:o.keyLines.name??1}],evidence:[`name: ${a}`,`directory: ${r}`],recommendation:"Rename the directory or the `name` field so they match.",confidence:.6})):e.push(D({id:Zt("missing-name",i),title:"Skill frontmatter is missing `name`",summary:`${i} has no \`name\` field. Claude uses \`name\` to identify and invoke the skill.`,filePaths:[i],locations:[{filePath:i,startLine:1,endLine:o.fenceEndLine>0?o.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(o.data).join(", ")||"(none)"}`],recommendation:"Add a `name` field to the frontmatter matching the skill directory name.",confidence:.85})),c?c.length<_d&&e.push(D({id:Zt("empty-description",i),title:"Skill `description` is too short to trigger reliably",summary:`${i}: \`description\` is only ${c.length} characters. Claude matches the description against the user's request to decide when to invoke the skill.`,filePaths:[i],locations:[{filePath:i,startLine:o.keyLines.description??1,endLine:o.keyLines.description??1}],evidence:[`description: ${c}`],recommendation:"Expand the description to describe the task and its trigger conditions.",confidence:.7})):e.push(D({id:Zt("missing-description",i),title:"Skill frontmatter is missing `description`",summary:`${i} has no \`description\`. The description is the trigger text Claude matches against \u2014 without it the skill rarely activates.`,filePaths:[i],locations:[{filePath:i,startLine:1,endLine:o.fenceEndLine>0?o.fenceEndLine:1}],evidence:[`Keys present: ${Object.keys(o.data).join(", ")||"(none)"}`],recommendation:"Add a `description` that says what the skill does and when to use it.",confidence:.85}));let l=_t(No.dirname(i));for(let{ref:p,line:u}of o_(s)){let d=l==="."?p:`${l}/${p}`;Ut(t.repoRoot,d)||e.push(D({id:Zt("dead-ref",i,p),title:"Skill references a bundled file that does not exist",summary:`${i} references \`${p}\`, but no such file exists relative to the skill directory.`,filePaths:[i],locations:[{filePath:i,startLine:u,endLine:u}],evidence:[`Reference: ${p}`,`Resolved to: ${d}`],recommendation:"Add the referenced file, fix the path, or remove the reference.",confidence:.75}))}c&&n.push({filePath:i,description:c})}return e.push(...a_(n)),Ee(t.repoRoot,e)}function a_(t){let e=[],n=new Map;for(let i of t){if(i.description.length<_d)continue;let s=s_(i.description);if(!s)continue;let r=n.get(s)??[];r.push(i),n.set(s,r)}for(let i of n.values()){if(i.length<2)continue;let s=[...i].sort((o,a)=>o.filePath.localeCompare(a.filePath)),r=s.map(o=>o.filePath);e.push(D({id:Zt("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:s.map(o=>({filePath:o.filePath,startLine:1,endLine:1})),evidence:[`Shared description: ${s[0].description}`,`Skills: ${r.join(", ")}`],recommendation:"Give each skill a distinct description that states its unique trigger conditions.",confidence:.75}))}return e}var Do=E(require("node:path"),1);var c_={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."},l_=new Set(["sonnet","opus","haiku","inherit","default","opusplan"]),u_=new Set(["Task","Bash","BashOutput","KillBash","KillShell","Glob","Grep","LS","Read","Edit","MultiEdit","Write","NotebookRead","NotebookEdit","WebFetch","WebSearch","TodoWrite","SlashCommand","ExitPlanMode","Agent"]),p_=.8,d_=5;function $n(t,e){return`ai-config-agent-${t}-${ce(e)}`}function f_(t){let e=new Set;for(let n of t.split(/\r?\n/)){let i=n.trim().toLowerCase().replace(/\s+/g," ");i.length>=8&&e.add(i)}return e}function h_(t,e){if(t.size===0||e.size===0)return 0;let n=0,[i,s]=t.size<=e.size?[t,e]:[e,t];for(let o of i)s.has(o)&&n++;let r=t.size+e.size-n;return r===0?0:n/r}function Fo(t){let e=[],n=[];for(let s of t.aiConfig.agents){let r=Se(t.repoRoot,s);if(r===void 0)continue;let o=Ue(r);if(e.push(...at(s,r,o,c_)),!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(D({id:$n("missing-name",s),title:"Subagent frontmatter is missing `name`",summary:`${s} has no \`name\` field, so it cannot be invoked by name.`,filePaths:[s],locations:[{filePath:s,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(D({id:$n("missing-description",s),title:"Subagent frontmatter is missing `description`",summary:`${s} has no \`description\`. The description tells the orchestrator when to delegate to this agent.`,filePaths:[s],locations:[{filePath:s,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&&!l_.has(l.toLowerCase())&&!/^claude-/i.test(l)&&e.push(D({id:$n("unknown-model",`${s}|${l}`),title:"Subagent references an unrecognized model",summary:`${s}: \`model: ${l}\` is not a known alias (sonnet, opus, haiku, inherit) or a \`claude-*\` id.`,filePaths:[s],locations:[{filePath:s,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 p=Kt(o.data.tools),u=p.filter(h=>h!=="*"&&!h.startsWith("mcp__")&&!u_.has(h));u.length>0&&e.push(D({id:$n("unknown-tools",`${s}|${u.join(",")}`),severity:"info",title:"Subagent grants tools that may not exist",summary:`${s} lists ${u.length} tool name(s) that are not built-in tools or \`mcp__*\` tools: ${u.join(", ")}.`,filePaths:[s],locations:[{filePath:s,startLine:o.keyLines.tools??1,endLine:o.keyLines.tools??1}],evidence:[`Unrecognized: ${u.join(", ")}`,`Declared tools: ${p.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(`
82
+ `),f=f_(d);n.push({filePath:s,bodyLines:f})}let i=n.filter(s=>s.bodyLines.size>=d_);for(let s=0;s<i.length;s++)for(let r=s+1;r<i.length;r++){let o=i[s],a=i[r],c=h_(o.bodyLines,a.bodyLines);if(c>=p_){let l=[o.filePath,a.filePath].sort();e.push(D({id:$n("dup-prompt",l.join("|")),title:"Two subagents share near-identical system prompts",summary:`${_t(Do.basename(l[0]))} and ${_t(Do.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(p=>({filePath:p,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 Ee(t.repoRoot,e)}var m_=/\b(curl|wget)\b[^|]*\|\s*(sudo\s+)?(sh|bash|zsh|dash)\b/i;function Hi(t,e){return`ai-config-hook-${t}-${ce(e)}`}function Bo(t,e,n){if(Array.isArray(t)){for(let s of t)Bo(s,e,n);return}if(typeof t!="object"||t===null)return;let i=t;i.type==="command"&&typeof i.command=="string"&&n.push({command:i.command,event:e});for(let[s,r]of Object.entries(i))typeof r=="object"&&r!==null&&Bo(r,e===""?s:e,n)}var g_=new Set(["bash","sh","zsh","dash","node","deno","python","python3","ruby","ts-node","tsx","pwsh","powershell"]),y_=new Set(["npx","bunx","pnpm","yarn","uv","uvx","env","timeout","nice","sudo","exec","command"]);function Ho(t){return t.replace(/^['"]|['"]$/g,"").replace(/^\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/,"")}function b_(t){let e=new Set,n=(i,s)=>{if(i.startsWith("-"))return;let r=i.replace(/^['"]|['"]$/g,""),o=Ho(i);if(!o||o.includes("$")||/[<>{}*?|"'`]/.test(o)||o.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(o)||/^https?:/i.test(o)||o.includes("..")||!wn.test(o))return;let a=r.startsWith("./")||r.startsWith(".claude/")||/^\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/.test(r);(s||a)&&e.add(o.replace(/\\/g,"/"))};for(let i of t.split(/&&|\|\||;|\|/)){let s=i.trim().split(/\s+/).filter(Boolean);if(s.length===0)continue;let r=Ho(s[0]);if(g_.has(r)||y_.has(r)){for(let o=1;o<s.length;o++)if(!s[o].startsWith("-")&&wn.test(Ho(s[o]))){n(s[o],!0);break}}else n(s[0],!0);for(let o=1;o<s.length;o++)n(s[o],!1)}return[...e]}function v_(t,e){let n="";for(let i=0;i<e;i++){let s=t[i];n?s===n&&(n=""):(s==='"'||s==="'")&&(n=s)}return n!==""}function w_(t){for(let e of t.matchAll(/\$\{?CLAUDE_PROJECT_DIR\}?[/\\]/g))if(!v_(t,e.index))return!0;return!1}function Go(t){let e=[];for(let n of t.aiConfig.settings){let i=Se(t.repoRoot,n);if(i===void 0)continue;let s;try{s=JSON.parse(i)}catch(c){e.push(D({id:Hi("invalid-json",n),severity:"high",title:"Settings file is not valid JSON",summary:`${n} could not be parsed as JSON, so Claude Code cannot load its hooks or permissions.`,filePaths:[n],locations:[{filePath:n,startLine:1,endLine:1}],evidence:[`Parse error: ${c.message}`],recommendation:"Fix the JSON syntax (trailing commas and comments are not allowed in settings.json).",confidence:.95}));continue}if(typeof s!="object"||s===null||Array.isArray(s))continue;let r=s.hooks;if(r===void 0)continue;let o=[];Bo(r,"",o);let a=new Set;for(let{command:c,event:l}of o){let p=ot(i,c);m_.test(c)&&e.push(D({id:Hi("curl-pipe-sh",`${n}|${c}`),severity:"high",impact:"high",title:"Hook pipes a remote download into a shell",summary:`A ${l||"hook"} command in ${n} pipes \`curl\`/\`wget\` output directly into a shell, running whatever the remote host serves with your permissions.`,filePaths:[n],locations:[{filePath:n,startLine:p,endLine:p}],evidence:[`Command: ${c.slice(0,160)}`],recommendation:"Download to a file, review it, and pin a checksum before executing \u2014 never pipe a network fetch straight into sh/bash.",confidence:.85})),w_(c)&&e.push(D({id:Hi("unquoted-project-dir",`${n}|${c}`),severity:"info",title:"Hook uses an unquoted $CLAUDE_PROJECT_DIR path",summary:`A ${l||"hook"} command in ${n} expands \`$CLAUDE_PROJECT_DIR\` unquoted; if the project path contains a space the command breaks or runs the wrong file.`,filePaths:[n],locations:[{filePath:n,startLine:p,endLine:p}],evidence:[`Command: ${c.slice(0,160)}`],recommendation:'Wrap the path in double quotes, e.g. `"$CLAUDE_PROJECT_DIR/script.sh"`.',confidence:.5}));for(let u of b_(c)){if(Ut(t.repoRoot,u))continue;let d=`${n}|${u}`;a.has(d)||(a.add(d),e.push(D({id:Hi("missing-script",d),title:"Hook command references a script that does not exist",summary:`A ${l||"hook"} command in ${n} runs \`${u}\`, but that file is not present in the repository.`,filePaths:[n],locations:[{filePath:n,startLine:p,endLine:p}],evidence:[`Referenced script: ${u}`,`Command: ${c.slice(0,160)}`],recommendation:"Add the script, fix the path, or remove the hook.",confidence:.75})))}}}return Ee(t.repoRoot,e)}function Tn(t,e){return`ai-config-mcp-${t}-${ce(e)}`}function __(t,e){let n=[],i=0,s=!1,r=!1,o="",a=null;for(let c=e;c<t.length;c++){let l=t[c];if(s){if(r){r=!1,o+=l;continue}if(l==="\\"){r=!0;continue}if(l==='"'){s=!1,i===1&&(a=o);continue}o+=l;continue}if(l==='"'){s=!0,o="";continue}if(l==="{"||l==="["){i++;continue}if(l==="}"||l==="]"){if(i--,i===0)break;continue}if(l===":"){i===1&&a!==null&&(n.push(a),a=null);continue}if(l===","){a=null;continue}}return n}function x_(t){let e=/"mcpServers"\s*:/.exec(t);if(!e)return[];let n=t.indexOf("{",e.index+e[0].length);if(n<0)return[];let i=__(t,n),s=new Map;for(let r of i)s.set(r,(s.get(r)??0)+1);return[...s.entries()].filter(([,r])=>r>1).map(([r])=>r).sort()}function S_(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 E_(t,e){let n=new Set,i=(s,r)=>{let o=s.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("/")&&wn.test(o))&&n.add(o.replace(/\\/g,"/"))};t&&i(t,!1);for(let s of e)i(s,!0);return[...n]}function Wo(t){let e=[];for(let n of t.aiConfig.mcp){let i=Se(t.repoRoot,n);if(i===void 0)continue;let s;try{s=JSON.parse(i)}catch(o){e.push(D({id:Tn("invalid-json",n),severity:"high",title:"MCP config is not valid JSON",summary:`${n} could not be parsed as JSON, so no MCP servers will load from it.`,filePaths:[n],locations:[{filePath:n,startLine:1,endLine:1}],evidence:[`Parse error: ${o.message}`],recommendation:"Fix the JSON syntax (no trailing commas, no comments).",confidence:.95}));continue}if(typeof s!="object"||s===null||Array.isArray(s))continue;let r=s.mcpServers;if(!(typeof r!="object"||r===null||Array.isArray(r))){for(let o of x_(i))e.push(D({id:Tn("duplicate-name",`${n}|${o}`),title:"Duplicate MCP server name",summary:`${n} defines the server "${o}" more than once. JSON keeps only the last definition and silently discards the earlier one.`,filePaths:[n],locations:[{filePath:n,startLine:ot(i,`"${o}"`),endLine:ot(i,`"${o}"`)}],evidence:[`Duplicated server name: ${o}`],recommendation:"Rename or remove the duplicate so each server name is unique.",confidence:.85}));for(let[o,a]of Object.entries(r)){if(typeof a!="object"||a===null||Array.isArray(a))continue;let c=a,l=typeof c.command=="string"?c.command:void 0,p=typeof c.url=="string"?c.url:void 0,u=Array.isArray(c.args)?c.args.filter(f=>typeof f=="string"):[],d=ot(i,`"${o}"`);if(!l&&!p&&e.push(D({id:Tn("no-command-or-url",`${n}|${o}`),title:"MCP server has neither a command nor a url",summary:`${n}: server "${o}" defines no \`command\` (stdio) and no \`url\` (http/sse), so it cannot start.`,filePaths:[n],locations:[{filePath:n,startLine:d,endLine:d}],evidence:[`Server: ${o}`,`Keys: ${Object.keys(c).join(", ")||"(none)"}`],recommendation:"Add a `command` (with `args`) for a stdio server, or a `url` for a remote server.",confidence:.8})),typeof c.env=="object"&&c.env!==null&&!Array.isArray(c.env))for(let[f,h]of Object.entries(c.env))typeof h!="string"||!S_(h)||e.push(D({id:Tn("placeholder-env",`${n}|${o}|${f}`),title:"MCP server env value is an unfilled placeholder",summary:`${n}: server "${o}" sets \`env.${f}\` to a placeholder (${JSON.stringify(h)}) that was never replaced with a real value.`,filePaths:[n],locations:[{filePath:n,startLine:ot(i,`"${f}"`),endLine:ot(i,`"${f}"`)}],evidence:[`${f}: ${h}`],recommendation:'Replace the placeholder with a real value, or reference a shell variable like `"${'+f+'}"`.',confidence:.7}));for(let f of E_(l,u))Ut(t.repoRoot,f)||e.push(D({id:Tn("missing-command",`${n}|${o}|${f}`),title:"MCP server command path does not exist",summary:`${n}: server "${o}" references the local path \`${f}\`, which is not present in the repository.`,filePaths:[n],locations:[{filePath:n,startLine:d,endLine:d}],evidence:[`Referenced path: ${f}`,`Server: ${o}`],recommendation:"Fix the path, add the missing file, or install the server so the path resolves.",confidence:.7}))}}}return Ee(t.repoRoot,e)}var Sd=E(jt(),1);var C_={idPrefix:"cursor",noun:"Cursor rule",why:"A .mdc rule needs metadata (`description`, `globs`, or `alwaysApply`) to control when it applies.",recommendation:"Add a frontmatter block describing the rule and its trigger (globs or alwaysApply).",noFrontmatterTitle:"Cursor rule is missing frontmatter",noFrontmatterSeverity:"warning",noFrontmatterConfidence:.7},P_=["**/node_modules/**","**/.git/**"];function xd(t,e){return`ai-config-cursor-${t}-${ce(e)}`}function A_(t){let e=t.trim();return!(!e||e.startsWith("!")||e.includes("$")||e.includes("<")||e.includes(">"))}function Vo(t){let e=[],n=t.aiConfig.cursorRules,i=null,s=r=>(i??=zt(t.repoRoot,["**/*"],P_),Sd.default.some(i,r,{dot:!0}));for(let r of n){let o=Se(t.repoRoot,r);if(o===void 0)continue;let a=Ue(o);if(e.push(...at(r,o,a,C_)),!a.present)continue;let c=typeof a.data.description=="string"?a.data.description.trim():"",l=Kt(a.data.globs),p=a.data.alwaysApply===!0||typeof a.data.alwaysApply=="string"&&a.data.alwaysApply.trim().toLowerCase()==="true";!c&&l.length===0&&!p&&e.push(D({id:xd("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 u of l){if(!A_(u))continue;let d=u.replace(/^\//,""),f=d.includes("/")?[d]:[d,`**/${d}`];s(f)||e.push(D({id:xd("dead-glob",`${r}|${u}`),title:"Cursor rule glob matches no files",summary:`${r}: the \`globs\` pattern \`${u}\` 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: ${u}`],recommendation:"Update the glob to match real paths, or remove the rule if the code it targeted is gone.",confidence:.6}))}}return Ee(t.repoRoot,e)}var Uo=E(jt(),1);var R_={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},k_=["**/node_modules/**","**/.git/**"],$_=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/out/**","**/coverage/**","**/worktrees/**","**/.worktrees/**"];function qo(t,e){return`ai-config-copilot-${t}-${ce(e)}`}function T_(t){let e=t.trim();return!(!e||e.startsWith("!")||e.includes("$")||e.includes("<")||e.includes(">"))}function O_(t){let e=t.trim();return e==="**"||e==="**/*"}function zo(t){let e=[],n=t.aiConfig.copilotInstructions,i=null,s=null,r=a=>(i??=zt(t.repoRoot,["**/*"],k_),Uo.default.some(i,a,{dot:!0})),o=a=>(s??=zt(t.repoRoot,["**/*"],$_),Uo.default.some(s,a,{dot:!0}));for(let a of n){let c=Se(t.repoRoot,a);if(c===void 0)continue;let l=Ue(c);if(e.push(...at(a,c,l,R_)),!l.present)continue;let p=Kt(l.data.applyTo);if(p.length===0){e.push(D({id:qo("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 u=l.keyLines.applyTo??1;for(let d of p){if(!T_(d)||O_(d))continue;let f=d.replace(/^\//,""),h=f.includes("/")?[f]:[f,`**/${f}`];r(h)?o(h)||e.push(D({id:qo("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:u,endLine:u}],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(D({id:qo("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:u,endLine:u}],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 Ee(t.repoRoot,e)}var L_=[{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}],I_=2;function Ko(t){let e=[];for(let n of t.files){if(n.fileType!=="windsurf")continue;let i=new Set;for(let s of n.sections){let r=s.heading;if(r)for(let o of L_)o.re.test(r)&&i.add(o.label)}if(i.size>=I_){let s=[...i].sort();e.push({id:`ai-config-windsurf-scope-${ce(n.path)}`,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 (${s.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:[n.path],locations:[{filePath:n.path,startLine:1}],evidence:[`Scoped topics found in headings: ${s.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 Ed=E(require("node:crypto"),1),Cd=E(require("node:path"),1);var j_=new Set(["claude","agents","cursor","windsurf","copilot","prompt"]),N_=[/\bdo\s+not\b/i,/\bdon['’]?t\b/i,/\bnever\b/i,/\bavoid\b/i,/\brefrain\s+from\b/i,/\bmust\s+not\b/i,/\bmustn['’]?t\b/i,/\bshould\s+not\b/i,/\bshouldn['’]?t\b/i,/\bcannot\b/i,/\bcan['’]?t\b/i,/\bwon['’]?t\b/i,/\bno\s+longer\b/i],M_=/^(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,D_=/\b(must|should|always|shall)\b/i,F_=8,H_=.4;function B_(t){return t.replace(/^\s*#{1,6}\s+/,"").replace(/^\s*[-*+]\s+/,"").replace(/^\s*\d+[.)]\s+/,"").replace(/^\s*>\s+/,"").trim()}function G_(t){return t.replace(/^[*_`]+/,"").trimStart()}function W_(t){let e=t.split(/\r?\n/),n=[],i=!1;for(let s of e){if(/^\s*(```|~~~)/.test(s)){i=!i;continue}if(i)continue;let o=B_(s);if(o)for(let a of o.split(/(?<=[.!?])\s+/)){let c=a.trim();c.split(/\s+/).length>=3&&n.push(c)}}return n}function V_(t){let e=G_(t);if(M_.test(e))return"positive";for(let n of N_)if(n.test(t))return"negative";return D_.test(t)?"positive":"none"}function q_(t){return`negative-overload-${Ed.createHash("sha1").update(`negative-overload:${t}`).digest("hex").slice(0,12)}`}function Jo(t){let e=[];for(let n of t){if(!j_.has(n.fileType))continue;let i=W_(n.content),s=[],r=0;for(let u of i){let d=V_(u);d==="negative"?s.push(u):d==="positive"&&r++}let o=s.length+r;if(o<F_)continue;let a=s.length/o;if(a<=H_)continue;let c=Cd.basename(n.path),l=Math.round(a*100),p=s.slice(0,3).map(u=>J(u,100));e.push({id:q_(n.path),severity:"info",category:"agent_practices",title:"High proportion of negative instructions",summary:`About ${l}% of the directive sentences in "${c}" are phrased as prohibitions (${s.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:p.map(u=>`Negative directive: "${u}"`),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 Pd=E(require("node:crypto"),1),Ad=E(require("node:path"),1);var U_=new Set(["claude","agents","cursor","windsurf","copilot","prompt"]),z_=[/\bnever\b/i,/\bcritical\b/i,/\bmust\s+not\b/i,/\bsecurity\b/i,/\bdangerous\b/i],K_=100,J_=.6;function Y_(t){return z_.some(e=>e.test(t))}function X_(t){return`buried-critical-${Pd.createHash("sha1").update(`buried-critical:${t}`).digest("hex").slice(0,12)}`}function Yo(t){let e=[];for(let n of t){if(!U_.has(n.fileType))continue;let i=n.content.split(/\r?\n/);i.length>0&&i[i.length-1]===""&&i.pop();let s=i.length;if(s<=K_)continue;let r=Math.floor(s/2),o=[],a=0,c=!1;for(let h=0;h<s;h++){let m=i[h]??"";if(/^\s*(```|~~~)/.test(m)){c=!c;continue}c||Y_(m)&&(o.push(h+1),h>=r&&a++)}if(o.length===0)continue;let l=a/o.length;if(l<=J_)continue;let p=Ad.basename(n.path),u=Math.round(l*100),d=o.filter(h=>h>r),f=i[(d[0]??o[0])-1]??"";e.push({id:X_(n.path),severity:"info",category:"structure",title:"Critical instructions near the bottom of a long file",summary:`${u}% of the high-severity lines in "${p}" (${a} of ${o.length}) sit in the bottom half of a ${s}-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]}: "${J(f,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 Rd=E(require("node:crypto"),1);var Q_=new Set(["claude","agents","cursor","windsurf","copilot","prompt"]),Z_=6,ex=.65,tx=40,nx=8;function ix(t){return t.toLowerCase().replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+[.)]\s+/gm,"").replace(/\s+/g," ").trim()}function sx(t){return new Set(t.match(/\b\w+\b/g)??[])}function rx(t,e){if(t.size===0||e.size===0)return 0;let n=0;for(let i of t)e.has(i)&&n++;return n/(t.size+e.size-n)}function ox(t){let e=t.text.split(`
83
+ `),n=[],i=[],s=t.startLine,r=0,o=()=>{if(i.length===0)return;r++;let a=i.join(`
84
+ `);if(!a.includes("```")&&!a.includes("~~~")){let c=ix(a),l=sx(c);c.length>=tx&&l.size>=nx&&n.push({number:r,text:a,startLine:s,tokens:l})}i=[]};for(let a=0;a<e.length;a++){let c=e[a]??"";c.trim()===""?o():(i.length===0&&(s=t.startLine+a),i.push(c))}return o(),n}function ax(t,e){return`within-section-dup-${Rd.createHash("sha1").update(`within-section-dup:${t}:${e}`).digest("hex").slice(0,12)}`}function Xo(t){let e=[];for(let n of t)if(Q_.has(n.fileType))for(let i of n.sections){let s=ox(i);if(s.length<Z_)continue;let r=null,o=0;for(let p=0;p<s.length;p++)for(let u=p+1;u<s.length;u++){let d=rx(s[p].tokens,s[u].tokens);d>=ex&&(o++,(!r||d>r.sim)&&(r={a:s[p],b:s[u],sim:d}))}if(!r)continue;let a=i.heading??"(untitled section)",c=Math.round(r.sim*100),l=o>1?` (${o} similar pairs in total)`:"";e.push({id:ax(n.path,i.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}: "${J(r.a.text,120)}"`,`Paragraph ${r.b.number}: "${J(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 Qo=[{id:"duplicates",run:t=>Wr(t.files)},{id:"duplicate-headings",run:t=>Vr(t.files)},{id:"within-section-dedup",run:t=>Xo(t.files)},{id:"conflicts",run:t=>Ur(t.files)},{id:"version-conflicts",run:t=>zr(t.files)},{id:"competing-tech-conflicts",run:t=>Kr(t.files)},{id:"context-bloat",run:t=>zp(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})},{id:"stale-instructions",run:t=>td(t.files)},{id:"command-validity",run:t=>Vp(t)},{id:"missing-context",run:t=>Yp(t.files,t.projectType)},{id:"manifest-consistency",run:t=>fo(t)},{id:"vague-guidance",run:t=>rd(t.files,{severityOverride:t.vagueGuidanceSeverity})},{id:"dead-references",run:t=>Xr(t.files,t.repoRoot)},{id:"agent-practices",run:t=>Qr(t.files)},{id:"canonical-owner",run:t=>Lp(t.files)},{id:"ci-alignment",run:t=>Mp(t)},{id:"security-pack",run:t=>od(t)},{id:"framework-packs",run:t=>gd(t)},{id:"prompt-cache-friendliness",run:t=>wd(t.files)},{id:"ai-config-skills",run:t=>Mo(t)},{id:"ai-config-subagents",run:t=>Fo(t)},{id:"ai-config-hooks-settings",run:t=>Go(t)},{id:"ai-config-mcp",run:t=>Wo(t)},{id:"ai-config-cursor-rules",run:t=>Vo(t)},{id:"ai-config-copilot-instructions",run:t=>zo(t)},{id:"ai-config-windsurf-rules",run:t=>Ko(t)},{id:"negative-instructions",run:t=>Jo(t.files)},{id:"buried-critical",run:t=>Yo(t.files)},{id:"custom-rules",run:t=>xo(t.files,t.customRules,t.repoRoot)}];function Zo(t){return Qo.flatMap(e=>e.run(t))}async function ea(t){let e=await Sn(t),n=Qo.find(s=>s.id==="context-bloat"),i=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:i}}async function ze(t){let e=await Sn(t),n=Zo(e),i=[...e.files,...e.onDemandFiles],s=Zr(i),r=[...n,...eo(s)],{active:o,suppressed:a}=to(r,s),c=io(o),l=so(o),p,u;if(t.baseline){let d=Vt(o,t.baseline,e.repoRoot);p=d.newIssues,u=d.baselinedIssues}return{schemaVersion:"0.1",generatedAt:new Date().toISOString(),repoPath:e.repoRoot,projectType:e.projectType,healthScore:c,metrics:e.metrics,filesScanned:i,issues:o,topFixes:l,newIssues:p,baselinedIssues:u,suppressedIssues:a.length>0?a:void 0}}var we=E(require("node:path"),1),Bi=E(require("node:fs/promises"),1);function kd(t,e){return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")).some(n=>Mi(n,e))}function On(t,e){let n=we.resolve(t),i=we.isAbsolute(e)?we.resolve(e):we.resolve(n,e);if(!He(n,i))throw new Error(`Path traversal detected: "${e}" is outside repo root "${n}"`);return i}async function ta(t,e){let n=[];if(t.id==="security-pack-no-promptci-gitignore"){let i=On(e,".gitignore"),s="";try{s=await Bi.readFile(i,"utf-8")}catch{}if(!kd(s,".promptci")){let r=s.includes(`\r
98
85
  `)?`\r
99
86
  `:`
100
- `;for(let a of t.evidence){let c=/Directory "([^"]+)" exists/.exec(a);if(c&&c[1]){let l=c[1];i.includes(`${l}/`)||(o+=`${l}/${r}`)}}if(o){let a=i.endsWith(`
101
- `)||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"){let s=/(?<![/-])\b(2019|2020|2021|2022|2023)\b(?![/-])/g;if(t.evidence.some(o=>o.includes("Year reference(s) that may be outdated"))&&t.locations.length>0){let o=t.locations[0],r=Lt(e,o.filePath),a="";try{a=await sn.readFile(r,"utf-8")}catch{return[]}let c=a.split(/\r?\n/),u=a.includes(`\r
87
+ `,o=Pn(r),a=s.endsWith(`
88
+ `)||s.endsWith("\r")?o:`${r}${o}`;n.push({filePath:i,originalContent:s,newContent:s+a})}return n}if(t.id==="security-pack-unignored-dirs"){let i=On(e,".gitignore"),s="";try{s=await Bi.readFile(i,"utf-8")}catch{}let r="",o=s.includes(`\r
102
89
  `)?`\r
103
90
  `:`
104
- `,p=(o.startLine??1)-1,d=(o.endLine??c.length)-1,f=!1;for(let h=p;h<=d;h++)if(h>=0&&h<c.length){let g=c[h],v=g.replace(s,"2026");v!==g&&(c[h]=v,f=!0)}f&&n.push({filePath:r,originalContent:a,newContent:c.join(u)})}return n}if(t.category==="duplicate"&&t.locations.length>=2){let s=t.locations.find(r=>ye.basename(r.filePath).toLowerCase()==="agents.md");s||(s=t.locations[0]);let i=Lt(e,s.filePath),o=ye.basename(i);for(let r of t.locations){let a=Lt(e,r.filePath);if(a===i)continue;let c="";try{c=await sn.readFile(a,"utf-8")}catch{continue}let l=c.split(/\r?\n/),p=c.includes(`\r
91
+ `;for(let a of t.evidence){let c=/Directory "([^"]+)" exists/.exec(a);if(c&&c[1]){let l=c[1];kd(s,l)||(r+=`${l}/${o}`)}}if(r){let a=s.endsWith(`
92
+ `)||s.endsWith("\r")?r:`${o}${r}`;n.push({filePath:i,originalContent:s,newContent:s+a})}return n}if(t.id.startsWith("stale-")&&t.category==="stale_instruction")return n;if(t.category==="duplicate"&&t.locations.length>=2){let i=t.locations.find(a=>we.basename(a.filePath).toLowerCase()==="agents.md");i||(i=t.locations[0]);let s=On(e,i.filePath),r=we.basename(s),o=new Map;for(let a of t.locations){let c=On(e,a.filePath);if(c===s)continue;let l=o.get(c)??[];l.push(a),o.set(c,l)}for(let[a,c]of o){let l;try{l=await Bi.readFile(a,"utf-8")}catch{continue}let p=l.split(/\r?\n/),u=l.includes(`\r
105
93
  `)?`\r
106
94
  `:`
107
- `,d=(r.startLine??1)-1,f=(r.endLine??l.length)-1,h=ye.relative(ye.dirname(a),i).replace(/\\/g,"/"),g=h.startsWith(".")?h:`./${h}`,v=l.slice(d,f+1),y="",b=d;v.length>0&&v[0].trim().startsWith("#")&&(y=v[0],b=d+1);let m=`See canonical instructions in [${o}](${g}) for details.`,x=l.slice(0,b),k=l.slice(f+1),C;y?C=[m]:C=[m];let A=[...x,...C,...k];n.push({filePath:a,originalContent:c,newContent:A.join(p)})}}return n}async function on(t,e,n=!1){let s=process.env.OPENAI_API_KEY,i=process.env.ANTHROPIC_API_KEY;if(!s&&!i)throw new Error("Please set OPENAI_API_KEY or ANTHROPIC_API_KEY to use this feature.");let o=process.env.PROMPTCI_LLM_MODEL;if(s){let a={model:o??"gpt-4o",messages:[{role:"system",content:t},{role:"user",content:e}]};n&&(a.response_format={type:"json_object"});let c=await globalThis.fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(a)});if(!c.ok){let u=await c.text();throw new Error(`OpenAI API request failed (${c.status}): ${u}`)}return(await c.json()).choices?.[0]?.message?.content||""}else{let a={model:o??"claude-3-5-sonnet-latest",max_tokens:4096,system:t,messages:[{role:"user",content:e}]},c=await globalThis.fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":i,"anthropic-version":"2023-06-01"},body:JSON.stringify(a)});if(!c.ok){let u=await c.text();throw new Error(`Anthropic API request failed (${c.status}): ${u}`)}return(await c.json()).content?.[0]?.text||""}}var pe=E(require("node:path"),1),us=require("node:fs"),Aw=[/\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],Rw=[/health\s+score\s*:\s*\d+/i,/files\s+scanned\s*:\s*\d+/i,/promptci\s+report/i,/\bgenerated\s+by\s+promptci\b/i,/latest\s+scan\s+results/i,/scan\s+history/i],$w=[/current\s+branch\s*:\s*\S+/i,/git\s+branch\s*:\s*\S+/i,/current\s+task\s*:\s*\S+/i],Tw=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i,Lw=[...Aw,...Rw,...$w,Tw],Iw=/^\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 $p(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ow(t,e){let n=e.replace(/\//g,"\\"),s=e.replace(/\\/g,"/"),i=t,o=$p(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=$p(s),c=new RegExp(a+`([^\\s"'\\)\\>]*)`,"gi");return i=i.replace(c,(l,u)=>{let p=u;return"."+(p.startsWith("/")?p:"/"+p)}),i}function jw(t){let n=t.split(/\r?\n/).filter(i=>!Iw.test(i)),s=t.includes(`\r
108
- `);return n.join(s?`\r
95
+ `,d=we.relative(we.dirname(a),s).replace(/\\/g,"/"),f=d.startsWith(".")?d:`./${d}`,h=`See canonical instructions in [${r}](${f}) for details.`,m=c.map(y=>({startIdx:(y.startLine??1)-1,endIdx:(y.endLine??p.length)-1})).sort((y,v)=>v.startIdx-y.startIdx),b=p;for(let{startIdx:y,endIdx:v}of m){let g=b.slice(y,v+1),$=g.length>0&&g[0].trim().startsWith("#")?y+1:y;b=[...b.slice(0,$),h,...b.slice(v+1)]}n.push({filePath:a,originalContent:l,newContent:b.join(u)})}}return n}function na(t){return t.autoApplySafe===!0}var ge=E(require("node:path"),1),Gi=require("node:fs");var cx=[/\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],lx=[/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],ux=[/current\s+branch\s*:\s*\S+/i,/git\s+branch\s*:\s*\S+/i,/current\s+task\s*:\s*\S+/i],px=/(?:[a-zA-Z]:\\users\\[a-zA-Z0-9_-]+)|(?:\/users\/[a-zA-Z0-9_-]+\/)|(?:\/home\/(?!runner)[a-zA-Z0-9_-]+\/)/i,dx=[...cx,...lx,...ux,px],fx=/^\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 $d(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hx(t,e){let n=e.replace(/\//g,"\\"),i=e.replace(/\\/g,"/"),s=t,r=$d(n),o=new RegExp(r+`([^\\s"'\\)\\>]*)`,"gi");s=s.replace(o,(l,p)=>{let u=p.replace(/\\/g,"/");return"."+(u.startsWith("/")?u:"/"+u)});let a=$d(i),c=new RegExp(a+`([^\\s"'\\)\\>]*)`,"gi");return s=s.replace(c,(l,p)=>{let u=p;return"."+(u.startsWith("/")?u:"/"+u)}),s}function mx(t){let n=t.split(/\r?\n/).filter(s=>!fx.test(s)),i=t.includes(`\r
96
+ `);return n.join(i?`\r
109
97
  `:`
110
- `)}function Tp(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}function Nw(t,e){let n=t.replace(/\r\n/g,`
98
+ `)}function gx(t){return t.toLowerCase().replace(/[^\w\s-]/g,"").replace(/[\s_]+/g,"-").replace(/^-+|-+$/g,"")}async function ia(t,e){let n=ge.resolve(e.repoRoot),i=e.characterLimit??2e3,s=e.docsDir;s||((0,Gi.existsSync)(ge.join(n,"Docs"))?s="Docs":(0,Gi.existsSync)(ge.join(n,"docs"))?s="docs/ai":s="Docs");let r=ge.resolve(n,s),o=new Set,a=[],c=t.filter(l=>["claude","agents","cursor","windsurf","copilot","prompt"].includes(l.fileType));for(let l of c){let p=l.content,u=mx(p);u=hx(u,n);let d=bi(u,l.path),f=[];for(let v of d){if(!v.heading)continue;let g=v.text.length>i,S=dx.some($=>$.test(v.text));if(g||S){let $=gx(v.heading);$||($="section");let P=`${$}.md`,O=1;for(;o.has(P.toLowerCase())||(0,Gi.existsSync)(ge.join(r,P));)O++,P=`${$}-${O}.md`;o.add(P.toLowerCase());let C=ge.join(r,P),I=ge.relative(ge.dirname(l.path),C).replace(/\\/g,"/");f.push({section:v,targetPath:C,relPath:I})}}if(f.length===0){u!==p&&a.push({filePath:l.path,originalContent:p,newContent:u});continue}let h=u.replace(/\r\n/g,`
111
99
  `).split(`
112
- `),s=[],i,o=1,r=[],a=l=>{let u=r.join(`
113
- `),p=i!==void 0?Tp(i):`${e}:0`;s.push({id:p,filePath:e,heading:i,startLine:o,endLine:l,text:u,normalizedText:u.toLowerCase().trim()})},c=!1;for(let l=0;l<n.length;l++){let u=l+1,p=n[l]??"";if(/^[`~]{3}/.test(p)){c=!c,r.push(p);continue}let d=!c&&/^(#{1,3})\s+(.+)/.exec(p);d?((r.length>0||i!==void 0)&&a(u-1),i=d[2].trim(),o=u,r=[p]):r.push(p)}return(r.length>0||i!==void 0)&&a(n.length),s}async function hr(t,e){let n=pe.resolve(e.repoRoot),s=e.characterLimit??2e3,i=e.docsDir;i||((0,us.existsSync)(pe.join(n,"Docs"))?i="Docs":(0,us.existsSync)(pe.join(n,"docs"))?i="docs/ai":i="Docs");let o=pe.resolve(n,i),r=new Set,a=[],c=t.filter(l=>["claude","agents","cursor","copilot","readme","prompt"].includes(l.fileType));for(let l of c){let u=l.content,p=jw(u);p=Ow(p,n);let d=Nw(p,l.path),f=[];for(let b of d){if(!b.heading)continue;let m=b.text.length>s,x=Lw.some(k=>k.test(b.text));if(m||x){let k=Tp(b.heading);k||(k="section");let C=`${k}.md`,A=1;for(;r.has(C.toLowerCase())||(0,us.existsSync)(pe.join(o,C));)A++,C=`${k}-${A}.md`;r.add(C.toLowerCase());let _=pe.join(o,C),L=pe.relative(pe.dirname(l.path),_).replace(/\\/g,"/");f.push({section:b,targetPath:_,relPath:L})}}if(f.length===0){p!==u&&a.push({filePath:l.path,originalContent:u,newContent:p});continue}let h=p.replace(/\r\n/g,`
114
- `).split(`
115
- `),v=p.includes(`\r
100
+ `),b=u.includes(`\r
116
101
  `)?`\r
117
102
  `:`
118
- `;f.sort((b,m)=>m.section.startLine-b.section.startLine);for(let b of f){let{section:m,targetPath:x,relPath:k}=b,C=m.text,A=/^(#{1,3})\s+(.+)$/m.exec(C);if(A){let N=A[2];C=C.replace(/^(#{1,3})\s+(.+)$/m,`# ${N}`)}a.push({filePath:x,originalContent:"",newContent:C+v});let _=m.startLine-1,L=m.endLine-1,w=[h[_],"",`For details, see [${i}/${pe.basename(x)}](${k}).`];h.splice(_,L-_+1,...w)}let y=h.join(v);y!==u&&a.push({filePath:l.path,originalContent:u,newContent:y})}return{changes:a}}var Ip=E(require("node:fs/promises"),1),rn=E(require("node:path"),1),Mw=rn.join(".promptci","config.json"),Op=["info","warning","high","critical"],jp=["auto","typescript","nextjs","unity","dotnet","unknown"];function Dw(t){return typeof t=="string"&&Op.includes(t)}function Fw(t){return typeof t=="string"&&jp.includes(t)}function Lp(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}async function X(t){let e=rn.join(rn.resolve(t),Mw),n;try{n=await Ip.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(!Lp(i.include))throw new Error("config.include must be an array of strings");o.include=i.include}if("exclude"in i){if(!Lp(i.exclude))throw new Error("config.exclude must be an array of strings");o.exclude=i.exclude}if("severityThreshold"in i){if(!Dw(i.severityThreshold))throw new Error(`config.severityThreshold must be one of: ${Op.join(", ")}`);o.severityThreshold=i.severityThreshold}if("projectType"in i){if(!Fw(i.projectType))throw new Error(`config.projectType must be one of: ${jp.join(", ")}`);o.projectType=i.projectType}if("apiUrl"in i){if(typeof i.apiUrl!="string")throw new Error("config.apiUrl must be a string");o.apiUrl=i.apiUrl}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}return o}var Mp=E(require("node:path"),1),Hw={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},Bw=["critical","high","warning","info"],Uw={critical:3,high:2,warning:1,info:0};function Np(t){return Uw[t]}function Vw(t,e){return Np(t)>=Np(e)}function an(t,e){return t.issues.some(n=>Vw(n.severity,e))}function Gw(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 Dp(t,e={}){let{healthScore:n,issues:s,topFixes:i}=t,o={};for(let f of s)o[f.severity]=(o[f.severity]??0)+1;let r=Bw.filter(f=>(o[f]??0)>0).map(f=>`${Hw[f]} ${o[f]} ${f}`).join(" \xB7 "),a=e.previousEntry!=null?Gw(n,e.previousEntry.healthScore):"",c=` Health score: ${n}/100`;if(t.trend){let f=t.trend,h=f.scoreDelta,g="";h>0?g=`\x1B[32m(+${h} vs last scan)\x1B[0m`:h<0?g=`\x1B[31m(${h} vs last scan)\x1B[0m`:g="\x1B[90m(+0 vs last scan)\x1B[0m",c+=` ${g}; new issues: ${f.newIssuesCount}; resolved: ${f.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;u>0&&l.push(` Suppressed: ${u} (see report for details)`),i.length>0&&(l.push(""),l.push(" Top fixes:"),i.forEach((f,h)=>{l.push(` ${h+1}. ${f.title}`)}));let p=f=>Mp.relative(process.cwd(),f)||f,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(`
119
- `)}var Fp=["info","warning","high","critical"];function mr(t){return Fp.includes(t)}async function Hp(t){let e=t.scanPath??process.cwd(),n=Ge.resolve(e);try{(await st.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 X(n)}catch(l){console.error(`Error: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}let i=t.failOn??s.severityThreshold;i!==void 0&&!mr(i)&&(console.error(`Error: invalid --fail-on value "${i}". Must be one of: ${Fp.join(", ")}`),process.exit(1));let o;if(t.baseline){let l=Ge.resolve(n,t.baseline);try{let u=await st.readFile(l,"utf-8"),p;try{p=JSON.parse(u)}catch(d){console.error(`Error: baseline file "${l}" contains invalid JSON: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}try{dr(p),o=p}catch(d){console.error(`Error: baseline file "${l}" has an unexpected format: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}}catch(u){u.code!=="ENOENT"&&(console.error(`Error loading baseline: ${u instanceof Error?u.message:String(u)}`),process.exit(1))}}let r=await Ee({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude,baseline:o,contextBudget:t.contextBudget??s.contextBudget,fileContextBudget:t.fileContextBudget??s.fileContextBudget}),a=t.output?await es(r,{mdPath:Ge.resolve(t.output),archive:!1}):await es(r);if(t.updateBaseline){let l=$t(r.issues,n),u=t.baseline?Ge.resolve(n,t.baseline):Ge.join(n,".promptci","baseline.json");await st.mkdir(Ge.dirname(u),{recursive:!0}),await st.writeFile(u,JSON.stringify(l,null,2)),t.json||console.log(`
120
- Baseline updated: ${u}`)}if(t.json?process.stdout.write(Zn(r)+`
121
- `):process.stdout.write(Dp(r,{mdPath:a.mdPath,jsonPath:a.jsonPath,previousEntry:a.archivedEntry})),i&&an(r,i)){let l=r.issues.filter(u=>mr(u.severity)&&an({...r,issues:[u]},i)).length;console.error(`
122
- Failed: ${l} issue(s) at or above "${i}" threshold. See ${a.mdPath} for details.`),process.exit(1)}let c=t.failOnNew;if(c&&r.newIssues&&an({...r,issues:r.newIssues},c)){let l=r.newIssues.filter(u=>mr(u.severity)&&an({...r,issues:[u]},c)).length;console.error(`
123
- Failed: ${l} NEW issue(s) at or above "${c}" threshold. See ${a.mdPath} for details.`),process.exit(1)}if(t.failOnBudget){let l=r.issues.filter(u=>u.category==="context_bloat");l.length>0&&(console.error(`
124
- Failed: ${l.length} context bloat issue(s) found and --fail-on-budget is enabled. See ${a.mdPath} for details.`),process.exit(1))}}var ae=E(require("node:fs/promises"),1),ke=E(require("node:path"),1),Gp=E(require("node:readline"),1);var Bp=["typescript","nextjs","unity","dotnet","python","go","rust","unknown"],Up={severityThreshold:"warning",projectType:"auto",apiUrl:"http://localhost:3000"},Vp={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
103
+ `;f.sort((v,g)=>g.section.startLine-v.section.startLine);for(let v of f){let{section:g,targetPath:S,relPath:$}=v,P=g.text,O=/^(#{1,3})\s+(.+)$/m.exec(P);if(O){let H=O[2];P=P.replace(/^(#{1,3})\s+(.+)$/m,`# ${H}`)}a.push({filePath:S,originalContent:"",newContent:P+b});let C=g.startLine-1,I=g.endLine-1,x=[h[C],"",`For details, see [${s}/${ge.basename(S)}](${$}).`];h.splice(C,I-C+1,...x)}let y=h.join(b);y!==p&&a.push({filePath:l.path,originalContent:p,newContent:y})}return{changes:a}}var Od=E(require("node:fs/promises"),1),Ln=E(require("node:path"),1);var yx=Ln.join(".promptci","config.json"),Ld=["info","warning","high","critical"],Id=Bn;function bx(t){return typeof t=="string"&&Ld.includes(t)}function vx(t){return typeof t=="string"&&Id.includes(t)}function Td(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}async function Oe(t){let e=Ln.join(Ln.resolve(t),yx),n;try{n=await Od.readFile(e,"utf-8")}catch{return{}}let i;try{i=JSON.parse(n)}catch{throw new Error("Failed to parse .promptci/config.json: invalid JSON")}if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(".promptci/config.json must be a JSON object");let s=i,r={};if("include"in s){if(!Td(s.include))throw new Error("config.include must be an array of strings");r.include=s.include}if("exclude"in s){if(!Td(s.exclude))throw new Error("config.exclude must be an array of strings");r.exclude=s.exclude}if("severityThreshold"in s){if(!bx(s.severityThreshold))throw new Error(`config.severityThreshold must be one of: ${Ld.join(", ")}`);r.severityThreshold=s.severityThreshold}if("projectType"in s){if(!vx(s.projectType))throw new Error(`config.projectType must be one of: ${Id.join(", ")}`);r.projectType=s.projectType}if("contextBudget"in s){if(typeof s.contextBudget!="number"||s.contextBudget<=0)throw new Error("config.contextBudget must be a positive number");r.contextBudget=s.contextBudget}if("fileContextBudget"in s){if(typeof s.fileContextBudget!="number"||s.fileContextBudget<=0)throw new Error("config.fileContextBudget must be a positive number");r.fileContextBudget=s.fileContextBudget}if("targetModel"in s){if(typeof s.targetModel!="string"||Jt(s.targetModel)===void 0)throw new Error(`config.targetModel must be one of: ${_n.join(", ")} (or a family alias like "claude"/"gpt"/"gemini")`);r.targetModel=s.targetModel}if("vagueGuidanceSeverity"in s){if(s.vagueGuidanceSeverity!=="info"&&s.vagueGuidanceSeverity!=="warning")throw new Error("config.vagueGuidanceSeverity must be one of: info, warning");r.vagueGuidanceSeverity=s.vagueGuidanceSeverity}return r}var Nd=E(require("node:path"),1),wx={critical:"\u{1F534}",high:"\u{1F7E0}",warning:"\u{1F7E1}",info:"\u{1F535}"},_x=["critical","high","warning","info"],xx={critical:3,high:2,warning:1,info:0};function jd(t){return xx[t]}function sa(t,e){return jd(t)>=jd(e)}function In(t,e){return t.issues.some(n=>sa(n.severity,e))}function Sx(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 Md(t,e={}){let{healthScore:n,issues:i,topFixes:s}=t,r={};for(let f of i)r[f.severity]=(r[f.severity]??0)+1;let o=_x.filter(f=>(r[f]??0)>0).map(f=>`${wx[f]} ${r[f]} ${f}`).join(" \xB7 "),a=e.previousEntry!=null?Sx(n,e.previousEntry.healthScore):"",c=` Health score: ${n}/100`;if(t.trend){let f=t.trend,h=f.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: ${f.newIssuesCount}; resolved: ${f.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 p=t.suppressedIssues?.length??0;p>0&&l.push(` Suppressed: ${p} (see report for details)`),s.length>0&&(l.push(""),l.push(" Top fixes:"),s.forEach((f,h)=>{l.push(` ${h+1}. ${f.title}`)}));let u=f=>Nd.relative(process.cwd(),f)||f,d=[];return e.mdPath&&d.push(` Markdown : ${u(e.mdPath)}`),e.jsonPath&&d.push(` JSON : ${u(e.jsonPath)}`),d.length>0&&(l.push(""),l.push(" Output:"),l.push(...d)),l.push(""),l.join(`
104
+ `)}var ra=["info","warning","high","critical"];function Wi(t){return ra.includes(t)}async function Dd(t){let e=t.scanPath??process.cwd(),n=Ke.resolve(e);try{(await lt.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 i;try{i=await Oe(n)}catch(p){console.error(`Error: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}let s=t.targetModel??i.targetModel;s!==void 0&&Jt(s)===void 0&&(console.error(`Error: invalid --target-model value "${s}". Must be one of: ${_n.join(", ")} (or a family alias like "claude"/"gpt"/"gemini").`),process.exit(1));let r=t.failOn??i.severityThreshold;r!==void 0&&!Wi(r)&&(console.error(`Error: invalid --fail-on value "${r}". Must be one of: ${ra.join(", ")}`),process.exit(1)),t.failOnNew!==void 0&&!Wi(t.failOnNew)&&(console.error(`Error: invalid --fail-on-new value "${t.failOnNew}". Must be one of: ${ra.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=Ke.resolve(n,t.baseline);try{let u=await lt.readFile(p,"utf-8"),d;try{d=JSON.parse(u)}catch(f){console.error(`Error: baseline file "${p}" contains invalid JSON: ${f instanceof Error?f.message:String(f)}`),process.exit(1)}try{ro(d),o=d}catch(f){console.error(`Error: baseline file "${p}" has an unexpected format: ${f instanceof Error?f.message:String(f)}`),process.exit(1)}}catch(u){u.code!=="ENOENT"&&(console.error(`Error loading baseline: ${u instanceof Error?u.message:String(u)}`),process.exit(1)),o=[]}}let a=await ze({repoPath:n,projectType:i.projectType,include:i.include,exclude:i.exclude,baseline:o,contextBudget:t.contextBudget??i.contextBudget,fileContextBudget:t.fileContextBudget??i.fileContextBudget,targetModel:s,vagueGuidanceSeverity:i.vagueGuidanceSeverity}),c=t.output?await Pi(a,{mdPath:Ke.resolve(t.output),archive:!1}):await Pi(a);if(t.updateBaseline){let p=Wt(a.issues,n),u=t.baseline?Ke.resolve(n,t.baseline):Ke.join(n,".promptci","baseline.json");await lt.mkdir(Ke.dirname(u),{recursive:!0}),await lt.writeFile(u,JSON.stringify(p,null,2)),t.json||console.log(`
105
+ Baseline updated: ${u}`)}if(t.json?process.stdout.write(Ci(a)+`
106
+ `):process.stdout.write(Md(a,{mdPath:c.mdPath,jsonPath:c.jsonPath,previousEntry:c.archivedEntry})),r&&In(a,r)){let p=a.issues.filter(d=>Wi(d.severity)&&In({...a,issues:[d]},r)).length,u=t.failOn!==void 0?"from --fail-on":"from severityThreshold in .promptci/config.json";console.error(`
107
+ Failed: ${p} issue(s) at or above the "${r}" threshold (${u}). See ${c.mdPath} for details.
108
+ Raise the gate with --fail-on <severity> or edit severityThreshold to only fail on higher severities.`),process.exit(1)}let l=t.failOnNew;if(l){let p=a.newIssues??[];if(In({...a,issues:p},l)){let u=p.filter(d=>Wi(d.severity)&&In({...a,issues:[d]},l)).length;console.error(`
109
+ Failed: ${u} NEW issue(s) at or above "${l}" threshold. See ${c.mdPath} for details.`),process.exit(1)}}if(t.failOnBudget){let p=a.issues.filter(u=>u.category==="context_bloat");p.length>0&&(console.error(`
110
+ Failed: ${p.length} context bloat issue(s) found and --fail-on-budget is enabled. See ${c.mdPath} for details.`),process.exit(1))}}var de=E(require("node:fs/promises"),1),Ct=E(require("node:path"),1),Bd=E(require("node:readline"),1);var jn=Bn.filter(t=>t!=="auto"),Fd={severityThreshold:"high",projectType:"auto"},Hd={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
125
111
 
126
112
  ## Project Type
127
113
  TypeScript (General)
@@ -269,103 +255,46 @@ Before finalizing any changes, perform these steps:
269
255
  ## Commands & Scripts
270
256
  - Locate any setup, build, and test scripts in the root directory (e.g. \`Makefile\`, \`package.json\`, or shell scripts).
271
257
  - Run validation commands before considering a task completed.
272
- `};function ps(t,e){let n=ke.resolve(t),s=ke.resolve(n,e),i=ke.relative(n,s);if(i.startsWith("..")||ke.isAbsolute(i))throw new Error(`Path escapes target directory: ${e}`);return s}async function gr(t){try{return await ae.access(t),!0}catch{return!1}}async function qp(t,e){let n=ps(t,".promptci"),s=ke.join(n,"config.json");await ae.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=Gp.createInterface({input:process.stdin,output:process.stdout});return new Promise(d=>{p.question(u,f=>{p.close(),d(f.trim())})})},a="auto",c=await zt(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 g=!1,v=0;for(;!g&&v<5;){v++;let y=await r(`Select project type:
273
- 1: typescript
274
- 2: nextjs
275
- 3: unity
276
- 4: dotnet
277
- 5: python
278
- 6: go
279
- 7: rust
280
- 8: unknown
281
- Enter choice (1-8 or name): `),b=parseInt(y,10);if(b>=1&&b<=8)a=Bp[b-1],g=!0;else{let m=y.toLowerCase().trim();Bp.includes(m)?(a=m,g=!0):console.log("Invalid selection. Please try again.")}}g||(console.log("No valid selection received. Defaulting to project type: auto"),a="auto")}let d=!1;try{await ae.access(s),d=!0,console.log(`Config already exists: ${s}`)}catch{}if(!d){let g={...Up,projectType:a};await ae.writeFile(s,JSON.stringify(g,null,2)+`
282
- `,"utf-8"),console.log(`Created ${s}`)}let f=["AGENTS.md",".cursorrules","CLAUDE.md",".github/copilot-instructions.md"],h=!1;for(let g of f){let v=ps(t,g);if(await gr(v)){h=!0;break}}if(!h){let g=await r("We did not find any AI instruction files. Would you like to generate a starter template? (Y/n): ");if(g===""||g.toLowerCase()==="y"||g.toLowerCase()==="yes"){let y,b=0;for(;!y&&b<5;){b++;let m=await r(`Which file type would you like to create?
258
+ `};function Vi(t,e){let n=Ct.resolve(t),i=Ct.resolve(n,e);if(!He(n,i))throw new Error(`Path escapes target directory: ${e}`);return i}async function oa(t){try{return await de.access(t),!0}catch{return!1}}async function Gd(t,e){let n=Vi(t,".promptci"),i=Ct.join(n,"config.json");await de.mkdir(n,{recursive:!0});let s=e?.interactive??!1,r=0,o=p=>{if(e?.answers&&r<e.answers.length){let d=e.answers[r];return r++,console.log(`${p}${d}`),Promise.resolve(d)}let u=Bd.createInterface({input:process.stdin,output:process.stdout});return new Promise(d=>{u.question(p,f=>{u.close(),d(f.trim())})})},a="auto",c=await hn(t);if(s){let p=await o(`We detected this is a ${c} repository. Confirm? (Y/n): `);if(p===""||p.toLowerCase()==="y"||p.toLowerCase()==="yes")a=c;else{let m=!1,b=0;for(;!m&&b<5;){b++;let y=jn.map((S,$)=>`${$+1}: ${S}`).join(`
259
+ `),v=await o(`Select project type:
260
+ ${y}
261
+ Enter choice (1-${jn.length} or name): `),g=parseInt(v,10);if(g>=1&&g<=jn.length)a=jn[g-1],m=!0;else{let S=v.toLowerCase().trim();jn.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 de.access(i),d=!0,console.log(`Config already exists: ${i}`)}catch{}if(!d){let m={...Fd,projectType:a};await de.writeFile(i,JSON.stringify(m,null,2)+`
262
+ `,"utf-8"),console.log(`Created ${i}`)}let f=["AGENTS.md",".cursorrules","CLAUDE.md",".github/copilot-instructions.md"],h=!1;for(let m of f){let b=Vi(t,m);if(await oa(b)){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,v=0;for(;!y&&v<5;){v++;let g=await o(`Which file type would you like to create?
283
263
  1: AGENTS.md (Recommended for monorepos & multi-agent instructions)
284
264
  2: .cursorrules (For Cursor users)
285
265
  3: CLAUDE.md (For Cline/Claude-dev users)
286
- Enter choice (1-3 or name): `);m==="1"||m.toLowerCase()==="agents.md"||m.toLowerCase()==="agents"?y="AGENTS.md":m==="2"||m.toLowerCase()===".cursorrules"||m.toLowerCase()==="cursorrules"?y=".cursorrules":m==="3"||m.toLowerCase()==="claude.md"||m.toLowerCase()==="claude"?y="CLAUDE.md":console.log("Invalid selection. Please try again.")}if(y){let m=ps(t,y);if(await gr(m))console.log(`Safety Warning: File already exists: ${m}. Skip writing.`);else{let x=Vp[a]||Vp.unknown;await ae.mkdir(ke.dirname(m),{recursive:!0}),await ae.writeFile(m,x,"utf-8"),console.log(`Created starter template: ${m}`)}}else console.log("No valid template selection received. Skipping template generation.")}}}else{try{await ae.access(s),console.log(`Config already exists: ${s}`),console.log("Remove it first if you want to reinitialize.");return}catch{}await ae.writeFile(s,JSON.stringify(Up,null,2)+`
287
- `,"utf-8"),console.log(`Created ${s}`),console.log("Edit it to set include/exclude patterns, severityThreshold, projectType, and apiUrl.")}let l=ps(t,".gitignore");if(await gr(l)){let u=await ae.readFile(l,"utf-8");if(!u.split(/\r?\n/).some(f=>{let h=f.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\//,"");return h===".promptci"||h.startsWith(".promptci/")||h.endsWith("/.promptci")||h.includes("/.promptci/")})){let f=!1;if(i){let h=await r("Add .promptci/ to .gitignore? (recommended) [Y/n]: ");f=h===""||h.toLowerCase()==="y"||h.toLowerCase()==="yes"}else f=!0;if(f){let g=`${u.length>0&&!u.endsWith(`
288
- `)?`
289
- `:""}.promptci/
290
- `;await ae.appendFile(l,g,"utf-8"),console.log("\u2714 Added .promptci/ to .gitignore")}}}}var yt=E(require("node:fs/promises"),1),Ae=E(require("node:path"),1),Wp=E(require("node:readline/promises"),1);async function zp(t){let e=t.scanPath??process.cwd(),n=Ae.resolve(e);try{(await yt.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 X(n)}catch(u){console.error(`Error loading config: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}t.dryRun||console.log("Scanning repository to identify issues...");let i=await Ee({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude}),o=[];if(t.llm){t.issueId||(console.error("Error: Please specify the issue to resolve using --issue <issue-id> when using --llm."),process.exit(1));let u=i.issues.find(p=>p.id===t.issueId);u||(console.error(`Error: No issue found with ID "${t.issueId}".`),process.exit(1)),u.category!=="vague_guidance"&&u.category!=="conflict"&&(console.error("Error: LLM-based fixes are only supported for vague guidance or conflicting instructions."),process.exit(1)),o=[u]}else{let u=i.issues.filter(p=>qw(p));if(t.issueId){let p=u.find(d=>d.id===t.issueId);p||(console.error(`Error: No repairable issue found with ID "${t.issueId}".`),process.exit(1)),u=[p]}if(u.length===0){console.log("No repairable issues found.");return}o=u}let r=t.interactive!==!1,a=r&&!t.answers?Wp.createInterface({input:process.stdin,output:process.stdout}):null,c=0,l=0;try{for(let u of o){let p=[];if(t.llm?p=await zw(u,n):p=await fr(u,n),p.length===0)continue;console.log(`
291
- ================================================================================`),console.log(`Issue ID: ${u.id}`),console.log(`Title: ${u.title}`),console.log(`Severity: ${u.severity.toUpperCase()}`),console.log(`Summary: ${u.summary}`),console.log("--------------------------------------------------------------------------------");for(let f of p)Ww(f,n);if(t.dryRun){console.log(`
292
- [Dry Run] Simulating fix for issue ${u.id}. No changes written.`);continue}let d=!0;if(r){let f=t.llm?`
293
- Apply this LLM patch? (y/N): `:`
294
- Apply this fix? (y/N): `;if(t.answers&&l<t.answers.length){let h=t.answers[l];l++,console.log(`${f}${h}`),d=h.toLowerCase().trim()==="y"}else a?d=(await a.question(f)).toLowerCase().trim()==="y":d=!1}if(d){for(let f of p){let h=Ae.resolve(n,f.filePath);if(!h.startsWith(n))throw new Error(`Path traversal guard triggered: "${f.filePath}" is outside repo root.`);await yt.writeFile(h,f.newContent,"utf-8"),console.log(`Applied change to ${Ae.relative(n,h)}`)}c++}else console.log("Skipped.")}}finally{a?.close()}if(c>0&&!t.dryRun){console.log(`
295
- Re-scanning repository...`);let u=await Ee({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude});console.log(`
296
- Fixes complete. Initial score: ${i.healthScore}/100 -> New score: ${u.healthScore}/100`)}else t.dryRun?console.log(`
266
+ Enter choice (1-3 or name): `);g==="1"||g.toLowerCase()==="agents.md"||g.toLowerCase()==="agents"?y="AGENTS.md":g==="2"||g.toLowerCase()===".cursorrules"||g.toLowerCase()==="cursorrules"?y=".cursorrules":g==="3"||g.toLowerCase()==="claude.md"||g.toLowerCase()==="claude"?y="CLAUDE.md":console.log("Invalid selection. Please try again.")}if(y){let g=Vi(t,y);if(await oa(g))console.log(`Safety Warning: File already exists: ${g}. Skip writing.`);else{let S=Hd[a]||Hd.unknown;await de.mkdir(Ct.dirname(g),{recursive:!0}),await de.writeFile(g,S,"utf-8"),console.log(`Created starter template: ${g}`)}}else console.log("No valid template selection received. Skipping template generation.")}}}else{try{await de.access(i),console.log(`Config already exists: ${i}`),console.log("Remove it first if you want to reinitialize.");return}catch{}await de.writeFile(i,JSON.stringify(Fd,null,2)+`
267
+ `,"utf-8"),console.log(`Created ${i}`),console.log("Edit it to set include/exclude patterns, severityThreshold, and projectType.")}let l=Vi(t,".gitignore");if(await oa(l)){let p=await de.readFile(l,"utf-8");if(!p.split(/\r?\n/).some(f=>{let h=f.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\//,"");return h===".promptci"||h.startsWith(".promptci/")||h.endsWith("/.promptci")||h.includes("/.promptci/")})){let f;if(s){let h=await o("Ignore .promptci/ reports in .gitignore (keeping baseline.json and config.json committed)? (recommended) [Y/n]: ");f=h===""||h.toLowerCase()==="y"||h.toLowerCase()==="yes"}else f=!0;if(f){let h=p.includes(`\r
268
+ `)?`\r
269
+ `:`
270
+ `,b=`${p.length>0&&!p.endsWith(`
271
+ `)?h:""}${Pn(h)}`;await de.appendFile(l,b,"utf-8"),console.log("\u2714 Added .promptci/ report ignore to .gitignore (baseline.json and config.json stay committed)")}}}}var qd=E(require("node:fs/promises"),1),aa=E(require("node:path"),1);var qi=E(require("node:fs/promises"),1),Ge=E(require("node:path"),1),Vd=E(require("node:readline/promises"),1);var Pt=class extends Error{constructor(e){super(e),this.name="NonInteractiveError"}},Wd="=".repeat(80),Ex="-".repeat(80);async function Ui(t,e){let n=e.log??((h="")=>console.log(h)),i=e.interactive!==!1,s=e.promptText??`
272
+ Apply this change? (y/N): `,r=!e.dryRun&&i&&!e.answers?Vd.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 p=0,u=0,d=0,f=new Set;try{for(let h of t){let m=(h.skipIfModified??[]).map(S=>Ge.resolve(e.repoRoot,S)).filter(S=>f.has(S));if(m.length>0){n(`
273
+ `+Wd);for(let $ of h.headerLines??[])n($);let S=m.map($=>Ge.relative(e.repoRoot,$)).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.`),u++;continue}let b=typeof h.changes=="function"?await h.changes():h.changes,y=Cx(b);if(y.length===0)continue;n(`
274
+ `+Wd);let v=h.headerLines??[];for(let S of v)n(S);v.length>0&&n(Ex);for(let S of y)Px(S,e.repoRoot,n);if(e.dryRun){n(`
275
+ [Dry run] No changes written.`);continue}let g=!0;if(i)if(e.answers){let S=e.answers[d]??"n";d++,n(`${s}${S}`),g=S.toLowerCase().trim()==="y"}else if(r){let S=await l(s);if(S===null)throw new Pt("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.");g=S.toLowerCase().trim()==="y"}else g=!1;if(!g){n("Skipped.");continue}for(let S of y){let $=Ge.resolve(e.repoRoot,S.filePath);if(!He(e.repoRoot,$))throw new Error(`Path traversal guard triggered: "${S.filePath}" is outside repo root.`);await qi.mkdir(Ge.dirname($),{recursive:!0}),await qi.writeFile($,S.newContent,"utf-8"),f.add($),n(`Applied change to ${Ge.relative(e.repoRoot,$)}`)}p++}}finally{r?.close()}return{appliedCount:p,staleSkippedCount:u}}function Cx(t){let e=new Map;for(let n of t){let i=Ge.resolve(n.filePath),s=e.get(i);if(!s)e.set(i,n);else if(s.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 Px(t,e,n){let i=Ge.relative(e,t.filePath);if(t.originalContent===""){n(`File: ${i} (new file)`);for(let l of t.newContent.split(/\r?\n/))n(`\x1B[32m+ ${l}\x1B[0m`);return}n(`File: ${i}`);let s=t.originalContent.split(/\r?\n/),r=t.newContent.split(/\r?\n/);if(s.length===r.length){for(let l=0;l<s.length;l++)s[l]!==r[l]&&(n(` Line ${l+1}:`),n(`\x1B[31m- ${s[l]}\x1B[0m`),n(`\x1B[32m+ ${r[l]}\x1B[0m`));return}let o=0;for(;o<s.length&&o<r.length&&s[o]===r[o];)o++;let a=s.length-1,c=r.length-1;for(;a>=o&&c>=o&&s[a]===r[c];)a--,c--;n(` Replacement in lines ${o+1} to ${a+1}:`);for(let l=o;l<=a;l++)s[l]!==void 0&&n(`\x1B[31m- ${s[l]}\x1B[0m`);for(let l=o;l<=c;l++)r[l]!==void 0&&n(`\x1B[32m+ ${r[l]}\x1B[0m`)}async function Ud(t){let e=t.scanPath??process.cwd(),n=aa.resolve(e);try{(await qd.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 i;try{i=await Oe(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 s=await ze({repoPath:n,projectType:i.projectType,include:i.include,exclude:i.exclude,vagueGuidanceSeverity:i.vagueGuidanceSeverity}),r=s.issues.filter(l=>na(l));if(t.issueId){let l=r.find(p=>p.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:()=>ta(l,n),skipIfModified:l.category==="duplicate"?l.locations.map(p=>aa.resolve(n,p.filePath)):void 0})),a,c;try{({appliedCount:a,staleSkippedCount:c}=await Ui(o,{repoRoot:n,dryRun:t.dryRun,interactive:t.interactive,answers:t.answers,promptText:`
276
+ Apply this fix? (y/N): `}))}catch(l){throw l instanceof Pt&&(console.error(`Error: ${l.message}`),process.exit(1)),l}if(a>0&&!t.dryRun){console.log(`
277
+ Re-scanning repository...`);let l=await ze({repoPath:n,projectType:i.projectType,include:i.include,exclude:i.exclude,vagueGuidanceSeverity:i.vagueGuidanceSeverity});console.log(`
278
+ Fixes complete. Initial score: ${s.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(`
297
279
  Dry run complete. No changes were made.`):console.log(`
298
- No changes applied.`)}function qw(t){return t.id==="security-pack-no-promptci-gitignore"||t.id==="security-pack-unignored-dirs"||t.category==="duplicate"&&t.locations.length>=2?!0:t.id.startsWith("stale-")&&t.category==="stale_instruction"?t.evidence.some(e=>e.includes("Year reference(s) that may be outdated")):!1}function Ww(t,e){let n=Ae.relative(e,t.filePath);console.log(`File: ${n}`);let s=t.originalContent.split(/\r?\n/),i=t.newContent.split(/\r?\n/);if(s.length===i.length)for(let o=0;o<s.length;o++)s[o]!==i[o]&&(console.log(` Line ${o+1}:`),console.log(`\x1B[31m- ${s[o]}\x1B[0m`),console.log(`\x1B[32m+ ${i[o]}\x1B[0m`));else if(i.length>s.length&&t.newContent.startsWith(t.originalContent)){let r=t.newContent.slice(t.originalContent.length).split(/\r?\n/).filter(Boolean);console.log(" Append to end of file:");for(let a of r)console.log(`\x1B[32m+ ${a}\x1B[0m`)}else{let o=0;for(;o<s.length&&o<i.length&&s[o]===i[o];)o++;let r=s.length-1,a=i.length-1;for(;r>=o&&a>=o&&s[r]===i[a];)r--,a--;console.log(` Replacement in lines ${o+1} to ${r+1}:`);for(let c=o;c<=r;c++)s[c]!==void 0&&console.log(`\x1B[31m- ${s[c]}\x1B[0m`);for(let c=o;c<=a;c++)i[c]!==void 0&&console.log(`\x1B[32m+ ${i[c]}\x1B[0m`)}}async function zw(t,e){let n=[];console.warn(`Warning: PromptCI is sending the target instruction file section and issue description to the LLM to generate a safe fix. No other project codebase files are sent.
299
- `);let s="",i=[];for(let l=0;l<t.locations.length;l++){let u=t.locations[l];if(!u.startLine||!u.endLine)continue;let{contextText:p,sectionStartLine:d,sectionEndLine:f}=await Kw(e,u.filePath,u.startLine,u.endLine);i.push({filePath:u.filePath,startLine:d,endLine:f,contextText:p}),s+=`
300
- Target File Section ${l+1} (lines ${d}-${f} of ${u.filePath}):
301
- \`\`\`markdown
302
- ${p}
303
- \`\`\`
304
- `}if(i.length===0)return console.error("Error: No issue location line information available to perform LLM repair."),[];let o=`You are PromptCI, an expert AI instruction file repair tool. Rewrite the vague or conflicting section(s) of the AI instruction file(s) to resolve the specific issue, while retaining all safety constraints and rules.
305
- You must output a JSON object in this format:
306
- {
307
- "changes": [
308
- {
309
- "filePath": "relative/path/to/file.md",
310
- "newSection": "the rewritten section text"
311
- }
312
- ]
313
- }`,r=`Issue to resolve:
314
- Category: ${t.category}
315
- Title: ${t.title}
316
- Summary: ${t.summary}
317
-
318
- Context Section(s):
319
- ${s}
320
- Please rewrite each section to resolve the issue while keeping all other rules intact. Return the JSON object containing the replacement patch.`,a=await on(o,r,!0),c;try{c=JSON.parse(a.trim())}catch{let l=a.match(/\{[\s\S]*\}/);if(l)c=JSON.parse(l[0]);else throw new Error("LLM output was not valid JSON.")}if(!c.changes||!Array.isArray(c.changes))throw new Error('LLM output JSON structure is missing "changes" array.');for(let l of c.changes){if(typeof l.filePath!="string"||typeof l.newSection!="string")throw new Error("Invalid changes structure in LLM output JSON.");if(!Jw(l.filePath))throw new Error(`Safety Guard: Editing non-instruction file "${l.filePath}" is blocked.`);let p=Ae.resolve(e,l.filePath);if(!p.startsWith(e))throw new Error(`Path traversal guard triggered: "${l.filePath}" is outside repo root.`);let d=p.replace(/\\/g,"/").toLowerCase(),f=i.find(b=>Ae.resolve(e,b.filePath).replace(/\\/g,"/").toLowerCase()===d);if(!f)throw new Error(`LLM returned change for file "${l.filePath}" which was not scanned.`);let h=await yt.readFile(p,"utf-8"),g=h.split(/\r?\n/),y=[...g.slice(0,f.startLine-1),l.newSection,...g.slice(f.endLine)].join(`
321
- `);n.push({filePath:l.filePath,originalContent:h,newContent:y})}return n}async function Kw(t,e,n,s){let i=Ae.resolve(t,e),r=(await yt.readFile(i,"utf-8")).split(/\r?\n/),a=1;for(let u=n-1;u>=0;u--)if(r[u].trim().startsWith("#")){a=u+1;break}let c=r.length;for(let u=s;u<r.length;u++)if(r[u].trim().startsWith("#")){c=u;break}return{contextText:r.slice(a-1,c).join(`
322
- `),sectionStartLine:a,sectionEndLine:c}}function Jw(t){let e=t.replace(/\\/g,"/").toLowerCase(),n=Ae.basename(e);return e.endsWith(".md")||n===".cursorrules"||n===".windsurfrules"}var it=E(require("node:fs/promises"),1),de=E(require("node:path"),1),Kp=E(require("node:os"),1),ds=require("node:child_process");function Yw(t){let e=t.replace(/\\/g,"/").toLowerCase(),n=e.split("/"),s=[".git","node_modules","dist","build","temp","tmp","bin","obj","library"];if(n.some(r=>s.includes(r)))return!1;if(e.endsWith(".md"))return!0;let i=[".cursorrules",".windsurfrules","package.json","pyproject.toml",".gitignore","tsconfig.json"];if(e.endsWith(".promptci/config.json")||e===".promptci/config.json")return!0;let o=de.basename(e);return i.includes(o)?!0:e.startsWith(".github/workflows/")?e.endsWith(".yml")||e.endsWith(".yaml"):!!(e.startsWith("supabase/migrations/")||e.endsWith(".sln")||e.endsWith(".csproj")||e==="assets/projectsettings/projectversion.txt")}async function Jp(t){let e=t.scanPath??process.cwd(),n=de.resolve(e);try{if((0,ds.execSync)("git rev-parse --is-inside-work-tree",{cwd:n,stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()!=="true")throw new Error}catch{console.error(`Error: Path "${n}" is not inside a git repository, or git is not installed.`),process.exit(1)}let s;try{s=(0,ds.execSync)(`git ls-tree -r --name-only ${t.baseBranch}`,{cwd:n,stdio:["ignore","pipe","ignore"],encoding:"utf8"})}catch{console.error(`Error: Could not retrieve file list for base branch/commit "${t.baseBranch}".`),process.exit(1)}let o=s.split(`
323
- `).map(a=>a.trim()).filter(Boolean).filter(Yw),r=await it.mkdtemp(de.join(Kp.tmpdir(),"promptci-review-"));try{for(let A of o)try{let _=(0,ds.execSync)(`git show ${t.baseBranch}:${A}`,{cwd:n,stdio:["ignore","pipe","ignore"],maxBuffer:10485760}),L=de.join(r,A);await it.mkdir(de.dirname(L),{recursive:!0}),await it.writeFile(L,_)}catch{}let a=await Ee({repoPath:r,projectType:"auto"}),c;try{c=await X(n)}catch{c={projectType:"auto"}}let l=await Ee({repoPath:n,projectType:c.projectType,include:c.include,exclude:c.exclude}),u=(A,_)=>A.map(L=>{let D=L.filePaths.map(N=>de.relative(_,N).replace(/\\/g,"/")),w=L.locations.map(N=>{let F=de.relative(_,N.filePath);return{...N,filePath:F.replace(/\\/g,"/")}});return{...L,filePaths:D,locations:w}}),p=(A,_)=>A.map(L=>{let D=L.filePaths.map(N=>de.resolve(_,N)),w=L.locations.map(N=>({...N,filePath:de.resolve(_,N.filePath)}));return{...L,filePaths:D,locations:w}}),d=u(a.issues,r),f=u(l.issues,n),h=a.healthScore,g=l.healthScore,v=g-h,y=$t(d),b=$t(f),{newIssues:m}=Tt(f,y),{newIssues:x}=Tt(d,b),k=p(m,n),C=p(x,n);if(t.json){let A={baseScore:h,currentScore:g,scoreDelta:v,newIssuesCount:k.length,resolvedIssuesCount:C.length,newIssues:k.map(_=>({id:_.id,category:_.category,severity:_.severity,title:_.title,summary:_.summary,filePaths:_.filePaths,locations:_.locations})),resolvedIssues:C.map(_=>({id:_.id,category:_.category,severity:_.severity,title:_.title}))};process.stdout.write(JSON.stringify(A,null,2)+`
324
- `)}else{console.log(`PromptCI Branch Review (compared to ${t.baseBranch})`),console.log("--------------------------------------------------");let A="\x1B[32m";if(v<0?A="\x1B[31m":v===0&&(A="\x1B[0m"),console.log(`Health Score: ${h} -> ${g} (${A}${v>=0?"+":""}${v}\x1B[0m points)`),console.log(`New Issues: ${k.length}`),console.log(`Resolved: ${C.length}`),k.length>0){console.log(`
325
- [+] New Issues:`);for(let _ of k){let L=_.locations.length>0?`${_.locations[0].filePath}:${_.locations[0].startLine??""}`:_.filePaths.join(", "),D=_.severity==="critical"||_.severity==="high"?"\x1B[31m":"\x1B[33m";console.log(` - ${D}${_.severity.toUpperCase()}\x1B[0m: ${_.title} (${L})`),console.log(` Summary: ${_.summary}`),console.log(` Recommend: ${_.recommendation}`)}}if(C.length>0){console.log(`
326
- [-] Resolved Issues:`);for(let _ of C)console.log(` - \x1B[32mRESOLVED\x1B[0m: ${_.title}`)}}t.failOnRegression&&(v<0||k.length>0)&&(t.json||console.error(`
327
- \x1B[31mFailed: Regression detected in instruction files.\x1B[0m`),process.exit(1))}finally{try{await it.rm(r,{recursive:!0,force:!0})}catch{}}}var wr=E(require("node:fs/promises"),1),rt=E(require("node:path"),1);var ot=E(require("node:fs/promises"),1),yr=E(require("node:path"),1),hs=E(require("node:os"),1),Yp=require("node:child_process"),Qp=require("node:util"),Qw=(0,Qp.promisify)(Yp.execFile),Xp=yr.join(hs.homedir(),".promptci"),fs=yr.join(Xp,"auth.json");async function It(){try{let t=await ot.readFile(fs,"utf-8");return JSON.parse(t)}catch{return{}}}async function qe(t){await ot.mkdir(Xp,{recursive:!0}),await ot.writeFile(fs,JSON.stringify(t,null,2),"utf-8");try{await ot.chmod(fs,384)}catch{}process.platform==="win32"&&await Xw(fs)}async function Xw(t){try{let e=hs.userInfo().username;await Qw("icacls",[t,"/inheritance:r","/grant:r",`${e}:F`])}catch{}}async function Zp(){await qe({})}function cn(t){try{let[,e]=t.split(".");if(!e)return null;let n=Buffer.from(e,"base64url").toString("utf-8"),s=JSON.parse(n);return typeof s.exp=="number"?s.exp:null}catch{return null}}var br=(typeof __SUPABASE_URL__<"u"?__SUPABASE_URL__:"")||process.env.SUPABASE_URL||"";async function ed(){let t=await It();if(!t.access_token)throw new Error("Not logged in. Run: promptci login");let e=Math.floor(Date.now()/1e3)+300;if((t.expires_at??0)>e)return t.access_token;if(!t.refresh_token)throw new Error("Session expired. Run: promptci login");let i=`${Zw(t.access_token)}/auth/v1/token?grant_type=refresh_token`,o;try{o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:t.refresh_token})})}catch{throw new Error("Session expired. Run: promptci login")}if(!o.ok)throw new Error("Session expired. Run: promptci login");let r=await o.json(),a=Math.floor(Date.now()/1e3)+(r.expires_in??3600);return await qe({access_token:r.access_token,refresh_token:r.refresh_token,expires_at:a}),r.access_token}function Zw(t){if(br)return br.replace(/\/$/,"");try{let[,e]=t.split(".");if(!e)throw new Error("bad jwt");let n=Buffer.from(e,"base64url").toString("utf-8"),s=JSON.parse(n);if(s.iss)return s.iss.replace(/\/auth\/v1\/?$/,"")}catch{}throw new Error("Could not determine Supabase URL. Set the SUPABASE_URL environment variable.")}var Ot=E(require("node:fs/promises"),1),vr=E(require("node:path"),1),td=E(require("node:os"),1),nd=vr.join(td.homedir(),".promptci"),sd=vr.join(nd,"global.json");async function jt(){try{let t=await Ot.readFile(sd,"utf-8");return JSON.parse(t)}catch{return{}}}async function Nt(t){await Ot.mkdir(nd,{recursive:!0}),await Ot.writeFile(sd,JSON.stringify(t,null,2),"utf-8")}async function id(t){let e=rt.resolve(t.uploadPath??process.cwd()),n=rt.join(e,".promptci"),s=rt.join(n,"report.json"),i=rt.join(n,"latest.md"),o;try{o=await X(e)}catch{o={}}let r=await jt(),a=(t.url??process.env.PROMPTCI_API_URL??o.apiUrl??r.apiUrl??"http://localhost:3000").replace(/\/$/,"");t.url&&await Nt({...r,apiUrl:a});let c;try{c=await wr.readFile(s,"utf-8")}catch{console.error(`Error: no report found at ${s}`),console.error('Run "promptci scan" first to generate a report.'),process.exit(1)}let l;try{l=JSON.parse(c)}catch{console.error(`Error: ${s} contains invalid JSON.`),process.exit(1)}let u="";try{u=await wr.readFile(i,"utf-8")}catch{}let p=rt.basename(l.repoPath)||"unknown",d=`${a}/api/upload`,f;try{f=await ed()}catch(m){let x=m instanceof Error?m.message:String(m);console.error(`Error: ${x}`),(x.includes("Not logged in")||x.includes("Session expired"))&&console.error(`Run \`promptci login --url ${a}\` to authenticate.`),process.exit(1)}console.log(`Uploading report for "${p}" to ${a} ...`);let h=15e3,g=2,v,y;for(let m=0;m<=g;m++){m>0&&(await new Promise(x=>setTimeout(x,m*1e3)),console.error(`Retrying\u2026 (attempt ${m+1} of ${g+1})`));try{v=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`},body:JSON.stringify({report:l,repoName:p,markdown:u}),signal:AbortSignal.timeout(h)});break}catch(x){if(y=x,!(x instanceof TypeError||x instanceof DOMException&&x.name==="TimeoutError"||x instanceof Error&&x.name==="AbortError")||m===g){let C=x instanceof Error?x.message:String(x),A=x instanceof DOMException&&x.name==="TimeoutError";console.error(A?`Error: request timed out after ${h/1e3}s`:`Error: could not reach ${d}`),A||console.error(C),console.error(`
328
- Make sure the dashboard is running or set PROMPTCI_API_URL.`),process.exit(1)}}}if(!v){let m=y instanceof Error?y.message:String(y);console.error(`Error: could not reach ${d}
329
- ${m}`),process.exit(1)}if(!v.ok){let m="";try{m=await v.text()}catch{}console.error(`Error: upload failed (HTTP ${v.status})`),m&&console.error(m),process.exit(1)}let b;try{b=await v.json()}catch{console.error("Error: unexpected response from server."),process.exit(1)}console.log(`
330
- Report uploaded successfully.`),console.log(`View at: ${b.url}`)}var ex="http://localhost:3000",tx=6e4;async function od(t){let e={};try{e=await X(process.cwd())}catch{e={}}let n=await jt(),s=(t.url??process.env.PROMPTCI_API_URL??e.apiUrl??n.apiUrl??ex).replace(/\/$/,"");t.url&&await Nt({...n,apiUrl:s}),console.log("Starting CLI login...");let i;try{let l=await fetch(`${s}/api/cli/device/init`,{method:"POST"});if(!l.ok){console.error(`Error: could not start login (HTTP ${l.status}).`),process.exitCode=1;return}i=await l.json()}catch(l){console.error(`Error: could not reach ${s}. ${l instanceof Error?l.message:String(l)}`),process.exitCode=1;return}let o=`${s}/auth/device?user_code=${encodeURIComponent(i.userCode)}`;console.log(`
331
- Confirm this code matches what's shown in your browser: ${i.userCode}
332
- `),console.log("Opening your browser to authenticate..."),console.log(`URL: ${o}
333
- `),await sx(o)||console.log(`Could not open a browser automatically. Open the URL above manually.
334
- `),console.log("Waiting for you to authorize this login in the browser...");let a=Date.now()+Math.max(i.expiresIn*1e3,tx),c=Math.max(i.interval,0)*1e3;for(;Date.now()<a;){await nx(c);let l;try{l=await fetch(`${s}/api/cli/device/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceCode:i.deviceCode})})}catch{continue}if(l.ok){let p=await l.json(),d=cn(p.accessToken)??Math.floor(Date.now()/1e3)+3600;await qe({access_token:p.accessToken,refresh_token:p.refreshToken,expires_at:d}),console.log(`
335
- \u2713 Logged in and token stored in ~/.promptci/auth.json`),console.log(`You can now run: promptci upload
336
- `);return}let u=await l.json().catch(()=>({}));if(u.error!=="authorization_pending"){console.error(`
337
- Login failed: ${u.error??`HTTP ${l.status}`}`),process.exitCode=1;return}}console.error("\nLogin timed out waiting for browser authorization. Run `promptci login` again."),process.exitCode=1}function nx(t){return new Promise(e=>setTimeout(e,t))}async function sx(t){let{exec:e}=await import("node:child_process"),{promisify:n}=await import("node:util"),s=n(e),i=process.platform,o;i==="win32"?o=`start "" "${t}"`:i==="darwin"?o=`open "${t}"`:o=`xdg-open "${t}"`;try{return await s(o),!0}catch{return!1}}async function rd(t,e){switch(t){case"set-token":{let n=e[0];n||(console.error("Error: token argument is required."),console.error("Usage: promptci auth set-token <token>"),process.exit(1));let s=ix(n);if(s){let i=cn(s.access_token)??Math.floor(Date.now()/1e3)+3600;await qe({access_token:s.access_token,refresh_token:s.refresh_token,expires_at:i}),console.log("\u2713 Token stored in ~/.promptci/auth.json"),console.log("You can now run: promptci upload")}else if(n.startsWith("ey")){let i=cn(n)??Math.floor(Date.now()/1e3)+3600;await qe({access_token:n,expires_at:i}),console.log("\u2713 Token stored in ~/.promptci/auth.json"),console.log("Note: this token expires in ~1 hour. Run `promptci login` again once it expires."),console.log("You can now run: promptci upload")}else console.warn("Warning: this does not look like a valid token. Make sure you copied the full token."),await qe({access_token:n}),console.log("\u2713 Token stored in ~/.promptci/auth.json"),console.log("You can now run: promptci upload");break}case"status":{let n=await It(),s=n.access_token;if(s){if(console.log("\u2713 Authenticated \u2014 token is set."),console.log(` Token starts with: ${s.slice(0,20)}...`),n.refresh_token)console.log(" Auto-refresh: enabled (does not expire)");else if(n.expires_at){let i=n.expires_at-Math.floor(Date.now()/1e3);i>0?console.log(` Expires in: ${Math.round(i/60)} minutes`):console.log(" Token has expired. Run: promptci login")}}else console.log("\u2717 Not authenticated."),console.log(" Run: promptci login");break}case"logout":{await Zp(),console.log("\u2713 Token cleared. You are now signed out.");break}default:console.error(`Unknown auth subcommand: ${t}`),console.error("Available: set-token, status, logout"),process.exit(1)}}function ix(t){try{let e=Buffer.from(t,"base64").toString("utf-8"),n=JSON.parse(e);if(typeof n=="object"&&n!==null&&typeof n.access_token=="string"&&typeof n.refresh_token=="string")return n}catch{}return null}var ln=require("node:child_process"),ad=E(require("node:fs/promises"),1),De=E(require("node:path"),1);function ox(){let t;try{t=(0,ln.execSync)("pnpm config get global-bin-dir",{stdio:"pipe"}).toString().trim()}catch{return}let e=(process.env.PATH??"").split(De.delimiter),n=o=>o.replace(/\\/g,"/").replace(/\/$/,"").toLowerCase(),s=n(t);if(e.some(o=>n(o)===s))return;let i;try{let o=(0,ln.execSync)(process.platform==="win32"?"where pnpm":"which pnpm",{stdio:"pipe"}).toString().trim().split(/\r?\n/)[0].trim();i=De.dirname(o)}catch{return}try{(0,ln.execSync)(`pnpm config set global-bin-dir "${i}"`,{stdio:"pipe"}),console.log(` note: repaired pnpm global-bin-dir \u2192 ${i}`)}catch{}}async function cd(t){let e=await jt(),n=t.source?De.resolve(t.source):e.sourceDir?De.resolve(e.sourceDir):null;n||(console.error(["PromptCI source directory not configured.","","Set it once with:"," promptci update --source <path-to-PromptCI-repo>","","Example:"," promptci update --source C:\\git\\SeriousGeese\\PromptCI"].join(`
338
- `)),process.exit(1));try{await ad.access(De.join(n,"pnpm-workspace.yaml"))}catch{console.error(`Directory does not look like the PromptCI repo (missing pnpm-workspace.yaml):
339
- ${n}`),process.exit(1)}n!==e.sourceDir&&(await Nt({...e,sourceDir:n}),console.log(`Saved source directory: ${n}
340
- `));let s=De.join(n,"packages","cli");ox();let i=[{label:"git pull",cmd:"git pull origin main",cwd:n},{label:"pnpm install",cmd:"pnpm install",cwd:n},{label:"pnpm build",cmd:"pnpm build",cwd:n},{label:"pnpm link --global",cmd:"pnpm link --global",cwd:s}];console.log(`Updating PromptCI from ${n}
341
- `);for(let o of i){process.stdout.write(` ${o.label} ... `);try{(0,ln.execSync)(o.cmd,{cwd:o.cwd,stdio:"pipe"}),console.log("done")}catch(r){console.log("FAILED");let a=r,c=r instanceof Error&&"stderr"in r?a.stderr?.toString().trim():String(r);c&&console.error(`
342
- ${c}
343
- `),console.error(`Update failed at: ${o.label}`),process.exit(1)}}console.log(`
344
- \u2714 PromptCI updated successfully.`)}var Mt=E(require("node:fs/promises"),1),at=E(require("node:path"),1);async function ud(t){let e=at.resolve(t);try{(await Mt.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 ld(t){return{critical:0,high:1,warning:2,info:3}[t.severity]}function rx(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-cost issues found.");else{e.push("Context-cost issues:");for(let n of[...t.issues].sort((s,i)=>ld(s)-ld(i)))e.push(`- [${n.severity}] ${n.title}`)}return e.push(""),e.join(`
345
- `)}async function pd(t){let e=await ud(t.scanPath??process.cwd()),n;try{n=await X(e)}catch(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exit(1)}let s=await ur({repoPath:e,projectType:n.projectType,include:n.include,exclude:n.exclude});t.json?process.stdout.write(JSON.stringify(s,null,2)+`
346
- `):process.stdout.write(rx(s))}async function dd(t){let e=await ud(t.scanPath??process.cwd()),n;try{n=await X(e)}catch(o){console.error(`Error loading config: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}let s=await Wt({repoPath:e,projectType:n.projectType,include:n.include,exclude:n.exclude}),{changes:i}=await hr(s,{repoRoot:e});if(i.length===0){J("No cache optimization changes needed.");return}t.dryRun?J(`
347
- Proposed caching optimization changes (${i.length} change(s)):`):J(`
348
- Applying caching optimization changes (${i.length} change(s)):`);for(let o of i)J(`
349
- ================================================================================`),ax(o,e),J("--------------------------------------------------------------------------------"),t.dryRun?J(`[Dry Run] Simulating optimization for ${at.relative(e,o.filePath)}. No changes written.`):(await Mt.mkdir(at.dirname(o.filePath),{recursive:!0}),await Mt.writeFile(o.filePath,o.newContent,"utf-8"),J(`Applied change to ${at.relative(e,o.filePath)}`));t.dryRun?J(`
350
- Dry run complete. No changes were made.`):J(`
351
- Optimization complete.`)}function J(t=""){process.stdout.write(t+`
352
- `)}function ax(t,e){let n=at.relative(e,t.filePath);if(t.originalContent===""){J(`File: ${n} (new file)`);let o=t.newContent.split(/\r?\n/);for(let r of o)J(`\x1B[32m+ ${r}\x1B[0m`);return}J(`File: ${n}`);let s=t.originalContent.split(/\r?\n/),i=t.newContent.split(/\r?\n/);if(s.length===i.length)for(let o=0;o<s.length;o++)s[o]!==i[o]&&(J(` Line ${o+1}:`),J(`\x1B[31m- ${s[o]}\x1B[0m`),J(`\x1B[32m+ ${i[o]}\x1B[0m`));else{let o=0;for(;o<s.length&&o<i.length&&s[o]===i[o];)o++;let r=s.length-1,a=i.length-1;for(;r>=o&&a>=o&&s[r]===i[a];)r--,a--;J(` Replacement in lines ${o+1} to ${r+1}:`);for(let c=o;c<=r;c++)s[c]!==void 0&&J(`\x1B[31m- ${s[c]}\x1B[0m`);for(let c=o;c<=a;c++)i[c]!==void 0&&J(`\x1B[32m+ ${i[c]}\x1B[0m`)}}var fd=E(require("node:fs/promises"),1),un=E(require("node:path"),1);async function hd(t){let e=t.scanPath??process.cwd(),n=un.resolve(e);try{(await fd.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 X(n)}catch(u){console.error(`Error loading config: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}let i=await Ee({repoPath:n,projectType:s.projectType,include:s.include,exclude:s.exclude});if(i.issues.length===0){console.log("No issues found. Your instruction files are clean!");return}let o={};for(let u of i.issues)o[u.category]=(o[u.category]||0)+1;console.warn(`Warning: PromptCI is sending scan results metadata (issue categories, counts, file sizes) to the LLM. No source code or instruction file contents are sent.
353
- `);let r="You are PromptCI, an AI assistant analyzing instruction-health scan reports. Write a concise, prioritized human-readable cleanup plan (3-5 items) with actionable advice for the developer based on the scan results. Focus on the most important issues and make your suggestions brief.",a=i.filesScanned.map(u=>`- ${un.relative(n,u.path)} (${u.charCount} characters)`).join(`
354
- `),c=i.issues.map(u=>{let p=u.filePaths.map(d=>un.relative(n,d)).join(", ");return`- [${u.severity.toUpperCase()}] ${u.title} (${p}): ${u.summary}`}).join(`
355
- `),l=`Scan Results:
356
- Total Health Score: ${i.healthScore}/100
357
-
358
- Category Counts:
359
- ${JSON.stringify(o,null,2)}
360
-
361
- Scanned Files:
362
- ${a}
363
-
364
- Issues Identified:
365
- ${c}`;try{let u=await on(r,l);console.log("PromptCI LLM Cleanup Roadmap:"),console.log("--------------------------------------------------"),console.log(u.trim())}catch(u){console.error(`Error generating LLM explanation: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}}var Dt=E(require("node:fs/promises"),1),pn=E(require("node:path"),1),md=require("node:child_process");async function gd(t){let e=t.scanPath??process.cwd(),n=pn.resolve(e);try{(await Dt.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)>=20,r="",a=!1;try{r=(0,md.execSync)("promptci --version",{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim(),a=!0}catch{r="Not linked globally (run pnpm link -g or npm link -g if desired)"}let c=!0,l="",u="http://localhost:3000",p=pn.join(n,".promptci","config.json");try{await Dt.access(p);try{let A=await X(n);l="Valid configuration file found",A.apiUrl&&(u=A.apiUrl)}catch(A){c=!1,l=`Invalid configuration: ${A instanceof Error?A.message:String(A)}`}}catch{l="No configuration file found (using default rules)"}let d=!1,f="",h=pn.join(n,".gitignore");try{(await Dt.readFile(h,"utf-8")).split(/\r?\n/).some(D=>{let w=D.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\//,"");return w===".promptci"||w.startsWith(".promptci/")||w.endsWith("/.promptci")||w.includes("/.promptci/")})?(d=!0,f=".promptci/ is ignored in .gitignore"):f=".promptci/ is not ignored in .gitignore"}catch{f="No .gitignore file found in target path"}let g=process.env.OPENAI_API_KEY,v=process.env.ANTHROPIC_API_KEY,y=!!g||!!v,b=await It(),m=Math.floor(Date.now()/1e3),x=!!b.access_token&&(!b.expires_at||b.expires_at>m),k=!1,C="";try{let A=new AbortController,_=setTimeout(()=>A.abort(),3e3),L=await globalThis.fetch(`${u}/api/health`,{signal:A.signal});clearTimeout(_),L.ok?(k=!0,C=`Connected to dashboard at ${u}`):C=`Dashboard at ${u} returned status ${L.status}`}catch(A){C=`Could not connect to ${u}: ${A instanceof Error?A.message:String(A)}`}if(console.log("PromptCI System Diagnostics (Doctor)"),console.log("--------------------------------------------------"),o?console.log(`\x1B[32m[\u2713]\x1B[0m Node.js version >= 20 (${process.version})`):(console.log(`\x1B[31m[\u2717]\x1B[0m Node.js version is too old (${process.version}). Upgrade to Node 20+`),s=!0),console.log(a?`\x1B[32m[\u2713]\x1B[0m Global CLI executable is linked (${r})`:`\x1B[33m[!]\x1B[0m Global CLI executable: ${r}`),c?console.log(`\x1B[32m[\u2713]\x1B[0m Config file schema: ${l}`):(console.log(`\x1B[31m[\u2717]\x1B[0m Config file schema: ${l}`),s=!0),d?console.log(`\x1B[32m[\u2713]\x1B[0m Gitignore protection: ${f}`):(console.log(`\x1B[31m[\u2717]\x1B[0m Gitignore protection: ${f}`),s=!0),y){let A=[g?"OpenAI":"",v?"Anthropic":""].filter(Boolean).join(", ");console.log(`\x1B[32m[\u2713]\x1B[0m LLM API Keys: Configured (${A})`)}else console.log(x?"\x1B[36m[i]\x1B[0m LLM API Keys: Local keys not configured (LLM features will use the dashboard server-side API)":"\x1B[33m[!]\x1B[0m LLM API Keys: Neither OPENAI_API_KEY nor ANTHROPIC_API_KEY is configured (explain/fix LLM features disabled)");console.log(x?"\x1B[32m[\u2713]\x1B[0m Dashboard Authentication: Authenticated":"\x1B[33m[!]\x1B[0m Dashboard Authentication: Not authenticated (run promptci login to set up)"),console.log(k?`\x1B[32m[\u2713]\x1B[0m Dashboard connection: ${C}`:`\x1B[33m[!]\x1B[0m Dashboard connection: ${C}`),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 be=new jr;be.name("promptci").description("Instruction health for AI coding workflows").version("0.0.1","-v, --version","print version");be.command("scan").description("Scan instruction files and generate a health report").option("--path <dir>","target directory to scan (default: current directory)").option("--json","print JSON report to stdout (files are still written)").option("--output <file>","write markdown report to this path instead of default").option("--fail-on <severity>","exit non-zero if any issue meets or exceeds this severity (info|warning|high|critical)").option("--baseline <path>","load baseline from file (relative to scan path)").option("--update-baseline","run scan and write result as the new baseline").option("--fail-on-new <severity>","exit non-zero only if NEW issues (not in baseline) meet this threshold").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)").action(async t=>{await Hp({scanPath:t.path,json:t.json,output:t.output,failOn:t.failOn,baseline:t.baseline,updateBaseline:t.updateBaseline,failOnNew:t.failOnNew,failOnBudget:t.failOnBudget,contextBudget:t.contextBudget?parseInt(t.contextBudget,10):void 0,fileContextBudget:t.fileContextBudget?parseInt(t.fileContextBudget,10):void 0})});be.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").option("--llm","use an LLM to automatically resolve vague or conflicting instructions").action(async t=>{await zp({scanPath:t.path,issueId:t.issue,interactive:t.interactive,dryRun:t.dryRun||!1,llm:t.llm||!1})});be.command("explain").description("Generate a prioritized, human-readable cleanup plan for scan issues using an LLM").option("--path <dir>","target directory to scan and explain (default: current directory)").action(async t=>{await hd({scanPath:t.path})});be.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").action(async t=>{await Jp({baseBranch:t.base||"main",scanPath:t.path,json:t.json||!1,failOnRegression:t.failOnRegression||!1})});be.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 qp(t.path??process.cwd(),{interactive:process.stdin.isTTY})});be.command("doctor").description("Verify local PromptCI configuration, gitignore settings, and system dependencies").option("--path <dir>","target directory (default: current directory)").action(async t=>{await gd({scanPath:t.path})});be.command("upload").description("Upload the latest scan report to your PromptCI dashboard").option("--path <dir>","repo directory containing .promptci/ (default: current directory)").option("--url <url>","dashboard API URL (overrides PROMPTCI_API_URL and config; default: http://localhost:3000)").action(async t=>{await id({uploadPath:t.path,url:t.url})});var yd=be.command("context").description("Analyze instruction context size, cost, and retrieval-readiness");yd.command("analyze").description("Print deterministic context-cost 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 pd({scanPath:t.path,json:t.json})});yd.command("optimize").description("Automatically refactor instruction files by splitting volatile or large sections").option("--path <dir>","target directory to optimize (default: current directory)").option("--dry-run","output a diff of what would change without modifying files").action(async t=>{await dd({scanPath:t.path,dryRun:t.dryRun})});be.command("login").description("Authenticate the CLI with your PromptCI dashboard via GitHub OAuth").option("--url <url>","dashboard URL (overrides PROMPTCI_API_URL; default: http://localhost:3000)").action(async t=>{await od({url:t.url})});be.command("auth <subcommand> [args...]").description(`Manage CLI authentication tokens
366
- set-token <token> Store your access token
367
- status Show current auth state
368
- logout Clear stored token`).action(async(t,e)=>{await rd(t,e)});be.command("update").description("Pull latest changes, rebuild, and re-link the CLI globally").option("--source <path>","path to the cloned PromptCI repo (saved for future updates)").action(async t=>{await cd({source:t.source})});be.parseAsync(process.argv).catch(t=>{console.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)});
280
+ No changes applied.`)}var ut=E(require("node:fs/promises"),1),ee=E(require("node:path"),1),Kd=E(require("node:os"),1),Jd=require("node:child_process");var Yd=["info","warning","high","critical"];function Ax(t){return Yd.includes(t)}async function Rx(t){try{return await ut.access(t),!0}catch{return!1}}function At(t,e){return(0,Jd.execFileSync)("git",t,{cwd:e,stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:32*1024*1024}).trim()}function zd(t,e,n){At(["worktree","add","--detach",n,e],t)}function kx(t){try{return At(["rev-parse","--is-shallow-repository"],t)==="true"}catch{return!1}}function $x(t,e){try{At(["worktree","remove","--force",e],t)}catch{}}async function Xd(t){let e=t.scanPath??process.cwd(),n=ee.resolve(e);t.failOn!==void 0&&!Ax(t.failOn)&&(console.error(`Error: invalid --fail-on value "${t.failOn}". Must be one of: ${Yd.join(", ")}`),process.exit(1));let i;try{i=ee.resolve(At(["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 s=ee.relative(i,n),r;try{r=At(["rev-parse","--verify",`${t.baseBranch}^{commit}`],i)}catch{let f=kx(i);console.error(`Error: Could not resolve base branch/commit "${t.baseBranch}".`),console.error(f?"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=At(["rev-parse","--verify","HEAD^{commit}"],i)}catch{console.error("Error: Could not resolve HEAD. Use --working-tree to compare uncommitted files."),process.exit(1)}let a;try{a=await Oe(n)}catch(f){console.error(`Error: ${f instanceof Error?f.message:String(f)}`),process.exit(1)}let c=await ut.mkdtemp(ee.join(Kd.tmpdir(),"promptci-review-")),l=ee.join(c,"base"),p=ee.join(c,"head"),u=[],d=!1;try{try{zd(i,r,l),u.push(l),o&&(zd(i,o,p),u.push(p))}catch(j){console.error(`Error: Could not check out a temporary worktree: ${j instanceof Error?j.message:String(j)}`),process.exitCode=1;return}let f=ee.join(l,s);if(s!==""&&!await Rx(f)){let j=ee.join(c,"empty-base");await ut.mkdir(j,{recursive:!0}),f=j,console.error(`Note: "${s.replace(/\\/g,"/")}" does not exist in the base commit (${r.slice(0,8)}); every finding under it is reported as new.`)}let h=o?ee.join(p,s):n,m={projectType:a.projectType,include:a.include,exclude:a.exclude,contextBudget:a.contextBudget,fileContextBudget:a.fileContextBudget,targetModel:a.targetModel,vagueGuidanceSeverity:a.vagueGuidanceSeverity},b=await ze({repoPath:f,...m}),y=await ze({repoPath:h,...m}),v=(j,T)=>(ee.isAbsolute(j)?ee.relative(T,j):j).replace(/\\/g,"/"),g=(j,T)=>j.map(z=>({...z,filePaths:z.filePaths.map(X=>v(X,T)),locations:z.locations.map(X=>({...X,filePath:v(X.filePath,T)}))})),S=(j,T)=>j.map(z=>{let X=z.filePaths.map(We=>ee.resolve(T,We)),ae=z.locations.map(We=>({...We,filePath:ee.resolve(T,We.filePath)}));return{...z,filePaths:X,locations:ae}}),$=g(b.issues,f),P=g(y.issues,h),O=b.healthScore,C=y.healthScore,I=C-O,U=Wt($),x=Wt(P),{newIssues:H}=Vt(P,U),{newIssues:B}=Vt($,x),oe=S(H,n),w=S(B,n);if(t.json){let j={baseScore:O,currentScore:C,scoreDelta:I,newIssuesCount:oe.length,resolvedIssuesCount:w.length,newIssues:oe.map(T=>({id:T.id,category:T.category,severity:T.severity,title:T.title,summary:T.summary,filePaths:T.filePaths,locations:T.locations})),resolvedIssues:w.map(T=>({id:T.id,category:T.category,severity:T.severity,title:T.title}))};process.stdout.write(JSON.stringify(j,null,2)+`
281
+ `)}else{console.log(`PromptCI Branch Review (compared to ${t.baseBranch})`),console.log("--------------------------------------------------");let j="\x1B[32m";if(I<0?j="\x1B[31m":I===0&&(j="\x1B[0m"),console.log(`Health Score: ${O} -> ${C} (${j}${I>=0?"+":""}${I}\x1B[0m points)`),console.log(`New Issues: ${oe.length}`),console.log(`Resolved: ${w.length}`),oe.length>0){console.log(`
282
+ [+] New Issues:`);for(let T of oe){let z=T.locations.length>0?`${T.locations[0].filePath}:${T.locations[0].startLine??""}`:T.filePaths.join(", "),X=T.severity==="critical"||T.severity==="high"?"\x1B[31m":"\x1B[33m";console.log(` - ${X}${T.severity.toUpperCase()}\x1B[0m: ${T.title} (${z})`),console.log(` Summary: ${T.summary}`),console.log(` Recommend: ${T.recommendation}`)}}if(w.length>0){console.log(`
283
+ [-] Resolved Issues:`);for(let T of w)console.log(` - \x1B[32mRESOLVED\x1B[0m: ${T.title}`)}}t.failOnRegression&&(I<0||oe.length>0)&&(d=!0,t.json||console.error(`
284
+ \x1B[31mFailed: Regression detected in instruction files.\x1B[0m`));let _=t.failOn;if(_){let j=y.issues.filter(T=>sa(T.severity,_)).length;j>0&&(d=!0,t.json||console.error(`
285
+ \x1B[31mFailed: ${j} issue(s) at or above "${_}" threshold on this branch.\x1B[0m`))}}finally{for(let f of u)$x(i,f);try{await ut.rm(c,{recursive:!0,force:!0})}catch{}try{At(["worktree","prune"],i)}catch{}}d&&process.exit(1)}var Zd=E(require("node:fs/promises"),1),ef=E(require("node:path"),1);async function tf(t){let e=ef.resolve(t);try{(await Zd.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 Qd(t){return{critical:0,high:1,warning:2,info:3}[t.severity]}function Tx(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((i,s)=>Qd(i)-Qd(s)))e.push(`- [${n.severity}] ${n.title}`)}return e.push(""),e.join(`
286
+ `)}async function nf(t){let e=await tf(t.scanPath??process.cwd()),n;try{n=await Oe(e)}catch(s){console.error(`Error: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}let i=await ea({repoPath:e,projectType:n.projectType,include:n.include,exclude:n.exclude});t.json?process.stdout.write(JSON.stringify(i,null,2)+`
287
+ `):process.stdout.write(Tx(i))}async function sf(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 tf(t.scanPath??process.cwd()),i;try{i=await Oe(n)}catch(c){console.error(`Error loading config: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}let s=await fn({repoPath:n,projectType:i.projectType,include:i.include,exclude:i.exclude}),{changes:r}=await ia(s,{repoRoot:n});if(r.length===0){Rt("No cache optimization changes needed.");return}Rt(e?`
288
+ Applying caching optimization changes (${r.length} change(s)):`:`
289
+ Proposed caching optimization changes (${r.length} change(s)):`);let o=r.map(c=>({changes:[c]})),a;try{({appliedCount:a}=await Ui(o,{repoRoot:n,dryRun:!e,interactive:t.interactive??!1,answers:t.answers,input:t.input,promptText:`
290
+ Apply this change? (y/N): `,log:Rt}))}catch(c){throw c instanceof Pt&&(console.error(`Error: ${c.message}`),process.exit(1)),c}e?a>0?Rt(`
291
+ Optimization complete.`):Rt(`
292
+ No changes applied.`):Rt(`
293
+ Preview only \u2014 no changes were made. Re-run with --write to apply them.`)}function Rt(t=""){process.stdout.write(t+`
294
+ `)}var kt=E(require("node:fs/promises"),1),en=E(require("node:path"),1),rf=require("node:child_process");var la=22;async function Lx(t){try{return await kt.access(t),!0}catch{return!1}}async function of(t){let e=t.scanPath??process.cwd(),n=en.resolve(e);try{(await kt.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 i=!1,r=parseInt(process.versions.node.split(".")[0],10)>=la,o=ca().version,a,c="";try{c=(0,rf.execSync)("promptci --version",{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim(),a=c===o}catch{a=null}let l=!0,p,u=en.join(n,".promptci","config.json");try{await kt.access(u);try{await Oe(n),p="Valid configuration file found"}catch(b){l=!1,p=`Invalid configuration: ${b instanceof Error?b.message:String(b)}`}}catch{p="No configuration file found (using default rules)"}let d,f,h=await Lx(en.join(n,".git")),m=en.join(n,".gitignore");try{(await kt.readFile(m,"utf-8")).split(/\r?\n/).some(g=>{let S=g.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\//,"");return S===".promptci"||S.startsWith(".promptci/")||S.endsWith("/.promptci")||S.includes("/.promptci/")})?(d="ok",f=".promptci/ is ignored in .gitignore"):(d="missing-rule",f=".promptci/ is not ignored in .gitignore")}catch{h?(d="no-gitignore",f='No .gitignore file found (run "promptci init" to add the .promptci/ rules)'):(d="not-a-repo",f="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 >= ${la} (${process.version})`):(console.log(`\x1B[31m[\u2717]\x1B[0m Node.js version is too old (${process.version}). Upgrade to Node ${la}+`),i=!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: ${p}`):(console.log(`\x1B[31m[\u2717]\x1B[0m Config file schema: ${p}`),i=!0),d==="ok"?console.log(`\x1B[32m[\u2713]\x1B[0m Gitignore protection: ${f}`):d==="missing-rule"?(console.log(`\x1B[31m[\u2717]\x1B[0m Gitignore protection: ${f}`),i=!0):console.log(d==="no-gitignore"?`\x1B[33m[!]\x1B[0m Gitignore protection: ${f}`:`\x1B[36m[i]\x1B[0m Gitignore protection: ${f}`),console.log("--------------------------------------------------"),i?(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 tn=E(require("node:fs/promises"),1),zi=E(require("node:path"),1),af=E(require("node:os"),1),Ix="https://registry.npmjs.org/@promptci/cli/latest",ua=zi.join(af.homedir(),".promptci","update-check.json"),jx=1440*60*1e3,Nx=2e3;function Mx(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}},i=n(t),s=n(e);for(let r=0;r<Math.max(i.nums.length,s.nums.length);r++){let o=i.nums[r]??0,a=s.nums[r]??0;if(o!==a)return o>a}return!i.pre&&s.pre}function Dx(){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 Fx(t){try{let e=JSON.parse(await tn.readFile(ua,"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 Hx(t){await tn.mkdir(zi.dirname(ua),{recursive:!0}),await tn.writeFile(ua,JSON.stringify(t,null,2),"utf-8")}async function Bx(){try{let t=await fetch(Ix,{signal:AbortSignal.timeout(Nx)});if(!t.ok)return null;let e=await t.json();return typeof e.version=="string"?e.version:null}catch{return null}}async function cf(t){if(Dx())return null;try{let e=Date.now(),n=await Fx(e),i=n?.latest;return(!n||e-n.checkedAt>jx)&&(i=await Bx()??i,await Hx({checkedAt:e,latest:i})),i&&Mx(i,t)?`
295
+ A new version of promptci is available: ${t} \u2192 ${i}
296
+ Update with: npm install -g @promptci/cli (or however you installed it)
297
+ `:null}catch{return null}}var{version:lf}=ca(),pt=new Tt;pt.name("promptci").description("Instruction health for AI coding workflows").version(lf,"-v, --version","print version");pt.command("scan").description("Scan instruction files and generate a health report").option("--path <dir>","target directory to scan (default: current directory)").option("--json","print JSON report to stdout (files are still written)").option("--output <file>","write markdown report to this path instead of default").option("--fail-on <severity>","exit non-zero if any issue meets or exceeds this severity (info|warning|high|critical)").option("--baseline <path>","load baseline from file (relative to scan path)").option("--update-baseline","run scan and write result as the new baseline").option("--fail-on-new <severity>","exit non-zero only if NEW issues (not in baseline) meet this threshold; requires --baseline").option("--fail-on-budget","exit non-zero if any context bloat issue is found").option("--context-budget <chars>","override total context budget (in characters)").option("--file-context-budget <chars>","override per-file context budget (in characters)").option("--target-model <model>","scale context-bloat thresholds to a model preset (e.g. claude-opus-5, gpt-5, gemini-2.5-pro); --context-budget overrides it").action(async t=>{await Dd({scanPath:t.path,json:t.json,output:t.output,failOn:t.failOn,baseline:t.baseline,updateBaseline:t.updateBaseline,failOnNew:t.failOnNew,failOnBudget:t.failOnBudget,contextBudget:t.contextBudget?parseInt(t.contextBudget,10):void 0,fileContextBudget:t.fileContextBudget?parseInt(t.fileContextBudget,10):void 0,targetModel:t.targetModel})});pt.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 Ud({scanPath:t.path,issueId:t.issue,interactive:t.interactive,dryRun:t.dryRun||!1})});pt.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 Xd({baseBranch:t.base||"main",scanPath:t.path,json:t.json||!1,failOnRegression:t.failOnRegression||!1,failOn:t.failOn,workingTree:t.workingTree||!1})});pt.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 Gd(t.path??process.cwd(),{interactive:process.stdin.isTTY})});pt.command("doctor").description("Verify local PromptCI configuration, gitignore settings, and system dependencies").option("--path <dir>","target directory (default: current directory)").action(async t=>{await of({scanPath:t.path})});var uf=pt.command("context").description("Analyze instruction context size, cost, and retrieval-readiness");uf.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 nf({scanPath:t.path,json:t.json})});uf.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 sf({scanPath:t.path,dryRun:t.dryRun,write:t.write})});async function Gx(){let t=cf(lf);await pt.parseAsync(process.argv);let e=await t;e&&process.stderr.write(e)}Gx().catch(t=>{console.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)});
369
298
  /*! Bundled license information:
370
299
 
371
300
  is-extglob/index.js: