@promptci/cli 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +33 -0
  3. package/dist/cli.cjs +416 -0
  4. package/package.json +51 -0
package/dist/cli.cjs ADDED
@@ -0,0 +1,416 @@
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
16
+ - 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}
18
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
+ `):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
+ `);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(`
39
+ `).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(`
57
+ `,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(`
60
+ `);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
98
+ `)?`\r
99
+ `:`
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
102
+ `)?`\r
103
+ `:`
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
105
+ `)?`\r
106
+ `:`
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
109
+ `:`
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,`
111
+ `).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
116
+ `)?`\r
117
+ `:`
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
125
+
126
+ ## Project Type
127
+ TypeScript (General)
128
+
129
+ ## Project Rules
130
+ - **TypeScript**: Enforce strict compilation options in \`tsconfig.json\`.
131
+ - **Coding Conventions**:
132
+ - Use camelCase for variables/functions and PascalCase for types/interfaces.
133
+ - Prefer modern ES6+ features and async/await syntax.
134
+ - **Dependency Management**: Use \`pnpm\` (or \`npm\`/\`yarn\`) as specified in the project.
135
+
136
+ ## Security Rules
137
+ - **Secrets**: Never commit API keys, passwords, or raw secrets. Use environment variables.
138
+ - **Input Validation**: Sanitize and validate all external parameters to prevent injection.
139
+
140
+ ## Commands & Scripts
141
+ - Run development build: \`pnpm dev\`
142
+ - Compile TypeScript: \`pnpm build\`
143
+ - Run tests: \`pnpm test\`
144
+ - Lint code: \`pnpm lint\`
145
+
146
+ ## Verification Loop
147
+ Before completing a task:
148
+ 1. Run \`pnpm lint\` to check styling.
149
+ 2. Run \`pnpm build\` or \`pnpm typecheck\` to compile without errors.
150
+ 3. Run \`pnpm test\` to verify all tests pass.
151
+ `,unity:`# Developer Instructions
152
+
153
+ ## Project Type
154
+ Unity & C#
155
+
156
+ ## Project Rules
157
+ - **Meta Files**:
158
+ - Always generate and preserve \`.meta\` files for all assets and directories.
159
+ - Never modify, delete, or commit empty \`.meta\` files manually unless strictly necessary.
160
+ - **Assembly References**:
161
+ - Use Assembly Definitions (\`.asmdef\`) to manage compilation dependencies and optimize build times.
162
+ - Avoid creating circular dependencies between assemblies.
163
+ - **C# Standards**:
164
+ - Use Microsoft C# coding conventions.
165
+ - Classes, Structs, and Methods: PascalCase.
166
+ - Local variables and parameters: camelCase.
167
+ - Interfaces: Prefix with \`I\` (e.g. \`IEnemy\`).
168
+ - **Asset Guidelines**:
169
+ - Organize files in directories under \`Assets/\` (e.g., \`Assets/Scripts\`, \`Assets/Prefabs\`, \`Assets/Textures\`).
170
+ - Do not place loose assets in the root \`Assets/\` directory.
171
+
172
+ ## Security Rules
173
+ - **Secrets**: Never commit API keys, passwords, or raw secrets. Use environment variables.
174
+ - **Input Validation**: Sanitize and validate all external parameters to prevent injection.
175
+
176
+ ## Commands & Verification
177
+ - Compile and verify C# scripts within the Unity Editor or your IDE.
178
+ - Ensure no compilation errors exist before saving or committing changes.
179
+ `,dotnet:`# Developer Instructions
180
+
181
+ ## Project Type
182
+ .NET & C#
183
+
184
+ ## Project Rules
185
+ - **C# Coding Standards**: Follow official Microsoft C# coding conventions.
186
+ - **Project Structure**: Structure solutions with clear separation of concerns using projects and solutions (\`.sln\`, \`...\`, \`.csproj\`).
187
+ - **Dependency Management**: Manage packages via NuGet.
188
+
189
+ ## Security Rules
190
+ - **Secrets**: Never commit API keys, passwords, or raw secrets. Use environment variables.
191
+ - **Input Validation**: Sanitize and validate all external parameters to prevent injection.
192
+
193
+ ## Commands & Scripts
194
+ - Build solution: \`dotnet build\`
195
+ - Run tests: \`dotnet test\`
196
+ - Restore packages: \`dotnet restore\`
197
+
198
+ ## Verification Loop
199
+ Before declaring a task done:
200
+ 1. Run \`dotnet build\` to ensure clean compilation without warnings or errors.
201
+ 2. Run \`dotnet test\` to execute all tests.
202
+ `,python:"# Developer Instructions\n\n## Project Type\nPython\n\n## Project Rules\n- **Environment & Dependency Management**:\n - Use `poetry` or `pipenv` to manage dependencies.\n - Declare packages in `pyproject.toml` or `Pipfile`.\n- **Formatting & Linting**:\n - Use `ruff` or `black` and `isort` for formatting.\n - Keep line lengths under 88 characters (standard black formatting).\n- **Testing**:\n - Write test suites under the `tests/` directory.\n - Use `pytest` for running and structuring unit tests.\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- Install dependencies: `poetry install` (or `pip install -r requirements.txt`)\n- Run linter/formatter: `ruff check` and `ruff format`\n- Run tests: `pytest`\n\n## Verification Loop\nBefore marking a task as complete:\n1. Run `ruff format` to auto-format the code.\n2. Run `ruff check` to lint and check for common issues.\n3. Run `pytest` to verify all unit tests pass successfully.\n",go:`# Developer Instructions
203
+
204
+ ## Project Type
205
+ Go (Golang)
206
+
207
+ ## Project Rules
208
+ - **Dependency Management**: Manage packages via \`go.mod\`. Ensure all dependencies are cleaned and formatted.
209
+ - **Idiomatic Go**:
210
+ - Follow instructions from "Effective Go".
211
+ - Always handle errors returned from functions. Do not ignore errors with \`_\`.
212
+ - **Formatting**: Format code strictly with \`go fmt\`.
213
+
214
+ ## Security Rules
215
+ - **Secrets**: Never commit API keys, passwords, or raw secrets. Use environment variables.
216
+ - **Input Validation**: Sanitize and validate all external parameters to prevent injection.
217
+
218
+ ## Commands & Scripts
219
+ - Build the project: \`go build ./...\`
220
+ - Run all tests: \`go test ./...\`
221
+ - Format code: \`go fmt ./...\`
222
+ - Run linter (if applicable): \`golangci-lint run\`
223
+
224
+ ## Verification Loop
225
+ Before completing a task, always:
226
+ 1. Run \`go fmt ./...\` to format code.
227
+ 2. Run \`go test ./...\` to verify all tests pass.
228
+ 3. Run \`go build ./...\` to ensure everything compiles.
229
+ `,rust:`# Developer Instructions
230
+
231
+ ## Project Type
232
+ Rust
233
+
234
+ ## Project Rules
235
+ - **Code Style**:
236
+ - Enforce idiomatic Rust style.
237
+ - Run \`cargo fmt\` to format all code.
238
+ - Address all warnings reported by \`cargo clippy\`.
239
+ - **Safety**: Prefer safe Rust. Use \`unsafe\` blocks only where absolutely necessary and fully document the safety guarantees.
240
+ - **Dependency Management**: Manage dependencies inside \`Cargo.toml\`.
241
+
242
+ ## Security Rules
243
+ - **Secrets**: Never commit API keys, passwords, or raw secrets. Use environment variables.
244
+ - **Input Validation**: Sanitize and validate all external parameters to prevent injection.
245
+
246
+ ## Commands & Scripts
247
+ - Format code: \`cargo fmt\`
248
+ - Run linter: \`cargo clippy\`
249
+ - Build: \`cargo build\`
250
+ - Run tests: \`cargo test\`
251
+
252
+ ## Verification Loop
253
+ Before finalizing any changes, perform these steps:
254
+ 1. Run \`cargo fmt -- --check\` to verify code format.
255
+ 2. Run \`cargo clippy --all-targets -- -D warnings\` to verify zero warnings.
256
+ 3. Run \`cargo test\` to execute the test suite and ensure all tests pass.
257
+ `,unknown:`# Developer Instructions
258
+
259
+ ## Guidelines
260
+ - **Read First**: Always read the existing codebase and context files before making edits.
261
+ - **Plan First**: For complex or multi-file changes, design an implementation plan first.
262
+ - **Code Consistency**: Follow the existing styling, naming conventions, and file structures in the repository.
263
+ - **Verification**: Enforce a local verification loop by compiling the code and running tests if they exist.
264
+
265
+ ## Security Rules
266
+ - **Secrets**: Never commit API keys, passwords, or raw secrets. Use environment variables.
267
+ - **Input Validation**: Sanitize and validate all external parameters to prevent injection.
268
+
269
+ ## Commands & Scripts
270
+ - Locate any setup, build, and test scripts in the root directory (e.g. \`Makefile\`, \`package.json\`, or shell scripts).
271
+ - 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?
283
+ 1: AGENTS.md (Recommended for monorepos & multi-agent instructions)
284
+ 2: .cursorrules (For Cursor users)
285
+ 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(`
297
+ 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)});
369
+ /*! Bundled license information:
370
+
371
+ is-extglob/index.js:
372
+ (*!
373
+ * is-extglob <https://github.com/jonschlinkert/is-extglob>
374
+ *
375
+ * Copyright (c) 2014-2016, Jon Schlinkert.
376
+ * Licensed under the MIT License.
377
+ *)
378
+
379
+ is-glob/index.js:
380
+ (*!
381
+ * is-glob <https://github.com/jonschlinkert/is-glob>
382
+ *
383
+ * Copyright (c) 2014-2017, Jon Schlinkert.
384
+ * Released under the MIT License.
385
+ *)
386
+
387
+ is-number/index.js:
388
+ (*!
389
+ * is-number <https://github.com/jonschlinkert/is-number>
390
+ *
391
+ * Copyright (c) 2014-present, Jon Schlinkert.
392
+ * Released under the MIT License.
393
+ *)
394
+
395
+ to-regex-range/index.js:
396
+ (*!
397
+ * to-regex-range <https://github.com/micromatch/to-regex-range>
398
+ *
399
+ * Copyright (c) 2015-present, Jon Schlinkert.
400
+ * Released under the MIT License.
401
+ *)
402
+
403
+ fill-range/index.js:
404
+ (*!
405
+ * fill-range <https://github.com/jonschlinkert/fill-range>
406
+ *
407
+ * Copyright (c) 2014-present, Jon Schlinkert.
408
+ * Licensed under the MIT License.
409
+ *)
410
+
411
+ queue-microtask/index.js:
412
+ (*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
413
+
414
+ run-parallel/index.js:
415
+ (*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
416
+ */