aide-memory 0.5.18 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,64 +1,64 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var ci=Object.create;var dt=Object.defineProperty;var li=Object.getOwnPropertyDescriptor;var ui=Object.getOwnPropertyNames;var di=Object.getPrototypeOf,pi=Object.prototype.hasOwnProperty;var $=(n,e)=>()=>(n&&(e=n(n=0)),e);var F=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Qt=(n,e)=>{for(var t in e)dt(n,t,{get:e[t],enumerable:!0})},ln=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ui(e))!pi.call(n,o)&&o!==t&&dt(n,o,{get:()=>e[o],enumerable:!(r=li(e,o))||r.enumerable});return n};var h=(n,e,t)=>(t=n!=null?ci(di(n)):{},ln(e||!n||!n.__esModule?dt(t,"default",{value:n,enumerable:!0}):t,n)),Zt=n=>ln(dt({},"__esModule",{value:!0}),n);var Ge=F(tr=>{var pt=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},er=class extends pt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};tr.CommanderError=pt;tr.InvalidArgumentError=er});var ft=F(nr=>{var{InvalidArgumentError:fi}=Ge(),rr=class{constructor(e,t){switch(this.description=t||"",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,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new fi(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function mi(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}nr.Argument=rr;nr.humanReadableArgName=mi});var sr=F(un=>{var{humanReadableArgName:hi}=ft(),or=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(o=>!o._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((o,s)=>o.name().localeCompare(s.name())),t}compareOptions(e,t){let r=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(o=>!o.hidden),r=e._getHelpOption();if(r&&!r.hidden){let o=r.short&&e._findOption(r.short),s=r.long&&e._findOption(r.long);!o&&!s?t.push(r):r.long&&!s?t.push(e.createOption(r.long,r.description)):r.short&&!o&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let o=r.options.filter(s=>!s.hidden);t.push(...o)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(r=>hi(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,o)=>Math.max(r,t.subcommandTerm(o).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,o)=>Math.max(r,t.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,o)=>Math.max(r,t.optionTerm(o).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,o)=>Math.max(r,t.argumentTerm(o).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let o=e.parent;o;o=o.parent)r=o.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),o=t.helpWidth||80,s=2,i=2;function a(g,_){if(_){let S=`${g.padEnd(r+i)}${_}`;return t.wrap(S,o-s,r+i)}return g}function c(g){return g.join(`
3
- `).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${t.commandUsage(e)}`,""],u=t.commandDescription(e);u.length>0&&(l=l.concat([t.wrap(u,o,0),""]));let d=t.visibleArguments(e).map(g=>a(t.argumentTerm(g),t.argumentDescription(g)));d.length>0&&(l=l.concat(["Arguments:",c(d),""]));let m=t.visibleOptions(e).map(g=>a(t.optionTerm(g),t.optionDescription(g)));if(m.length>0&&(l=l.concat(["Options:",c(m),""])),this.showGlobalOptions){let g=t.visibleGlobalOptions(e).map(_=>a(t.optionTerm(_),t.optionDescription(_)));g.length>0&&(l=l.concat(["Global Options:",c(g),""]))}let w=t.visibleCommands(e).map(g=>a(t.subcommandTerm(g),t.subcommandDescription(g)));return w.length>0&&(l=l.concat(["Commands:",c(w),""])),l.join(`
2
+ "use strict";var ui=Object.create;var mt=Object.defineProperty;var di=Object.getOwnPropertyDescriptor;var pi=Object.getOwnPropertyNames;var mi=Object.getPrototypeOf,fi=Object.prototype.hasOwnProperty;var T=(n,e)=>()=>(n&&(e=n(n=0)),e);var F=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Zt=(n,e)=>{for(var t in e)mt(n,t,{get:e[t],enumerable:!0})},un=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pi(e))!fi.call(n,o)&&o!==t&&mt(n,o,{get:()=>e[o],enumerable:!(r=di(e,o))||r.enumerable});return n};var g=(n,e,t)=>(t=n!=null?ui(mi(n)):{},un(e||!n||!n.__esModule?mt(t,"default",{value:n,enumerable:!0}):t,n)),er=n=>un(mt({},"__esModule",{value:!0}),n);var Ye=F(rr=>{var ft=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},tr=class extends ft{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};rr.CommanderError=ft;rr.InvalidArgumentError=tr});var ht=F(or=>{var{InvalidArgumentError:hi}=Ye(),nr=class{constructor(e,t){switch(this.description=t||"",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,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new hi(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function gi(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}or.Argument=nr;or.humanReadableArgName=gi});var ir=F(dn=>{var{humanReadableArgName:yi}=ht(),sr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(o=>!o._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((o,s)=>o.name().localeCompare(s.name())),t}compareOptions(e,t){let r=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(o=>!o.hidden),r=e._getHelpOption();if(r&&!r.hidden){let o=r.short&&e._findOption(r.short),s=r.long&&e._findOption(r.long);!o&&!s?t.push(r):r.long&&!s?t.push(e.createOption(r.long,r.description)):r.short&&!o&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let o=r.options.filter(s=>!s.hidden);t.push(...o)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(r=>yi(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,o)=>Math.max(r,t.subcommandTerm(o).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,o)=>Math.max(r,t.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,o)=>Math.max(r,t.optionTerm(o).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,o)=>Math.max(r,t.argumentTerm(o).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let o=e.parent;o;o=o.parent)r=o.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),o=t.helpWidth||80,s=2,i=2;function a(h,w){if(w){let E=`${h.padEnd(r+i)}${w}`;return t.wrap(E,o-s,r+i)}return h}function c(h){return h.join(`
3
+ `).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${t.commandUsage(e)}`,""],u=t.commandDescription(e);u.length>0&&(l=l.concat([t.wrap(u,o,0),""]));let d=t.visibleArguments(e).map(h=>a(t.argumentTerm(h),t.argumentDescription(h)));d.length>0&&(l=l.concat(["Arguments:",c(d),""]));let f=t.visibleOptions(e).map(h=>a(t.optionTerm(h),t.optionDescription(h)));if(f.length>0&&(l=l.concat(["Options:",c(f),""])),this.showGlobalOptions){let h=t.visibleGlobalOptions(e).map(w=>a(t.optionTerm(w),t.optionDescription(w)));h.length>0&&(l=l.concat(["Global Options:",c(h),""]))}let y=t.visibleCommands(e).map(h=>a(t.subcommandTerm(h),t.subcommandDescription(h)));return y.length>0&&(l=l.concat(["Commands:",c(y),""])),l.join(`
4
4
  `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,r,o=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",i=new RegExp(`[\\n][${s}]+`);if(e.match(i))return e;let a=t-r;if(a<o)return e;let c=e.slice(0,r),l=e.slice(r).replace(`\r
5
5
  `,`
6
- `),u=" ".repeat(r),m="\\s\u200B",w=new RegExp(`
7
- |.{1,${a-1}}([${m}]|$)|[^${m}]+?([${m}]|$)`,"g"),g=l.match(w)||[];return c+g.map((_,S)=>_===`
8
- `?"":(S>0?u:"")+_.trimEnd()).join(`
9
- `)}};un.Help=or});var lr=F(cr=>{var{InvalidArgumentError:gi}=Ge(),ir=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=bi(e);this.short=r.shortFlag,this.long=r.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,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),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,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new gi(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return yi(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ar=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let o=this.negativeOptions.get(r).presetArg,s=o!==void 0?o:!1;return t.negate===(s===e)}};function yi(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function bi(n){let e,t,r=n.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),t=r.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}cr.Option=ir;cr.DualOptions=ar});var pn=F(dn=>{function wi(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let r=0;r<=n.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let o=1;o<=n.length;o++){let s=1;n[o-1]===e[r-1]?s=0:s=1,t[o][r]=Math.min(t[o-1][r]+1,t[o][r-1]+1,t[o-1][r-1]+s),o>1&&r>1&&n[o-1]===e[r-2]&&n[o-2]===e[r-1]&&(t[o][r]=Math.min(t[o][r],t[o-2][r-2]+1))}return t[n.length][e.length]}function _i(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(i=>i.slice(2)));let r=[],o=3,s=.4;return e.forEach(i=>{if(i.length<=1)return;let a=wi(n,i),c=Math.max(n.length,i.length);(c-a)/c>s&&(a<o?(o=a,r=[i]):a===o&&r.push(i))}),r.sort((i,a)=>i.localeCompare(a)),t&&(r=r.map(i=>`--${i}`)),r.length>1?`
6
+ `),u=" ".repeat(r),f="\\s\u200B",y=new RegExp(`
7
+ |.{1,${a-1}}([${f}]|$)|[^${f}]+?([${f}]|$)`,"g"),h=l.match(y)||[];return c+h.map((w,E)=>w===`
8
+ `?"":(E>0?u:"")+w.trimEnd()).join(`
9
+ `)}};dn.Help=sr});var ur=F(lr=>{var{InvalidArgumentError:bi}=Ye(),ar=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=wi(e);this.short=r.shortFlag,this.long=r.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,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),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,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new bi(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return _i(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},cr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let o=this.negativeOptions.get(r).presetArg,s=o!==void 0?o:!1;return t.negate===(s===e)}};function _i(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function wi(n){let e,t,r=n.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),t=r.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}lr.Option=ar;lr.DualOptions=cr});var mn=F(pn=>{function Si(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let r=0;r<=n.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let o=1;o<=n.length;o++){let s=1;n[o-1]===e[r-1]?s=0:s=1,t[o][r]=Math.min(t[o-1][r]+1,t[o][r-1]+1,t[o-1][r-1]+s),o>1&&r>1&&n[o-1]===e[r-2]&&n[o-2]===e[r-1]&&(t[o][r]=Math.min(t[o][r],t[o-2][r-2]+1))}return t[n.length][e.length]}function Ei(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(i=>i.slice(2)));let r=[],o=3,s=.4;return e.forEach(i=>{if(i.length<=1)return;let a=Si(n,i),c=Math.max(n.length,i.length);(c-a)/c>s&&(a<o?(o=a,r=[i]):a===o&&r.push(i))}),r.sort((i,a)=>i.localeCompare(a)),t&&(r=r.map(i=>`--${i}`)),r.length>1?`
10
10
  (Did you mean one of ${r.join(", ")}?)`:r.length===1?`
11
- (Did you mean ${r[0]}?)`:""}dn.suggestSimilar=_i});var yn=F(gn=>{var Si=require("node:events").EventEmitter,ur=require("node:child_process"),ce=require("node:path"),dr=require("node:fs"),j=require("node:process"),{Argument:Ei,humanReadableArgName:vi}=ft(),{CommanderError:pr}=Ge(),{Help:ki}=sr(),{Option:fn,DualOptions:xi}=lr(),{suggestSimilar:mn}=pn(),fr=class n extends Si{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:t=>j.stdout.write(t),writeErr:t=>j.stderr.write(t),getOutHelpWidth:()=>j.stdout.isTTY?j.stdout.columns:void 0,getErrHelpWidth:()=>j.stderr.isTTY?j.stderr.columns:void 0,outputError:(t,r)=>r(t)},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 t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let o=t,s=r;typeof o=="object"&&o!==null&&(s=o,o=null),s=s||{};let[,i,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(i);return o&&(c.description(o),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),o?this:c}createCommand(e){return new n(e)}createHelp(){return Object.assign(new ki,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,t){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 t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Ei(e,t)}argument(e,t,r,o){let s=this.createArgument(e,t);return typeof r=="function"?s.default(o).argParser(r):s.default(r),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.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,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,o]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",i=this.createCommand(r);return i.helpOption(!1),o&&i.arguments(o),s&&i.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=i,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),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,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
- Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new pr(e,t,r)),j.exit(e)}action(e){let t=r=>{let o=this.registeredArguments.length,s=r.slice(0,o);return this._storeOptionsAsProperties?s[o]=this:s[o]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new fn(e,t)}_callParseArg(e,t,r,o){try{return e.parseArg(t,r)}catch(s){if(s.code==="commander.invalidArgument"){let i=`${o} ${s.message}`;this.error(i,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=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 '${r}'
14
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=o=>[o.name()].concat(o.aliases()),r=t(e).find(o=>this._findCommand(o));if(r){let o=t(this._findCommand(r)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${o}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let o=(s,i,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(r);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,i):s!==null&&e.variadic&&(s=e._concatValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(r,s,a)};return this.on("option:"+t,s=>{let i=`error: option '${e.flags}' argument '${s}' is invalid.`;o(s,i,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let i=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;o(s,i,"env")}),this}_optionEx(e,t,r,o,s){if(typeof t=="object"&&t instanceof fn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(t,r);if(i.makeOptionMandatory(!!e.mandatory),typeof o=="function")i.default(s).argParser(o);else if(o instanceof RegExp){let a=o;o=(c,l)=>{let u=a.exec(c);return u?u[0]:l},i.default(s).argParser(o)}else i.default(o);return this.addOption(i)}option(e,t,r,o){return this._optionEx({},e,t,r,o)}requiredOption(e,t,r,o){return this._optionEx({mandatory:!0},e,t,r,o)}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,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){j.versions?.electron&&(t.from="electron");let o=j.execArgv??[];(o.includes("-e")||o.includes("--eval")||o.includes("-p")||o.includes("--print"))&&(t.from="eval")}e===void 0&&(e=j.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":j.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,t){let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_executeSubCommand(e,t){t=t.slice();let r=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,d){let m=ce.resolve(u,d);if(dr.existsSync(m))return m;if(o.includes(ce.extname(d)))return;let w=o.find(g=>dr.existsSync(`${m}${g}`));if(w)return`${m}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=dr.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=ce.resolve(ce.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let d=ce.basename(this._scriptPath,ce.extname(this._scriptPath));d!==this._name&&(u=s(a,`${d}-${e._name}`))}i=u||i}r=o.includes(ce.extname(i));let c;j.platform!=="win32"?r?(t.unshift(i),t=hn(j.execArgv).concat(t),c=ur.spawn(j.argv[0],t,{stdio:"inherit"})):c=ur.spawn(i,t,{stdio:"inherit"}):(t.unshift(i),t=hn(j.execArgv).concat(t),c=ur.spawn(j.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{j.on(d,()=>{c.killed===!1&&c.exitCode===null&&c.kill(d)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new pr(u,"commander.executeSubCommandAsync","(close)")):j.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",m=`'${i}' does not exist
11
+ (Did you mean ${r[0]}?)`:""}pn.suggestSimilar=Ei});var bn=F(yn=>{var vi=require("node:events").EventEmitter,dr=require("node:child_process"),le=require("node:path"),pr=require("node:fs"),$=require("node:process"),{Argument:ki,humanReadableArgName:xi}=ht(),{CommanderError:mr}=Ye(),{Help:Oi}=ir(),{Option:fn,DualOptions:Ri}=ur(),{suggestSimilar:hn}=mn(),fr=class n extends vi{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:t=>$.stdout.write(t),writeErr:t=>$.stderr.write(t),getOutHelpWidth:()=>$.stdout.isTTY?$.stdout.columns:void 0,getErrHelpWidth:()=>$.stderr.isTTY?$.stderr.columns:void 0,outputError:(t,r)=>r(t)},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 t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let o=t,s=r;typeof o=="object"&&o!==null&&(s=o,o=null),s=s||{};let[,i,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(i);return o&&(c.description(o),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),o?this:c}createCommand(e){return new n(e)}createHelp(){return Object.assign(new Oi,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,t){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 t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new ki(e,t)}argument(e,t,r,o){let s=this.createArgument(e,t);return typeof r=="function"?s.default(o).argParser(r):s.default(r),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.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,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,o]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",i=this.createCommand(r);return i.helpOption(!1),o&&i.arguments(o),s&&i.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=i,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),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,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
+ Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new mr(e,t,r)),$.exit(e)}action(e){let t=r=>{let o=this.registeredArguments.length,s=r.slice(0,o);return this._storeOptionsAsProperties?s[o]=this:s[o]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new fn(e,t)}_callParseArg(e,t,r,o){try{return e.parseArg(t,r)}catch(s){if(s.code==="commander.invalidArgument"){let i=`${o} ${s.message}`;this.error(i,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=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 '${r}'
14
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=o=>[o.name()].concat(o.aliases()),r=t(e).find(o=>this._findCommand(o));if(r){let o=t(this._findCommand(r)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${o}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let o=(s,i,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(r);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,i):s!==null&&e.variadic&&(s=e._concatValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(r,s,a)};return this.on("option:"+t,s=>{let i=`error: option '${e.flags}' argument '${s}' is invalid.`;o(s,i,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let i=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;o(s,i,"env")}),this}_optionEx(e,t,r,o,s){if(typeof t=="object"&&t instanceof fn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(t,r);if(i.makeOptionMandatory(!!e.mandatory),typeof o=="function")i.default(s).argParser(o);else if(o instanceof RegExp){let a=o;o=(c,l)=>{let u=a.exec(c);return u?u[0]:l},i.default(s).argParser(o)}else i.default(o);return this.addOption(i)}option(e,t,r,o){return this._optionEx({},e,t,r,o)}requiredOption(e,t,r,o){return this._optionEx({mandatory:!0},e,t,r,o)}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,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){$.versions?.electron&&(t.from="electron");let o=$.execArgv??[];(o.includes("-e")||o.includes("--eval")||o.includes("-p")||o.includes("--print"))&&(t.from="eval")}e===void 0&&(e=$.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":$.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,t){let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_executeSubCommand(e,t){t=t.slice();let r=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,d){let f=le.resolve(u,d);if(pr.existsSync(f))return f;if(o.includes(le.extname(d)))return;let y=o.find(h=>pr.existsSync(`${f}${h}`));if(y)return`${f}${y}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=pr.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=le.resolve(le.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let d=le.basename(this._scriptPath,le.extname(this._scriptPath));d!==this._name&&(u=s(a,`${d}-${e._name}`))}i=u||i}r=o.includes(le.extname(i));let c;$.platform!=="win32"?r?(t.unshift(i),t=gn($.execArgv).concat(t),c=dr.spawn($.argv[0],t,{stdio:"inherit"})):c=dr.spawn(i,t,{stdio:"inherit"}):(t.unshift(i),t=gn($.execArgv).concat(t),c=dr.spawn($.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{$.on(d,()=>{c.killed===!1&&c.exitCode===null&&c.kill(d)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new mr(u,"commander.executeSubCommandAsync","(close)")):$.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",f=`'${i}' does not exist
15
15
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${d}`;throw new Error(m)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)j.exit(1);else{let d=new pr(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_dispatchSubcommand(e,t,r){let o=this._findCommand(e);o||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,o,"preSubcommand"),s=this._chainOrCall(s,()=>{if(o._executableHandler)this._executeSubCommand(o,t.concat(r));else return o._parseCommand(t,r)}),s}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==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=(r,o,s)=>{let i=o;if(o!==null&&r.parseArg){let a=`error: command-argument value '${o}' is invalid for argument '${r.name()}'.`;i=this._callParseArg(r,o,s,a)}return i};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,o)=>{let s=r.defaultValue;r.variadic?o<this.args.length?(s=this.args.slice(o),r.parseArg&&(s=s.reduce((i,a)=>e(r,a,i),r.defaultValue))):s===void 0&&(s=[]):o<this.args.length&&(s=this.args[o],r.parseArg&&(s=e(r,s,r.defaultValue))),t[o]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,o=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(i=>{o.push({hookedCommand:s,callback:i})})}),t==="postAction"&&o.reverse(),o.forEach(s=>{r=this._chainOrCall(r,()=>s.callback(s.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let o=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(s=>{o=this._chainOrCall(o,()=>s(this,t))}),o}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(s,e,t)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(s))o(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let o=r.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let o=e.find(s=>r.conflictsWith.includes(s.attributeName()));o&&this._conflictingOption(r,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],o=t,s=e.slice();function i(c){return c.length>1&&c[0]==="-"}let a=null;for(;s.length;){let c=s.shift();if(c==="--"){o===r&&o.push(c),o.push(...s);break}if(a&&!i(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,i(c)){let l=this._findOption(c);if(l){if(l.required){let u=s.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;s.length>0&&!i(s[0])&&(u=s.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()}`),s.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(i(c)&&(o=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(c)){t.push(c),s.length>0&&r.push(...s);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){r.push(c),s.length>0&&r.push(...s);break}}if(this._passThroughOptions){o.push(c),s.length>0&&o.push(...s);break}o.push(c)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let o=this.options[r].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
17
+ - ${d}`;throw new Error(f)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)$.exit(1);else{let d=new mr(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_dispatchSubcommand(e,t,r){let o=this._findCommand(e);o||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,o,"preSubcommand"),s=this._chainOrCall(s,()=>{if(o._executableHandler)this._executeSubCommand(o,t.concat(r));else return o._parseCommand(t,r)}),s}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==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=(r,o,s)=>{let i=o;if(o!==null&&r.parseArg){let a=`error: command-argument value '${o}' is invalid for argument '${r.name()}'.`;i=this._callParseArg(r,o,s,a)}return i};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,o)=>{let s=r.defaultValue;r.variadic?o<this.args.length?(s=this.args.slice(o),r.parseArg&&(s=s.reduce((i,a)=>e(r,a,i),r.defaultValue))):s===void 0&&(s=[]):o<this.args.length&&(s=this.args[o],r.parseArg&&(s=e(r,s,r.defaultValue))),t[o]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,o=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(i=>{o.push({hookedCommand:s,callback:i})})}),t==="postAction"&&o.reverse(),o.forEach(s=>{r=this._chainOrCall(r,()=>s.callback(s.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let o=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(s=>{o=this._chainOrCall(o,()=>s(this,t))}),o}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(s,e,t)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(s))o(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let o=r.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let o=e.find(s=>r.conflictsWith.includes(s.attributeName()));o&&this._conflictingOption(r,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],o=t,s=e.slice();function i(c){return c.length>1&&c[0]==="-"}let a=null;for(;s.length;){let c=s.shift();if(c==="--"){o===r&&o.push(c),o.push(...s);break}if(a&&!i(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,i(c)){let l=this._findOption(c);if(l){if(l.required){let u=s.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;s.length>0&&!i(s[0])&&(u=s.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()}`),s.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(i(c)&&(o=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(c)){t.push(c),s.length>0&&r.push(...s);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){t.push(c),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){r.push(c),s.length>0&&r.push(...s);break}}if(this._passThroughOptions){o.push(c),s.length>0&&o.push(...s);break}o.push(c)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let o=this.options[r].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
18
18
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
19
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
20
- `),this.outputHelp({error:!0}));let r=t||{},o=r.exitCode||1,s=r.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in j.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,j.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new xi(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(o=>!t(o)).forEach(o=>{this.setOptionValueWithSource(o,r.implied[o],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=i=>{let a=i.attributeName(),c=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||i},o=i=>{let a=r(i),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${o(e)} cannot be used with ${o(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],s=this;do{let i=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);o=o.concat(i),s=s.parent}while(s&&!s._enablePositionalOptions);t=mn(e,o)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(s=>{o.push(s.name()),s.alias()&&o.push(s.alias())}),t=mn(e,o)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let o=this.createOption(t,r);return this._versionOptionName=o.attributeName(),this._registerOption(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let o=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${o}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>vi(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=ce.basename(e,ce.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},r;return t.error?r=o=>this._outputConfiguration.writeErr(o):r=o=>this._outputConfiguration.writeOut(o),t.write=e.write||r,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let o=this.helpInformation(r);if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",r))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),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 t=j.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
20
+ `),this.outputHelp({error:!0}));let r=t||{},o=r.exitCode||1,s=r.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in $.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,$.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ri(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(o=>!t(o)).forEach(o=>{this.setOptionValueWithSource(o,r.implied[o],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=i=>{let a=i.attributeName(),c=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||i},o=i=>{let a=r(i),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${o(e)} cannot be used with ${o(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],s=this;do{let i=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);o=o.concat(i),s=s.parent}while(s&&!s._enablePositionalOptions);t=hn(e,o)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(s=>{o.push(s.name()),s.alias()&&o.push(s.alias())}),t=hn(e,o)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let o=this.createOption(t,r);return this._versionOptionName=o.attributeName(),this._registerOption(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let o=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${o}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>xi(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=le.basename(e,le.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},r;return t.error?r=o=>this._outputConfiguration.writeErr(o):r=o=>this._outputConfiguration.writeOut(o),t.write=e.write||r,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let o=this.helpInformation(r);if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",r))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),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 t=$.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
22
  Expecting one of '${r.join("', '")}'`);let o=`${e}Help`;return this.on(o,s=>{let i;typeof t=="function"?i=t({error:s.error,command:s.command}):i=t,i&&s.write(`${i}
23
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(o=>t.is(o))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function hn(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",o="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?o=s[3]:r=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],r=s[3],o=s[4]),t&&o!=="0"?`${t}=${r}:${parseInt(o)+1}`:e})}gn.Command=fr});var Sn=F(G=>{var{Argument:bn}=ft(),{Command:mr}=yn(),{CommanderError:Oi,InvalidArgumentError:wn}=Ge(),{Help:Ri}=sr(),{Option:_n}=lr();G.program=new mr;G.createCommand=n=>new mr(n);G.createOption=(n,e)=>new _n(n,e);G.createArgument=(n,e)=>new bn(n,e);G.Command=mr;G.Option=_n;G.Argument=bn;G.Help=Ri;G.CommanderError=Oi;G.InvalidArgumentError=wn;G.InvalidOptionArgumentError=wn});var xn=F((qc,kn)=>{"use strict";kn.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var hr=F((Gc,Rn)=>{var Xe=xn(),On={};for(let n of Object.keys(Xe))On[Xe[n]]=n;var y={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};Rn.exports=y;for(let n of Object.keys(y)){if(!("channels"in y[n]))throw new Error("missing channels property: "+n);if(!("labels"in y[n]))throw new Error("missing channel labels property: "+n);if(y[n].labels.length!==y[n].channels)throw new Error("channel and label counts mismatch: "+n);let{channels:e,labels:t}=y[n];delete y[n].channels,delete y[n].labels,Object.defineProperty(y[n],"channels",{value:e}),Object.defineProperty(y[n],"labels",{value:t})}y.rgb.hsl=function(n){let e=n[0]/255,t=n[1]/255,r=n[2]/255,o=Math.min(e,t,r),s=Math.max(e,t,r),i=s-o,a,c;s===o?a=0:e===s?a=(t-r)/i:t===s?a=2+(r-e)/i:r===s&&(a=4+(e-t)/i),a=Math.min(a*60,360),a<0&&(a+=360);let l=(o+s)/2;return s===o?c=0:l<=.5?c=i/(s+o):c=i/(2-s-o),[a,c*100,l*100]};y.rgb.hsv=function(n){let e,t,r,o,s,i=n[0]/255,a=n[1]/255,c=n[2]/255,l=Math.max(i,a,c),u=l-Math.min(i,a,c),d=function(m){return(l-m)/6/u+1/2};return u===0?(o=0,s=0):(s=u/l,e=d(i),t=d(a),r=d(c),i===l?o=r-t:a===l?o=1/3+e-r:c===l&&(o=2/3+t-e),o<0?o+=1:o>1&&(o-=1)),[o*360,s*100,l*100]};y.rgb.hwb=function(n){let e=n[0],t=n[1],r=n[2],o=y.rgb.hsl(n)[0],s=1/255*Math.min(e,Math.min(t,r));return r=1-1/255*Math.max(e,Math.max(t,r)),[o,s*100,r*100]};y.rgb.cmyk=function(n){let e=n[0]/255,t=n[1]/255,r=n[2]/255,o=Math.min(1-e,1-t,1-r),s=(1-e-o)/(1-o)||0,i=(1-t-o)/(1-o)||0,a=(1-r-o)/(1-o)||0;return[s*100,i*100,a*100,o*100]};function Ci(n,e){return(n[0]-e[0])**2+(n[1]-e[1])**2+(n[2]-e[2])**2}y.rgb.keyword=function(n){let e=On[n];if(e)return e;let t=1/0,r;for(let o of Object.keys(Xe)){let s=Xe[o],i=Ci(n,s);i<t&&(t=i,r=o)}return r};y.keyword.rgb=function(n){return Xe[n]};y.rgb.xyz=function(n){let e=n[0]/255,t=n[1]/255,r=n[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92;let o=e*.4124+t*.3576+r*.1805,s=e*.2126+t*.7152+r*.0722,i=e*.0193+t*.1192+r*.9505;return[o*100,s*100,i*100]};y.rgb.lab=function(n){let e=y.rgb.xyz(n),t=e[0],r=e[1],o=e[2];t/=95.047,r/=100,o/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116;let s=116*r-16,i=500*(t-r),a=200*(r-o);return[s,i,a]};y.hsl.rgb=function(n){let e=n[0]/360,t=n[1]/100,r=n[2]/100,o,s,i;if(t===0)return i=r*255,[i,i,i];r<.5?o=r*(1+t):o=r+t-r*t;let a=2*r-o,c=[0,0,0];for(let l=0;l<3;l++)s=e+1/3*-(l-1),s<0&&s++,s>1&&s--,6*s<1?i=a+(o-a)*6*s:2*s<1?i=o:3*s<2?i=a+(o-a)*(2/3-s)*6:i=a,c[l]=i*255;return c};y.hsl.hsv=function(n){let e=n[0],t=n[1]/100,r=n[2]/100,o=t,s=Math.max(r,.01);r*=2,t*=r<=1?r:2-r,o*=s<=1?s:2-s;let i=(r+t)/2,a=r===0?2*o/(s+o):2*t/(r+t);return[e,a*100,i*100]};y.hsv.rgb=function(n){let e=n[0]/60,t=n[1]/100,r=n[2]/100,o=Math.floor(e)%6,s=e-Math.floor(e),i=255*r*(1-t),a=255*r*(1-t*s),c=255*r*(1-t*(1-s));switch(r*=255,o){case 0:return[r,c,i];case 1:return[a,r,i];case 2:return[i,r,c];case 3:return[i,a,r];case 4:return[c,i,r];case 5:return[r,i,a]}};y.hsv.hsl=function(n){let e=n[0],t=n[1]/100,r=n[2]/100,o=Math.max(r,.01),s,i;i=(2-t)*r;let a=(2-t)*o;return s=t*o,s/=a<=1?a:2-a,s=s||0,i/=2,[e,s*100,i*100]};y.hwb.rgb=function(n){let e=n[0]/360,t=n[1]/100,r=n[2]/100,o=t+r,s;o>1&&(t/=o,r/=o);let i=Math.floor(6*e),a=1-r;s=6*e-i,(i&1)!==0&&(s=1-s);let c=t+s*(a-t),l,u,d;switch(i){default:case 6:case 0:l=a,u=c,d=t;break;case 1:l=c,u=a,d=t;break;case 2:l=t,u=a,d=c;break;case 3:l=t,u=c,d=a;break;case 4:l=c,u=t,d=a;break;case 5:l=a,u=t,d=c;break}return[l*255,u*255,d*255]};y.cmyk.rgb=function(n){let e=n[0]/100,t=n[1]/100,r=n[2]/100,o=n[3]/100,s=1-Math.min(1,e*(1-o)+o),i=1-Math.min(1,t*(1-o)+o),a=1-Math.min(1,r*(1-o)+o);return[s*255,i*255,a*255]};y.xyz.rgb=function(n){let e=n[0]/100,t=n[1]/100,r=n[2]/100,o,s,i;return o=e*3.2406+t*-1.5372+r*-.4986,s=e*-.9689+t*1.8758+r*.0415,i=e*.0557+t*-.204+r*1.057,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,o=Math.min(Math.max(0,o),1),s=Math.min(Math.max(0,s),1),i=Math.min(Math.max(0,i),1),[o*255,s*255,i*255]};y.xyz.lab=function(n){let e=n[0],t=n[1],r=n[2];e/=95.047,t/=100,r/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,t=t>.008856?t**(1/3):7.787*t+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;let o=116*t-16,s=500*(e-t),i=200*(t-r);return[o,s,i]};y.lab.xyz=function(n){let e=n[0],t=n[1],r=n[2],o,s,i;s=(e+16)/116,o=t/500+s,i=s-r/200;let a=s**3,c=o**3,l=i**3;return s=a>.008856?a:(s-16/116)/7.787,o=c>.008856?c:(o-16/116)/7.787,i=l>.008856?l:(i-16/116)/7.787,o*=95.047,s*=100,i*=108.883,[o,s,i]};y.lab.lch=function(n){let e=n[0],t=n[1],r=n[2],o;o=Math.atan2(r,t)*360/2/Math.PI,o<0&&(o+=360);let i=Math.sqrt(t*t+r*r);return[e,i,o]};y.lch.lab=function(n){let e=n[0],t=n[1],o=n[2]/360*2*Math.PI,s=t*Math.cos(o),i=t*Math.sin(o);return[e,s,i]};y.rgb.ansi16=function(n,e=null){let[t,r,o]=n,s=e===null?y.rgb.hsv(n)[2]:e;if(s=Math.round(s/50),s===0)return 30;let i=30+(Math.round(o/255)<<2|Math.round(r/255)<<1|Math.round(t/255));return s===2&&(i+=60),i};y.hsv.ansi16=function(n){return y.rgb.ansi16(y.hsv.rgb(n),n[2])};y.rgb.ansi256=function(n){let e=n[0],t=n[1],r=n[2];return e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5)};y.ansi16.rgb=function(n){let e=n%10;if(e===0||e===7)return n>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let t=(~~(n>50)+1)*.5,r=(e&1)*t*255,o=(e>>1&1)*t*255,s=(e>>2&1)*t*255;return[r,o,s]};y.ansi256.rgb=function(n){if(n>=232){let s=(n-232)*10+8;return[s,s,s]}n-=16;let e,t=Math.floor(n/36)/5*255,r=Math.floor((e=n%36)/6)/5*255,o=e%6/5*255;return[t,r,o]};y.rgb.hex=function(n){let t=(((Math.round(n[0])&255)<<16)+((Math.round(n[1])&255)<<8)+(Math.round(n[2])&255)).toString(16).toUpperCase();return"000000".substring(t.length)+t};y.hex.rgb=function(n){let e=n.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let t=e[0];e[0].length===3&&(t=t.split("").map(a=>a+a).join(""));let r=parseInt(t,16),o=r>>16&255,s=r>>8&255,i=r&255;return[o,s,i]};y.rgb.hcg=function(n){let e=n[0]/255,t=n[1]/255,r=n[2]/255,o=Math.max(Math.max(e,t),r),s=Math.min(Math.min(e,t),r),i=o-s,a,c;return i<1?a=s/(1-i):a=0,i<=0?c=0:o===e?c=(t-r)/i%6:o===t?c=2+(r-e)/i:c=4+(e-t)/i,c/=6,c%=1,[c*360,i*100,a*100]};y.hsl.hcg=function(n){let e=n[1]/100,t=n[2]/100,r=t<.5?2*e*t:2*e*(1-t),o=0;return r<1&&(o=(t-.5*r)/(1-r)),[n[0],r*100,o*100]};y.hsv.hcg=function(n){let e=n[1]/100,t=n[2]/100,r=e*t,o=0;return r<1&&(o=(t-r)/(1-r)),[n[0],r*100,o*100]};y.hcg.rgb=function(n){let e=n[0]/360,t=n[1]/100,r=n[2]/100;if(t===0)return[r*255,r*255,r*255];let o=[0,0,0],s=e%1*6,i=s%1,a=1-i,c=0;switch(Math.floor(s)){case 0:o[0]=1,o[1]=i,o[2]=0;break;case 1:o[0]=a,o[1]=1,o[2]=0;break;case 2:o[0]=0,o[1]=1,o[2]=i;break;case 3:o[0]=0,o[1]=a,o[2]=1;break;case 4:o[0]=i,o[1]=0,o[2]=1;break;default:o[0]=1,o[1]=0,o[2]=a}return c=(1-t)*r,[(t*o[0]+c)*255,(t*o[1]+c)*255,(t*o[2]+c)*255]};y.hcg.hsv=function(n){let e=n[1]/100,t=n[2]/100,r=e+t*(1-e),o=0;return r>0&&(o=e/r),[n[0],o*100,r*100]};y.hcg.hsl=function(n){let e=n[1]/100,r=n[2]/100*(1-e)+.5*e,o=0;return r>0&&r<.5?o=e/(2*r):r>=.5&&r<1&&(o=e/(2*(1-r))),[n[0],o*100,r*100]};y.hcg.hwb=function(n){let e=n[1]/100,t=n[2]/100,r=e+t*(1-e);return[n[0],(r-e)*100,(1-r)*100]};y.hwb.hcg=function(n){let e=n[1]/100,r=1-n[2]/100,o=r-e,s=0;return o<1&&(s=(r-o)/(1-o)),[n[0],o*100,s*100]};y.apple.rgb=function(n){return[n[0]/65535*255,n[1]/65535*255,n[2]/65535*255]};y.rgb.apple=function(n){return[n[0]/255*65535,n[1]/255*65535,n[2]/255*65535]};y.gray.rgb=function(n){return[n[0]/100*255,n[0]/100*255,n[0]/100*255]};y.gray.hsl=function(n){return[0,0,n[0]]};y.gray.hsv=y.gray.hsl;y.gray.hwb=function(n){return[0,100,n[0]]};y.gray.cmyk=function(n){return[0,0,0,n[0]]};y.gray.lab=function(n){return[n[0],0,0]};y.gray.hex=function(n){let e=Math.round(n[0]/100*255)&255,r=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(r.length)+r};y.rgb.gray=function(n){return[(n[0]+n[1]+n[2])/3/255*100]}});var An=F((Xc,Cn)=>{var mt=hr();function Ai(){let n={},e=Object.keys(mt);for(let t=e.length,r=0;r<t;r++)n[e[r]]={distance:-1,parent:null};return n}function Ti(n){let e=Ai(),t=[n];for(e[n].distance=0;t.length;){let r=t.pop(),o=Object.keys(mt[r]);for(let s=o.length,i=0;i<s;i++){let a=o[i],c=e[a];c.distance===-1&&(c.distance=e[r].distance+1,c.parent=r,t.unshift(a))}}return e}function Mi(n,e){return function(t){return e(n(t))}}function Ni(n,e){let t=[e[n].parent,n],r=mt[e[n].parent][n],o=e[n].parent;for(;e[o].parent;)t.unshift(e[o].parent),r=Mi(mt[e[o].parent][o],r),o=e[o].parent;return r.conversion=t,r}Cn.exports=function(n){let e=Ti(n),t={},r=Object.keys(e);for(let o=r.length,s=0;s<o;s++){let i=r[s];e[i].parent!==null&&(t[i]=Ni(i,e))}return t}});var Mn=F((Yc,Tn)=>{var gr=hr(),$i=An(),Ne={},ji=Object.keys(gr);function Ii(n){let e=function(...t){let r=t[0];return r==null?r:(r.length>1&&(t=r),n(t))};return"conversion"in n&&(e.conversion=n.conversion),e}function Di(n){let e=function(...t){let r=t[0];if(r==null)return r;r.length>1&&(t=r);let o=n(t);if(typeof o=="object")for(let s=o.length,i=0;i<s;i++)o[i]=Math.round(o[i]);return o};return"conversion"in n&&(e.conversion=n.conversion),e}ji.forEach(n=>{Ne[n]={},Object.defineProperty(Ne[n],"channels",{value:gr[n].channels}),Object.defineProperty(Ne[n],"labels",{value:gr[n].labels});let e=$i(n);Object.keys(e).forEach(r=>{let o=e[r];Ne[n][r]=Di(o),Ne[n][r].raw=Ii(o)})});Tn.exports=Ne});var Fn=F((Kc,Dn)=>{"use strict";var Nn=(n,e)=>(...t)=>`\x1B[${n(...t)+e}m`,$n=(n,e)=>(...t)=>{let r=n(...t);return`\x1B[${38+e};5;${r}m`},jn=(n,e)=>(...t)=>{let r=n(...t);return`\x1B[${38+e};2;${r[0]};${r[1]};${r[2]}m`},ht=n=>n,In=(n,e,t)=>[n,e,t],$e=(n,e,t)=>{Object.defineProperty(n,e,{get:()=>{let r=t();return Object.defineProperty(n,e,{value:r,enumerable:!0,configurable:!0}),r},enumerable:!0,configurable:!0})},yr,je=(n,e,t,r)=>{yr===void 0&&(yr=Mn());let o=r?10:0,s={};for(let[i,a]of Object.entries(yr)){let c=i==="ansi16"?"ansi":i;i===e?s[c]=n(t,o):typeof a=="object"&&(s[c]=n(a[e],o))}return s};function Fi(){let n=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[t,r]of Object.entries(e)){for(let[o,s]of Object.entries(r))e[o]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},r[o]=e[o],n.set(s[0],s[1]);Object.defineProperty(e,t,{value:r,enumerable:!1})}return Object.defineProperty(e,"codes",{value:n,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",$e(e.color,"ansi",()=>je(Nn,"ansi16",ht,!1)),$e(e.color,"ansi256",()=>je($n,"ansi256",ht,!1)),$e(e.color,"ansi16m",()=>je(jn,"rgb",In,!1)),$e(e.bgColor,"ansi",()=>je(Nn,"ansi16",ht,!0)),$e(e.bgColor,"ansi256",()=>je($n,"ansi256",ht,!0)),$e(e.bgColor,"ansi16m",()=>je(jn,"rgb",In,!0)),e}Object.defineProperty(Dn,"exports",{enumerable:!0,get:Fi})});var Ln=F((zc,Pn)=>{"use strict";Pn.exports=(n,e=process.argv)=>{let t=n.startsWith("-")?"":n.length===1?"-":"--",r=e.indexOf(t+n),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var Bn=F((Qc,Un)=>{"use strict";var Pi=require("os"),Hn=require("tty"),X=Ln(),{env:I}=process,fe;X("no-color")||X("no-colors")||X("color=false")||X("color=never")?fe=0:(X("color")||X("colors")||X("color=true")||X("color=always"))&&(fe=1);"FORCE_COLOR"in I&&(I.FORCE_COLOR==="true"?fe=1:I.FORCE_COLOR==="false"?fe=0:fe=I.FORCE_COLOR.length===0?1:Math.min(parseInt(I.FORCE_COLOR,10),3));function br(n){return n===0?!1:{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function wr(n,e){if(fe===0)return 0;if(X("color=16m")||X("color=full")||X("color=truecolor"))return 3;if(X("color=256"))return 2;if(n&&!e&&fe===void 0)return 0;let t=fe||0;if(I.TERM==="dumb")return t;if(process.platform==="win32"){let r=Pi.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in I)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(r=>r in I)||I.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in I)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(I.TEAMCITY_VERSION)?1:0;if(I.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in I){let r=parseInt((I.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(I.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(I.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(I.TERM)||"COLORTERM"in I?1:t}function Li(n){let e=wr(n,n&&n.isTTY);return br(e)}Un.exports={supportsColor:Li,stdout:br(wr(!0,Hn.isatty(1))),stderr:br(wr(!0,Hn.isatty(2)))}});var Wn=F((Zc,Vn)=>{"use strict";var Hi=(n,e,t)=>{let r=n.indexOf(e);if(r===-1)return n;let o=e.length,s=0,i="";do i+=n.substr(s,r-s)+e+t,s=r+o,r=n.indexOf(e,s);while(r!==-1);return i+=n.substr(s),i},Ui=(n,e,t,r)=>{let o=0,s="";do{let i=n[r-1]==="\r";s+=n.substr(o,(i?r-1:r)-o)+e+(i?`\r
23
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(o=>t.is(o))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function gn(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",o="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?o=s[3]:r=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],r=s[3],o=s[4]),t&&o!=="0"?`${t}=${r}:${parseInt(o)+1}`:e})}yn.Command=fr});var En=F(X=>{var{Argument:_n}=ht(),{Command:hr}=bn(),{CommanderError:Ci,InvalidArgumentError:wn}=Ye(),{Help:Ai}=ir(),{Option:Sn}=ur();X.program=new hr;X.createCommand=n=>new hr(n);X.createOption=(n,e)=>new Sn(n,e);X.createArgument=(n,e)=>new _n(n,e);X.Command=hr;X.Option=Sn;X.Argument=_n;X.Help=Ai;X.CommanderError=Ci;X.InvalidArgumentError=wn;X.InvalidOptionArgumentError=wn});var On=F((Yc,xn)=>{"use strict";xn.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var gr=F((Kc,Cn)=>{var Ke=On(),Rn={};for(let n of Object.keys(Ke))Rn[Ke[n]]=n;var b={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};Cn.exports=b;for(let n of Object.keys(b)){if(!("channels"in b[n]))throw new Error("missing channels property: "+n);if(!("labels"in b[n]))throw new Error("missing channel labels property: "+n);if(b[n].labels.length!==b[n].channels)throw new Error("channel and label counts mismatch: "+n);let{channels:e,labels:t}=b[n];delete b[n].channels,delete b[n].labels,Object.defineProperty(b[n],"channels",{value:e}),Object.defineProperty(b[n],"labels",{value:t})}b.rgb.hsl=function(n){let e=n[0]/255,t=n[1]/255,r=n[2]/255,o=Math.min(e,t,r),s=Math.max(e,t,r),i=s-o,a,c;s===o?a=0:e===s?a=(t-r)/i:t===s?a=2+(r-e)/i:r===s&&(a=4+(e-t)/i),a=Math.min(a*60,360),a<0&&(a+=360);let l=(o+s)/2;return s===o?c=0:l<=.5?c=i/(s+o):c=i/(2-s-o),[a,c*100,l*100]};b.rgb.hsv=function(n){let e,t,r,o,s,i=n[0]/255,a=n[1]/255,c=n[2]/255,l=Math.max(i,a,c),u=l-Math.min(i,a,c),d=function(f){return(l-f)/6/u+1/2};return u===0?(o=0,s=0):(s=u/l,e=d(i),t=d(a),r=d(c),i===l?o=r-t:a===l?o=1/3+e-r:c===l&&(o=2/3+t-e),o<0?o+=1:o>1&&(o-=1)),[o*360,s*100,l*100]};b.rgb.hwb=function(n){let e=n[0],t=n[1],r=n[2],o=b.rgb.hsl(n)[0],s=1/255*Math.min(e,Math.min(t,r));return r=1-1/255*Math.max(e,Math.max(t,r)),[o,s*100,r*100]};b.rgb.cmyk=function(n){let e=n[0]/255,t=n[1]/255,r=n[2]/255,o=Math.min(1-e,1-t,1-r),s=(1-e-o)/(1-o)||0,i=(1-t-o)/(1-o)||0,a=(1-r-o)/(1-o)||0;return[s*100,i*100,a*100,o*100]};function Ti(n,e){return(n[0]-e[0])**2+(n[1]-e[1])**2+(n[2]-e[2])**2}b.rgb.keyword=function(n){let e=Rn[n];if(e)return e;let t=1/0,r;for(let o of Object.keys(Ke)){let s=Ke[o],i=Ti(n,s);i<t&&(t=i,r=o)}return r};b.keyword.rgb=function(n){return Ke[n]};b.rgb.xyz=function(n){let e=n[0]/255,t=n[1]/255,r=n[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92;let o=e*.4124+t*.3576+r*.1805,s=e*.2126+t*.7152+r*.0722,i=e*.0193+t*.1192+r*.9505;return[o*100,s*100,i*100]};b.rgb.lab=function(n){let e=b.rgb.xyz(n),t=e[0],r=e[1],o=e[2];t/=95.047,r/=100,o/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116;let s=116*r-16,i=500*(t-r),a=200*(r-o);return[s,i,a]};b.hsl.rgb=function(n){let e=n[0]/360,t=n[1]/100,r=n[2]/100,o,s,i;if(t===0)return i=r*255,[i,i,i];r<.5?o=r*(1+t):o=r+t-r*t;let a=2*r-o,c=[0,0,0];for(let l=0;l<3;l++)s=e+1/3*-(l-1),s<0&&s++,s>1&&s--,6*s<1?i=a+(o-a)*6*s:2*s<1?i=o:3*s<2?i=a+(o-a)*(2/3-s)*6:i=a,c[l]=i*255;return c};b.hsl.hsv=function(n){let e=n[0],t=n[1]/100,r=n[2]/100,o=t,s=Math.max(r,.01);r*=2,t*=r<=1?r:2-r,o*=s<=1?s:2-s;let i=(r+t)/2,a=r===0?2*o/(s+o):2*t/(r+t);return[e,a*100,i*100]};b.hsv.rgb=function(n){let e=n[0]/60,t=n[1]/100,r=n[2]/100,o=Math.floor(e)%6,s=e-Math.floor(e),i=255*r*(1-t),a=255*r*(1-t*s),c=255*r*(1-t*(1-s));switch(r*=255,o){case 0:return[r,c,i];case 1:return[a,r,i];case 2:return[i,r,c];case 3:return[i,a,r];case 4:return[c,i,r];case 5:return[r,i,a]}};b.hsv.hsl=function(n){let e=n[0],t=n[1]/100,r=n[2]/100,o=Math.max(r,.01),s,i;i=(2-t)*r;let a=(2-t)*o;return s=t*o,s/=a<=1?a:2-a,s=s||0,i/=2,[e,s*100,i*100]};b.hwb.rgb=function(n){let e=n[0]/360,t=n[1]/100,r=n[2]/100,o=t+r,s;o>1&&(t/=o,r/=o);let i=Math.floor(6*e),a=1-r;s=6*e-i,(i&1)!==0&&(s=1-s);let c=t+s*(a-t),l,u,d;switch(i){default:case 6:case 0:l=a,u=c,d=t;break;case 1:l=c,u=a,d=t;break;case 2:l=t,u=a,d=c;break;case 3:l=t,u=c,d=a;break;case 4:l=c,u=t,d=a;break;case 5:l=a,u=t,d=c;break}return[l*255,u*255,d*255]};b.cmyk.rgb=function(n){let e=n[0]/100,t=n[1]/100,r=n[2]/100,o=n[3]/100,s=1-Math.min(1,e*(1-o)+o),i=1-Math.min(1,t*(1-o)+o),a=1-Math.min(1,r*(1-o)+o);return[s*255,i*255,a*255]};b.xyz.rgb=function(n){let e=n[0]/100,t=n[1]/100,r=n[2]/100,o,s,i;return o=e*3.2406+t*-1.5372+r*-.4986,s=e*-.9689+t*1.8758+r*.0415,i=e*.0557+t*-.204+r*1.057,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,o=Math.min(Math.max(0,o),1),s=Math.min(Math.max(0,s),1),i=Math.min(Math.max(0,i),1),[o*255,s*255,i*255]};b.xyz.lab=function(n){let e=n[0],t=n[1],r=n[2];e/=95.047,t/=100,r/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,t=t>.008856?t**(1/3):7.787*t+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;let o=116*t-16,s=500*(e-t),i=200*(t-r);return[o,s,i]};b.lab.xyz=function(n){let e=n[0],t=n[1],r=n[2],o,s,i;s=(e+16)/116,o=t/500+s,i=s-r/200;let a=s**3,c=o**3,l=i**3;return s=a>.008856?a:(s-16/116)/7.787,o=c>.008856?c:(o-16/116)/7.787,i=l>.008856?l:(i-16/116)/7.787,o*=95.047,s*=100,i*=108.883,[o,s,i]};b.lab.lch=function(n){let e=n[0],t=n[1],r=n[2],o;o=Math.atan2(r,t)*360/2/Math.PI,o<0&&(o+=360);let i=Math.sqrt(t*t+r*r);return[e,i,o]};b.lch.lab=function(n){let e=n[0],t=n[1],o=n[2]/360*2*Math.PI,s=t*Math.cos(o),i=t*Math.sin(o);return[e,s,i]};b.rgb.ansi16=function(n,e=null){let[t,r,o]=n,s=e===null?b.rgb.hsv(n)[2]:e;if(s=Math.round(s/50),s===0)return 30;let i=30+(Math.round(o/255)<<2|Math.round(r/255)<<1|Math.round(t/255));return s===2&&(i+=60),i};b.hsv.ansi16=function(n){return b.rgb.ansi16(b.hsv.rgb(n),n[2])};b.rgb.ansi256=function(n){let e=n[0],t=n[1],r=n[2];return e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5)};b.ansi16.rgb=function(n){let e=n%10;if(e===0||e===7)return n>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let t=(~~(n>50)+1)*.5,r=(e&1)*t*255,o=(e>>1&1)*t*255,s=(e>>2&1)*t*255;return[r,o,s]};b.ansi256.rgb=function(n){if(n>=232){let s=(n-232)*10+8;return[s,s,s]}n-=16;let e,t=Math.floor(n/36)/5*255,r=Math.floor((e=n%36)/6)/5*255,o=e%6/5*255;return[t,r,o]};b.rgb.hex=function(n){let t=(((Math.round(n[0])&255)<<16)+((Math.round(n[1])&255)<<8)+(Math.round(n[2])&255)).toString(16).toUpperCase();return"000000".substring(t.length)+t};b.hex.rgb=function(n){let e=n.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let t=e[0];e[0].length===3&&(t=t.split("").map(a=>a+a).join(""));let r=parseInt(t,16),o=r>>16&255,s=r>>8&255,i=r&255;return[o,s,i]};b.rgb.hcg=function(n){let e=n[0]/255,t=n[1]/255,r=n[2]/255,o=Math.max(Math.max(e,t),r),s=Math.min(Math.min(e,t),r),i=o-s,a,c;return i<1?a=s/(1-i):a=0,i<=0?c=0:o===e?c=(t-r)/i%6:o===t?c=2+(r-e)/i:c=4+(e-t)/i,c/=6,c%=1,[c*360,i*100,a*100]};b.hsl.hcg=function(n){let e=n[1]/100,t=n[2]/100,r=t<.5?2*e*t:2*e*(1-t),o=0;return r<1&&(o=(t-.5*r)/(1-r)),[n[0],r*100,o*100]};b.hsv.hcg=function(n){let e=n[1]/100,t=n[2]/100,r=e*t,o=0;return r<1&&(o=(t-r)/(1-r)),[n[0],r*100,o*100]};b.hcg.rgb=function(n){let e=n[0]/360,t=n[1]/100,r=n[2]/100;if(t===0)return[r*255,r*255,r*255];let o=[0,0,0],s=e%1*6,i=s%1,a=1-i,c=0;switch(Math.floor(s)){case 0:o[0]=1,o[1]=i,o[2]=0;break;case 1:o[0]=a,o[1]=1,o[2]=0;break;case 2:o[0]=0,o[1]=1,o[2]=i;break;case 3:o[0]=0,o[1]=a,o[2]=1;break;case 4:o[0]=i,o[1]=0,o[2]=1;break;default:o[0]=1,o[1]=0,o[2]=a}return c=(1-t)*r,[(t*o[0]+c)*255,(t*o[1]+c)*255,(t*o[2]+c)*255]};b.hcg.hsv=function(n){let e=n[1]/100,t=n[2]/100,r=e+t*(1-e),o=0;return r>0&&(o=e/r),[n[0],o*100,r*100]};b.hcg.hsl=function(n){let e=n[1]/100,r=n[2]/100*(1-e)+.5*e,o=0;return r>0&&r<.5?o=e/(2*r):r>=.5&&r<1&&(o=e/(2*(1-r))),[n[0],o*100,r*100]};b.hcg.hwb=function(n){let e=n[1]/100,t=n[2]/100,r=e+t*(1-e);return[n[0],(r-e)*100,(1-r)*100]};b.hwb.hcg=function(n){let e=n[1]/100,r=1-n[2]/100,o=r-e,s=0;return o<1&&(s=(r-o)/(1-o)),[n[0],o*100,s*100]};b.apple.rgb=function(n){return[n[0]/65535*255,n[1]/65535*255,n[2]/65535*255]};b.rgb.apple=function(n){return[n[0]/255*65535,n[1]/255*65535,n[2]/255*65535]};b.gray.rgb=function(n){return[n[0]/100*255,n[0]/100*255,n[0]/100*255]};b.gray.hsl=function(n){return[0,0,n[0]]};b.gray.hsv=b.gray.hsl;b.gray.hwb=function(n){return[0,100,n[0]]};b.gray.cmyk=function(n){return[0,0,0,n[0]]};b.gray.lab=function(n){return[n[0],0,0]};b.gray.hex=function(n){let e=Math.round(n[0]/100*255)&255,r=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(r.length)+r};b.rgb.gray=function(n){return[(n[0]+n[1]+n[2])/3/255*100]}});var Tn=F((zc,An)=>{var gt=gr();function Mi(){let n={},e=Object.keys(gt);for(let t=e.length,r=0;r<t;r++)n[e[r]]={distance:-1,parent:null};return n}function Ni(n){let e=Mi(),t=[n];for(e[n].distance=0;t.length;){let r=t.pop(),o=Object.keys(gt[r]);for(let s=o.length,i=0;i<s;i++){let a=o[i],c=e[a];c.distance===-1&&(c.distance=e[r].distance+1,c.parent=r,t.unshift(a))}}return e}function $i(n,e){return function(t){return e(n(t))}}function Ii(n,e){let t=[e[n].parent,n],r=gt[e[n].parent][n],o=e[n].parent;for(;e[o].parent;)t.unshift(e[o].parent),r=$i(gt[e[o].parent][o],r),o=e[o].parent;return r.conversion=t,r}An.exports=function(n){let e=Ni(n),t={},r=Object.keys(e);for(let o=r.length,s=0;s<o;s++){let i=r[s];e[i].parent!==null&&(t[i]=Ii(i,e))}return t}});var Nn=F((Qc,Mn)=>{var yr=gr(),ji=Tn(),$e={},Pi=Object.keys(yr);function Di(n){let e=function(...t){let r=t[0];return r==null?r:(r.length>1&&(t=r),n(t))};return"conversion"in n&&(e.conversion=n.conversion),e}function Fi(n){let e=function(...t){let r=t[0];if(r==null)return r;r.length>1&&(t=r);let o=n(t);if(typeof o=="object")for(let s=o.length,i=0;i<s;i++)o[i]=Math.round(o[i]);return o};return"conversion"in n&&(e.conversion=n.conversion),e}Pi.forEach(n=>{$e[n]={},Object.defineProperty($e[n],"channels",{value:yr[n].channels}),Object.defineProperty($e[n],"labels",{value:yr[n].labels});let e=ji(n);Object.keys(e).forEach(r=>{let o=e[r];$e[n][r]=Fi(o),$e[n][r].raw=Di(o)})});Mn.exports=$e});var Fn=F((Zc,Dn)=>{"use strict";var $n=(n,e)=>(...t)=>`\x1B[${n(...t)+e}m`,In=(n,e)=>(...t)=>{let r=n(...t);return`\x1B[${38+e};5;${r}m`},jn=(n,e)=>(...t)=>{let r=n(...t);return`\x1B[${38+e};2;${r[0]};${r[1]};${r[2]}m`},yt=n=>n,Pn=(n,e,t)=>[n,e,t],Ie=(n,e,t)=>{Object.defineProperty(n,e,{get:()=>{let r=t();return Object.defineProperty(n,e,{value:r,enumerable:!0,configurable:!0}),r},enumerable:!0,configurable:!0})},br,je=(n,e,t,r)=>{br===void 0&&(br=Nn());let o=r?10:0,s={};for(let[i,a]of Object.entries(br)){let c=i==="ansi16"?"ansi":i;i===e?s[c]=n(t,o):typeof a=="object"&&(s[c]=n(a[e],o))}return s};function Li(){let n=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[t,r]of Object.entries(e)){for(let[o,s]of Object.entries(r))e[o]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},r[o]=e[o],n.set(s[0],s[1]);Object.defineProperty(e,t,{value:r,enumerable:!1})}return Object.defineProperty(e,"codes",{value:n,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",Ie(e.color,"ansi",()=>je($n,"ansi16",yt,!1)),Ie(e.color,"ansi256",()=>je(In,"ansi256",yt,!1)),Ie(e.color,"ansi16m",()=>je(jn,"rgb",Pn,!1)),Ie(e.bgColor,"ansi",()=>je($n,"ansi16",yt,!0)),Ie(e.bgColor,"ansi256",()=>je(In,"ansi256",yt,!0)),Ie(e.bgColor,"ansi16m",()=>je(jn,"rgb",Pn,!0)),e}Object.defineProperty(Dn,"exports",{enumerable:!0,get:Li})});var Hn=F((el,Ln)=>{"use strict";Ln.exports=(n,e=process.argv)=>{let t=n.startsWith("-")?"":n.length===1?"-":"--",r=e.indexOf(t+n),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var Vn=F((tl,Bn)=>{"use strict";var Hi=require("os"),Un=require("tty"),Y=Hn(),{env:P}=process,me;Y("no-color")||Y("no-colors")||Y("color=false")||Y("color=never")?me=0:(Y("color")||Y("colors")||Y("color=true")||Y("color=always"))&&(me=1);"FORCE_COLOR"in P&&(P.FORCE_COLOR==="true"?me=1:P.FORCE_COLOR==="false"?me=0:me=P.FORCE_COLOR.length===0?1:Math.min(parseInt(P.FORCE_COLOR,10),3));function _r(n){return n===0?!1:{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function wr(n,e){if(me===0)return 0;if(Y("color=16m")||Y("color=full")||Y("color=truecolor"))return 3;if(Y("color=256"))return 2;if(n&&!e&&me===void 0)return 0;let t=me||0;if(P.TERM==="dumb")return t;if(process.platform==="win32"){let r=Hi.release().split(".");return Number(r[0])>=10&&Number(r[2])>=10586?Number(r[2])>=14931?3:2:1}if("CI"in P)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(r=>r in P)||P.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in P)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(P.TEAMCITY_VERSION)?1:0;if(P.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in P){let r=parseInt((P.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(P.TERM_PROGRAM){case"iTerm.app":return r>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(P.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(P.TERM)||"COLORTERM"in P?1:t}function Ui(n){let e=wr(n,n&&n.isTTY);return _r(e)}Bn.exports={supportsColor:Ui,stdout:_r(wr(!0,Un.isatty(1))),stderr:_r(wr(!0,Un.isatty(2)))}});var Jn=F((rl,Wn)=>{"use strict";var Bi=(n,e,t)=>{let r=n.indexOf(e);if(r===-1)return n;let o=e.length,s=0,i="";do i+=n.substr(s,r-s)+e+t,s=r+o,r=n.indexOf(e,s);while(r!==-1);return i+=n.substr(s),i},Vi=(n,e,t,r)=>{let o=0,s="";do{let i=n[r-1]==="\r";s+=n.substr(o,(i?r-1:r)-o)+e+(i?`\r
24
24
  `:`
25
25
  `)+t,o=r+1,r=n.indexOf(`
26
- `,o)}while(r!==-1);return s+=n.substr(o),s};Vn.exports={stringReplaceAll:Hi,stringEncaseCRLFWithFirstIndex:Ui}});var Yn=F((el,Xn)=>{"use strict";var Bi=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,Jn=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,Vi=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,Wi=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,Ji=new Map([["n",`
27
- `],["r","\r"],["t"," "],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e","\x1B"],["a","\x07"]]);function Gn(n){let e=n[0]==="u",t=n[1]==="{";return e&&!t&&n.length===5||n[0]==="x"&&n.length===3?String.fromCharCode(parseInt(n.slice(1),16)):e&&t?String.fromCodePoint(parseInt(n.slice(2,-1),16)):Ji.get(n)||n}function qi(n,e){let t=[],r=e.trim().split(/\s*,\s*/g),o;for(let s of r){let i=Number(s);if(!Number.isNaN(i))t.push(i);else if(o=s.match(Vi))t.push(o[2].replace(Wi,(a,c,l)=>c?Gn(c):l));else throw new Error(`Invalid Chalk template style argument: ${s} (in style '${n}')`)}return t}function Gi(n){Jn.lastIndex=0;let e=[],t;for(;(t=Jn.exec(n))!==null;){let r=t[1];if(t[2]){let o=qi(r,t[2]);e.push([r].concat(o))}else e.push([r])}return e}function qn(n,e){let t={};for(let o of e)for(let s of o.styles)t[s[0]]=o.inverse?null:s.slice(1);let r=n;for(let[o,s]of Object.entries(t))if(Array.isArray(s)){if(!(o in r))throw new Error(`Unknown Chalk style: ${o}`);r=s.length>0?r[o](...s):r[o]}return r}Xn.exports=(n,e)=>{let t=[],r=[],o=[];if(e.replace(Bi,(s,i,a,c,l,u)=>{if(i)o.push(Gn(i));else if(c){let d=o.join("");o=[],r.push(t.length===0?d:qn(n,t)(d)),t.push({inverse:a,styles:Gi(c)})}else if(l){if(t.length===0)throw new Error("Found extraneous } in Chalk template literal");r.push(qn(n,t)(o.join(""))),o=[],t.pop()}else o.push(u)}),r.push(o.join("")),t.length>0){let s=`Chalk template literal is missing ${t.length} closing bracket${t.length===1?"":"s"} (\`}\`)`;throw new Error(s)}return r.join("")}});var V=F((tl,to)=>{"use strict";var Ye=Fn(),{stdout:Sr,stderr:Er}=Bn(),{stringReplaceAll:Xi,stringEncaseCRLFWithFirstIndex:Yi}=Wn(),{isArray:gt}=Array,zn=["ansi","ansi","ansi256","ansi16m"],Ie=Object.create(null),Ki=(n,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let t=Sr?Sr.level:0;n.level=e.level===void 0?t:e.level},vr=class{constructor(e){return Qn(e)}},Qn=n=>{let e={};return Ki(e,n),e.template=(...t)=>eo(e.template,...t),Object.setPrototypeOf(e,yt.prototype),Object.setPrototypeOf(e.template,e),e.template.constructor=()=>{throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},e.template.Instance=vr,e.template};function yt(n){return Qn(n)}for(let[n,e]of Object.entries(Ye))Ie[n]={get(){let t=bt(this,kr(e.open,e.close,this._styler),this._isEmpty);return Object.defineProperty(this,n,{value:t}),t}};Ie.visible={get(){let n=bt(this,this._styler,!0);return Object.defineProperty(this,"visible",{value:n}),n}};var Zn=["rgb","hex","keyword","hsl","hsv","hwb","ansi","ansi256"];for(let n of Zn)Ie[n]={get(){let{level:e}=this;return function(...t){let r=kr(Ye.color[zn[e]][n](...t),Ye.color.close,this._styler);return bt(this,r,this._isEmpty)}}};for(let n of Zn){let e="bg"+n[0].toUpperCase()+n.slice(1);Ie[e]={get(){let{level:t}=this;return function(...r){let o=kr(Ye.bgColor[zn[t]][n](...r),Ye.bgColor.close,this._styler);return bt(this,o,this._isEmpty)}}}}var zi=Object.defineProperties(()=>{},{...Ie,level:{enumerable:!0,get(){return this._generator.level},set(n){this._generator.level=n}}}),kr=(n,e,t)=>{let r,o;return t===void 0?(r=n,o=e):(r=t.openAll+n,o=e+t.closeAll),{open:n,close:e,openAll:r,closeAll:o,parent:t}},bt=(n,e,t)=>{let r=(...o)=>gt(o[0])&&gt(o[0].raw)?Kn(r,eo(r,...o)):Kn(r,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(r,zi),r._generator=n,r._styler=e,r._isEmpty=t,r},Kn=(n,e)=>{if(n.level<=0||!e)return n._isEmpty?"":e;let t=n._styler;if(t===void 0)return e;let{openAll:r,closeAll:o}=t;if(e.indexOf("\x1B")!==-1)for(;t!==void 0;)e=Xi(e,t.close,t.open),t=t.parent;let s=e.indexOf(`
28
- `);return s!==-1&&(e=Yi(e,o,r,s)),r+e+o},_r,eo=(n,...e)=>{let[t]=e;if(!gt(t)||!gt(t.raw))return e.join(" ");let r=e.slice(1),o=[t.raw[0]];for(let s=1;s<t.length;s++)o.push(String(r[s-1]).replace(/[{}\\]/g,"\\$&"),String(t.raw[s]));return _r===void 0&&(_r=Yn()),_r(n,o.join(""))};Object.defineProperties(yt.prototype,Ie);var wt=yt();wt.supportsColor=Sr;wt.stderr=yt({level:Er?Er.level:0});wt.stderr.supportsColor=Er;to.exports=wt});function no(){let n=new Set;process.env.AIDE_DEBUG_HOOK==="1"&&n.add("hooks");let e=process.env.AIDE_DEBUG;if(!e)return n;let t=e.split(",").map(r=>r.trim()).filter(Boolean);for(let r of t){if(r==="all"||r==="1"){for(let o of ro)n.add(o);return n}ro.includes(r)&&n.add(r)}return n}function Q(n,e){no().has(n)&&process.stderr.write(`[AIDE_DEBUG/${n}] ${e}
29
- `)}function _e(n,e){let t=e?` \u2014 ${e}`:"";process.stderr.write(`[AIDE_ERROR] ${n}${t}
30
- `)}function oo(n){return no().has(n)}var ro,_t=$(()=>{"use strict";ro=["hooks","mcp","binding","recall"]});function Qi(n){let e=n?.message??String(n);return/NODE_MODULE_VERSION/i.test(e)?{class:"abi-mismatch",hint:"reinstall aide-memory or run `npm rebuild libsql` in the install dir"}:/Cannot find module|MODULE_NOT_FOUND/i.test(e)?{class:"missing-module",hint:"reinstall aide-memory \u2014 the libsql platform package may be missing"}:/dlopen|wrong ELF class|invalid ELF header|image not found|symbol not found/i.test(e)?{class:"binary-incompatible",hint:"reinstall aide-memory \u2014 prebuilt binary may be wrong for this platform/arch"}:{class:"unknown",hint:"reinstall aide-memory; if the issue persists, file an issue with this stderr line"}}function Zi(){if(xr)return xr;try{let n=require("libsql");return xr=n,Q("binding",`loaded lib=libsql node=${process.versions.node} abi=${process.versions.modules} platform=${process.platform}-${process.arch}`),n}catch(n){let{class:e,hint:t}=Qi(n),r=n?.message??String(n);throw _e(`aide-memory: failed to load native binding (libsql, ${e}): ${r}`,t),Q("binding",`load-failed lib=libsql class=${e} msg=${JSON.stringify(r)}`),n}}function so(n,e){let t=Zi();return new t(n,e)}var xr,io=$(()=>{"use strict";_t();xr=null});function sa(n){try{return n.exec("CREATE VIRTUAL TABLE IF NOT EXISTS _fts5_probe USING fts5(x)"),n.exec("DROP TABLE IF EXISTS _fts5_probe"),!0}catch{return!1}}function ao(n){return sa(n)?(n.exec(ea),n.exec(ta),n.exec(ra),n.exec(na),!0):!1}function co(n){n.prepare("SELECT COUNT(*) as c FROM memories").get().c===0||n.prepare("SELECT COUNT(*) as c FROM memories_fts").get().c>0||n.exec(`
26
+ `,o)}while(r!==-1);return s+=n.substr(o),s};Wn.exports={stringReplaceAll:Bi,stringEncaseCRLFWithFirstIndex:Vi}});var Kn=F((nl,Yn)=>{"use strict";var Wi=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,qn=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,Ji=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,qi=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,Gi=new Map([["n",`
27
+ `],["r","\r"],["t"," "],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e","\x1B"],["a","\x07"]]);function Xn(n){let e=n[0]==="u",t=n[1]==="{";return e&&!t&&n.length===5||n[0]==="x"&&n.length===3?String.fromCharCode(parseInt(n.slice(1),16)):e&&t?String.fromCodePoint(parseInt(n.slice(2,-1),16)):Gi.get(n)||n}function Xi(n,e){let t=[],r=e.trim().split(/\s*,\s*/g),o;for(let s of r){let i=Number(s);if(!Number.isNaN(i))t.push(i);else if(o=s.match(Ji))t.push(o[2].replace(qi,(a,c,l)=>c?Xn(c):l));else throw new Error(`Invalid Chalk template style argument: ${s} (in style '${n}')`)}return t}function Yi(n){qn.lastIndex=0;let e=[],t;for(;(t=qn.exec(n))!==null;){let r=t[1];if(t[2]){let o=Xi(r,t[2]);e.push([r].concat(o))}else e.push([r])}return e}function Gn(n,e){let t={};for(let o of e)for(let s of o.styles)t[s[0]]=o.inverse?null:s.slice(1);let r=n;for(let[o,s]of Object.entries(t))if(Array.isArray(s)){if(!(o in r))throw new Error(`Unknown Chalk style: ${o}`);r=s.length>0?r[o](...s):r[o]}return r}Yn.exports=(n,e)=>{let t=[],r=[],o=[];if(e.replace(Wi,(s,i,a,c,l,u)=>{if(i)o.push(Xn(i));else if(c){let d=o.join("");o=[],r.push(t.length===0?d:Gn(n,t)(d)),t.push({inverse:a,styles:Yi(c)})}else if(l){if(t.length===0)throw new Error("Found extraneous } in Chalk template literal");r.push(Gn(n,t)(o.join(""))),o=[],t.pop()}else o.push(u)}),r.push(o.join("")),t.length>0){let s=`Chalk template literal is missing ${t.length} closing bracket${t.length===1?"":"s"} (\`}\`)`;throw new Error(s)}return r.join("")}});var J=F((ol,ro)=>{"use strict";var ze=Fn(),{stdout:Er,stderr:vr}=Vn(),{stringReplaceAll:Ki,stringEncaseCRLFWithFirstIndex:zi}=Jn(),{isArray:bt}=Array,Qn=["ansi","ansi","ansi256","ansi16m"],Pe=Object.create(null),Qi=(n,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let t=Er?Er.level:0;n.level=e.level===void 0?t:e.level},kr=class{constructor(e){return Zn(e)}},Zn=n=>{let e={};return Qi(e,n),e.template=(...t)=>to(e.template,...t),Object.setPrototypeOf(e,_t.prototype),Object.setPrototypeOf(e.template,e),e.template.constructor=()=>{throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},e.template.Instance=kr,e.template};function _t(n){return Zn(n)}for(let[n,e]of Object.entries(ze))Pe[n]={get(){let t=wt(this,xr(e.open,e.close,this._styler),this._isEmpty);return Object.defineProperty(this,n,{value:t}),t}};Pe.visible={get(){let n=wt(this,this._styler,!0);return Object.defineProperty(this,"visible",{value:n}),n}};var eo=["rgb","hex","keyword","hsl","hsv","hwb","ansi","ansi256"];for(let n of eo)Pe[n]={get(){let{level:e}=this;return function(...t){let r=xr(ze.color[Qn[e]][n](...t),ze.color.close,this._styler);return wt(this,r,this._isEmpty)}}};for(let n of eo){let e="bg"+n[0].toUpperCase()+n.slice(1);Pe[e]={get(){let{level:t}=this;return function(...r){let o=xr(ze.bgColor[Qn[t]][n](...r),ze.bgColor.close,this._styler);return wt(this,o,this._isEmpty)}}}}var Zi=Object.defineProperties(()=>{},{...Pe,level:{enumerable:!0,get(){return this._generator.level},set(n){this._generator.level=n}}}),xr=(n,e,t)=>{let r,o;return t===void 0?(r=n,o=e):(r=t.openAll+n,o=e+t.closeAll),{open:n,close:e,openAll:r,closeAll:o,parent:t}},wt=(n,e,t)=>{let r=(...o)=>bt(o[0])&&bt(o[0].raw)?zn(r,to(r,...o)):zn(r,o.length===1?""+o[0]:o.join(" "));return Object.setPrototypeOf(r,Zi),r._generator=n,r._styler=e,r._isEmpty=t,r},zn=(n,e)=>{if(n.level<=0||!e)return n._isEmpty?"":e;let t=n._styler;if(t===void 0)return e;let{openAll:r,closeAll:o}=t;if(e.indexOf("\x1B")!==-1)for(;t!==void 0;)e=Ki(e,t.close,t.open),t=t.parent;let s=e.indexOf(`
28
+ `);return s!==-1&&(e=zi(e,o,r,s)),r+e+o},Sr,to=(n,...e)=>{let[t]=e;if(!bt(t)||!bt(t.raw))return e.join(" ");let r=e.slice(1),o=[t.raw[0]];for(let s=1;s<t.length;s++)o.push(String(r[s-1]).replace(/[{}\\]/g,"\\$&"),String(t.raw[s]));return Sr===void 0&&(Sr=Kn()),Sr(n,o.join(""))};Object.defineProperties(_t.prototype,Pe);var St=_t();St.supportsColor=Er;St.stderr=_t({level:vr?vr.level:0});St.stderr.supportsColor=vr;ro.exports=St});function oo(){let n=new Set;process.env.AIDE_DEBUG_HOOK==="1"&&n.add("hooks");let e=process.env.AIDE_DEBUG;if(!e)return n;let t=e.split(",").map(r=>r.trim()).filter(Boolean);for(let r of t){if(r==="all"||r==="1"){for(let o of no)n.add(o);return n}no.includes(r)&&n.add(r)}return n}function Z(n,e){oo().has(n)&&process.stderr.write(`[AIDE_DEBUG/${n}] ${e}
29
+ `)}function we(n,e){let t=e?` \u2014 ${e}`:"";process.stderr.write(`[AIDE_ERROR] ${n}${t}
30
+ `)}function so(n){return oo().has(n)}var no,Et=T(()=>{"use strict";no=["hooks","mcp","binding","recall"]});function ea(n){let e=n?.message??String(n);return/NODE_MODULE_VERSION/i.test(e)?{class:"abi-mismatch",hint:"reinstall aide-memory or run `npm rebuild libsql` in the install dir"}:/Cannot find module|MODULE_NOT_FOUND/i.test(e)?{class:"missing-module",hint:"reinstall aide-memory \u2014 the libsql platform package may be missing"}:/dlopen|wrong ELF class|invalid ELF header|image not found|symbol not found/i.test(e)?{class:"binary-incompatible",hint:"reinstall aide-memory \u2014 prebuilt binary may be wrong for this platform/arch"}:{class:"unknown",hint:"reinstall aide-memory; if the issue persists, file an issue with this stderr line"}}function ta(){if(Or)return Or;try{let n=require("libsql");return Or=n,Z("binding",`loaded lib=libsql node=${process.versions.node} abi=${process.versions.modules} platform=${process.platform}-${process.arch}`),n}catch(n){let{class:e,hint:t}=ea(n),r=n?.message??String(n);throw we(`aide-memory: failed to load native binding (libsql, ${e}): ${r}`,t),Z("binding",`load-failed lib=libsql class=${e} msg=${JSON.stringify(r)}`),n}}function io(n,e){let t=ta();return new t(n,e)}var Or,ao=T(()=>{"use strict";Et();Or=null});function aa(n){try{return n.exec("CREATE VIRTUAL TABLE IF NOT EXISTS _fts5_probe USING fts5(x)"),n.exec("DROP TABLE IF EXISTS _fts5_probe"),!0}catch{return!1}}function co(n){return aa(n)?(n.exec(ra),n.exec(na),n.exec(oa),n.exec(sa),!0):!1}function lo(n){n.prepare("SELECT COUNT(*) as c FROM memories").get().c===0||n.prepare("SELECT COUNT(*) as c FROM memories_fts").get().c>0||n.exec(`
31
31
  INSERT INTO memories_fts(rowid, what, why, context_label)
32
32
  SELECT id, what, why, context_label FROM memories
33
- `)}function lo(n){if(!n||!n.trim())return null;let e=n.slice(0,500);if(e=e.replace(oa," "),e=e.replace(/\s+/g," ").trim(),!e)return null;let t=e.split(" ").filter(r=>r.length>0);return t.length===0?null:t.map(r=>`"${r}"`).join(" ")}var ea,ta,ra,na,oa,uo=$(()=>{"use strict";ea=`
33
+ `)}function uo(n){if(!n||!n.trim())return null;let e=n.slice(0,500);if(e=e.replace(ia," "),e=e.replace(/\s+/g," ").trim(),!e)return null;let t=e.split(" ").filter(r=>r.length>0);return t.length===0?null:t.map(r=>`"${r}"`).join(" ")}var ra,na,oa,sa,ia,po=T(()=>{"use strict";ra=`
34
34
  CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
35
35
  what, why, context_label,
36
36
  content=memories, content_rowid=id
37
37
  );
38
- `,ta=`
38
+ `,na=`
39
39
  CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN
40
40
  INSERT INTO memories_fts(rowid, what, why, context_label)
41
41
  VALUES (new.id, new.what, new.why, new.context_label);
42
42
  END;
43
- `,ra=`
43
+ `,oa=`
44
44
  CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN
45
45
  INSERT INTO memories_fts(memories_fts, rowid, what, why, context_label)
46
46
  VALUES ('delete', old.id, old.what, old.why, old.context_label);
47
47
  END;
48
- `,na=`
48
+ `,sa=`
49
49
  CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
50
50
  INSERT INTO memories_fts(memories_fts, rowid, what, why, context_label)
51
51
  VALUES ('delete', old.id, old.what, old.why, old.context_label);
52
52
  INSERT INTO memories_fts(rowid, what, why, context_label)
53
53
  VALUES (new.id, new.what, new.why, new.context_label);
54
54
  END;
55
- `,oa=/["*(){}[\]:^~!@#$%&+\\|<>=,;]/g});function aa(n,e){if(n.length!==e.length||n.length===0)return 0;let t=0,r=0,o=0;for(let i=0;i<n.length;i++)t+=n[i]*e[i],r+=n[i]*n[i],o+=e[i]*e[i];let s=Math.sqrt(r)*Math.sqrt(o);return s===0?0:t/s}function ca(n){return Buffer.from(n.buffer,n.byteOffset,n.byteLength)}function po(n){if(n instanceof ArrayBuffer)return new Float32Array(n.slice(0));let e=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);return new Float32Array(e)}function St(n){n.exec(ia)}var ia,Ke,ze,Et,fo=$(()=>{"use strict";ia=`
55
+ `,ia=/["*(){}[\]:^~!@#$%&+\\|<>=,;]/g});function la(n,e){if(n.length!==e.length||n.length===0)return 0;let t=0,r=0,o=0;for(let i=0;i<n.length;i++)t+=n[i]*e[i],r+=n[i]*n[i],o+=e[i]*e[i];let s=Math.sqrt(r)*Math.sqrt(o);return s===0?0:t/s}function ua(n){return Buffer.from(n.buffer,n.byteOffset,n.byteLength)}function mo(n){if(n instanceof ArrayBuffer)return new Float32Array(n.slice(0));let e=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);return new Float32Array(e)}function vt(n){n.exec(ca)}var ca,Qe,Ze,kt,fo=T(()=>{"use strict";ca=`
56
56
  CREATE TABLE IF NOT EXISTS embeddings (
57
57
  uuid TEXT PRIMARY KEY,
58
58
  vector BLOB NOT NULL,
59
59
  dimensions INTEGER NOT NULL
60
60
  );
61
- `;Ke=class{constructor(e="Xenova/bge-small-en-v1.5"){this.modelName=e;this.pipeline=null;this.ready=!1}async initialize(){try{let{pipeline:e,env:t}=await import("@huggingface/transformers"),r=await import("os"),o=await import("path");return t.cacheDir=o.join(r.homedir(),".cache","aide-memory","models"),this.pipeline=await e("feature-extraction",this.modelName,{dtype:"fp32"}),this.ready=!0,!0}catch{return this.ready=!1,!1}}isReady(){return this.ready}async generateEmbedding(e){if(!this.ready||!this.pipeline)return null;try{let t=await this.pipeline(e,{pooling:"mean",normalize:!0});return new Float32Array(t.data)}catch{return null}}},ze=class{constructor(e="nomic-embed-text",t="http://localhost:11434"){this.model=e;this.baseUrl=t;this.ready=!1}async initialize(){try{return(await fetch(`${this.baseUrl}/api/tags`)).ok?(this.ready=!0,!0):(this.ready=!1,!1)}catch{return this.ready=!1,!1}}isReady(){return this.ready}async generateEmbedding(e){if(!this.ready)return null;try{let t=await fetch(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,prompt:e})});if(!t.ok)return null;let r=await t.json();return!r.embedding||!Array.isArray(r.embedding)?null:new Float32Array(r.embedding)}catch{return null}}},Et=class{constructor(e){this.preferredBackend=e;this.backend=null;this._ready=!1}async initialize(){if(this.preferredBackend)return await this.preferredBackend.initialize()?(this.backend=this.preferredBackend,this._ready=!0,!0):(this._ready=!1,!1);let e=new Ke;if(await e.initialize())return this.backend=e,this._ready=!0,!0;let r=new ze;return await r.initialize()?(this.backend=r,this._ready=!0,!0):(this._ready=!1,!1)}isReady(){return this._ready}async generateEmbedding(e){return!this._ready||!this.backend?null:this.backend.generateEmbedding(e)}storeEmbedding(e,t,r){St(e);let o=ca(r);e.prepare("INSERT OR REPLACE INTO embeddings (uuid, vector, dimensions) VALUES (?, ?, ?)").run(t,o,r.length)}getEmbedding(e,t){St(e);let r=e.prepare("SELECT vector FROM embeddings WHERE uuid = ?").get(t);return r?po(r.vector):null}removeEmbedding(e,t){return St(e),e.prepare("DELETE FROM embeddings WHERE uuid = ?").run(t).changes>0}async semanticSearch(e,t,r=10){if(!this._ready||!this.backend)return[];let o=await this.backend.generateEmbedding(t);return o?this.semanticSearchWithVector(e,o,r):[]}semanticSearchWithVector(e,t,r=10){St(e);let o=e.prepare("SELECT uuid, vector FROM embeddings").all(),s=[];for(let i of o){let a=po(i.vector);if(a.length!==t.length)continue;let c=aa(t,a);s.push({uuid:i.uuid,score:c})}return s.sort((i,a)=>a.score-i.score),s.slice(0,r)}}});var ho,Qe,mo,la,ua,vt,go=$(()=>{"use strict";ho=h(require("crypto")),Qe=h(require("os")),mo=process.env.AIDE_TELEMETRY==="off"?"":"phc_ztrzpvbZQTa4ymkGxVdYZnFKiFFLyJMcf5zYUXVAqPzS",la="https://us.i.posthog.com",ua=`
61
+ `;Qe=class{constructor(e="Xenova/bge-small-en-v1.5"){this.modelName=e;this.pipeline=null;this.ready=!1}async initialize(){try{let{pipeline:e,env:t}=await import("@huggingface/transformers"),r=await import("os"),o=await import("path");return t.cacheDir=o.join(r.homedir(),".cache","aide-memory","models"),this.pipeline=await e("feature-extraction",this.modelName,{dtype:"fp32"}),this.ready=!0,!0}catch{return this.ready=!1,!1}}isReady(){return this.ready}async generateEmbedding(e){if(!this.ready||!this.pipeline)return null;try{let t=await this.pipeline(e,{pooling:"mean",normalize:!0});return new Float32Array(t.data)}catch{return null}}},Ze=class{constructor(e="nomic-embed-text",t="http://localhost:11434"){this.model=e;this.baseUrl=t;this.ready=!1}async initialize(){try{return(await fetch(`${this.baseUrl}/api/tags`)).ok?(this.ready=!0,!0):(this.ready=!1,!1)}catch{return this.ready=!1,!1}}isReady(){return this.ready}async generateEmbedding(e){if(!this.ready)return null;try{let t=await fetch(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,prompt:e})});if(!t.ok)return null;let r=await t.json();return!r.embedding||!Array.isArray(r.embedding)?null:new Float32Array(r.embedding)}catch{return null}}},kt=class{constructor(e){this.preferredBackend=e;this.backend=null;this._ready=!1}async initialize(){if(this.preferredBackend)return await this.preferredBackend.initialize()?(this.backend=this.preferredBackend,this._ready=!0,!0):(this._ready=!1,!1);let e=new Qe;if(await e.initialize())return this.backend=e,this._ready=!0,!0;let r=new Ze;return await r.initialize()?(this.backend=r,this._ready=!0,!0):(this._ready=!1,!1)}isReady(){return this._ready}async generateEmbedding(e){return!this._ready||!this.backend?null:this.backend.generateEmbedding(e)}storeEmbedding(e,t,r){vt(e);let o=ua(r);e.prepare("INSERT OR REPLACE INTO embeddings (uuid, vector, dimensions) VALUES (?, ?, ?)").run(t,o,r.length)}getEmbedding(e,t){vt(e);let r=e.prepare("SELECT vector FROM embeddings WHERE uuid = ?").get(t);return r?mo(r.vector):null}removeEmbedding(e,t){return vt(e),e.prepare("DELETE FROM embeddings WHERE uuid = ?").run(t).changes>0}async semanticSearch(e,t,r=10){if(!this._ready||!this.backend)return[];let o=await this.backend.generateEmbedding(t);return o?this.semanticSearchWithVector(e,o,r):[]}semanticSearchWithVector(e,t,r=10){vt(e);let o=e.prepare("SELECT uuid, vector FROM embeddings").all(),s=[];for(let i of o){let a=mo(i.vector);if(a.length!==t.length)continue;let c=la(t,a);s.push({uuid:i.uuid,score:c})}return s.sort((i,a)=>a.score-i.score),s.slice(0,r)}}});var go,et,ho,da,pa,xt,yo=T(()=>{"use strict";go=g(require("crypto")),et=g(require("os")),ho=process.env.AIDE_TELEMETRY==="off"?"":"phc_ztrzpvbZQTa4ymkGxVdYZnFKiFFLyJMcf5zYUXVAqPzS",da="https://us.i.posthog.com",pa=`
62
62
  CREATE TABLE IF NOT EXISTS analytics (
63
63
  id INTEGER PRIMARY KEY AUTOINCREMENT,
64
64
  event TEXT NOT NULL,
@@ -68,7 +68,7 @@ CREATE TABLE IF NOT EXISTS analytics (
68
68
  );
69
69
  CREATE INDEX IF NOT EXISTS idx_analytics_event ON analytics(event);
70
70
  CREATE INDEX IF NOT EXISTS idx_analytics_timestamp ON analytics(timestamp);
71
- `,vt=class{constructor(e){this.eventBuffer=[];this.flushTimer=null;this.remoteDisabled=!1;this.db=e,this.init(),this.distinctId=ho.default.createHash("sha256").update(`${Qe.default.hostname()}:${Qe.default.userInfo().username}`).digest("hex").slice(0,16)}init(){this.db.exec(ua)}disableRemote(){this.remoteDisabled=!0}logEvent(e,t,r){let o=new Date().toISOString();this.db.prepare("INSERT INTO analytics (event, value, tool, timestamp) VALUES (?, ?, ?, ?)").run(e,t??null,r??null,o),mo&&!this.remoteDisabled&&(this.eventBuffer.push({event:e,properties:{value:t??void 0,tool:r??void 0,platform:Qe.default.platform(),arch:Qe.default.arch(),node_version:process.version},timestamp:o}),this.eventBuffer.length>=10?this.flush():this.flushTimer||(this.flushTimer=setTimeout(()=>this.flush(),3e4)))}flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.eventBuffer.length===0)return;let e=this.eventBuffer.splice(0),t=JSON.stringify({api_key:mo,batch:e.map(r=>({event:r.event,properties:{...r.properties,distinct_id:this.distinctId,$ip:null,$geoip_disable:!0},timestamp:r.timestamp}))});fetch(`${la}/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:t}).catch(()=>{})}shutdown(){this.flush()}getEvents(e){let t=[],r=[];e?.event&&(t.push("event = ?"),r.push(e.event)),e?.since&&(t.push("timestamp >= ?"),r.push(e.since));let o="SELECT * FROM analytics";return t.length>0&&(o+=" WHERE "+t.join(" AND ")),o+=" ORDER BY timestamp DESC, id DESC",e?.limit&&(o+=" LIMIT ?",r.push(e.limit)),this.db.prepare(o).all(...r)}countEvents(e,t){let r=["event = ?"],o=[e];t&&(r.push("timestamp >= ?"),o.push(t));let s="SELECT COUNT(*) as count FROM analytics WHERE "+r.join(" AND ");return this.db.prepare(s).get(...o).count}getStats(){let t=this.db.prepare("SELECT COUNT(*) as count FROM memories WHERE 1=1").get().count,r=this.db.prepare("SELECT layer, COUNT(*) as count FROM memories WHERE 1=1 GROUP BY layer").all(),o={};for(let m of r)o[m.layer]=m.count;let i=this.db.prepare("SELECT what, layer, recalled_count FROM memories WHERE 1=1 AND recalled_count > 0 ORDER BY recalled_count DESC LIMIT 5").all().map(m=>({what:m.what,layer:m.layer,recalled_count:m.recalled_count})),a=this.db.prepare("SELECT source, COUNT(*) as count FROM memories WHERE 1=1 GROUP BY source").all(),c={};for(let m of a)c[m.source]=m.count;let l=new Date(Date.now()-30*864e5).toISOString(),d=this.db.prepare("SELECT COUNT(*) as count FROM memories WHERE 1=1 AND recalled_count = 0 AND created_at < ?").get(l).count;return{totalMemories:t,byLayer:o,mostRecalled:i,captureSourceBreakdown:c,staleCount:d}}prune(e){let t=new Date(Date.now()-e*864e5).toISOString();return this.db.prepare("DELETE FROM analytics WHERE timestamp < ?").run(t).changes}}});function _o(n){let e=H.default.resolve(n);return kt.default.createHash("sha1").update(e).digest("hex").slice(0,12)}function fa(n){let e=_o(n);return H.default.join(Or.default.homedir(),".aide","projects",e,"memory.db")}function ma(){try{return(0,wo.execSync)("git config user.name",{encoding:"utf-8"}).trim()}catch{return"unknown"}}var H,Or,L,kt,wo,yo,bo,da,pa,A,Y=$(()=>{"use strict";io();H=h(require("path")),Or=h(require("os")),L=h(require("fs")),kt=h(require("crypto")),wo=require("child_process");uo();fo();go();yo=3,bo=`
71
+ `,xt=class{constructor(e){this.eventBuffer=[];this.flushTimer=null;this.remoteDisabled=!1;this.db=e,this.init(),this.distinctId=go.default.createHash("sha256").update(`${et.default.hostname()}:${et.default.userInfo().username}`).digest("hex").slice(0,16)}init(){this.db.exec(pa)}disableRemote(){this.remoteDisabled=!0}logEvent(e,t,r){let o=new Date().toISOString();this.db.prepare("INSERT INTO analytics (event, value, tool, timestamp) VALUES (?, ?, ?, ?)").run(e,t??null,r??null,o),ho&&!this.remoteDisabled&&(this.eventBuffer.push({event:e,properties:{value:t??void 0,tool:r??void 0,platform:et.default.platform(),arch:et.default.arch(),node_version:process.version},timestamp:o}),this.eventBuffer.length>=10?this.flush():this.flushTimer||(this.flushTimer=setTimeout(()=>this.flush(),3e4)))}flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.eventBuffer.length===0)return;let e=this.eventBuffer.splice(0),t=JSON.stringify({api_key:ho,batch:e.map(r=>({event:r.event,properties:{...r.properties,distinct_id:this.distinctId,$ip:null,$geoip_disable:!0},timestamp:r.timestamp}))});fetch(`${da}/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:t}).catch(()=>{})}shutdown(){this.flush()}getEvents(e){let t=[],r=[];e?.event&&(t.push("event = ?"),r.push(e.event)),e?.since&&(t.push("timestamp >= ?"),r.push(e.since));let o="SELECT * FROM analytics";return t.length>0&&(o+=" WHERE "+t.join(" AND ")),o+=" ORDER BY timestamp DESC, id DESC",e?.limit&&(o+=" LIMIT ?",r.push(e.limit)),this.db.prepare(o).all(...r)}countEvents(e,t){let r=["event = ?"],o=[e];t&&(r.push("timestamp >= ?"),o.push(t));let s="SELECT COUNT(*) as count FROM analytics WHERE "+r.join(" AND ");return this.db.prepare(s).get(...o).count}getStats(){let t=this.db.prepare("SELECT COUNT(*) as count FROM memories WHERE 1=1").get().count,r=this.db.prepare("SELECT layer, COUNT(*) as count FROM memories WHERE 1=1 GROUP BY layer").all(),o={};for(let f of r)o[f.layer]=f.count;let i=this.db.prepare("SELECT what, layer, recalled_count FROM memories WHERE 1=1 AND recalled_count > 0 ORDER BY recalled_count DESC LIMIT 5").all().map(f=>({what:f.what,layer:f.layer,recalled_count:f.recalled_count})),a=this.db.prepare("SELECT source, COUNT(*) as count FROM memories WHERE 1=1 GROUP BY source").all(),c={};for(let f of a)c[f.source]=f.count;let l=new Date(Date.now()-30*864e5).toISOString(),d=this.db.prepare("SELECT COUNT(*) as count FROM memories WHERE 1=1 AND recalled_count = 0 AND created_at < ?").get(l).count;return{totalMemories:t,byLayer:o,mostRecalled:i,captureSourceBreakdown:c,staleCount:d}}prune(e){let t=new Date(Date.now()-e*864e5).toISOString();return this.db.prepare("DELETE FROM analytics WHERE timestamp < ?").run(t).changes}}});function So(n){let e=B.default.resolve(n);return Ot.default.createHash("sha1").update(e).digest("hex").slice(0,12)}function ha(n){let e=So(n);return B.default.join(Rr.default.homedir(),".aide","projects",e,"memory.db")}function ga(){try{return(0,wo.execSync)("git config user.name",{encoding:"utf-8"}).trim()}catch{return"unknown"}}var B,Rr,U,Ot,wo,bo,_o,ma,fa,A,K=T(()=>{"use strict";ao();B=g(require("path")),Rr=g(require("os")),U=g(require("fs")),Ot=g(require("crypto")),wo=require("child_process");po();fo();yo();bo=3,_o=`
72
72
  CREATE TABLE IF NOT EXISTS memories (
73
73
  id INTEGER PRIMARY KEY AUTOINCREMENT,
74
74
  uuid TEXT NOT NULL UNIQUE,
@@ -94,13 +94,13 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_memories_uuid ON memories(uuid);
94
94
  CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope);
95
95
  CREATE INDEX IF NOT EXISTS idx_memories_layer ON memories(layer);
96
96
  CREATE INDEX IF NOT EXISTS idx_memories_contributor ON memories(contributor);
97
- `,da=`
97
+ `,ma=`
98
98
  CREATE TABLE IF NOT EXISTS meta (
99
99
  key TEXT PRIMARY KEY,
100
100
  value TEXT NOT NULL
101
101
  );
102
- `,pa={preferences:"preferences",technical:"technical",area_context:"area_context",guidelines:"guidelines"};A=class{constructor(e){this._fts5Available=!1;this.embeddingService=null;this.analytics=null;this.telemetryEnabled=!0;this.memoriesDir=null;this.projectRoot=null;this.defaultShared=!0;if(this.defaultContributor=ma(),typeof e=="string")this.dbPath=fa(e);else if("projectRoot"in e){let r=e.projectRoot;this.projectRoot=r,this.memoriesDir=H.default.join(r,".aide","memories");let o=_o(r);this.dbPath=H.default.join(Or.default.homedir(),".aide","projects",o,"memory.db"),this.ensureMemoryDirs()}else this.dbPath=e.dbPath;let t=H.default.dirname(this.dbPath);if(L.default.existsSync(t)||L.default.mkdirSync(t,{recursive:!0}),this.db=so(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.init(),this.analytics=new vt(this.db),typeof e!="string"&&"projectRoot"in e)try{let r=H.default.join(e.projectRoot,".aide","config.json");if(L.default.existsSync(r)){let o=JSON.parse(L.default.readFileSync(r,"utf-8"));o.telemetry?.enabled===!1&&(this.telemetryEnabled=!1,this.analytics?.disableRemote()),o.memories?.defaultShared===!1&&(this.defaultShared=!1);let s=o.contributor;typeof s=="string"&&s!=="auto"&&s.trim()!==""&&(this.defaultContributor=s);let i=o.embeddings?.backend??"auto",a=o.embeddings?.model??"auto";if(i==="none")this.embeddingService=null;else if(i==="transformers"||i==="ollama"){let c=a!=="auto"?a:void 0,l=i==="transformers"?new Ke(c):new ze(c);this.embeddingService=new Et(l)}}}catch{}this.memoriesDir&&this.rebuildCacheIfNeeded()}get fts5Available(){return this._fts5Available}getDatabase(){return this.db}ensureMemoryDirs(){if(!this.memoriesDir)return;let e=[H.default.join(this.memoriesDir,"preferences","personal"),H.default.join(this.memoriesDir,"preferences","shared"),H.default.join(this.memoriesDir,"technical"),H.default.join(this.memoriesDir,"area_context"),H.default.join(this.memoriesDir,"guidelines")];for(let t of e)L.default.existsSync(t)||L.default.mkdirSync(t,{recursive:!0})}setEmbeddingService(e){this.embeddingService=e}getEmbeddingService(){return this.embeddingService}getAnalytics(){return this.analytics}logEvent(e,t,r){this.telemetryEnabled&&this.analytics&&this.analytics.logEvent(e,t,r)}init(){this.db.exec(da);let e=this.db.prepare("SELECT value FROM meta WHERE key = ?").get("schema_version");(e?parseInt(e.value,10):0)<yo?(this.db.exec("DROP TABLE IF EXISTS memories"),this.db.exec(bo),this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run("schema_version",String(yo))):this.db.exec(bo),this._fts5Available=ao(this.db),this._fts5Available&&co(this.db)}getMemoryDir(e,t){if(!this.memoriesDir)throw new Error("File I/O not available in dbPath-only mode");return e==="preferences"?H.default.join(this.memoriesDir,"preferences",t?"shared":"personal"):H.default.join(this.memoriesDir,pa[e])}getMemoryFilePath(e,t,r){return H.default.join(this.getMemoryDir(t,r),`${e}.json`)}toMemoryFile(e){return{id:e.id,uuid:e.uuid,layer:e.layer,what:e.what,why:e.why,scope:e.scope,context_label:e.context_label,contributor:e.contributor,tags:e.tags,source:e.source,shared:e.shared,priority:e.priority,generated_by:e.generated_by,derived_from:e.derived_from,created_at:e.created_at,updated_at:e.updated_at}}writeMemoryFile(e){if(!this.memoriesDir)return;let t=this.getMemoryFilePath(e.uuid,e.layer,e.shared),r=t+".tmp",o=JSON.stringify(this.toMemoryFile(e),null,2)+`
103
- `;L.default.writeFileSync(r,o,"utf-8"),L.default.renameSync(r,t)}deleteMemoryFile(e,t,r){if(!this.memoriesDir)return;let o=this.getMemoryFilePath(e,t,r);L.default.existsSync(o)&&L.default.unlinkSync(o)}hashMemoriesDir(){if(!this.memoriesDir)return"";let e=kt.default.createHash("sha1"),t=this.collectJsonFiles();for(let r of t.sort()){let o=L.default.statSync(r);e.update(r+":"+o.mtimeMs+":"+o.size)}return e.digest("hex")}collectJsonFiles(){if(!this.memoriesDir||!L.default.existsSync(this.memoriesDir))return[];let e=[],t=r=>{if(!L.default.existsSync(r))return;let o=L.default.readdirSync(r,{withFileTypes:!0});for(let s of o){let i=H.default.join(r,s.name);s.isDirectory()?t(i):s.name.endsWith(".json")&&!s.name.endsWith(".tmp")&&e.push(i)}};return t(this.memoriesDir),e}rebuildCacheIfNeeded(){if(!this.memoriesDir)return;let e=this.hashMemoriesDir();this.db.prepare("SELECT value FROM meta WHERE key = ?").get("dir_hash")?.value!==e&&(this.rebuildCache(),this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run("dir_hash",e))}rebuildCache(){if(!this.memoriesDir)return;let e=this.collectJsonFiles(),t=new Set;this.db.transaction(()=>{for(let s of e)try{let i=L.default.readFileSync(s,"utf-8"),a=JSON.parse(i);if(!a.uuid||!a.layer||!a.what)continue;if(t.add(a.uuid),this.db.prepare("SELECT id, recalled_count, last_recalled_at FROM memories WHERE uuid = ?").get(a.uuid))this.db.prepare(`
102
+ `,fa={preferences:"preferences",technical:"technical",area_context:"area_context",guidelines:"guidelines"};A=class{constructor(e){this._fts5Available=!1;this.embeddingService=null;this.analytics=null;this.telemetryEnabled=!0;this.memoriesDir=null;this.projectRoot=null;this.defaultShared=!0;if(this.defaultContributor=ga(),typeof e=="string")this.dbPath=ha(e);else if("projectRoot"in e){let r=e.projectRoot;this.projectRoot=r,this.memoriesDir=B.default.join(r,".aide","memories");let o=So(r);this.dbPath=B.default.join(Rr.default.homedir(),".aide","projects",o,"memory.db"),this.ensureMemoryDirs()}else this.dbPath=e.dbPath;let t=B.default.dirname(this.dbPath);if(U.default.existsSync(t)||U.default.mkdirSync(t,{recursive:!0}),this.db=io(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.init(),this.analytics=new xt(this.db),typeof e!="string"&&"projectRoot"in e)try{let r=B.default.join(e.projectRoot,".aide","config.json");if(U.default.existsSync(r)){let o=JSON.parse(U.default.readFileSync(r,"utf-8"));o.telemetry?.enabled===!1&&(this.telemetryEnabled=!1,this.analytics?.disableRemote()),o.memories?.defaultShared===!1&&(this.defaultShared=!1);let s=o.contributor;typeof s=="string"&&s!=="auto"&&s.trim()!==""&&(this.defaultContributor=s);let i=o.embeddings?.backend??"auto",a=o.embeddings?.model??"auto";if(i==="none")this.embeddingService=null;else if(i==="transformers"||i==="ollama"){let c=a!=="auto"?a:void 0,l=i==="transformers"?new Qe(c):new Ze(c);this.embeddingService=new kt(l)}}}catch{}this.memoriesDir&&this.rebuildCacheIfNeeded()}get fts5Available(){return this._fts5Available}getDatabase(){return this.db}ensureMemoryDirs(){if(!this.memoriesDir)return;let e=[B.default.join(this.memoriesDir,"preferences","personal"),B.default.join(this.memoriesDir,"preferences","shared"),B.default.join(this.memoriesDir,"technical"),B.default.join(this.memoriesDir,"area_context"),B.default.join(this.memoriesDir,"guidelines")];for(let t of e)U.default.existsSync(t)||U.default.mkdirSync(t,{recursive:!0})}setEmbeddingService(e){this.embeddingService=e}getEmbeddingService(){return this.embeddingService}getAnalytics(){return this.analytics}logEvent(e,t,r){this.telemetryEnabled&&this.analytics&&this.analytics.logEvent(e,t,r)}init(){this.db.exec(ma);let e=this.db.prepare("SELECT value FROM meta WHERE key = ?").get("schema_version");(e?parseInt(e.value,10):0)<bo?(this.db.exec("DROP TABLE IF EXISTS memories"),this.db.exec(_o),this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run("schema_version",String(bo))):this.db.exec(_o),this._fts5Available=co(this.db),this._fts5Available&&lo(this.db)}getMemoryDir(e,t){if(!this.memoriesDir)throw new Error("File I/O not available in dbPath-only mode");return e==="preferences"?B.default.join(this.memoriesDir,"preferences",t?"shared":"personal"):B.default.join(this.memoriesDir,fa[e])}getMemoryFilePath(e,t,r){return B.default.join(this.getMemoryDir(t,r),`${e}.json`)}toMemoryFile(e){return{id:e.id,uuid:e.uuid,layer:e.layer,what:e.what,why:e.why,scope:e.scope,context_label:e.context_label,contributor:e.contributor,tags:e.tags,source:e.source,shared:e.shared,priority:e.priority,generated_by:e.generated_by,derived_from:e.derived_from,created_at:e.created_at,updated_at:e.updated_at}}writeMemoryFile(e){if(!this.memoriesDir)return;let t=this.getMemoryFilePath(e.uuid,e.layer,e.shared),r=t+".tmp",o=JSON.stringify(this.toMemoryFile(e),null,2)+`
103
+ `;U.default.writeFileSync(r,o,"utf-8"),U.default.renameSync(r,t)}deleteMemoryFile(e,t,r){if(!this.memoriesDir)return;let o=this.getMemoryFilePath(e,t,r);U.default.existsSync(o)&&U.default.unlinkSync(o)}hashMemoriesDir(){if(!this.memoriesDir)return"";let e=Ot.default.createHash("sha1"),t=this.collectJsonFiles();for(let r of t.sort()){let o=U.default.statSync(r);e.update(r+":"+o.mtimeMs+":"+o.size)}return e.digest("hex")}collectJsonFiles(){if(!this.memoriesDir||!U.default.existsSync(this.memoriesDir))return[];let e=[],t=r=>{if(!U.default.existsSync(r))return;let o=U.default.readdirSync(r,{withFileTypes:!0});for(let s of o){let i=B.default.join(r,s.name);s.isDirectory()?t(i):s.name.endsWith(".json")&&!s.name.endsWith(".tmp")&&e.push(i)}};return t(this.memoriesDir),e}rebuildCacheIfNeeded(){if(!this.memoriesDir)return;let e=this.hashMemoriesDir();this.db.prepare("SELECT value FROM meta WHERE key = ?").get("dir_hash")?.value!==e&&(this.rebuildCache(),this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run("dir_hash",e))}rebuildCache(){if(!this.memoriesDir)return;let e=this.collectJsonFiles(),t=new Set;this.db.transaction(()=>{for(let s of e)try{let i=U.default.readFileSync(s,"utf-8"),a=JSON.parse(i);if(!a.uuid||!a.layer||!a.what)continue;if(t.add(a.uuid),this.db.prepare("SELECT id, recalled_count, last_recalled_at FROM memories WHERE uuid = ?").get(a.uuid))this.db.prepare(`
104
104
  UPDATE memories SET layer = ?, what = ?, why = ?, scope = ?, context_label = ?,
105
105
  contributor = ?, tags = ?, source = ?, shared = ?, priority = ?, generated_by = ?,
106
106
  derived_from = ?, created_at = ?, updated_at = ?
@@ -113,94 +113,108 @@ CREATE TABLE IF NOT EXISTS meta (
113
113
  INSERT INTO memories (uuid, layer, what, why, scope, context_label, contributor,
114
114
  tags, source, shared, priority, generated_by, derived_from, created_at, updated_at)
115
115
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
116
- `).run(a.uuid,a.layer,a.what,a.why??null,a.scope??null,a.context_label??null,a.contributor,JSON.stringify(a.tags??[]),a.source??"conversation",a.shared?1:0,a.priority??"normal",a.generated_by?JSON.stringify(a.generated_by):null,a.derived_from?JSON.stringify(a.derived_from):null,a.created_at,a.updated_at);try{let u=Number(l.lastInsertRowid),d=this.get(u);d&&this.writeMemoryFile(d)}catch{}}}catch{}let o=this.db.prepare("SELECT uuid FROM memories").all();for(let s of o)t.has(s.uuid)||this.db.prepare("DELETE FROM memories WHERE uuid = ?").run(s.uuid)})()}updateDirHash(){if(!this.memoriesDir)return;let e=this.hashMemoriesDir();this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run("dir_hash",e)}add(e){let t=new Date().toISOString(),r=kt.default.randomUUID(),o=e.contributor??this.defaultContributor,s=e.tags??[],i=e.shared??this.defaultShared,a=e.derived_from?JSON.stringify(e.derived_from):null,c=e.generated_by?JSON.stringify(e.generated_by):null,l=e.priority??"normal",u=this.db.prepare(`
116
+ `).run(a.uuid,a.layer,a.what,a.why??null,a.scope??null,a.context_label??null,a.contributor,JSON.stringify(a.tags??[]),a.source??"conversation",a.shared?1:0,a.priority??"normal",a.generated_by?JSON.stringify(a.generated_by):null,a.derived_from?JSON.stringify(a.derived_from):null,a.created_at,a.updated_at);try{let u=Number(l.lastInsertRowid),d=this.get(u);d&&this.writeMemoryFile(d)}catch{}}}catch{}let o=this.db.prepare("SELECT uuid FROM memories").all();for(let s of o)t.has(s.uuid)||this.db.prepare("DELETE FROM memories WHERE uuid = ?").run(s.uuid)})()}updateDirHash(){if(!this.memoriesDir)return;let e=this.hashMemoriesDir();this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)").run("dir_hash",e)}add(e){let t=new Date().toISOString(),r=Ot.default.randomUUID(),o=e.contributor??this.defaultContributor,s=e.tags??[],i=e.shared??this.defaultShared,a=e.derived_from?JSON.stringify(e.derived_from):null,c=e.generated_by?JSON.stringify(e.generated_by):null,l=e.priority??"normal",u=this.db.prepare(`
117
117
  INSERT INTO memories (uuid, layer, what, why, scope, context_label, contributor,
118
118
  tags, source, shared, priority, generated_by, derived_from, created_at, updated_at)
119
119
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
120
- `).run(r,e.layer,e.what,e.why??null,e.scope??null,e.context_label??null,o,JSON.stringify(s),e.source??"conversation",i?1:0,l,c,a,t,t),d=this.get(Number(u.lastInsertRowid));if(this.logEvent("memory_stored",e.layer),this.memoriesDir&&(this.writeMemoryFile(d),this.updateDirHash()),this.embeddingService?.isReady()){let m=[d.what,d.why,d.context_label].filter(Boolean).join(" ");this.embeddingService.generateEmbedding(m).then(w=>{w&&this.embeddingService&&this.embeddingService.storeEmbedding(this.db,d.uuid,w)}).catch(()=>{})}return d}get(e){let t=this.db.prepare("SELECT * FROM memories WHERE id = ?").get(e);return t?this.rowToMemory(t):null}getByUuid(e){let t=this.db.prepare("SELECT * FROM memories WHERE uuid = ?").get(e);return t?this.rowToMemory(t):null}list(e){let t=[],r=[];e?.layer&&(t.push("layer = ?"),r.push(e.layer)),e?.scope&&(t.push("scope = ?"),r.push(e.scope)),e?.contributor&&(t.push("contributor = ?"),r.push(e.contributor)),e?.priority&&(t.push("priority = ?"),r.push(e.priority));let o="SELECT * FROM memories";return t.length>0&&(o+=" WHERE "+t.join(" AND ")),o+=" ORDER BY created_at DESC, id DESC",e?.limit&&(o+=" LIMIT ?",r.push(e.limit)),this.db.prepare(o).all(...r).map(i=>this.rowToMemory(i))}update(e,t){let r=this.get(e);if(!r)return null;let o=[],s=[];for(let[c,l]of Object.entries(t))l!==void 0&&(c==="tags"?(o.push("tags = ?"),s.push(JSON.stringify(l))):c==="generated_by"?(o.push("generated_by = ?"),s.push(l?JSON.stringify(l):null)):c==="shared"?(o.push("shared = ?"),s.push(l?1:0)):(o.push(`${c} = ?`),s.push(l)));if(o.length===0)return r;let i=new Date().toISOString();o.push("updated_at = ?"),s.push(i),s.push(e),this.db.prepare(`UPDATE memories SET ${o.join(", ")} WHERE id = ?`).run(...s);let a=this.get(e);if(this.logEvent("memory_updated",a.layer),this.memoriesDir&&(t.shared!==void 0&&t.shared!==r.shared&&this.deleteMemoryFile(r.uuid,r.layer,r.shared),this.writeMemoryFile(a),this.updateDirHash()),this.embeddingService?.isReady()&&(t.what!==void 0||t.why!==void 0||t.context_label!==void 0)){let c=[a.what,a.why,a.context_label].filter(Boolean).join(" ");this.embeddingService.generateEmbedding(c).then(l=>{l&&this.embeddingService&&this.embeddingService.storeEmbedding(this.db,a.uuid,l)}).catch(()=>{})}return a}remove(e){let t=this.get(e);if(!t)return!1;this.logEvent("memory_deleted",t.layer);let r=this.db.prepare("DELETE FROM memories WHERE id = ?").run(e);if(r.changes>0&&this.memoriesDir&&(this.deleteMemoryFile(t.uuid,t.layer,t.shared),this.updateDirHash()),r.changes>0&&this.embeddingService)try{this.embeddingService.removeEmbedding(this.db,t.uuid)}catch{}return r.changes>0}removeByUuid(e){let t=this.getByUuid(e);return t?this.remove(t.id):!1}recordRecall(e){if(e.length===0)return;let t=new Date().toISOString(),r=this.db.prepare("UPDATE memories SET recalled_count = recalled_count + 1, last_recalled_at = ? WHERE id = ?");this.db.transaction(()=>{for(let s of e)r.run(t,s)})(),this.logEvent("memory_recalled",String(e.length))}count(e){let t=[],r=[];e?.layer&&(t.push("layer = ?"),r.push(e.layer)),e?.contributor&&(t.push("contributor = ?"),r.push(e.contributor));let o="SELECT COUNT(*) as count FROM memories";return t.length>0&&(o+=" WHERE "+t.join(" AND ")),this.db.prepare(o).get(...r).count}search(e,t){let r=t?.mode??"auto",o,s;if(r==="semantic")o=[],s="semantic";else if(r==="keyword")if(this._fts5Available){let i=this.searchFts5(e,t);o=i.length>0?i:this.searchLike(e,t),s=i.length>0?"fts5":"like"}else o=this.searchLike(e,t),s="like";else if(this._fts5Available){let i=this.searchFts5(e,t);i.length>0?(o=i,s="fts5"):(o=this.searchLike(e,t),s="like")}else o=this.searchLike(e,t),s="like";return this.logEvent("search_performed",s),o}searchFts5(e,t){let r=lo(e);if(r===null)return[];let o=t?.limit??50,s=`
120
+ `).run(r,e.layer,e.what,e.why??null,e.scope??null,e.context_label??null,o,JSON.stringify(s),e.source??"conversation",i?1:0,l,c,a,t,t),d=this.get(Number(u.lastInsertRowid));if(this.logEvent("memory_stored",e.layer),this.memoriesDir&&(this.writeMemoryFile(d),this.updateDirHash()),this.embeddingService?.isReady()){let f=[d.what,d.why,d.context_label].filter(Boolean).join(" ");this.embeddingService.generateEmbedding(f).then(y=>{y&&this.embeddingService&&this.embeddingService.storeEmbedding(this.db,d.uuid,y)}).catch(()=>{})}return d}get(e){let t=this.db.prepare("SELECT * FROM memories WHERE id = ?").get(e);return t?this.rowToMemory(t):null}getByUuid(e){let t=this.db.prepare("SELECT * FROM memories WHERE uuid = ?").get(e);return t?this.rowToMemory(t):null}list(e){let t=[],r=[];e?.layer&&(t.push("layer = ?"),r.push(e.layer)),e?.scope&&(t.push("scope = ?"),r.push(e.scope)),e?.contributor&&(t.push("contributor = ?"),r.push(e.contributor)),e?.priority&&(t.push("priority = ?"),r.push(e.priority));let o="SELECT * FROM memories";return t.length>0&&(o+=" WHERE "+t.join(" AND ")),o+=" ORDER BY created_at DESC, id DESC",e?.limit&&(o+=" LIMIT ?",r.push(e.limit)),this.db.prepare(o).all(...r).map(i=>this.rowToMemory(i))}update(e,t){let r=this.get(e);if(!r)return null;let o=[],s=[];for(let[c,l]of Object.entries(t))l!==void 0&&(c==="tags"?(o.push("tags = ?"),s.push(JSON.stringify(l))):c==="generated_by"?(o.push("generated_by = ?"),s.push(l?JSON.stringify(l):null)):c==="shared"?(o.push("shared = ?"),s.push(l?1:0)):(o.push(`${c} = ?`),s.push(l)));if(o.length===0)return r;let i=new Date().toISOString();o.push("updated_at = ?"),s.push(i),s.push(e),this.db.prepare(`UPDATE memories SET ${o.join(", ")} WHERE id = ?`).run(...s);let a=this.get(e);if(this.logEvent("memory_updated",a.layer),this.memoriesDir&&(t.shared!==void 0&&t.shared!==r.shared&&this.deleteMemoryFile(r.uuid,r.layer,r.shared),this.writeMemoryFile(a),this.updateDirHash()),this.embeddingService?.isReady()&&(t.what!==void 0||t.why!==void 0||t.context_label!==void 0)){let c=[a.what,a.why,a.context_label].filter(Boolean).join(" ");this.embeddingService.generateEmbedding(c).then(l=>{l&&this.embeddingService&&this.embeddingService.storeEmbedding(this.db,a.uuid,l)}).catch(()=>{})}return a}remove(e){let t=this.get(e);if(!t)return!1;this.logEvent("memory_deleted",t.layer);let r=this.db.prepare("DELETE FROM memories WHERE id = ?").run(e);if(r.changes>0&&this.memoriesDir&&(this.deleteMemoryFile(t.uuid,t.layer,t.shared),this.updateDirHash()),r.changes>0&&this.embeddingService)try{this.embeddingService.removeEmbedding(this.db,t.uuid)}catch{}return r.changes>0}removeByUuid(e){let t=this.getByUuid(e);return t?this.remove(t.id):!1}recordRecall(e){if(e.length===0)return;let t=new Date().toISOString(),r=this.db.prepare("UPDATE memories SET recalled_count = recalled_count + 1, last_recalled_at = ? WHERE id = ?");this.db.transaction(()=>{for(let s of e)r.run(t,s)})(),this.logEvent("memory_recalled",String(e.length))}count(e){let t=[],r=[];e?.layer&&(t.push("layer = ?"),r.push(e.layer)),e?.contributor&&(t.push("contributor = ?"),r.push(e.contributor));let o="SELECT COUNT(*) as count FROM memories";return t.length>0&&(o+=" WHERE "+t.join(" AND ")),this.db.prepare(o).get(...r).count}search(e,t){let r=t?.mode??"auto",o,s;if(r==="semantic")o=[],s="semantic";else if(r==="keyword")if(this._fts5Available){let i=this.searchFts5(e,t);o=i.length>0?i:this.searchLike(e,t),s=i.length>0?"fts5":"like"}else o=this.searchLike(e,t),s="like";else if(this._fts5Available){let i=this.searchFts5(e,t);i.length>0?(o=i,s="fts5"):(o=this.searchLike(e,t),s="like")}else o=this.searchLike(e,t),s="like";return this.logEvent("search_performed",s),o}searchFts5(e,t){let r=uo(e);if(r===null)return[];let o=t?.limit??50,s=`
121
121
  SELECT m.* FROM memories m
122
122
  INNER JOIN (
123
123
  SELECT rowid, rank FROM memories_fts WHERE memories_fts MATCH ?
124
124
  ORDER BY rank
125
125
  ) fts ON m.id = fts.rowid
126
- `,i=[r],a=[];return t?.layer&&(a.push("m.layer = ?"),i.push(t.layer)),a.length>0&&(s+=" WHERE "+a.join(" AND ")),s+=" ORDER BY fts.rank",s+=" LIMIT ?",i.push(o),this.db.prepare(s).all(...i).map(l=>this.rowToMemory(l))}searchLike(e,t){if(!e||!e.trim())return[];let r=["(what LIKE ? OR why LIKE ?)"],o=`%${e}%`,s=[o,o];t?.layer&&(r.push("layer = ?"),s.push(t.layer));let i="SELECT * FROM memories WHERE "+r.join(" AND ");i+=" ORDER BY created_at DESC, id DESC";let a=t?.limit??50;i+=" LIMIT ?",s.push(a);let l=this.db.prepare(i).all(...s).map(u=>this.rowToMemory(u));return l.length<3&&this.embeddingService?.isReady(),l}async searchWithEmbeddings(e,t){let r=t?.limit??50,o=t?.mode??"auto";if(o==="semantic"){if(!this.embeddingService?.isReady())return[];try{let i=await this.embeddingService.semanticSearch(this.db,e,r),a=[];for(let c of i){if(c.score<.3)continue;let l=this.getByUuid(c.uuid);if(l&&!(t?.layer&&l.layer!==t.layer)&&(a.push(l),a.length>=r))break}return this.logEvent("search_performed","semantic"),a}catch{return[]}}if(o==="keyword")return this.search(e,t);let s=this.search(e,t);if(s.length<3&&this.embeddingService?.isReady())try{let i=await this.embeddingService.semanticSearch(this.db,e,r),a=new Set(s.map(c=>c.id));for(let c of i){if(c.score<.3)continue;let l=this.getByUuid(c.uuid);if(l&&!a.has(l.id)&&!(t?.layer&&l.layer!==t.layer)&&(s.push(l),a.add(l.id),s.length>=r))break}}catch{}return s}pruneOld(e){let t=new Date(Date.now()-e*864e5).toISOString();if(this.memoriesDir){let o=this.db.prepare("SELECT uuid, layer, shared FROM memories WHERE created_at < ?").all(t);for(let s of o)this.deleteMemoryFile(s.uuid,s.layer,s.shared===1)}let r=this.db.prepare("DELETE FROM memories WHERE created_at < ?").run(t);return this.memoriesDir&&this.updateDirHash(),r.changes}close(){this.analytics&&this.analytics.shutdown(),this.db.close()}getProjectRoot(){return this.projectRoot}get hasFileStorage(){return this.memoriesDir!==null}get memoriesPath(){return this.memoriesDir}rowToMemory(e){return{id:e.id,uuid:e.uuid,layer:e.layer,what:e.what,why:e.why,scope:e.scope,context_label:e.context_label,contributor:e.contributor,tags:e.tags?JSON.parse(e.tags):[],source:e.source,shared:e.shared===1,priority:e.priority==="always"?"always":"normal",generated_by:e.generated_by?JSON.parse(e.generated_by):null,derived_from:e.derived_from?JSON.parse(e.derived_from):null,created_at:e.created_at,updated_at:e.updated_at,recalled_count:e.recalled_count,last_recalled_at:e.last_recalled_at}}}});var xt,Rr=$(()=>{xt={"hooks.read.maxBlocks":{value:1,public:!0,pro:!1,description:"Max pre-read hard-blocks per file path per session. 0 disables the pre-read hook entirely. 1 is the default and fires a block on the first read of each file that has scoped memories."},"hooks.edit.maxBlocks":{value:1,public:!0,pro:!1,description:"Max pre-edit hard-blocks per file path per session. 0 disables the pre-edit hook entirely. 1 is the default."},"hooks.stop.schedule":{value:[{until:9,every:3},{until:29,every:5},{every:10}],public:!0,pro:!1,description:"Phased interval schedule for the Stop hook's 'worth remembering?' nudge. Each entry = {until, every}. Default ramps from every-3-turns for first 9 turns \u2192 every-5 for turns 10-29 \u2192 every-10 afterwards."},"hooks.search.mode":{value:"soft",public:!0,pro:!1,description:"Pre-search hook mode: 'off' (no nudge), 'soft' (additionalContext only, default), 'block' (hard decision:block envelope)."},"hooks.correction.enabled":{value:!0,public:!0,pro:!1,description:"Enable UserPromptSubmit correction detection. When true, messages like 'no, use X instead' trigger a nudge to call aide_remember."},"hooks.correction.escalate":{value:"off",public:!0,pro:!1,description:"When a correction is detected, optionally write a correction-pending flag so the next Stop fire reminds the agent if the correction wasn't stored. 'off' (default) \u2014 never reminds; correction surfaces only as the soft UserPromptSubmit hint at detection time. 'block' \u2014 flag is written and the next Stop fires decision:block with the reminder, regardless of hooks.stop.mode. Master switch: hooks.correction.enabled=false disables the entire correction system including this. (A 'soft' value existed in spec drafts but was dropped \u2014 Claude Code's Stop hook protocol doesn't accept hookSpecificOutput.additionalContext, so a soft Stop emit is impossible. Use the always-on UserPromptSubmit soft hint as the soft channel; escalate to 'block' only when you want an explicit follow-up reminder.)"},"hooks.stop.mode":{value:"block",public:!0,pro:!1,description:"How the scheduled Stop checkpoint surfaces. 'block' (default) uses decision:block + a softened reason prompt + chrome systemMessage. The Claude Code TUI collapses the 'Stop hook error:' label behind ctrl+o when systemMessage is present, so the brand chrome is the primary visible line. 'off' skips the scheduled checkpoint entirely (zero Stop noise). Frequency is still controlled by hooks.stop.schedule. (A 'soft' mode existed in spec drafts but was dropped \u2014 Claude Code's Stop hook protocol doesn't accept hookSpecificOutput.additionalContext, so 'block' is the only way to deliver text to the agent on Stop.) When a correction-pending flag is set and hooks.correction.escalate='block', that branch wins and the scheduled checkpoint is skipped that turn."},"hooks.precompact.mode":{value:"cleanup",public:!0,pro:!1,description:"PreCompact hook behavior: 'off' preserves tracking files across compaction; 'cleanup' (default) clears recalled-paths/stop-count/correction-pending so the post-compact turn re-blocks cleanly."},"hooks.visible":{value:!0,public:!0,pro:!1,description:"Surface user-facing systemMessage lines when hooks fire (soft recalls, correction detected, session-start injection, Stop checkpoints, etc). Default true so users can see what aide-memory is doing. Set to false to hide all aide-memory systemMessages \u2014 hooks still function (context injection + block enforcement unchanged). Does not affect what Claude sees."},"recall.limit":{value:20,public:!0,pro:!1,description:"Max memories returned per aide_recall call before layer-diversity balancing applies."},"recall.ensureLayerDiversity":{value:!0,public:!0,pro:!1,description:"If true, recall results are swapped to surface under-represented layers up to recall.layerDiversityMinLimit. Ensures each enabled layer gets at least some representation instead of the top-scoring one dominating."},"recall.layerDiversityMinLimit":{value:5,public:!0,pro:!1,description:"Minimum total results below which layer diversity swap kicks in. Above this threshold, natural ranking wins."},"recall.minScopeDepth":{value:1,public:!0,pro:!1,description:"Minimum fixed-prefix segment count a scope needs to surface via per-file path-recall. Scopes below this threshold surface only at SessionStart injection instead. Think of it as 'how specific must a scope be to show up when I open a file?' Default 1 is permissive \u2014 any scope with \u22651 segment (e.g. 'src/**', 'pages/**', 'packages/**') counts. Works across project shapes (src-wrapped, flat Next.js, deep monorepos). Bump to 2 if you have many broad scopes and want per-file recall quieter (broad scopes still surface at SessionStart). Bump to 3+ for very strict per-file recall."},"injection.enabled":{value:!0,public:!0,pro:!1,description:"Master switch for SessionStart dynamic injection. When true (default), the sessionStart handler loads + injects preferences / guidelines / priority:always memories into the agent's starting context; when false, the handler short-circuits before any SQLite read or template render \u2014 zero per-turn overhead from dynamic injection. The rules file still ships (static content) but carries no memory-derived content. Granular per-layer knobs (injection.preferences, injection.guidelines, etc.) only apply when this master switch is true. Flip to false if you want aide-memory's hooks + MCP tools without any session-start context injection."},"injection.preferences":{value:15,public:!0,pro:!1,description:"Max preferences injected at SessionStart. 0/false disables; number = hard cap; 'all' = every preference. Default 15 matches spec memory #297 ('top 15 most-recalled preferences'). Only honored when injection.enabled is true."},"injection.excludeScopedPreferences":{value:!1,public:!0,pro:!1,description:"If true, SessionStart injection skips preferences with a non-null scope \u2014 they surface via Read/Edit path hooks when the agent touches matching paths. Default false preserves current 'inject all preferences regardless of scope' behavior. Set to true for tighter SessionStart token usage when you have many scoped preferences. (NB: renamed from `injection.preferences.excludeScoped` to avoid key collision with `injection.preferences` which is a scalar limit, not an object.)"},"injection.technical":{value:!1,public:!0,pro:!1,description:"Inject technical-layer memories at SessionStart? Default false \u2014 technical context should surface via path hooks when relevant. Set to a number to cap, 'all' for unlimited, true for enabled-with-no-cap."},"injection.area_context":{value:!1,public:!0,pro:!1,description:"Inject area_context-layer memories at SessionStart? Default false \u2014 area context by definition is area-specific and should surface via path hooks."},"injection.guidelines":{value:"all",public:!0,pro:!1,description:"Inject guidelines at SessionStart. 'all' (default) injects every guideline regardless of scope \u2014 guidelines apply broadly so early visibility matters. Set to a number for a cap, or false to disable."},"injection.priorityAlwaysOverride":{value:!0,public:!0,pro:!1,description:"When true (default), any memory with priority='always' is injected at SessionStart regardless of layer-specific injection settings. User-marked 'always' memories surface in the ## Always section (rendered first since 0.4.3 so they survive char-cap truncation)."},"injection.maxChars":{value:1200,public:!0,pro:!1,description:"Overall character cap for the combined SessionStart injection (preferences + technical + area_context + guidelines + always). Applied after all layer sections are concatenated; truncates with '...truncated' suffix. Bump to 2000+ for richer context, drop to 600 for token-conscious sessions. Default 1200 matches the pre-0.4.3 hard-coded MAX_INJECT_CHARS constant."},"memories.hideFromGrep":{value:!0,public:!0,pro:!1,description:"Add an aide-memory-managed block to .ignore so grep/ripgrep/etc skip .aide/memories/ by default. Flipping this live triggers drift-repair on the next hook fire."},"memories.softening.threshold":{value:10,public:!0,pro:!1,description:"Total-memory count below which pre-read/pre-edit hard blocks become soft additionalContext nudges. Keeps small projects from feeling hostile. Default 10 \u2014 once you have 10+ total memories, hard blocking resumes on first-touch."},"memories.defaultShared":{value:!0,public:!0,pro:!1,description:"Default `shared` flag for new memories when the caller doesn't pass one. When true (default), aide_remember without an explicit shared param writes to `.aide/memories/preferences/shared/` (committed to repo). When false, defaults to `personal/` (gitignored). Per-call `shared: true|false` always overrides this default. Flip to false if you want personal-by-default and explicit opt-in for shared memories."}}});function Se(){return ga}function ya(n,e){let t=n;for(let r of e){if(t==null||typeof t!="object"||Array.isArray(t)||!Object.prototype.hasOwnProperty.call(t,r))return!1;t=t[r]}return!0}function ba(n,e){let t=n;for(let r of e)t=t[r];return t}function W(n,e){let r=Se()[e];if(!r)return;let o=r.value;if(r.public!==!0||!n)return o;let s=So.default.join(n,".aide","config.json");if(!Cr.default.existsSync(s))return o;let i;try{i=JSON.parse(Cr.default.readFileSync(s,"utf8"))}catch{return o}let a=e.split(".");return ya(i,a)?ba(i,a):o}function Eo(){let n=Se(),e={};for(let[t,r]of Object.entries(n))r.public===!0&&(e[t]=r.value);return e}function vo(n){let e={};for(let[t,r]of Object.entries(n)){let o=t.split("."),s=e;for(let i=0;i<o.length-1;i++){let a=o[i],c=s[a];(!c||typeof c!="object"||Array.isArray(c))&&(s[a]={}),s=s[a]}s[o[o.length-1]]=r}return e}var Cr,So,ga,Ze=$(()=>{"use strict";Cr=h(require("fs")),So=h(require("path"));Rr();ga=xt});function Tt(n,e,t,r){if(t===!1||t===0)return[];let o=n.list({layer:e});return e==="preferences"?(W(r,"injection.excludeScopedPreferences")===!0&&(o=o.filter(i=>!i.scope||i.scope==="project")),o.sort((i,a)=>{let c=i.recalled_count??0,l=a.recalled_count??0;return l!==c?l-c:(a.updated_at||"").localeCompare(i.updated_at||"")})):o.sort((s,i)=>(i.updated_at||"").localeCompare(s.updated_at||"")),t==="all"?o:typeof t=="number"&&t>0?o.slice(0,t):o}function Mt(n,e){if(!(W(n,"injection.enabled")??!0))return{content:"",injectedIds:[],truncated:!1};let r=W(n,"injection.preferences")??15,o=W(n,"injection.technical")??!1,s=W(n,"injection.area_context")??!1,i=W(n,"injection.guidelines")??"all",a=W(n,"injection.priorityAlwaysOverride")??!0,c=Number(W(n,"injection.maxChars")??1200),l=Tt(e,"preferences",r,n),u=Tt(e,"technical",o,n),d=Tt(e,"area_context",s,n),m=Tt(e,"guidelines",i,n),w=a?e.list({priority:"always"}):[],g=[],_=new Set,S=(k,re)=>{for(let J of k){let de=J.uuid||String(J.id);_.has(de)||(_.add(de),re.push(J.what),g.push(J.id))}},p={preferences:[],technical:[],area_context:[],guidelines:[],always:[]};if(S(l,p.preferences),S(u,p.technical),S(d,p.area_context),S(m,p.guidelines),S(w,p.always),p.preferences.length+p.technical.length+p.area_context.length+p.guidelines.length+p.always.length===0)return{content:"",injectedIds:[],truncated:!1};let f=[];if(p.always.length>0){f.push("## Always");for(let k of p.always)f.push(`- ${k}`)}if(p.preferences.length>0){f.push("## Session Preferences");for(let k of p.preferences)f.push(`- ${k}`)}if(p.technical.length>0){f.push("## Technical Context");for(let k of p.technical)f.push(`- ${k}`)}if(p.area_context.length>0){f.push("## Area Context");for(let k of p.area_context)f.push(`- ${k}`)}if(p.guidelines.length>0){f.push("## Guidelines");for(let k of p.guidelines)f.push(`- ${k}`)}let E=f.join(`
127
- `),T=!1;return E.length>c&&(E=E.slice(0,c)+`
128
- ...truncated`,T=!0),{content:E,injectedIds:g,truncated:T}}var Tr=$(()=>{"use strict";Ze()});var No={};Qt(No,{_resetPackageRootCache:()=>ka,findPackageRoot:()=>tt,getTemplatesDir:()=>Mr});function tt(){if(Nt)return Nt;let n=__dirname;for(let e=0;e<32&&n!==Ee.parse(n).root;e++){let t=Ee.join(n,"package.json");if(et.existsSync(t))try{let r=JSON.parse(et.readFileSync(t,"utf8"));if(typeof r.name=="string"&&va.has(r.name))return Nt=n,n}catch{}n=Ee.dirname(n)}throw new Error(`aide-memory: could not find package.json walking up from ${__dirname}. This indicates a broken install \u2014 reinstall aide-memory.`)}function Mr(){let n=tt(),e=Ee.join(n,"src","templates","rules");if(!et.existsSync(e))throw new Error(`aide-memory: templates directory not found at ${e}. This indicates a broken install \u2014 reinstall aide-memory.`);return e}function ka(){Nt=null}var et,Ee,Sa,Ea,va,Nt,$t=$(()=>{"use strict";et=h(require("fs")),Ee=h(require("path")),Sa="aide-memory",Ea=["aide","v0"].join("-"),va=new Set([Ea,Sa]),Nt=null});function xa(){if(jt!==null)return jt;let n=jo.join(Mr(),"shared","body.md");return jt=$o.readFileSync(n,"utf8"),jt}function Oa(n,e){let t=n;for(let[r,o]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${r}\\}\\}`,"g"),o);return t}function It(n,e){let t=xa(),r=n.ruleFrontmatter+t;return Oa(r,{contributor:e.contributor,tools_list:e.tools_list,tool_id:n.ruleToolId,editor_notes:n.ruleNotes})}var $o,jo,jt,Nr=$(()=>{"use strict";$o=h(require("fs")),jo=h(require("path"));$t();jt=null});function Io(n,e=""){let t=new Map;for(let[r,o]of Object.entries(n)){let s=e?`${e}.${r}`:r;if(Array.isArray(o))t.set(s,{type:"array"});else if(o!==null&&typeof o=="object"){t.set(s,{type:"object"});let i=Io(o,s);for(let[a,c]of i)t.set(a,c)}else t.set(s,{type:typeof o})}return t}function Ra(n,e){let t=e.split("."),r=n;for(let o of t){if(r==null||typeof r!="object")return;r=r[o]}return r}function Ca(n,e,t){let r=e.split("."),o=n;for(let s=0;s<r.length-1;s++){let i=r[s];(o[i]===void 0||o[i]===null||typeof o[i]!="object")&&(o[i]={}),o=o[i]}o[r[r.length-1]]=t}function ve(n){return JSON.parse(JSON.stringify(n))}var Pe,$r,ke,Dt,he,Ft=$(()=>{"use strict";Pe=h(require("fs")),$r=h(require("path")),ke={version:1,tags:{presets:["architecture","testing","security","style","integration","config","migration","performance","api-contract"]},telemetry:{enabled:!0},contributor:"auto",embeddings:{model:"auto",backend:"auto"},updates:{check:!0}};Dt=Io(ke);he=class{constructor(e){this.projectRoot=e,this.configPath=$r.default.join(e,".aide","config.json"),this.config=this.load()}get(e){return Ra(this.config,e)}set(e,t){this.validateKey(e),this.validateValue(e,t),Ca(this.config,e,t),this.save()}addTag(e){let t=this.config.tags.presets;t.includes(e)||(t.push(e),this.save())}removeTag(e){let t=this.config.tags.presets,r=t.indexOf(e);r!==-1&&(t.splice(r,1),this.save())}reset(){this.config=ve(ke),this.save()}list(){return ve(this.config)}static defaults(){return ve(ke)}load(){if(!Pe.default.existsSync(this.configPath))return ve(ke);let e;try{e=Pe.default.readFileSync(this.configPath,"utf-8")}catch{return console.warn(`[aide-config] Could not read ${this.configPath}, using defaults`),ve(ke)}try{let t=JSON.parse(e);return this.mergeWithDefaults(t)}catch{return console.warn(`[aide-config] Malformed JSON in ${this.configPath}, using defaults. Call config.reset() to overwrite the file with valid defaults.`),ve(ke)}}mergeWithDefaults(e){let t=ve(ke);return this.deepMerge(t,e)}deepMerge(e,t){if(t==null)return e;if(typeof t!="object"||Array.isArray(t)||typeof e!="object"||Array.isArray(e))return t;let r={...e};for(let o of Object.keys(t))o in r&&typeof r[o]=="object"&&!Array.isArray(r[o])&&typeof t[o]=="object"&&!Array.isArray(t[o])?r[o]=this.deepMerge(r[o],t[o]):r[o]=t[o];return r}save(){let e=$r.default.dirname(this.configPath);Pe.default.existsSync(e)||Pe.default.mkdirSync(e,{recursive:!0}),Pe.default.writeFileSync(this.configPath,JSON.stringify(this.config,null,2)+`
129
- `,"utf-8")}validateKey(e){if(!Dt.has(e)){let t=Array.from(Dt.keys()).filter(r=>!Dt.get(r).type.startsWith("object")).sort();throw new Error(`Unknown config key: "${e}". Valid keys: ${t.join(", ")}`)}}validateValue(e,t){let r=Dt.get(e);if(!r)return;let o=Array.isArray(t)?"array":typeof t;if(r.type!==o)throw new Error(`Invalid value type for "${e}": expected ${r.type}, got ${o}`)}}});function Ir(n,e){let t=jr.default.join(n,".ignore"),r=xe.default.existsSync(t),o=r?xe.default.readFileSync(t,"utf8"):"",{withoutManaged:s,withoutLegacy:i}=Ta(o),a;if(e){let c=Aa();a=Ma(i,c)}else a=s===i?s:i;return a===o?{ignorePath:t,changed:!1}:!e&&a.trim().length===0?r?(xe.default.unlinkSync(t),{ignorePath:t,changed:!0,message:".ignore removed (memories.hideFromGrep disabled, no other entries)"}):{ignorePath:t,changed:!1}:(xe.default.writeFileSync(t,a,"utf8"),{ignorePath:t,changed:!0,message:e?r?".ignore (aide-memory section updated)":".ignore (created with .aide/memories/ hidden from grep)":".ignore (aide-memory section removed)"})}function Dr(n){let e=jr.default.join(n,".aide","config.json");if(!xe.default.existsSync(e))return!0;try{return JSON.parse(xe.default.readFileSync(e,"utf8"))?.memories?.hideFromGrep!==!1}catch{return!0}}function Aa(){return`${Fo}
126
+ `,i=[r],a=[];return t?.layer&&(a.push("m.layer = ?"),i.push(t.layer)),a.length>0&&(s+=" WHERE "+a.join(" AND ")),s+=" ORDER BY fts.rank",s+=" LIMIT ?",i.push(o),this.db.prepare(s).all(...i).map(l=>this.rowToMemory(l))}searchLike(e,t){if(!e||!e.trim())return[];let r=["(what LIKE ? OR why LIKE ?)"],o=`%${e}%`,s=[o,o];t?.layer&&(r.push("layer = ?"),s.push(t.layer));let i="SELECT * FROM memories WHERE "+r.join(" AND ");i+=" ORDER BY created_at DESC, id DESC";let a=t?.limit??50;i+=" LIMIT ?",s.push(a);let l=this.db.prepare(i).all(...s).map(u=>this.rowToMemory(u));return l.length<3&&this.embeddingService?.isReady(),l}async searchWithEmbeddings(e,t){let r=t?.limit??50,o=t?.mode??"auto";if(o==="semantic"){if(!this.embeddingService?.isReady())return[];try{let i=await this.embeddingService.semanticSearch(this.db,e,r),a=[];for(let c of i){if(c.score<.3)continue;let l=this.getByUuid(c.uuid);if(l&&!(t?.layer&&l.layer!==t.layer)&&(a.push(l),a.length>=r))break}return this.logEvent("search_performed","semantic"),a}catch{return[]}}if(o==="keyword")return this.search(e,t);let s=this.search(e,t);if(s.length<3&&this.embeddingService?.isReady())try{let i=await this.embeddingService.semanticSearch(this.db,e,r),a=new Set(s.map(c=>c.id));for(let c of i){if(c.score<.3)continue;let l=this.getByUuid(c.uuid);if(l&&!a.has(l.id)&&!(t?.layer&&l.layer!==t.layer)&&(s.push(l),a.add(l.id),s.length>=r))break}}catch{}return s}pruneOld(e){let t=new Date(Date.now()-e*864e5).toISOString();if(this.memoriesDir){let o=this.db.prepare("SELECT uuid, layer, shared FROM memories WHERE created_at < ?").all(t);for(let s of o)this.deleteMemoryFile(s.uuid,s.layer,s.shared===1)}let r=this.db.prepare("DELETE FROM memories WHERE created_at < ?").run(t);return this.memoriesDir&&this.updateDirHash(),r.changes}close(){this.analytics&&this.analytics.shutdown(),this.db.close()}getProjectRoot(){return this.projectRoot}get hasFileStorage(){return this.memoriesDir!==null}get memoriesPath(){return this.memoriesDir}rowToMemory(e){return{id:e.id,uuid:e.uuid,layer:e.layer,what:e.what,why:e.why,scope:e.scope,context_label:e.context_label,contributor:e.contributor,tags:e.tags?JSON.parse(e.tags):[],source:e.source,shared:e.shared===1,priority:e.priority==="always"?"always":"normal",generated_by:e.generated_by?JSON.parse(e.generated_by):null,derived_from:e.derived_from?JSON.parse(e.derived_from):null,created_at:e.created_at,updated_at:e.updated_at,recalled_count:e.recalled_count,last_recalled_at:e.last_recalled_at}}}});var Rt,Cr=T(()=>{Rt={"hooks.read.maxBlocks":{value:1,public:!0,pro:!1,description:"Max pre-read hard-blocks per file path per session. 0 disables the pre-read hook entirely. 1 is the default and fires a block on the first read of each file that has scoped memories."},"hooks.edit.maxBlocks":{value:1,public:!0,pro:!1,description:"Max pre-edit hard-blocks per file path per session. 0 disables the pre-edit hook entirely. 1 is the default."},"hooks.stop.schedule":{value:[{until:9,every:3},{until:29,every:5},{every:10}],public:!0,pro:!1,description:"Phased interval schedule for the Stop hook's 'worth remembering?' nudge. Each entry = {until, every}. Default ramps from every-3-turns for first 9 turns \u2192 every-5 for turns 10-29 \u2192 every-10 afterwards."},"hooks.search.mode":{value:"soft",public:!0,pro:!1,description:"Pre-search hook mode: 'off' (no nudge), 'soft' (additionalContext only, default), 'block' (hard decision:block envelope)."},"hooks.correction.enabled":{value:!0,public:!0,pro:!1,description:"Enable UserPromptSubmit correction detection. When true, messages like 'no, use X instead' trigger a nudge to call aide_remember."},"hooks.correction.escalate":{value:"off",public:!0,pro:!1,description:"When a correction is detected, optionally write a correction-pending flag so the next Stop fire reminds the agent if the correction wasn't stored. 'off' (default) \u2014 never reminds; correction surfaces only as the soft UserPromptSubmit hint at detection time. 'block' \u2014 flag is written and the next Stop fires decision:block with the reminder, regardless of hooks.stop.mode. Master switch: hooks.correction.enabled=false disables the entire correction system including this. (A 'soft' value existed in spec drafts but was dropped \u2014 Claude Code's Stop hook protocol doesn't accept hookSpecificOutput.additionalContext, so a soft Stop emit is impossible. Use the always-on UserPromptSubmit soft hint as the soft channel; escalate to 'block' only when you want an explicit follow-up reminder.)"},"hooks.stop.mode":{value:"block",public:!0,pro:!1,description:"How the scheduled Stop checkpoint surfaces. 'block' (default) uses decision:block + a softened reason prompt + chrome systemMessage. The Claude Code TUI collapses the 'Stop hook error:' label behind ctrl+o when systemMessage is present, so the brand chrome is the primary visible line. 'off' skips the scheduled checkpoint entirely (zero Stop noise). Frequency is still controlled by hooks.stop.schedule. (A 'soft' mode existed in spec drafts but was dropped \u2014 Claude Code's Stop hook protocol doesn't accept hookSpecificOutput.additionalContext, so 'block' is the only way to deliver text to the agent on Stop.) When a correction-pending flag is set and hooks.correction.escalate='block', that branch wins and the scheduled checkpoint is skipped that turn."},"hooks.precompact.mode":{value:"cleanup",public:!0,pro:!1,description:"PreCompact hook behavior: 'off' preserves tracking files across compaction; 'cleanup' (default) clears recalled-paths/stop-count/correction-pending so the post-compact turn re-blocks cleanly."},"hooks.visible":{value:!0,public:!0,pro:!1,description:"Surface user-facing systemMessage lines when hooks fire (soft recalls, correction detected, session-start injection, Stop checkpoints, etc). Default true so users can see what aide-memory is doing. Set to false to hide all aide-memory systemMessages \u2014 hooks still function (context injection + block enforcement unchanged). Does not affect what Claude sees."},"recall.limit":{value:20,public:!0,pro:!1,description:"Max memories returned per aide_recall call before layer-diversity balancing applies."},"recall.ensureLayerDiversity":{value:!0,public:!0,pro:!1,description:"If true, recall results are swapped to surface under-represented layers up to recall.layerDiversityMinLimit. Ensures each enabled layer gets at least some representation instead of the top-scoring one dominating."},"recall.layerDiversityMinLimit":{value:5,public:!0,pro:!1,description:"Minimum total results below which layer diversity swap kicks in. Above this threshold, natural ranking wins."},"recall.minScopeDepth":{value:1,public:!0,pro:!1,description:"Minimum fixed-prefix segment count a scope needs to surface via per-file path-recall. Scopes below this threshold surface only at SessionStart injection instead. Think of it as 'how specific must a scope be to show up when I open a file?' Default 1 is permissive \u2014 any scope with \u22651 segment (e.g. 'src/**', 'pages/**', 'packages/**') counts. Works across project shapes (src-wrapped, flat Next.js, deep monorepos). Bump to 2 if you have many broad scopes and want per-file recall quieter (broad scopes still surface at SessionStart). Bump to 3+ for very strict per-file recall."},"injection.enabled":{value:!0,public:!0,pro:!1,description:"Master switch for SessionStart dynamic injection. When true (default), the sessionStart handler loads + injects preferences / guidelines / priority:always memories into the agent's starting context; when false, the handler short-circuits before any SQLite read or template render \u2014 zero per-turn overhead from dynamic injection. The rules file still ships (static content) but carries no memory-derived content. Granular per-layer knobs (injection.preferences, injection.guidelines, etc.) only apply when this master switch is true. Flip to false if you want aide-memory's hooks + MCP tools without any session-start context injection."},"injection.preferences":{value:15,public:!0,pro:!1,description:"Max preferences injected at SessionStart. 0/false disables; number = hard cap; 'all' = every preference. Default 15 matches spec memory #297 ('top 15 most-recalled preferences'). Only honored when injection.enabled is true."},"injection.excludeScopedPreferences":{value:!1,public:!0,pro:!1,description:"If true, SessionStart injection skips preferences with a non-null scope \u2014 they surface via Read/Edit path hooks when the agent touches matching paths. Default false preserves current 'inject all preferences regardless of scope' behavior. Set to true for tighter SessionStart token usage when you have many scoped preferences. (NB: renamed from `injection.preferences.excludeScoped` to avoid key collision with `injection.preferences` which is a scalar limit, not an object.)"},"injection.technical":{value:!1,public:!0,pro:!1,description:"Inject technical-layer memories at SessionStart? Default false \u2014 technical context should surface via path hooks when relevant. Set to a number to cap, 'all' for unlimited, true for enabled-with-no-cap."},"injection.area_context":{value:!1,public:!0,pro:!1,description:"Inject area_context-layer memories at SessionStart? Default false \u2014 area context by definition is area-specific and should surface via path hooks."},"injection.guidelines":{value:"all",public:!0,pro:!1,description:"Inject guidelines at SessionStart. 'all' (default) injects every guideline regardless of scope \u2014 guidelines apply broadly so early visibility matters. Set to a number for a cap, or false to disable."},"injection.priorityAlwaysOverride":{value:!0,public:!0,pro:!1,description:"When true (default), any memory with priority='always' is injected at SessionStart regardless of layer-specific injection settings. User-marked 'always' memories surface in the ## Always section (rendered first since 0.4.3 so they survive char-cap truncation)."},"injection.maxChars":{value:1200,public:!0,pro:!1,description:"Overall character cap for the combined SessionStart injection (preferences + technical + area_context + guidelines + always). Applied after all layer sections are concatenated; truncates with '...truncated' suffix. Bump to 2000+ for richer context, drop to 600 for token-conscious sessions. Default 1200 matches the pre-0.4.3 hard-coded MAX_INJECT_CHARS constant."},"memories.hideFromGrep":{value:!0,public:!0,pro:!1,description:"Add an aide-memory-managed block to .ignore so grep/ripgrep/etc skip .aide/memories/ by default. Flipping this live triggers drift-repair on the next hook fire."},"memories.softening.threshold":{value:10,public:!0,pro:!1,description:"Total-memory count below which pre-read/pre-edit hard blocks become soft additionalContext nudges. Keeps small projects from feeling hostile. Default 10 \u2014 once you have 10+ total memories, hard blocking resumes on first-touch."},"memories.defaultShared":{value:!0,public:!0,pro:!1,description:"Default `shared` flag for new memories when the caller doesn't pass one. When true (default), aide_remember without an explicit shared param writes to `.aide/memories/preferences/shared/` (committed to repo). When false, defaults to `personal/` (gitignored). Per-call `shared: true|false` always overrides this default. Flip to false if you want personal-by-default and explicit opt-in for shared memories."}}});function Se(){return ba}function _a(n,e){let t=n;for(let r of e){if(t==null||typeof t!="object"||Array.isArray(t)||!Object.prototype.hasOwnProperty.call(t,r))return!1;t=t[r]}return!0}function wa(n,e){let t=n;for(let r of e)t=t[r];return t}function q(n,e){let r=Se()[e];if(!r)return;let o=r.value;if(r.public!==!0||!n)return o;let s=Eo.default.join(n,".aide","config.json");if(!Ar.default.existsSync(s))return o;let i;try{i=JSON.parse(Ar.default.readFileSync(s,"utf8"))}catch{return o}let a=e.split(".");return _a(i,a)?wa(i,a):o}function vo(){let n=Se(),e={};for(let[t,r]of Object.entries(n))r.public===!0&&(e[t]=r.value);return e}function ko(n){let e={};for(let[t,r]of Object.entries(n)){let o=t.split("."),s=e;for(let i=0;i<o.length-1;i++){let a=o[i],c=s[a];(!c||typeof c!="object"||Array.isArray(c))&&(s[a]={}),s=s[a]}s[o[o.length-1]]=r}return e}var Ar,Eo,ba,tt=T(()=>{"use strict";Ar=g(require("fs")),Eo=g(require("path"));Cr();ba=Rt});function Nt(n,e,t,r){if(t===!1||t===0)return[];let o=n.list({layer:e});return e==="preferences"?(q(r,"injection.excludeScopedPreferences")===!0&&(o=o.filter(i=>!i.scope||i.scope==="project")),o.sort((i,a)=>{let c=i.recalled_count??0,l=a.recalled_count??0;return l!==c?l-c:(a.updated_at||"").localeCompare(i.updated_at||"")})):o.sort((s,i)=>(i.updated_at||"").localeCompare(s.updated_at||"")),t==="all"?o:typeof t=="number"&&t>0?o.slice(0,t):o}function $t(n,e){if(!(q(n,"injection.enabled")??!0))return{content:"",injectedIds:[],truncated:!1};let r=q(n,"injection.preferences")??15,o=q(n,"injection.technical")??!1,s=q(n,"injection.area_context")??!1,i=q(n,"injection.guidelines")??"all",a=q(n,"injection.priorityAlwaysOverride")??!0,c=Number(q(n,"injection.maxChars")??1200),l=Nt(e,"preferences",r,n),u=Nt(e,"technical",o,n),d=Nt(e,"area_context",s,n),f=Nt(e,"guidelines",i,n),y=a?e.list({priority:"always"}):[],h=[],w=new Set,E=(k,H)=>{for(let I of k){let ce=I.uuid||String(I.id);w.has(ce)||(w.add(ce),H.push(I.what),h.push(I.id))}},p={preferences:[],technical:[],area_context:[],guidelines:[],always:[]};if(E(l,p.preferences),E(u,p.technical),E(d,p.area_context),E(f,p.guidelines),E(y,p.always),p.preferences.length+p.technical.length+p.area_context.length+p.guidelines.length+p.always.length===0)return{content:"",injectedIds:[],truncated:!1};let m=[];if(p.always.length>0){m.push("## Always");for(let k of p.always)m.push(`- ${k}`)}if(p.preferences.length>0){m.push("## Session Preferences");for(let k of p.preferences)m.push(`- ${k}`)}if(p.technical.length>0){m.push("## Technical Context");for(let k of p.technical)m.push(`- ${k}`)}if(p.area_context.length>0){m.push("## Area Context");for(let k of p.area_context)m.push(`- ${k}`)}if(p.guidelines.length>0){m.push("## Guidelines");for(let k of p.guidelines)m.push(`- ${k}`)}let S=m.join(`
127
+ `),j=!1;return S.length>c&&(S=S.slice(0,c)+`
128
+ ...truncated`,j=!0),{content:S,injectedIds:h,truncated:j}}var Mr=T(()=>{"use strict";tt()});var $o={};Zt($o,{_resetPackageRootCache:()=>Oa,findPackageRoot:()=>nt,getTemplatesDir:()=>Nr});function nt(){if(It)return It;let n=__dirname;for(let e=0;e<32&&n!==Ee.parse(n).root;e++){let t=Ee.join(n,"package.json");if(rt.existsSync(t))try{let r=JSON.parse(rt.readFileSync(t,"utf8"));if(typeof r.name=="string"&&xa.has(r.name))return It=n,n}catch{}n=Ee.dirname(n)}throw new Error(`aide-memory: could not find package.json walking up from ${__dirname}. This indicates a broken install \u2014 reinstall aide-memory.`)}function Nr(){let n=nt(),e=Ee.join(n,"src","templates","rules");if(!rt.existsSync(e))throw new Error(`aide-memory: templates directory not found at ${e}. This indicates a broken install \u2014 reinstall aide-memory.`);return e}function Oa(){It=null}var rt,Ee,va,ka,xa,It,jt=T(()=>{"use strict";rt=g(require("fs")),Ee=g(require("path")),va="aide-memory",ka=["aide","v0"].join("-"),xa=new Set([ka,va]),It=null});function Ra(){if(Pt!==null)return Pt;let n=jo.join(Nr(),"shared","body.md");return Pt=Io.readFileSync(n,"utf8"),Pt}function Ca(n,e){let t=n;for(let[r,o]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${r}\\}\\}`,"g"),o);return t}function Dt(n,e){let t=Ra(),r=n.ruleFrontmatter+t;return Ca(r,{contributor:e.contributor,tools_list:e.tools_list,tool_id:n.ruleToolId,editor_notes:n.ruleNotes})}var Io,jo,Pt,$r=T(()=>{"use strict";Io=g(require("fs")),jo=g(require("path"));jt();Pt=null});function Po(n,e=""){let t=new Map;for(let[r,o]of Object.entries(n)){let s=e?`${e}.${r}`:r;if(Array.isArray(o))t.set(s,{type:"array"});else if(o!==null&&typeof o=="object"){t.set(s,{type:"object"});let i=Po(o,s);for(let[a,c]of i)t.set(a,c)}else t.set(s,{type:typeof o})}return t}function Aa(n,e){let t=e.split("."),r=n;for(let o of t){if(r==null||typeof r!="object")return;r=r[o]}return r}function Ta(n,e,t){let r=e.split("."),o=n;for(let s=0;s<r.length-1;s++){let i=r[s];(o[i]===void 0||o[i]===null||typeof o[i]!="object")&&(o[i]={}),o=o[i]}o[r[r.length-1]]=t}function ve(n){return JSON.parse(JSON.stringify(n))}var Le,Ir,ke,Ft,he,Lt=T(()=>{"use strict";Le=g(require("fs")),Ir=g(require("path")),ke={version:1,tags:{presets:["architecture","testing","security","style","integration","config","migration","performance","api-contract"]},telemetry:{enabled:!0},contributor:"auto",embeddings:{model:"auto",backend:"auto"},updates:{check:!0}};Ft=Po(ke);he=class{constructor(e){this.projectRoot=e,this.configPath=Ir.default.join(e,".aide","config.json"),this.config=this.load()}get(e){return Aa(this.config,e)}set(e,t){this.validateKey(e),this.validateValue(e,t),Ta(this.config,e,t),this.save()}addTag(e){let t=this.config.tags.presets;t.includes(e)||(t.push(e),this.save())}removeTag(e){let t=this.config.tags.presets,r=t.indexOf(e);r!==-1&&(t.splice(r,1),this.save())}reset(){this.config=ve(ke),this.save()}list(){return ve(this.config)}static defaults(){return ve(ke)}load(){if(!Le.default.existsSync(this.configPath))return ve(ke);let e;try{e=Le.default.readFileSync(this.configPath,"utf-8")}catch{return console.warn(`[aide-config] Could not read ${this.configPath}, using defaults`),ve(ke)}try{let t=JSON.parse(e);return this.mergeWithDefaults(t)}catch{return console.warn(`[aide-config] Malformed JSON in ${this.configPath}, using defaults. Call config.reset() to overwrite the file with valid defaults.`),ve(ke)}}mergeWithDefaults(e){let t=ve(ke);return this.deepMerge(t,e)}deepMerge(e,t){if(t==null)return e;if(typeof t!="object"||Array.isArray(t)||typeof e!="object"||Array.isArray(e))return t;let r={...e};for(let o of Object.keys(t))o in r&&typeof r[o]=="object"&&!Array.isArray(r[o])&&typeof t[o]=="object"&&!Array.isArray(t[o])?r[o]=this.deepMerge(r[o],t[o]):r[o]=t[o];return r}save(){let e=Ir.default.dirname(this.configPath);Le.default.existsSync(e)||Le.default.mkdirSync(e,{recursive:!0}),Le.default.writeFileSync(this.configPath,JSON.stringify(this.config,null,2)+`
129
+ `,"utf-8")}validateKey(e){if(!Ft.has(e)){let t=Array.from(Ft.keys()).filter(r=>!Ft.get(r).type.startsWith("object")).sort();throw new Error(`Unknown config key: "${e}". Valid keys: ${t.join(", ")}`)}}validateValue(e,t){let r=Ft.get(e);if(!r)return;let o=Array.isArray(t)?"array":typeof t;if(r.type!==o)throw new Error(`Invalid value type for "${e}": expected ${r.type}, got ${o}`)}}});function Pr(n,e){let t=jr.default.join(n,".ignore"),r=xe.default.existsSync(t),o=r?xe.default.readFileSync(t,"utf8"):"",{withoutManaged:s,withoutLegacy:i}=Na(o),a;if(e){let c=Ma();a=$a(i,c)}else a=s===i?s:i;return a===o?{ignorePath:t,changed:!1}:!e&&a.trim().length===0?r?(xe.default.unlinkSync(t),{ignorePath:t,changed:!0,message:".ignore removed (memories.hideFromGrep disabled, no other entries)"}):{ignorePath:t,changed:!1}:(xe.default.writeFileSync(t,a,"utf8"),{ignorePath:t,changed:!0,message:e?r?".ignore (aide-memory section updated)":".ignore (created with .aide/memories/ hidden from grep)":".ignore (aide-memory section removed)"})}function Dr(n){let e=jr.default.join(n,".aide","config.json");if(!xe.default.existsSync(e))return!0;try{return JSON.parse(xe.default.readFileSync(e,"utf8"))?.memories?.hideFromGrep!==!1}catch{return!0}}function Ma(){return`${Fo}
130
+ ${Ho}
130
131
  ${Lo}
131
- ${Po}
132
- `}function Ta(n){let e=new RegExp(`(?:^|\\n)[ \\t]*${Do(Fo)}[^\\n]*\\n[\\s\\S]*?${Do(Po)}[^\\n]*(?:\\n|$)`,"g"),t=n.replace(e,o=>o.startsWith(`
132
+ `}function Na(n){let e=new RegExp(`(?:^|\\n)[ \\t]*${Do(Fo)}[^\\n]*\\n[\\s\\S]*?${Do(Lo)}[^\\n]*(?:\\n|$)`,"g"),t=n.replace(e,o=>o.startsWith(`
133
133
  `)?`
134
134
  `:""),r=t.split(`
135
- `).filter(o=>o.trim()!==Lo).join(`
136
- `);return{withoutManaged:t,withoutLegacy:r}}function Ma(n,e){if(n.length===0)return e;let t=n.replace(/\n+$/,"");return t.length===0?e:`${t}
135
+ `).filter(o=>o.trim()!==Ho).join(`
136
+ `);return{withoutManaged:t,withoutLegacy:r}}function $a(n,e){if(n.length===0)return e;let t=n.replace(/\n+$/,"");return t.length===0?e:`${t}
137
137
 
138
- ${e}`}function Do(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var xe,jr,Fo,Po,Lo,Ho=$(()=>{"use strict";xe=h(require("fs")),jr=h(require("path")),Fo="# BEGIN aide-memory-managed",Po="# END aide-memory-managed",Lo=".aide/memories/"});function Uo(n=rt){let e=[];for(let t of n){if(!t.hasMatcher||!t.matchers||t.matchers.length===0){e.push({event:t,matcher:null});continue}for(let r of t.matchers)e.push({event:t,matcher:r})}return e}var rt,Fr=$(()=>{"use strict";rt=[{id:"session-start",script:"session-start-clear.sh",purpose:"Inject top-N preferences + guidelines + priority:always at session start",timeout:10,hasMatcher:!1},{id:"pre-compact",script:"pre-compact-save.sh",purpose:"Clear session tracking before compaction",timeout:30,hasMatcher:!1},{id:"stop",script:"stop-remember.sh",purpose:"Reflection nudge on schedule + correction-pending flag",timeout:30,hasMatcher:!1},{id:"pre-prompt",script:"detect-correction.sh",purpose:"Detect correction/decision/preference in user prompt",timeout:5,hasMatcher:!1},{id:"pre-read",script:"pre-read-recall.sh",purpose:"Block/soft on file read with scoped memories",timeout:10,hasMatcher:!0,matchers:["read"]},{id:"pre-edit",script:"pre-edit-recall.sh",purpose:"Block/soft on file edit with scoped memories",timeout:10,hasMatcher:!0,matchers:["edit","write"]},{id:"pre-search",script:"pre-search-nudge.sh",purpose:"Nudge aide_search when matching memories exist",timeout:10,hasMatcher:!0,matchers:["search","glob"]},{id:"pre-recall",script:"track-recall.sh",purpose:"Track paths on aide_recall pre-tool-use",timeout:5,hasMatcher:!0,matchers:["mcp-aide-recall"]},{id:"post-tool-use-recall",script:"track-recall-post.sh",purpose:"Record recalled ids post-tool-use",timeout:5,hasMatcher:!0,matchers:["mcp-aide-recall"]},{id:"post-remember",script:"track-remember.sh",purpose:"Clear correction-pending flag on aide_remember/update/forget",timeout:5,hasMatcher:!0,matchers:["mcp-aide-remember","mcp-aide-update","mcp-aide-forget"]},{id:"post-search",script:"track-search.sh",purpose:"Mark query as searched post aide_search",timeout:5,hasMatcher:!0,matchers:["mcp-aide-search"]}]});function Pt(n,e){let t=[],r=new Set;for(let{event:o,matcher:s}of Uo(rt)){let i=n.eventNameMap[o.id];if(i===null)continue;let a=null;if(s!==null){let u=n.matcherMap[s];if(u===null)continue;a=u}let c=Na(e.packageRoot,o.script),l=`${i}|${a??""}|${c}`;r.has(l)||(r.add(l),t.push({eventName:i,matcher:a,command:c,timeout:o.timeout}))}return t}function Na(n,e){return`bash ${Bo.join(n,"scripts","hooks",e)}`}function Lt(n){let e=new Map;for(let t of n){let r=e.get(t.eventName)??[];r.push(t),e.set(t.eventName,r)}return e}var Bo,Pr=$(()=>{"use strict";Bo=h(require("path"));Fr()});var Ht,Vo=$(()=>{"use strict";Pr();Ht={id:"claude-code",displayName:"Claude Code",hookConfigPath:".claude/settings.json",mcpConfigPath:".mcp.json",rules:[{template:"claude-code.md",dest:".claude/rules/aide-memory.md"}],ruleFrontmatter:"",ruleNotes:"",ruleToolId:"claude-code",supportsHooks:!0,supportsMcp:!0,supportsRules:!0,eventNameMap:{"session-start":"SessionStart","pre-compact":"PreCompact",stop:"Stop","pre-prompt":"UserPromptSubmit","pre-read":"PreToolUse","pre-edit":"PreToolUse","pre-search":"PreToolUse","pre-recall":"PreToolUse","post-tool-use-recall":"PostToolUse","post-remember":"PostToolUse","post-search":"PostToolUse"},matcherMap:{read:"Read",edit:"Edit",write:"Write",search:"Grep",glob:"Glob","mcp-aide-recall":"mcp__aide-memory__aide_recall","mcp-aide-remember":"mcp__aide-memory__aide_remember","mcp-aide-update":"mcp__aide-memory__aide_update","mcp-aide-forget":"mcp__aide-memory__aide_forget","mcp-aide-search":"mcp__aide-memory__aide_search"},buildHookConfig(n){let e=Pt(Ht,n),t=Lt(e),r={};for(let[o,s]of t){let i=s.some(a=>a.matcher!==null);r[o]=s.map(a=>{let c={type:"command",command:a.command,timeout:a.timeout};return i?{matcher:a.matcher,hooks:[c]}:{hooks:[c]}})}return{hooks:r}},buildMcpConfig({serverEntry:n,projectRoot:e}){return{mcpServers:{"aide-memory":{command:"node",args:[n,e]}}}},detectRuntime(n){return n.CURSOR_VERSION||n.CURSOR_PROJECT_DIR?!1:!!n.CLAUDECODE},translateInput(n){return n},translateOutput(n){switch(n.kind){case"block":{let e={decision:"block",reason:n.reason};return n.systemMessage&&(e.systemMessage=n.systemMessage),JSON.stringify(e,null,2)}case"additionalContext":{let e={hookSpecificOutput:{hookEventName:n.event,additionalContext:n.context}};return n.systemMessage&&(e.systemMessage=n.systemMessage),JSON.stringify(e,null,2)}case"systemMessage":return JSON.stringify({systemMessage:n.text},null,2);case"silent":return""}}}});function Oe(n){return n.replace($a,"")}var $a,Lr,Wo=$(()=>{"use strict";Pr();$a=/\[[0-9;]*m/g;Lr={id:"cursor",displayName:"Cursor",hookConfigPath:".cursor/hooks.json",mcpConfigPath:".cursor/mcp.json",rules:[{template:"cursor.mdc",dest:".cursor/rules/aide-memory.mdc"}],ruleFrontmatter:`---
138
+ ${e}`}function Do(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var xe,jr,Fo,Lo,Ho,Uo=T(()=>{"use strict";xe=g(require("fs")),jr=g(require("path")),Fo="# BEGIN aide-memory-managed",Lo="# END aide-memory-managed",Ho=".aide/memories/"});function Bo(n=ot){let e=[];for(let t of n){if(!t.hasMatcher||!t.matchers||t.matchers.length===0){e.push({event:t,matcher:null});continue}for(let r of t.matchers)e.push({event:t,matcher:r})}return e}var ot,Fr=T(()=>{"use strict";ot=[{id:"session-start",script:"session-start-clear.sh",purpose:"Inject top-N preferences + guidelines + priority:always at session start",timeout:10,hasMatcher:!1},{id:"pre-compact",script:"pre-compact-save.sh",purpose:"Clear session tracking before compaction",timeout:30,hasMatcher:!1},{id:"stop",script:"stop-remember.sh",purpose:"Reflection nudge on schedule + correction-pending flag",timeout:30,hasMatcher:!1},{id:"pre-prompt",script:"detect-correction.sh",purpose:"Detect correction/decision/preference in user prompt",timeout:5,hasMatcher:!1},{id:"pre-read",script:"pre-read-recall.sh",purpose:"Block/soft on file read with scoped memories",timeout:10,hasMatcher:!0,matchers:["read"]},{id:"pre-edit",script:"pre-edit-recall.sh",purpose:"Block/soft on file edit with scoped memories",timeout:10,hasMatcher:!0,matchers:["edit","write"]},{id:"pre-search",script:"pre-search-nudge.sh",purpose:"Nudge aide_search when matching memories exist",timeout:10,hasMatcher:!0,matchers:["search","glob"]},{id:"pre-recall",script:"track-recall.sh",purpose:"Track paths on aide_recall pre-tool-use",timeout:5,hasMatcher:!0,matchers:["mcp-aide-recall"]},{id:"post-tool-use-recall",script:"track-recall-post.sh",purpose:"Record recalled ids post-tool-use",timeout:5,hasMatcher:!0,matchers:["mcp-aide-recall"]},{id:"post-remember",script:"track-remember.sh",purpose:"Clear correction-pending flag on aide_remember/update/forget",timeout:5,hasMatcher:!0,matchers:["mcp-aide-remember","mcp-aide-update","mcp-aide-forget"]},{id:"post-search",script:"track-search.sh",purpose:"Mark query as searched post aide_search",timeout:5,hasMatcher:!0,matchers:["mcp-aide-search"]}]});function He(n,e){let t=[],r=new Set;for(let{event:o,matcher:s}of Bo(ot)){let i=n.eventNameMap[o.id];if(i===null)continue;let a=null;if(s!==null){let u=n.matcherMap[s];if(u===null)continue;a=u}let c=Ia(e.packageRoot,o.script),l=`${i}|${a??""}|${c}`;r.has(l)||(r.add(l),t.push({eventName:i,matcher:a,command:c,timeout:o.timeout}))}return t}function Ia(n,e){return`bash ${Vo.join(n,"scripts","hooks",e)}`}function Ue(n){let e=new Map;for(let t of n){let r=e.get(t.eventName)??[];r.push(t),e.set(t.eventName,r)}return e}var Vo,Ht=T(()=>{"use strict";Vo=g(require("path"));Fr()});var Ut,Wo=T(()=>{"use strict";Ht();Ut={id:"claude-code",displayName:"Claude Code",hookConfigPath:".claude/settings.json",mcpConfigPath:".mcp.json",rules:[{template:"claude-code.md",dest:".claude/rules/aide-memory.md"}],ruleFrontmatter:"",ruleNotes:"",ruleToolId:"claude-code",supportsHooks:!0,supportsMcp:!0,supportsRules:!0,eventNameMap:{"session-start":"SessionStart","pre-compact":"PreCompact",stop:"Stop","pre-prompt":"UserPromptSubmit","pre-read":"PreToolUse","pre-edit":"PreToolUse","pre-search":"PreToolUse","pre-recall":"PreToolUse","post-tool-use-recall":"PostToolUse","post-remember":"PostToolUse","post-search":"PostToolUse"},matcherMap:{read:"Read",edit:"Edit",write:"Write",search:"Grep",glob:"Glob","mcp-aide-recall":"mcp__aide-memory__aide_recall","mcp-aide-remember":"mcp__aide-memory__aide_remember","mcp-aide-update":"mcp__aide-memory__aide_update","mcp-aide-forget":"mcp__aide-memory__aide_forget","mcp-aide-search":"mcp__aide-memory__aide_search"},buildHookConfig(n){let e=He(Ut,n),t=Ue(e),r={};for(let[o,s]of t){let i=s.some(a=>a.matcher!==null);r[o]=s.map(a=>{let c={type:"command",command:a.command,timeout:a.timeout};return i?{matcher:a.matcher,hooks:[c]}:{hooks:[c]}})}return{hooks:r}},buildMcpConfig({serverEntry:n,projectRoot:e}){return{mcpServers:{"aide-memory":{command:"node",args:[n,e]}}}},detectRuntime(n){return n.CURSOR_VERSION||n.CURSOR_PROJECT_DIR?!1:!!n.CLAUDECODE},translateInput(n){return n},translateOutput(n){switch(n.kind){case"block":{let e={decision:"block",reason:n.reason};return n.systemMessage&&(e.systemMessage=n.systemMessage),JSON.stringify(e,null,2)}case"additionalContext":{let e={hookSpecificOutput:{hookEventName:n.event,additionalContext:n.context}};return n.systemMessage&&(e.systemMessage=n.systemMessage),JSON.stringify(e,null,2)}case"systemMessage":return JSON.stringify({systemMessage:n.text},null,2);case"silent":return""}}}});function Oe(n){return n.replace(ja,"")}var ja,Lr,Jo=T(()=>{"use strict";Ht();ja=/\[[0-9;]*m/g;Lr={id:"cursor",displayName:"Cursor",hookConfigPath:".cursor/hooks.json",mcpConfigPath:".cursor/mcp.json",rules:[{template:"cursor.mdc",dest:".cursor/rules/aide-memory.mdc"}],ruleFrontmatter:`---
139
139
  description: AIDE Memory - persistent context for AI coding agents
140
140
  globs: **/*
141
141
  alwaysApply: true
142
142
  ---
143
143
 
144
- `,ruleNotes:"\nNote: Cursor uses `agent_message` for hook responses rather than `additionalContext`. The nudge content appears directly in the agent message flow.\n",ruleToolId:"cursor",supportsHooks:!0,supportsMcp:!0,supportsRules:!0,needsDynamicRules:!0,eventNameMap:{"session-start":"sessionStart","pre-compact":"preCompact",stop:"stop","pre-prompt":"beforeSubmitPrompt","pre-read":"preToolUse","pre-edit":"preToolUse","pre-search":"preToolUse","pre-recall":"preToolUse","post-tool-use-recall":"postToolUse","post-remember":"postToolUse","post-search":"postToolUse"},matcherMap:{read:"Read",edit:"Write",write:"Write",search:"Grep",glob:null,"mcp-aide-recall":"MCP:aide_recall","mcp-aide-remember":"MCP:aide_remember","mcp-aide-update":"MCP:aide_update","mcp-aide-forget":"MCP:aide_forget","mcp-aide-search":"MCP:aide_search"},buildHookConfig(n){let e=Pt(Lr,n),t=Lt(e),r={};for(let[o,s]of t)r[o]=s.map(i=>{let a={type:"command",command:i.command,timeout:i.timeout};return i.matcher!==null&&(a.matcher=i.matcher),a});return{version:1,hooks:r}},buildMcpConfig({serverEntry:n}){return{mcpServers:{"aide-memory":{type:"stdio",command:"node",args:[n,"${workspaceFolder}"]}}}},detectRuntime(n){return!!n.CURSOR_VERSION||!!n.CURSOR_PROJECT_DIR},translateInput(n){let e={...n};if(typeof e.session_id!="string"&&typeof n.conversation_id=="string"&&(e.session_id=n.conversation_id),typeof e.cwd!="string"&&Array.isArray(n.workspace_roots)&&n.workspace_roots.length>0){let t=n.workspace_roots[0];typeof t=="string"&&(e.cwd=t)}return e.tool_response===void 0&&n.tool_output!==void 0&&(e.tool_response=n.tool_output),e},translateOutput(n){switch(n.kind){case"block":{let e=n.event??"preToolUse";if(e==="stop")return n.systemMessage?JSON.stringify({followup_message:`${Oe(n.systemMessage)} \u2014 ${n.reason}`},null,2):JSON.stringify({followup_message:n.reason},null,2);if(e==="userPromptSubmit"){let r=n.systemMessage?`${Oe(n.systemMessage)} \u2014 ${Oe(n.reason)}`:Oe(n.reason);return JSON.stringify({continue:!1,user_message:r},null,2)}let t={permission:"deny"};return n.systemMessage?(t.user_message=Oe(n.systemMessage),t.agent_message=n.reason):t.user_message=Oe(n.reason),JSON.stringify(t,null,2)}case"additionalContext":{if(String(n.event??"").toLowerCase()==="pretooluse"){let t={permission:"allow",agent_message:n.context};return n.systemMessage&&(t.user_message=Oe(n.systemMessage)),JSON.stringify(t,null,2)}return""}case"systemMessage":return"";case"silent":return""}}}});var Jo,qo=$(()=>{"use strict";Jo={id:"codex",displayName:"OpenAI Codex",hookConfigPath:".codex/hooks.json",mcpConfigPath:".codex/mcp.json",rules:[{template:"codex.md",dest:".codex/rules/aide-memory.md"}],ruleFrontmatter:"",ruleNotes:"",ruleToolId:"codex",supportsHooks:!1,supportsMcp:!1,supportsRules:!1,eventNameMap:{"session-start":null,"pre-compact":null,stop:null,"pre-prompt":null,"pre-read":null,"pre-edit":null,"pre-search":null,"pre-recall":null,"post-tool-use-recall":null,"post-remember":null,"post-search":null},matcherMap:{read:null,edit:null,write:null,search:null,glob:null,"mcp-aide-recall":null,"mcp-aide-remember":null,"mcp-aide-update":null,"mcp-aide-forget":null,"mcp-aide-search":null},buildHookConfig(n){return{}},buildMcpConfig(n){return{}},detectRuntime(n){return!1},translateInput(n){return n},translateOutput(n){return""}}});var Go,Xo=$(()=>{"use strict";Go={id:"copilot",displayName:"GitHub Copilot",hookConfigPath:".github/copilot/hooks.json",mcpConfigPath:".github/copilot/mcp.json",rules:[{template:"copilot.md",dest:".github/copilot-instructions.md"}],ruleFrontmatter:"",ruleNotes:"",ruleToolId:"copilot",supportsHooks:!1,supportsMcp:!1,supportsRules:!1,eventNameMap:{"session-start":null,"pre-compact":null,stop:null,"pre-prompt":null,"pre-read":null,"pre-edit":null,"pre-search":null,"pre-recall":null,"post-tool-use-recall":null,"post-remember":null,"post-search":null},matcherMap:{read:null,edit:null,write:null,search:null,glob:null,"mcp-aide-recall":null,"mcp-aide-remember":null,"mcp-aide-update":null,"mcp-aide-forget":null,"mcp-aide-search":null},buildHookConfig(n){return{}},buildMcpConfig(n){return{}},detectRuntime(n){return!1},translateInput(n){return n},translateOutput(n){return""}}});var Yo,Ko=$(()=>{"use strict";Yo={id:"windsurf",displayName:"Windsurf",hookConfigPath:".windsurf/hooks.json",mcpConfigPath:".windsurf/mcp.json",rules:[{template:"windsurf.md",dest:".windsurf/rules/aide-memory.md"}],ruleFrontmatter:"",ruleNotes:"",ruleToolId:"windsurf",supportsHooks:!1,supportsMcp:!1,supportsRules:!1,eventNameMap:{"session-start":null,"pre-compact":null,stop:null,"pre-prompt":null,"pre-read":null,"pre-edit":null,"pre-search":null,"pre-recall":null,"post-tool-use-recall":null,"post-remember":null,"post-search":null},matcherMap:{read:null,edit:null,write:null,search:null,glob:null,"mcp-aide-recall":null,"mcp-aide-remember":null,"mcp-aide-update":null,"mcp-aide-forget":null,"mcp-aide-search":null},buildHookConfig(n){return{}},buildMcpConfig(n){return{}},detectRuntime(n){return!1},translateInput(n){return n},translateOutput(n){return""}}});function Bt(){return Ut.filter(n=>n.supportsHooks)}function Hr(){return Ut.filter(n=>n.supportsMcp)}function q(){return Ut.filter(n=>n.supportsRules)}function Le(n=process.env){for(let e of Ut)if(e.detectRuntime(n))return e;return Ht}var Ut,ne=$(()=>{"use strict";Vo();Wo();qo();Xo();Ko();Ut=[Ht,Lr,Jo,Go,Yo]});var ns={};Qt(ns,{MCP_TOOLS_LIST:()=>He,autoUpdateIfNeeded:()=>Va,detectContributor:()=>nt,ingestPendingMemories:()=>Ja,initProject:()=>qr,resyncDerivedArtifacts:()=>Jt});function Wt(){return R.default.resolve(__dirname,"..","..")}function Ia(){let n=Wt();return n.includes("/_npx/")||n.includes("\\_npx\\")}function Zo(n,e,t,r){let o=[],s=[],i=n.hookConfigPath,a=R.default.join(e,i),c=R.default.dirname(a);b.default.existsSync(c)||b.default.mkdirSync(c,{recursive:!0});let l=Wt(),u=n.buildHookConfig({packageRoot:l}),d=r?{_aideMemoryVersion:r}:{},m=p=>{b.default.writeFileSync(a,JSON.stringify({...u,...d},null,2)+`
145
- `,"utf8"),o.push(`${i}${p?` (${p})`:""}`)};if(!b.default.existsSync(a))return m(""),{created:o,skipped:s};let w;try{w=JSON.parse(b.default.readFileSync(a,"utf8"))}catch{return m(""),{created:o,skipped:s}}if(Fa(w,l)&&!t)return s.push(`${i} (hooks already configured)`),{created:o,skipped:s};let _=Da(w.hooks??{},u.hooks??{},l),S={...w,...u,hooks:_,...d};return b.default.writeFileSync(a,JSON.stringify(S,null,2)+`
146
- `,"utf8"),o.push(`${i} (hooks ${t?"force-updated":"added"})`),{created:o,skipped:s}}function Da(n,e,t){let r=R.default.join(t,"scripts","hooks"),o=new Set(rt.map(c=>c.script)),s=c=>{let l=u=>{if(typeof u=="string"){if(u.includes(r))return!0;for(let d of o)if(u.includes(`/${d}`)||u.endsWith(d))return!0;return!1}return Array.isArray(u)?u.some(l):u&&typeof u=="object"?Object.values(u).some(l):!1};return l(c)},i={},a=new Set([...Object.keys(n),...Object.keys(e)]);for(let c of a){let l=Array.isArray(n[c])?n[c]:[],u=Array.isArray(e[c])?e[c]:[],m=[...l.filter(w=>!s(w)),...u];m.length>0&&(i[c]=m)}return i}function Fa(n,e){let t=R.default.join(e,"scripts","hooks"),r=o=>typeof o=="string"?o.includes(t):Array.isArray(o)?o.some(r):o&&typeof o=="object"?Object.values(o).some(r):!1;return r(n.hooks)}function es(n,e,t){let r=[],o=[],s=R.default.join(e,n.mcpConfigPath),i=R.default.dirname(s);b.default.existsSync(i)||b.default.mkdirSync(i,{recursive:!0});let a=Wt(),c=R.default.join(a,"dist","memory","cli.js"),l=n.buildMcpConfig({serverEntry:c,projectRoot:e});if(!b.default.existsSync(s))return b.default.writeFileSync(s,JSON.stringify(l,null,2)+`
147
- `,"utf8"),r.push(n.mcpConfigPath),{created:r,skipped:o};try{let u=JSON.parse(b.default.readFileSync(s,"utf8"));if(!!u.mcpServers?.["aide-memory"]&&!t)return o.push(`${n.mcpConfigPath} (aide-memory already configured)`),{created:r,skipped:o};u.mcpServers=u.mcpServers||{},u.mcpServers["aide-memory"]=l.mcpServers["aide-memory"],b.default.writeFileSync(s,JSON.stringify(u,null,2)+`
148
- `,"utf8"),r.push(`${n.mcpConfigPath} (aide-memory ${t?"force-updated":"server added"})`)}catch{b.default.writeFileSync(s,JSON.stringify(l,null,2)+`
149
- `,"utf8"),r.push(n.mcpConfigPath)}return{created:r,skipped:o}}function nt(n){try{return(0,Vr.execSync)("git rev-parse --git-dir",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"]}),(0,Vr.execSync)("git config user.name",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()||"unknown"}catch{return"unknown"}}function Pa(n,e){let t=[],r=[];for(let o of zo){let s=R.default.join(n,o);if(b.default.existsSync(s)&&!e){r.push(o);continue}b.default.mkdirSync(s,{recursive:!0}),t.push(o)}return{created:t,skipped:r}}function Wr(n,e,t){let r=[],o=[];for(let s of q())for(let i of s.rules){let a=R.default.join(n,i.dest);if(b.default.existsSync(a)&&!t){o.push(i.dest);continue}let c=R.default.dirname(a);b.default.existsSync(c)||b.default.mkdirSync(c,{recursive:!0});let l=It(s,{contributor:e,tools_list:He});b.default.writeFileSync(a,l,"utf8"),r.push(i.dest)}return{created:r,skipped:o}}function ts(n,e){for(let[t,r]of Object.entries(e)){let o=n[t];o!=null&&typeof o=="object"&&!Array.isArray(o)&&r!==null&&typeof r=="object"&&!Array.isArray(r)?ts(o,r):o===void 0&&(n[t]=r)}return n}function Jr(n){let e=R.default.join(n,".aide","config.json"),t=Eo(),r=vo(t),o={};if(b.default.existsSync(e))try{o=JSON.parse(b.default.readFileSync(e,"utf8"))}catch{o={}}let s=JSON.stringify(o);ts(o,r);let i=JSON.stringify(o);if(s===i)return{written:!1};let a=R.default.dirname(e);return b.default.existsSync(a)||b.default.mkdirSync(a,{recursive:!0}),b.default.writeFileSync(e,JSON.stringify(o,null,2)+`
150
- `,"utf8"),{written:!0}}function La(n,e){let t=R.default.join(n,".aide","config-reference.md");if(b.default.existsSync(t)&&!e)return{created:[],skipped:[".aide/config-reference.md"]};let r=Se(),o=Object.keys(r).filter(a=>r[a].public===!0).sort(),s=["# aide-memory configuration reference","","Auto-generated by `aide-memory init`. Every public setting from","`scripts/hooks/defaults.json` with its default and description.","","Override any of these with:","","```bash","aide-memory config <key> <value>","```","","Or see the live list with current values:","","```bash","aide-memory config list","```","","## Settings",""];for(let a of o){let c=r[a],l=typeof c.value=="object"?"`"+JSON.stringify(c.value)+"`":"`"+String(c.value)+"`";s.push("### `"+a+"`"),s.push(""),s.push("**Default:** "+l),s.push(""),c.description&&(s.push(c.description),s.push(""))}s.push("---"),s.push(""),s.push("_Reference regenerated at init time. If this file drifts from your installed aide-memory, re-run `aide-memory init --force` to refresh._"),s.push("");let i=R.default.dirname(t);return b.default.existsSync(i)||b.default.mkdirSync(i,{recursive:!0}),b.default.writeFileSync(t,s.join(`
151
- `),"utf8"),{created:[".aide/config-reference.md"],skipped:[]}}function Ha(n,e,t){let r=R.default.join(n,".aide","config.json");if(b.default.existsSync(r)&&!t){let{written:i}=Jr(n);return i?{created:[".aide/config.json (public settings seeded)"],skipped:[]}:{created:[],skipped:[".aide/config.json"]}}let s=new he(n);return t&&s.reset(),s.set("contributor",e),Jr(n),{created:[".aide/config.json"],skipped:[]}}function Ua(n){let e=R.default.join(n,".gitignore"),t=[],r=[],o="";b.default.existsSync(e)&&(o=b.default.readFileSync(e,"utf8"));let s=o.split(`
152
- `),i=[];for(let a of Qo)s.some(c=>c.trim()===a)?r.push(`.gitignore entry: ${a}`):(i.push(a),t.push(`.gitignore entry: ${a}`));if(i.length>0){let c=`${o.length>0&&!o.endsWith(`
144
+ `,ruleNotes:"\nNote: Cursor uses `agent_message` for hook responses rather than `additionalContext`. The nudge content appears directly in the agent message flow.\n",ruleToolId:"cursor",supportsHooks:!0,supportsMcp:!0,supportsRules:!0,needsDynamicRules:!0,eventNameMap:{"session-start":"sessionStart","pre-compact":"preCompact",stop:"stop","pre-prompt":"beforeSubmitPrompt","pre-read":"preToolUse","pre-edit":"preToolUse","pre-search":"preToolUse","pre-recall":"preToolUse","post-tool-use-recall":"postToolUse","post-remember":"postToolUse","post-search":"postToolUse"},matcherMap:{read:"Read",edit:"Write",write:"Write",search:"Grep",glob:null,"mcp-aide-recall":"MCP:aide_recall","mcp-aide-remember":"MCP:aide_remember","mcp-aide-update":"MCP:aide_update","mcp-aide-forget":"MCP:aide_forget","mcp-aide-search":"MCP:aide_search"},buildHookConfig(n){let e=He(Lr,n),t=Ue(e),r={};for(let[o,s]of t)r[o]=s.map(i=>{let a={type:"command",command:i.command,timeout:i.timeout};return i.matcher!==null&&(a.matcher=i.matcher),a});return{version:1,hooks:r}},buildMcpConfig({serverEntry:n}){return{mcpServers:{"aide-memory":{type:"stdio",command:"node",args:[n,"${workspaceFolder}"]}}}},detectRuntime(n){return!!n.CURSOR_VERSION||!!n.CURSOR_PROJECT_DIR},translateInput(n){let e={...n};if(typeof e.session_id!="string"&&typeof n.conversation_id=="string"&&(e.session_id=n.conversation_id),typeof e.cwd!="string"&&Array.isArray(n.workspace_roots)&&n.workspace_roots.length>0){let t=n.workspace_roots[0];typeof t=="string"&&(e.cwd=t)}return e.tool_response===void 0&&n.tool_output!==void 0&&(e.tool_response=n.tool_output),e},translateOutput(n){switch(n.kind){case"block":{let e=n.event??"preToolUse";if(e==="stop")return n.systemMessage?JSON.stringify({followup_message:`${Oe(n.systemMessage)} \u2014 ${n.reason}`},null,2):JSON.stringify({followup_message:n.reason},null,2);if(e==="userPromptSubmit"){let r=n.systemMessage?`${Oe(n.systemMessage)} \u2014 ${Oe(n.reason)}`:Oe(n.reason);return JSON.stringify({continue:!1,user_message:r},null,2)}let t={permission:"deny"};return n.systemMessage?(t.user_message=Oe(n.systemMessage),t.agent_message=n.reason):t.user_message=Oe(n.reason),JSON.stringify(t,null,2)}case"additionalContext":{if(String(n.event??"").toLowerCase()==="pretooluse"){let t={permission:"allow",agent_message:n.context};return n.systemMessage&&(t.user_message=Oe(n.systemMessage)),JSON.stringify(t,null,2)}return""}case"systemMessage":return"";case"silent":return""}}}});var Hr,qo=T(()=>{"use strict";Ht();Hr={id:"devin",displayName:"Devin CLI",hookConfigPath:".devin/config.json",mcpConfigPath:".devin/config.json",rules:[{template:"devin.md",dest:".devin/skills/aide-memory/SKILL.md"}],ruleFrontmatter:`---
145
+ name: aide-memory
146
+ description: >-
147
+ How aide-memory works in this project \u2014 persistent cross-session memory.
148
+ Consult this when an aide-memory hook fires (a PreToolUse "call aide_recall"
149
+ nudge, the Stop checkpoint, or correction detection), or before recalling or
150
+ storing project knowledge. Covers when to call aide_recall / aide_remember /
151
+ aide_search, the memory layers (preferences, technical, area_context,
152
+ guidelines), and how to format a memory.
153
+ triggers:
154
+ - user
155
+ - model
156
+ ---
157
+
158
+ `,ruleNotes:"\nNote: On Devin CLI the compaction hook fires AFTER context compaction (PostCompaction), not before. Don't rely on a pre-compaction save prompt \u2014 save important context proactively as the conversation grows, and re-run `aide_recall` after a compaction.\n",ruleToolId:"devin",supportsHooks:!0,supportsMcp:!0,supportsRules:!0,needsDynamicRules:!1,eventNameMap:{"session-start":"SessionStart","pre-compact":"PostCompaction",stop:"Stop","pre-prompt":"UserPromptSubmit","pre-read":"PreToolUse","pre-edit":"PreToolUse","pre-search":"PreToolUse","pre-recall":"PreToolUse","post-tool-use-recall":"PostToolUse","post-remember":"PostToolUse","post-search":"PostToolUse"},matcherMap:{read:"read",edit:"edit",write:"write",search:"grep",glob:"glob","mcp-aide-recall":"mcp__aide-memory__aide_recall","mcp-aide-remember":"mcp__aide-memory__aide_remember","mcp-aide-update":"mcp__aide-memory__aide_update","mcp-aide-forget":"mcp__aide-memory__aide_forget","mcp-aide-search":"mcp__aide-memory__aide_search"},buildHookConfig(n){let e=He(Hr,n),t=Ue(e),r={};for(let[o,s]of t){let i=s.some(a=>a.matcher!==null);r[o]=s.map(a=>{let c={type:"command",command:a.command,timeout:a.timeout};return i?{matcher:a.matcher,hooks:[c]}:{hooks:[c]}})}return{hooks:r}},buildMcpConfig({serverEntry:n,projectRoot:e}){return{mcpServers:{"aide-memory":{command:"node",args:[n,e]}}}},detectRuntime(n){return!!n.DEVIN_PROJECT_DIR},translateInput(n){let e={...n};if(typeof e.cwd!="string"||e.cwd.length===0){let r=process.env.DEVIN_PROJECT_DIR;typeof r=="string"&&r.length>0&&(e.cwd=r)}if(typeof e.session_id!="string"||e.session_id.length===0){let r=typeof n.conversation_id=="string"&&n.conversation_id||typeof n.sessionId=="string"&&n.sessionId||typeof n.session=="string"&&n.session||"";r&&(e.session_id=r)}let t=e.tool_response;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;typeof r.output=="string"&&typeof r.text!="string"&&(e.tool_response={...r,text:r.output})}return e},translateOutput(n){switch(n.kind){case"block":{if((n.event??"preToolUse")==="preToolUse"){let r={hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:n.reason}};return n.systemMessage&&(r.systemMessage=n.systemMessage),JSON.stringify(r,null,2)}let t={decision:"block",reason:n.reason};return n.systemMessage&&(t.systemMessage=n.systemMessage),JSON.stringify(t,null,2)}case"additionalContext":{let e={hookSpecificOutput:{hookEventName:n.event,additionalContext:n.context}};return n.systemMessage&&(e.systemMessage=n.systemMessage),JSON.stringify(e,null,2)}case"systemMessage":return JSON.stringify({systemMessage:n.text},null,2);case"silent":return""}}}});var Go,Xo=T(()=>{"use strict";Go={id:"codex",displayName:"OpenAI Codex",hookConfigPath:".codex/hooks.json",mcpConfigPath:".codex/mcp.json",rules:[{template:"codex.md",dest:".codex/rules/aide-memory.md"}],ruleFrontmatter:"",ruleNotes:"",ruleToolId:"codex",supportsHooks:!1,supportsMcp:!1,supportsRules:!1,eventNameMap:{"session-start":null,"pre-compact":null,stop:null,"pre-prompt":null,"pre-read":null,"pre-edit":null,"pre-search":null,"pre-recall":null,"post-tool-use-recall":null,"post-remember":null,"post-search":null},matcherMap:{read:null,edit:null,write:null,search:null,glob:null,"mcp-aide-recall":null,"mcp-aide-remember":null,"mcp-aide-update":null,"mcp-aide-forget":null,"mcp-aide-search":null},buildHookConfig(n){return{}},buildMcpConfig(n){return{}},detectRuntime(n){return!1},translateInput(n){return n},translateOutput(n){return""}}});var Yo,Ko=T(()=>{"use strict";Yo={id:"copilot",displayName:"GitHub Copilot",hookConfigPath:".github/copilot/hooks.json",mcpConfigPath:".github/copilot/mcp.json",rules:[{template:"copilot.md",dest:".github/copilot-instructions.md"}],ruleFrontmatter:"",ruleNotes:"",ruleToolId:"copilot",supportsHooks:!1,supportsMcp:!1,supportsRules:!1,eventNameMap:{"session-start":null,"pre-compact":null,stop:null,"pre-prompt":null,"pre-read":null,"pre-edit":null,"pre-search":null,"pre-recall":null,"post-tool-use-recall":null,"post-remember":null,"post-search":null},matcherMap:{read:null,edit:null,write:null,search:null,glob:null,"mcp-aide-recall":null,"mcp-aide-remember":null,"mcp-aide-update":null,"mcp-aide-forget":null,"mcp-aide-search":null},buildHookConfig(n){return{}},buildMcpConfig(n){return{}},detectRuntime(n){return!1},translateInput(n){return n},translateOutput(n){return""}}});var zo,Qo=T(()=>{"use strict";zo={id:"windsurf",displayName:"Windsurf",hookConfigPath:".windsurf/hooks.json",mcpConfigPath:".windsurf/mcp.json",rules:[{template:"windsurf.md",dest:".windsurf/rules/aide-memory.md"}],ruleFrontmatter:"",ruleNotes:"",ruleToolId:"windsurf",supportsHooks:!1,supportsMcp:!1,supportsRules:!1,eventNameMap:{"session-start":null,"pre-compact":null,stop:null,"pre-prompt":null,"pre-read":null,"pre-edit":null,"pre-search":null,"pre-recall":null,"post-tool-use-recall":null,"post-remember":null,"post-search":null},matcherMap:{read:null,edit:null,write:null,search:null,glob:null,"mcp-aide-recall":null,"mcp-aide-remember":null,"mcp-aide-update":null,"mcp-aide-forget":null,"mcp-aide-search":null},buildHookConfig(n){return{}},buildMcpConfig(n){return{}},detectRuntime(n){return!1},translateInput(n){return n},translateOutput(n){return""}}});function Vt(){return Bt.filter(n=>n.supportsHooks)}function Ur(){return Bt.filter(n=>n.supportsMcp)}function G(){return Bt.filter(n=>n.supportsRules)}function Re(n=process.env){for(let e of Bt)if(e.detectRuntime(n))return e;return Ut}var Bt,ne=T(()=>{"use strict";Wo();Jo();qo();Xo();Ko();Qo();Bt=[Ut,Lr,Hr,Go,Yo,zo]});var ss={};Zt(ss,{MCP_TOOLS_LIST:()=>Be,autoUpdateIfNeeded:()=>Ja,detectContributor:()=>st,ingestPendingMemories:()=>Ga,initProject:()=>Gr,resyncDerivedArtifacts:()=>qt});function Jt(){return O.default.resolve(__dirname,"..","..")}function Da(){let n=Jt();return n.includes("/_npx/")||n.includes("\\_npx\\")}function ts(n,e,t,r){let o=[],s=[],i=n.hookConfigPath,a=O.default.join(e,i),c=O.default.dirname(a);_.default.existsSync(c)||_.default.mkdirSync(c,{recursive:!0});let l=Jt(),u=n.buildHookConfig({packageRoot:l}),d=r?{_aideMemoryVersion:r}:{},f=p=>{_.default.writeFileSync(a,JSON.stringify({...u,...d},null,2)+`
159
+ `,"utf8"),o.push(`${i}${p?` (${p})`:""}`)};if(!_.default.existsSync(a))return f(""),{created:o,skipped:s};let y;try{y=JSON.parse(_.default.readFileSync(a,"utf8"))}catch{return f(""),{created:o,skipped:s}}if(La(y,l)&&!t)return s.push(`${i} (hooks already configured)`),{created:o,skipped:s};let w=Fa(y.hooks??{},u.hooks??{},l),E={...y,...u,hooks:w,...d};return _.default.writeFileSync(a,JSON.stringify(E,null,2)+`
160
+ `,"utf8"),o.push(`${i} (hooks ${t?"force-updated":"added"})`),{created:o,skipped:s}}function Fa(n,e,t){let r=O.default.join(t,"scripts","hooks"),o=new Set(ot.map(c=>c.script)),s=c=>{let l=u=>{if(typeof u=="string"){if(u.includes(r))return!0;for(let d of o)if(u.includes(`/${d}`)||u.endsWith(d))return!0;return!1}return Array.isArray(u)?u.some(l):u&&typeof u=="object"?Object.values(u).some(l):!1};return l(c)},i={},a=new Set([...Object.keys(n),...Object.keys(e)]);for(let c of a){let l=Array.isArray(n[c])?n[c]:[],u=Array.isArray(e[c])?e[c]:[],f=[...l.filter(y=>!s(y)),...u];f.length>0&&(i[c]=f)}return i}function La(n,e){let t=O.default.join(e,"scripts","hooks"),r=o=>typeof o=="string"?o.includes(t):Array.isArray(o)?o.some(r):o&&typeof o=="object"?Object.values(o).some(r):!1;return r(n.hooks)}function rs(n,e,t){let r=[],o=[],s=O.default.join(e,n.mcpConfigPath),i=O.default.dirname(s);_.default.existsSync(i)||_.default.mkdirSync(i,{recursive:!0});let a=Jt(),c=O.default.join(a,"dist","memory","cli.js"),l=n.buildMcpConfig({serverEntry:c,projectRoot:e});if(!_.default.existsSync(s))return _.default.writeFileSync(s,JSON.stringify(l,null,2)+`
161
+ `,"utf8"),r.push(n.mcpConfigPath),{created:r,skipped:o};try{let u=JSON.parse(_.default.readFileSync(s,"utf8"));if(!!u.mcpServers?.["aide-memory"]&&!t)return o.push(`${n.mcpConfigPath} (aide-memory already configured)`),{created:r,skipped:o};u.mcpServers=u.mcpServers||{},u.mcpServers["aide-memory"]=l.mcpServers["aide-memory"],_.default.writeFileSync(s,JSON.stringify(u,null,2)+`
162
+ `,"utf8"),r.push(`${n.mcpConfigPath} (aide-memory ${t?"force-updated":"server added"})`)}catch{_.default.writeFileSync(s,JSON.stringify(l,null,2)+`
163
+ `,"utf8"),r.push(n.mcpConfigPath)}return{created:r,skipped:o}}function st(n){try{return(0,Wr.execSync)("git rev-parse --git-dir",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"]}),(0,Wr.execSync)("git config user.name",{cwd:n,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()||"unknown"}catch{return"unknown"}}function Ha(n,e){let t=[],r=[];for(let o of Zo){let s=O.default.join(n,o);if(_.default.existsSync(s)&&!e){r.push(o);continue}_.default.mkdirSync(s,{recursive:!0}),t.push(o)}return{created:t,skipped:r}}function Jr(n,e,t){let r=[],o=[];for(let s of G())for(let i of s.rules){let a=O.default.join(n,i.dest);if(_.default.existsSync(a)&&!t){o.push(i.dest);continue}let c=O.default.dirname(a);_.default.existsSync(c)||_.default.mkdirSync(c,{recursive:!0});let l=Dt(s,{contributor:e,tools_list:Be});_.default.writeFileSync(a,l,"utf8"),r.push(i.dest)}return{created:r,skipped:o}}function ns(n,e){for(let[t,r]of Object.entries(e)){let o=n[t];o!=null&&typeof o=="object"&&!Array.isArray(o)&&r!==null&&typeof r=="object"&&!Array.isArray(r)?ns(o,r):o===void 0&&(n[t]=r)}return n}function qr(n){let e=O.default.join(n,".aide","config.json"),t=vo(),r=ko(t),o={};if(_.default.existsSync(e))try{o=JSON.parse(_.default.readFileSync(e,"utf8"))}catch{o={}}let s=JSON.stringify(o);ns(o,r);let i=JSON.stringify(o);if(s===i)return{written:!1};let a=O.default.dirname(e);return _.default.existsSync(a)||_.default.mkdirSync(a,{recursive:!0}),_.default.writeFileSync(e,JSON.stringify(o,null,2)+`
164
+ `,"utf8"),{written:!0}}function Ua(n,e){let t=O.default.join(n,".aide","config-reference.md");if(_.default.existsSync(t)&&!e)return{created:[],skipped:[".aide/config-reference.md"]};let r=Se(),o=Object.keys(r).filter(a=>r[a].public===!0).sort(),s=["# aide-memory configuration reference","","Auto-generated by `aide-memory init`. Every public setting from","`scripts/hooks/defaults.json` with its default and description.","","Override any of these with:","","```bash","aide-memory config <key> <value>","```","","Or see the live list with current values:","","```bash","aide-memory config list","```","","## Settings",""];for(let a of o){let c=r[a],l=typeof c.value=="object"?"`"+JSON.stringify(c.value)+"`":"`"+String(c.value)+"`";s.push("### `"+a+"`"),s.push(""),s.push("**Default:** "+l),s.push(""),c.description&&(s.push(c.description),s.push(""))}s.push("---"),s.push(""),s.push("_Reference regenerated at init time. If this file drifts from your installed aide-memory, re-run `aide-memory init --force` to refresh._"),s.push("");let i=O.default.dirname(t);return _.default.existsSync(i)||_.default.mkdirSync(i,{recursive:!0}),_.default.writeFileSync(t,s.join(`
165
+ `),"utf8"),{created:[".aide/config-reference.md"],skipped:[]}}function Ba(n,e,t){let r=O.default.join(n,".aide","config.json");if(_.default.existsSync(r)&&!t){let{written:i}=qr(n);return i?{created:[".aide/config.json (public settings seeded)"],skipped:[]}:{created:[],skipped:[".aide/config.json"]}}let s=new he(n);return t&&s.reset(),s.set("contributor",e),qr(n),{created:[".aide/config.json"],skipped:[]}}function Va(n){let e=O.default.join(n,".gitignore"),t=[],r=[],o="";_.default.existsSync(e)&&(o=_.default.readFileSync(e,"utf8"));let s=o.split(`
166
+ `),i=[];for(let a of es)s.some(c=>c.trim()===a)?r.push(`.gitignore entry: ${a}`):(i.push(a),t.push(`.gitignore entry: ${a}`));if(i.length>0){let c=`${o.length>0&&!o.endsWith(`
153
167
  `)?`
154
168
  `:""}
155
169
  # aide-memory
156
170
  ${i.join(`
157
171
  `)}
158
- `;b.default.writeFileSync(e,o+c,"utf8")}return{created:t,skipped:r}}function Ba(n){let e=[],t=[],r=Dr(n),o=Ir(n,r);return o.changed&&o.message?e.push(o.message):!o.changed&&r&&t.push(".ignore (aide-memory section already present)"),{created:e,skipped:t}}function rs(n,e){let t=[],r=[],o=[],s="",i=n;for(let u=0;u<20;u++){let d=R.default.join(i,".git");if(b.default.existsSync(d)&&b.default.statSync(d).isDirectory()){s=d;break}let m=R.default.dirname(i);if(m===i||i!==n&&b.default.existsSync(R.default.join(m,".aide")))break;i=m}if(!s)return o.push("No git repository found \u2014 skipping post-checkout hook"),{created:t,skipped:r,warnings:o};let a=R.default.join(s,"hooks");b.default.existsSync(a)||b.default.mkdirSync(a,{recursive:!0});let c=R.default.join(a,"post-checkout"),l=`${Ur}
159
- ${ja}
160
- ${Br}
161
- `;if(b.default.existsSync(c)){let u=b.default.readFileSync(c,"utf8");if(u.includes(Ur)){if(!e)return r.push(".git/hooks/post-checkout (aide section already present)"),{created:t,skipped:r,warnings:o};let d=u.substring(0,u.indexOf(Ur)),m=u.indexOf(Br),w=m>=0?u.substring(m+Br.length+1):"";b.default.writeFileSync(c,d+l+w,"utf8")}else{let d=u.endsWith(`
172
+ `;_.default.writeFileSync(e,o+c,"utf8")}return{created:t,skipped:r}}function Wa(n){let e=[],t=[],r=Dr(n),o=Pr(n,r);return o.changed&&o.message?e.push(o.message):!o.changed&&r&&t.push(".ignore (aide-memory section already present)"),{created:e,skipped:t}}function os(n,e){let t=[],r=[],o=[],s="",i=n;for(let u=0;u<20;u++){let d=O.default.join(i,".git");if(_.default.existsSync(d)&&_.default.statSync(d).isDirectory()){s=d;break}let f=O.default.dirname(i);if(f===i||i!==n&&_.default.existsSync(O.default.join(f,".aide")))break;i=f}if(!s)return o.push("No git repository found \u2014 skipping post-checkout hook"),{created:t,skipped:r,warnings:o};let a=O.default.join(s,"hooks");_.default.existsSync(a)||_.default.mkdirSync(a,{recursive:!0});let c=O.default.join(a,"post-checkout"),l=`${Br}
173
+ ${Pa}
174
+ ${Vr}
175
+ `;if(_.default.existsSync(c)){let u=_.default.readFileSync(c,"utf8");if(u.includes(Br)){if(!e)return r.push(".git/hooks/post-checkout (aide section already present)"),{created:t,skipped:r,warnings:o};let d=u.substring(0,u.indexOf(Br)),f=u.indexOf(Vr),y=f>=0?u.substring(f+Vr.length+1):"";_.default.writeFileSync(c,d+l+y,"utf8")}else{let d=u.endsWith(`
162
176
  `)?"":`
163
- `;b.default.writeFileSync(c,u+d+`
164
- `+l,"utf8")}}else b.default.writeFileSync(c,`#!/bin/bash
177
+ `;_.default.writeFileSync(c,u+d+`
178
+ `+l,"utf8")}}else _.default.writeFileSync(c,`#!/bin/bash
165
179
 
166
- `+l,"utf8");return b.default.chmodSync(c,493),t.push(".git/hooks/post-checkout"),{created:t,skipped:r,warnings:o}}async function qr(n,e){let t=R.default.resolve(n),r=e?.force??!1,o={created:[],skipped:[],warnings:[]};if(e?.updateRules){let _=nt(t),S=Wr(t,_,!0);o.created.push(...S.created),o.skipped.push(...S.skipped);try{let p=Vt(q(),t,{contributor:_,tools_list:He});for(let x of p)x.written&&o.created.push(`${x.dest} (rules regenerated)`),x.budgetWarning&&o.warnings.push(x.budgetWarning)}catch(p){o.warnings.push(`rulesGen: ${p.message}`)}return o}Ia()&&o.warnings.push("aide-memory is running from the npx cache. Hook and MCP paths may break if the cache is cleaned, Node version changes, or aide-memory is upgraded. For a stable install, run: npm install -g aide-memory && aide-memory init");let s=nt(t),i=Pa(t,r);o.created.push(...i.created),o.skipped.push(...i.skipped);let a=Wr(t,s,r);o.created.push(...a.created),o.skipped.push(...a.skipped);let c=Wt(),l;try{l=JSON.parse(b.default.readFileSync(R.default.join(c,"package.json"),"utf8")).version}catch{}for(let _ of Bt()){let S=Zo(_,t,r,l);o.created.push(...S.created),o.skipped.push(...S.skipped)}for(let _ of Hr()){let S=es(_,t,r);o.created.push(...S.created),o.skipped.push(...S.skipped)}let u=Ha(t,s,r);o.created.push(...u.created),o.skipped.push(...u.skipped);let d=La(t,r);o.created.push(...d.created),o.skipped.push(...d.skipped);let m=Ua(t);o.created.push(...m.created),o.skipped.push(...m.skipped);let w=Ba(t);o.created.push(...w.created),o.skipped.push(...w.skipped);let g=rs(t,r);o.created.push(...g.created),o.skipped.push(...g.skipped),o.warnings.push(...g.warnings);try{let _=Vt(q(),t,{contributor:s,tools_list:He});for(let S of _)S.written&&o.created.push(`${S.dest} (rules regenerated)`),S.budgetWarning&&o.warnings.push(S.budgetWarning)}catch(_){o.warnings.push(`rulesGen: ${_.message}`)}return o.warnings.push("Restart your editor (or start a fresh session) to ensure the MCP server is picked up."),b.default.existsSync(R.default.join(t,".cursor"))&&o.warnings.push("For Cursor: also enable aide-memory in Settings > MCP after restart."),o}function Jt(n){let e=[];try{let t=Dr(n),r=Ir(n,t);r.changed&&r.message&&e.push(r.message)}catch{}return e}function Va(n,e){let t=[];try{try{let c=Jt(n);t.push(...c)}catch{}let r=!1;for(let c of Bt()){let l=R.default.join(n,c.hookConfigPath);if(!b.default.existsSync(l)){r=!0;break}try{let d=JSON.parse(b.default.readFileSync(l,"utf8"))._aideMemoryVersion;if(!d||Wa(d,e)){r=!0;break}}catch{r=!0;break}}if(!r)return t;for(let c of Bt()){let l=Zo(c,n,!0,e);for(let u of l.created)t.push(`${u} (auto-updated)`)}for(let c of Hr()){let l=es(c,n,!0);t.push(...l.created)}let o=R.default.join(n,".claude","rules","aide-memory.md");if(b.default.existsSync(o)){let c=Wr(n,"",!0);t.push(...c.created)}for(let c of zo){let l=R.default.join(n,c);b.default.existsSync(l)||(b.default.mkdirSync(l,{recursive:!0}),t.push(`${c}/ (created)`))}let s=R.default.join(n,".gitignore");if(b.default.existsSync(s)){let c=b.default.readFileSync(s,"utf8"),l=Qo.filter(u=>!c.includes(u));l.length>0&&(b.default.appendFileSync(s,`
180
+ `+l,"utf8");return _.default.chmodSync(c,493),t.push(".git/hooks/post-checkout"),{created:t,skipped:r,warnings:o}}async function Gr(n,e){let t=O.default.resolve(n),r=e?.force??!1,o={created:[],skipped:[],warnings:[]};if(e?.updateRules){let w=st(t),E=Jr(t,w,!0);o.created.push(...E.created),o.skipped.push(...E.skipped);try{let p=Wt(G(),t,{contributor:w,tools_list:Be});for(let R of p)R.written&&o.created.push(`${R.dest} (rules regenerated)`),R.budgetWarning&&o.warnings.push(R.budgetWarning)}catch(p){o.warnings.push(`rulesGen: ${p.message}`)}return o}Da()&&o.warnings.push("aide-memory is running from the npx cache. Hook and MCP paths may break if the cache is cleaned, Node version changes, or aide-memory is upgraded. For a stable install, run: npm install -g aide-memory && aide-memory init");let s=st(t),i=Ha(t,r);o.created.push(...i.created),o.skipped.push(...i.skipped);let a=Jr(t,s,r);o.created.push(...a.created),o.skipped.push(...a.skipped);let c=Jt(),l;try{l=JSON.parse(_.default.readFileSync(O.default.join(c,"package.json"),"utf8")).version}catch{}for(let w of Vt()){let E=ts(w,t,r,l);o.created.push(...E.created),o.skipped.push(...E.skipped)}for(let w of Ur()){let E=rs(w,t,r);o.created.push(...E.created),o.skipped.push(...E.skipped)}let u=Ba(t,s,r);o.created.push(...u.created),o.skipped.push(...u.skipped);let d=Ua(t,r);o.created.push(...d.created),o.skipped.push(...d.skipped);let f=Va(t);o.created.push(...f.created),o.skipped.push(...f.skipped);let y=Wa(t);o.created.push(...y.created),o.skipped.push(...y.skipped);let h=os(t,r);o.created.push(...h.created),o.skipped.push(...h.skipped),o.warnings.push(...h.warnings);try{let w=Wt(G(),t,{contributor:s,tools_list:Be});for(let E of w)E.written&&o.created.push(`${E.dest} (rules regenerated)`),E.budgetWarning&&o.warnings.push(E.budgetWarning)}catch(w){o.warnings.push(`rulesGen: ${w.message}`)}return o.warnings.push("Restart your editor (or start a fresh session) to ensure the MCP server is picked up."),_.default.existsSync(O.default.join(t,".cursor"))&&o.warnings.push("For Cursor: also enable aide-memory in Settings > MCP after restart."),o}function qt(n){let e=[];try{let t=Dr(n),r=Pr(n,t);r.changed&&r.message&&e.push(r.message)}catch{}return e}function Ja(n,e){let t=[];try{try{let c=qt(n);t.push(...c)}catch{}let r=!1;for(let c of Vt()){let l=O.default.join(n,c.hookConfigPath);if(!_.default.existsSync(l)){r=!0;break}try{let d=JSON.parse(_.default.readFileSync(l,"utf8"))._aideMemoryVersion;if(!d||qa(d,e)){r=!0;break}}catch{r=!0;break}}if(!r)return t;for(let c of Vt()){let l=ts(c,n,!0,e);for(let u of l.created)t.push(`${u} (auto-updated)`)}for(let c of Ur()){let l=rs(c,n,!0);t.push(...l.created)}let o=O.default.join(n,".claude","rules","aide-memory.md");if(_.default.existsSync(o)){let c=Jr(n,"",!0);t.push(...c.created)}for(let c of Zo){let l=O.default.join(n,c);_.default.existsSync(l)||(_.default.mkdirSync(l,{recursive:!0}),t.push(`${c}/ (created)`))}let s=O.default.join(n,".gitignore");if(_.default.existsSync(s)){let c=_.default.readFileSync(s,"utf8"),l=es.filter(u=>!c.includes(u));l.length>0&&(_.default.appendFileSync(s,`
167
181
  `+l.join(`
168
182
  `)+`
169
- `,"utf8"),t.push(`.gitignore (${l.length} entries added)`))}let i=rs(n,!0);i.created.length>0&&t.push(...i.created),Jr(n).written&&t.push(".aide/config.json (public settings seeded)")}catch{}return t}function Wa(n,e){let t=s=>s.replace(/^v/,"").split(".").map(Number),r=t(n),o=t(e);for(let s=0;s<3;s++){if((r[s]||0)<(o[s]||0))return!0;if((r[s]||0)>(o[s]||0))return!1}return!1}function Ja(n,e){let t=R.default.join(n,".aide","pending-memories.jsonl");if(!b.default.existsSync(t))return 0;let r;try{r=b.default.readFileSync(t,"utf8")}catch{return 0}let o=r.split(`
170
- `).filter(a=>a.trim().length>0);if(o.length===0){try{b.default.unlinkSync(t)}catch{}return 0}let s=0,i=[];for(let a of o)try{let c=JSON.parse(a),l=c.what??c.content;if(!c.layer||!l){i.push(a);continue}e.add({layer:c.layer,what:l,why:c.why,scope:c.scope??void 0,context_label:c.context_label,contributor:c.contributor,tags:Array.isArray(c.tags)?c.tags:void 0,source:c.source??"hook",shared:typeof c.shared=="boolean"?c.shared:void 0,priority:c.priority,generated_by:c.generated_by}),s++}catch{i.push(a)}if(s>0){let a=`${t}.imported-${Date.now()}`;try{b.default.renameSync(t,a)}catch{}}if(i.length>0)try{b.default.writeFileSync(t,i.join(`
183
+ `,"utf8"),t.push(`.gitignore (${l.length} entries added)`))}let i=os(n,!0);i.created.length>0&&t.push(...i.created),qr(n).written&&t.push(".aide/config.json (public settings seeded)")}catch{}return t}function qa(n,e){let t=s=>s.replace(/^v/,"").split(".").map(Number),r=t(n),o=t(e);for(let s=0;s<3;s++){if((r[s]||0)<(o[s]||0))return!0;if((r[s]||0)>(o[s]||0))return!1}return!1}function Ga(n,e){let t=O.default.join(n,".aide","pending-memories.jsonl");if(!_.default.existsSync(t))return 0;let r;try{r=_.default.readFileSync(t,"utf8")}catch{return 0}let o=r.split(`
184
+ `).filter(a=>a.trim().length>0);if(o.length===0){try{_.default.unlinkSync(t)}catch{}return 0}let s=0,i=[];for(let a of o)try{let c=JSON.parse(a),l=c.what??c.content;if(!c.layer||!l){i.push(a);continue}e.add({layer:c.layer,what:l,why:c.why,scope:c.scope??void 0,context_label:c.context_label,contributor:c.contributor,tags:Array.isArray(c.tags)?c.tags:void 0,source:c.source??"hook",shared:typeof c.shared=="boolean"?c.shared:void 0,priority:c.priority,generated_by:c.generated_by}),s++}catch{i.push(a)}if(s>0){let a=`${t}.imported-${Date.now()}`;try{_.default.renameSync(t,a)}catch{}}if(i.length>0)try{_.default.writeFileSync(t,i.join(`
171
185
  `)+`
172
- `,"utf8")}catch{}else if(s===0)try{b.default.unlinkSync(t)}catch{}return s}var b,R,Vr,zo,Qo,Ur,Br,ja,He,ot=$(()=>{"use strict";b=h(require("fs")),R=h(require("path")),Vr=require("child_process");Ft();Ho();Ze();ne();Nr();Re();Fr();zo=[".aide",".aide/memories",".aide/memories/preferences",".aide/memories/preferences/personal",".aide/memories/preferences/shared",".aide/memories/technical",".aide/memories/area_context",".aide/memories/guidelines",".aide/cache"],Qo=[".aide/memories/preferences/personal/",".aide/cache/",".aide/recall-log.jsonl",".aide/pending-memories.jsonl",".cursor/rules/aide-memory.mdc"],Ur="# >>> aide-memory post-checkout hook >>>",Br="# <<< aide-memory post-checkout hook <<<",ja=`
186
+ `,"utf8")}catch{}else if(s===0)try{_.default.unlinkSync(t)}catch{}return s}var _,O,Wr,Zo,es,Br,Vr,Pa,Be,it=T(()=>{"use strict";_=g(require("fs")),O=g(require("path")),Wr=require("child_process");Lt();Uo();tt();ne();$r();Ce();Fr();Zo=[".aide",".aide/memories",".aide/memories/preferences",".aide/memories/preferences/personal",".aide/memories/preferences/shared",".aide/memories/technical",".aide/memories/area_context",".aide/memories/guidelines",".aide/cache"],es=[".aide/memories/preferences/personal/",".aide/cache/",".aide/recall-log.jsonl",".aide/pending-memories.jsonl",".cursor/rules/aide-memory.mdc"],Br="# >>> aide-memory post-checkout hook >>>",Vr="# <<< aide-memory post-checkout hook <<<",Pa=`
173
187
  # Rebuild aide-memory SQLite index from .aide/memories/ files after checkout.
174
188
  # This keeps the cached index in sync when switching branches.
175
189
  if command -v aide >/dev/null 2>&1; then
176
190
  aide reindex --quiet &
177
191
  fi
178
- `;He="- `aide_recall` \u2014 retrieve stored context for file paths you're about to work on\n- `aide_remember` \u2014 store discoveries, decisions, corrections, and preferences\n- `aide_update` \u2014 update an existing memory when information changes\n- `aide_forget` \u2014 remove outdated memories\n- `aide_search` \u2014 find memories by keyword\n- `aide_import` \u2014 seed knowledge from existing markdown docs\n- `aide_memories` \u2014 list all stored memories"});function Ga(n,e,t){if(!n.needsDynamicRules)return"";let{content:r}=Mt(e,t),o="";try{let a=require("os"),c=ge.resolve(tt(),"src","cli");if(!D.existsSync(c)){let l=ge.join(tt(),"package.json"),u=JSON.parse(D.readFileSync(l,"utf8")).version,d=ge.join(a.homedir(),".aide","update-check.json");if(D.existsSync(d)){let m=JSON.parse(D.readFileSync(d,"utf8"));if(m.latestVersion&&m.latestVersion!==u){let w=u.replace(/^v/,"").split(".").map(Number),g=m.latestVersion.replace(/^v/,"").split(".").map(Number);(g[0]>w[0]||g[0]===w[0]&&g[1]>w[1]||g[0]===w[0]&&g[1]===w[1]&&g[2]>w[2])&&(o=`
192
+ `;Be="- `aide_recall` \u2014 retrieve stored context for file paths you're about to work on\n- `aide_remember` \u2014 store discoveries, decisions, corrections, and preferences\n- `aide_update` \u2014 update an existing memory when information changes\n- `aide_forget` \u2014 remove outdated memories\n- `aide_search` \u2014 find memories by keyword\n- `aide_import` \u2014 seed knowledge from existing markdown docs\n- `aide_memories` \u2014 list all stored memories"});function Ya(n,e,t){if(!n.needsDynamicRules)return"";let{content:r}=$t(e,t),o="";try{let a=require("os"),c=ge.resolve(nt(),"src","cli");if(!D.existsSync(c)){let l=ge.join(nt(),"package.json"),u=JSON.parse(D.readFileSync(l,"utf8")).version,d=ge.join(a.homedir(),".aide","update-check.json");if(D.existsSync(d)){let f=JSON.parse(D.readFileSync(d,"utf8"));if(f.latestVersion&&f.latestVersion!==u){let y=u.replace(/^v/,"").split(".").map(Number),h=f.latestVersion.replace(/^v/,"").split(".").map(Number);(h[0]>y[0]||h[0]===y[0]&&h[1]>y[1]||h[0]===y[0]&&h[1]===y[1]&&h[2]>y[2])&&(o=`
179
193
  ## Update available
180
- aide-memory v${m.latestVersion} is available (current: v${u}). Tell the user to run \`npm update -g aide-memory\` to upgrade.
181
- `)}}}}catch{}if(!r&&!o)return"";let i=[[os,"<!-- Content below reflects current memories + config. Do not edit by hand; -->","<!-- changes will be overwritten on the next memory / config write. -->",""].join(`
194
+ aide-memory v${f.latestVersion} is available (current: v${u}). Tell the user to run \`npm update -g aide-memory\` to upgrade.
195
+ `)}}}}catch{}if(!r&&!o)return"";let i=[[is,"<!-- Content below reflects current memories + config. Do not edit by hand; -->","<!-- changes will be overwritten on the next memory / config write. -->",""].join(`
182
196
  `)];return r&&(i.push(`## Current memory context
183
197
  `),i.push(r)),o&&i.push(o),i.join(`
184
198
  `)+`
185
- `}function Xa(n,e,t){let r={adapterId:n.id,dest:"",written:!1};if(!n.supportsRules||n.rules.length===0)return r;let o=n.rules[0];if(r.dest=o.dest,!n.needsDynamicRules)return r;let s=ge.join(e,o.dest),i=ge.dirname(s);D.existsSync(i)||D.mkdirSync(i,{recursive:!0});let a=new A({projectRoot:e}),c;try{c=Ga(n,e,a)}finally{a.close()}let l;if(D.existsSync(s)){let d=D.readFileSync(s,"utf8"),m=d.indexOf(os);if(!c)return r;if(m===-1)l=d.replace(/\n+$/,"")+`
199
+ `}function Ka(n,e,t){let r={adapterId:n.id,dest:"",written:!1};if(!n.supportsRules||n.rules.length===0)return r;let o=n.rules[0];if(r.dest=o.dest,!n.needsDynamicRules)return r;let s=ge.join(e,o.dest),i=ge.dirname(s);D.existsSync(i)||D.mkdirSync(i,{recursive:!0});let a=new A({projectRoot:e}),c;try{c=Ya(n,e,a)}finally{a.close()}let l;if(D.existsSync(s)){let d=D.readFileSync(s,"utf8"),f=d.indexOf(is);if(!c)return r;if(f===-1)l=d.replace(/\n+$/,"")+`
186
200
 
187
- `+c;else{let w=d.lastIndexOf(`
188
- `,m)+1;l=d.slice(0,w).replace(/\n+$/,"")+`
201
+ `+c;else{let y=d.lastIndexOf(`
202
+ `,f)+1;l=d.slice(0,y).replace(/\n+$/,"")+`
189
203
 
190
- `+c}}else{let d=It(n,t);l=c?d+`
191
- `+c:d}let u=`${s}.tmp`;try{D.writeFileSync(u,l,"utf8"),D.renameSync(u,s),r.written=!0}catch(d){try{D.existsSync(u)&&D.unlinkSync(u)}catch{}return console.warn(`aide-memory: failed to regenerate ${o.dest}: ${d.message}`),r}if(l.length>qa){let d=Math.round(l.length/4);r.budgetWarning=`${o.dest} is ~${d} tokens \u2014 above Cursor's ~2000-token soft cap for alwaysApply rules. Consider lowering injection.maxChars or disabling layers you don't need in SessionStart (see docs/user/editors/cursor.md).`,console.warn(`aide-memory: ${r.budgetWarning}`)}return r}function Vt(n,e,t){let r=[];for(let o of n)if(o.supportsRules)try{r.push(Xa(o,e,t))}catch(s){console.warn(`aide-memory: rulesGen failed for ${o.id}: ${s.message}`),r.push({adapterId:o.id,dest:o.rules[0]?.dest??"",written:!1})}return r}function Ce(n){return n?n.priority==="always"||n.layer==="preferences"||n.layer==="guidelines":!1}function oe(n,e){try{let t=nt(e)||"unknown";return Vt(n,e,{contributor:t,tools_list:He})}catch(t){return console.warn(`aide-memory: triggerRulesRegen failed: ${t.message}`),[]}}var D,ge,qa,os,Re=$(()=>{"use strict";D=h(require("fs")),ge=h(require("path"));Y();Tr();Nr();ot();$t();qa=8e3,os="<!-- \u2500\u2500\u2500 AUTOGENERATED section \u2014 regenerated by aide-memory \u2500\u2500\u2500 -->"});var Oc={};Qt(Oc,{createProgram:()=>ai});module.exports=Zt(Oc);var En=h(Sn(),1),{program:Ic,createCommand:Dc,createArgument:Fc,createOption:Pc,CommanderError:Lc,InvalidArgumentError:Hc,InvalidOptionArgumentError:Uc,Command:vn,Argument:Bc,Option:Vc,Help:Wc}=En.default;var At=h(V());Y();var Oo=h(require("fs")),Ot=h(require("path"));Ze();_t();var ko=["area_context","technical","preferences","guidelines"],Ro=20;function Co(n,e,t){let r=t?Number(W(t,"recall.minScopeDepth")??1):1,o=n.filter(a=>!a.scope||a.scope==="project"?!1:Ao(a.scope,e,{focused:!0,minScopeDepth:r})),s={},i=[];for(let a of o)s[a.layer]=(s[a.layer]||0)+1,i.push(a.id);return{memories:o,ids:i,layers:s,count:o.length}}function xo(n,e,t,r,o){if(n)try{let s=Ot.default.join(n,"recall-log.jsonl"),i={timestamp:new Date().toISOString(),query:{paths:o??e.paths??[],text:e.query??null,layers:e.layers??null,limit:e.limit??Ro},matched_scopes:r,memories_returned:t.map(a=>({id:a.id,uuid:a.uuid,layer:a.layer,what:a.what,scope:a.scope,tags:a.tags,recalled_count:a.recalled_count+1})),count:t.length};Oo.default.appendFileSync(s,JSON.stringify(i)+`
192
- `)}catch{}}function Ao(n,e,t){if(!n||n==="project")return!0;let r=n.replace(/\\/g,"/"),o=e.replace(/\\/g,"/"),s=r.replace(/\/?\*\*\/?$/,"").replace(/\/?\*$/,"").replace(/\/$/,"");if(!s)return!0;let i=o.startsWith(s+"/")||o===s,a=s.startsWith(o.replace(/\/$/,"")+"/");if(!i&&!a)return!1;if(t?.focused&&i){let c=t.minScopeDepth??1;if(s.split("/").length<c)return!1}return!0}function wa(n,e){if(!e)return 0;let t=e.toLowerCase().split(/\s+/).filter(s=>s.length>2);if(t.length===0)return 0;let r=[n.what,n.context_label,n.why].filter(Boolean).join(" ").toLowerCase(),o=0;for(let s of t)r.includes(s)&&o++;return o/t.length}function To(n,e,t){let r=performance.now();Q("recall",`enter paths=${JSON.stringify(e.paths??[])} ids=${JSON.stringify(e.ids??[])} query=${JSON.stringify(e.query??"")} layers=${JSON.stringify(e.layers??[])} limit=${e.limit??"default"}`);let o=n.getProjectRoot(),s=o?W(o,"recall.limit"):null,i=o?W(o,"recall.ensureLayerDiversity")??!0:!0,a=o?W(o,"recall.layerDiversityMinLimit")??5:5,c=e.limit??s??Ro,l=o?Number(W(o,"recall.minScopeDepth")??1):1,u={};e.contributor&&(u.contributor=e.contributor);let d=n.list(u),m=e.layers?d.filter(f=>e.layers.includes(f.layer)):d,w=new Set,g=e.paths?.map(f=>{if(Ot.default.isAbsolute(f)&&n.getProjectRoot()){let E=Ot.default.relative(n.getProjectRoot(),f),T=f.endsWith("/"),k=E!==""?E:".";return T&&!k.endsWith("/")?k+"/":k}return f});if(e.ids&&e.ids.length>0){let f=e.ids.map(T=>n.get(T)).filter(Boolean),E=f.map(T=>T.id);return E.length>0&&n.recordRecall(E),xo(t??null,e,f,[],g),{memories:f,matched_scopes:[]}}g&&g.length>0&&(m=m.filter(f=>{for(let E of g)if(Ao(f.scope,E,{focused:!0,minScopeDepth:l}))return f.scope&&w.add(f.scope),!0;return!1}));let _=g?.some(f=>f.endsWith("/"))??!1,S=m.map(f=>{let E=f.scope&&f.scope!=="project"?f.scope.split("/").length:0,T=E>0?1:0;return{memory:f,isScoped:T,layerRank:ko.indexOf(f.layer),relevance:e.query?wa(f,e.query):0,scopeSpecificity:E}});S.sort((f,E)=>f.isScoped!==E.isScoped?E.isScoped-f.isScoped:f.layerRank!==E.layerRank?f.layerRank-E.layerRank:E.relevance!==f.relevance?E.relevance-f.relevance:_?f.scopeSpecificity-E.scopeSpecificity:E.scopeSpecificity-f.scopeSpecificity);let p;if(c){let f=S.slice(0,c);if(i&&c>=a){let E=new Set(f.map(k=>k.memory.layer)),T=S.slice(c);for(let k of ko)if(!E.has(k)){let re=T.filter(J=>J.memory.layer===k);if(re.length>0){let J=new Map;for(let O of f)J.set(O.memory.layer,(J.get(O.memory.layer)||0)+1);let de=!1;for(let O=f.length-1;O>=0;O--){let B=f[O].memory.layer;if((J.get(B)||0)>1){f[O]=re[0],J.set(B,(J.get(B)||0)-1),E.add(k),de=!0;break}}de||(f[f.length-1]=re[0],E.add(k))}}}p=f.map(E=>E.memory)}else p=S.map(f=>f.memory);let x=p.map(f=>f.id);return x.length>0&&n.recordRecall(x),xo(t??null,e,p,Array.from(w),g),Q("recall",`exit candidates=${m.length} matched_scopes=${w.size} returned=${p.length} duration=${(performance.now()-r).toFixed(1)}ms`),{memories:p,matched_scopes:Array.from(w)}}var De=h(require("path")),Ar=h(require("fs")),Rt=h(V()),v=Rt.default.hex("#00c2cb"),le={preferences:"Preferences",technical:"Technical Context",area_context:"Area Context",guidelines:"Guidelines"},me=["preferences","technical","area_context","guidelines"];function _a(n){let e=De.default.resolve(n),t=De.default.parse(e).root;for(;e!==t;){if(Ar.default.existsSync(De.default.join(e,".aide")))return e;e=De.default.dirname(e)}return Ar.default.existsSync(De.default.join(t,".aide"))?t:null}function M(){let n=_a(process.cwd());return n||(console.error(Rt.default.red("No .aide/ directory found. Run `aide-memory init` first.")),process.exit(1)),n}function Ct(n){let e=new Map;for(let t of n)e.has(t.layer)||e.set(t.layer,[]),e.get(t.layer).push(t);return Array.from(e.entries())}function Fe(n){let e=` [${n.id}] ${n.what}`;return n.contributor&&(e+=v(` (from ${n.contributor})`)),n.scope&&n.scope!=="project"&&(e+=Rt.default.gray(` [${n.scope}]`)),e}function Mo(n){let e=M(),t=new A({projectRoot:e});try{let r=To(t,{paths:[n]});if(r.memories.length===0){console.log(At.default.gray("No memories found for this area."));return}console.log(At.default.white(`Recalled ${r.memories.length} memories for "${n}":
193
- `));let o=Ct(r.memories);for(let[s,i]of o){console.log(v.bold(`## ${le[s]??s}`));for(let a of i)console.log(Fe(a)),a.why&&console.log(At.default.gray(` Why: ${a.why}`));console.log()}}finally{t.close()}}var ss=h(V());Y();Re();ne();function is(n,e){me.includes(e.layer)||(console.error(ss.default.red(`Invalid layer "${e.layer}". Must be one of: ${me.join(", ")}`)),process.exit(1));let t=M(),r=new A({projectRoot:t});try{let o=r.add({layer:e.layer,what:n,why:e.why,scope:e.scope,context_label:e.tags,contributor:e.contributor});if(console.log(v(`Stored memory (id: ${o.id}):`)),console.log(` Layer: ${o.layer}`),console.log(` What: ${o.what}`),o.scope&&console.log(` Scope: ${o.scope}`),o.why&&console.log(` Why: ${o.why}`),o.contributor&&console.log(` From: ${o.contributor}`),o.context_label&&console.log(` Tags: ${o.context_label}`),Ce(o))try{oe(q(),t)}catch{}}finally{r.close()}}var st=h(V());Y();Re();ne();function as(n,e){let t=parseInt(n,10);isNaN(t)&&(console.error(st.default.red(`Invalid memory ID: "${n}". Must be a number.`)),process.exit(1));let r=M(),o=new A({projectRoot:r});try{let s=o.get(t);s||(console.error(st.default.red(`Memory ${t} not found.`)),process.exit(1));let i={};e.what!==void 0&&(i.what=e.what),e.why!==void 0&&(i.why=e.why),e.scope!==void 0&&(i.scope=e.scope),e.tags!==void 0&&(i.context_label=e.tags),Object.keys(i).length===0&&(console.error(st.default.yellow("No changes specified. Use --what, --why, --scope, or --tags.")),process.exit(1));let a=o.update(t,i);if(a||(console.error(st.default.red(`Failed to update memory ${t}.`)),process.exit(1)),console.log(v(`Updated memory (id: ${a.id}):`)),console.log(` Layer: ${a.layer}`),console.log(` What: ${a.what}`),a.scope&&console.log(` Scope: ${a.scope}`),a.why&&console.log(` Why: ${a.why}`),Ce(s)||Ce(a))try{oe(q(),r)}catch{}}finally{o.close()}}var Gr=h(V());Y();Re();ne();function cs(n){let e=parseInt(n,10);isNaN(e)&&(console.error(Gr.default.red(`Invalid memory ID: "${n}". Must be a number.`)),process.exit(1));let t=M(),r=new A({projectRoot:t});try{let o=r.get(e);if(o||(console.error(Gr.default.red(`Memory ${e} not found.`)),process.exit(1)),r.remove(e),console.log(v(`Deleted memory ${e}: "${o.what}"`)),Ce(o))try{oe(q(),t)}catch{}}finally{r.close()}}var qt=h(V());Y();function ls(n,e){let t=M(),r=new A({projectRoot:t});try{let o=r.search(n,{layer:e.layer,limit:e.limit?parseInt(e.limit,10):50});if(o.length===0){console.log(qt.default.gray(`No memories found matching "${n}".`));return}console.log(qt.default.white(`Found ${o.length} matching "${n}":
194
- `));let s=Ct(o);for(let[i,a]of s){console.log(v.bold(` ${le[i]??i}`));for(let c of a)console.log(Fe(c)),c.why&&console.log(qt.default.gray(` Why: ${c.why}`));console.log()}}finally{r.close()}}var it=h(V());Y();function us(n){n.layer&&!me.includes(n.layer)&&(console.error(it.default.red(`Invalid layer "${n.layer}". Must be one of: ${me.join(", ")}`)),process.exit(1));let e=M(),t=new A({projectRoot:e});try{let r=t.list({layer:n.layer,scope:n.scope,limit:n.limit?parseInt(n.limit,10):void 0});if(n.contributor&&(r=r.filter(s=>s.contributor===n.contributor)),n.tag){let s=n.tag.toLowerCase();r=r.filter(i=>i.context_label?.toLowerCase().includes(s))}if(r.length===0){console.log(it.default.gray("No memories found."));return}let o=t.count();console.log(it.default.white(`Showing ${r.length} of ${o} memories:
195
- `));for(let s of r){let i=Fe(s);i+=it.default.gray(` | recalled ${s.recalled_count}x`),console.log(i)}}finally{t.close()}}var ds=h(V());Y();function ps(){let n=M(),e=new A({projectRoot:n});try{let t=e.count();console.log(ds.default.white.bold(`Memory Statistics
196
- `)),console.log(` Total memories: ${t}`),console.log(),console.log(v.bold(" By Layer:"));for(let a of me){let c=e.count({layer:a});console.log(` ${le[a]}: ${c}`)}console.log();let r=e.list(),s=[...r].sort((a,c)=>c.recalled_count-a.recalled_count).filter(a=>a.recalled_count>0).slice(0,5);if(s.length>0){console.log(v.bold(" Most Recalled:"));for(let a of s)console.log(` [${a.id}] ${a.what} (${a.recalled_count}x)`);console.log()}let i=new Map;for(let a of r)i.set(a.source,(i.get(a.source)??0)+1);if(i.size>0){console.log(v.bold(" By Source:"));for(let[a,c]of i)console.log(` ${a}: ${c}`)}}finally{e.close()}}var fs=h(require("path")),at=h(require("fs")),N=h(V());function ms(n){let e=M(),t=fs.default.join(e,".aide","recall-log.jsonl");if(n.clear){at.default.existsSync(t)?(at.default.unlinkSync(t),console.log(v("Recall log cleared."))):console.log(N.default.yellow("No recall log to clear."));return}if(!at.default.existsSync(t)){console.log(N.default.yellow("No recall log found. Recalls will be logged after the next aide_recall call.")),console.log(N.default.gray(` Expected at: ${t}`));return}let r=at.default.readFileSync(t,"utf-8").trim();if(!r){console.log(N.default.yellow("Recall log is empty."));return}let o=r.split(`
204
+ `+c}}else{let d=Dt(n,t);l=c?d+`
205
+ `+c:d}let u=`${s}.tmp`;try{D.writeFileSync(u,l,"utf8"),D.renameSync(u,s),r.written=!0}catch(d){try{D.existsSync(u)&&D.unlinkSync(u)}catch{}return console.warn(`aide-memory: failed to regenerate ${o.dest}: ${d.message}`),r}if(l.length>Xa){let d=Math.round(l.length/4);r.budgetWarning=`${o.dest} is ~${d} tokens \u2014 above Cursor's ~2000-token soft cap for alwaysApply rules. Consider lowering injection.maxChars or disabling layers you don't need in SessionStart (see docs/user/editors/cursor.md).`,console.warn(`aide-memory: ${r.budgetWarning}`)}return r}function Wt(n,e,t){let r=[];for(let o of n)if(o.supportsRules)try{r.push(Ka(o,e,t))}catch(s){console.warn(`aide-memory: rulesGen failed for ${o.id}: ${s.message}`),r.push({adapterId:o.id,dest:o.rules[0]?.dest??"",written:!1})}return r}function Ae(n){return n?n.priority==="always"||n.layer==="preferences"||n.layer==="guidelines":!1}function oe(n,e){try{let t=st(e)||"unknown";return Wt(n,e,{contributor:t,tools_list:Be})}catch(t){return console.warn(`aide-memory: triggerRulesRegen failed: ${t.message}`),[]}}var D,ge,Xa,is,Ce=T(()=>{"use strict";D=g(require("fs")),ge=g(require("path"));K();Mr();$r();it();jt();Xa=8e3,is="<!-- \u2500\u2500\u2500 AUTOGENERATED section \u2014 regenerated by aide-memory \u2500\u2500\u2500 -->"});var Ac={};Zt(Ac,{createProgram:()=>li});module.exports=er(Ac);var vn=g(En(),1),{program:Fc,createCommand:Lc,createArgument:Hc,createOption:Uc,CommanderError:Bc,InvalidArgumentError:Vc,InvalidOptionArgumentError:Wc,Command:kn,Argument:Jc,Option:qc,Help:Gc}=vn.default;var Mt=g(J());K();var Ro=g(require("fs")),Ct=g(require("path"));tt();Et();var xo=["area_context","technical","preferences","guidelines"],Co=20;function Ao(n,e,t){let r=t?Number(q(t,"recall.minScopeDepth")??1):1,o=n.filter(a=>!a.scope||a.scope==="project"?!1:To(a.scope,e,{focused:!0,minScopeDepth:r})),s={},i=[];for(let a of o)s[a.layer]=(s[a.layer]||0)+1,i.push(a.id);return{memories:o,ids:i,layers:s,count:o.length}}function Oo(n,e,t,r,o){if(n)try{let s=Ct.default.join(n,"recall-log.jsonl"),i={timestamp:new Date().toISOString(),query:{paths:o??e.paths??[],text:e.query??null,layers:e.layers??null,limit:e.limit??Co},matched_scopes:r,memories_returned:t.map(a=>({id:a.id,uuid:a.uuid,layer:a.layer,what:a.what,scope:a.scope,tags:a.tags,recalled_count:a.recalled_count+1})),count:t.length};Ro.default.appendFileSync(s,JSON.stringify(i)+`
206
+ `)}catch{}}function To(n,e,t){if(!n||n==="project")return!0;let r=n.replace(/\\/g,"/"),o=e.replace(/\\/g,"/"),s=r.replace(/\/?\*\*\/?$/,"").replace(/\/?\*$/,"").replace(/\/$/,"");if(!s)return!0;let i=o.startsWith(s+"/")||o===s,a=s.startsWith(o.replace(/\/$/,"")+"/");if(!i&&!a)return!1;if(t?.focused&&i){let c=t.minScopeDepth??1;if(s.split("/").length<c)return!1}return!0}function Sa(n,e){if(!e)return 0;let t=e.toLowerCase().split(/\s+/).filter(s=>s.length>2);if(t.length===0)return 0;let r=[n.what,n.context_label,n.why].filter(Boolean).join(" ").toLowerCase(),o=0;for(let s of t)r.includes(s)&&o++;return o/t.length}function Mo(n,e,t){let r=performance.now();Z("recall",`enter paths=${JSON.stringify(e.paths??[])} ids=${JSON.stringify(e.ids??[])} query=${JSON.stringify(e.query??"")} layers=${JSON.stringify(e.layers??[])} limit=${e.limit??"default"}`);let o=n.getProjectRoot(),s=o?q(o,"recall.limit"):null,i=o?q(o,"recall.ensureLayerDiversity")??!0:!0,a=o?q(o,"recall.layerDiversityMinLimit")??5:5,c=e.limit??s??Co,l=o?Number(q(o,"recall.minScopeDepth")??1):1,u={};e.contributor&&(u.contributor=e.contributor);let d=n.list(u),f=e.layers?d.filter(m=>e.layers.includes(m.layer)):d,y=new Set,h=e.paths?.map(m=>{if(Ct.default.isAbsolute(m)&&n.getProjectRoot()){let S=Ct.default.relative(n.getProjectRoot(),m),j=m.endsWith("/"),k=S!==""?S:".";return j&&!k.endsWith("/")?k+"/":k}return m});if(e.ids&&e.ids.length>0){let m=e.ids.map(j=>n.get(j)).filter(Boolean),S=m.map(j=>j.id);return S.length>0&&n.recordRecall(S),Oo(t??null,e,m,[],h),{memories:m,matched_scopes:[]}}h&&h.length>0&&(f=f.filter(m=>{for(let S of h)if(To(m.scope,S,{focused:!0,minScopeDepth:l}))return m.scope&&y.add(m.scope),!0;return!1}));let w=h?.some(m=>m.endsWith("/"))??!1,E=f.map(m=>{let S=m.scope&&m.scope!=="project"?m.scope.split("/").length:0,j=S>0?1:0;return{memory:m,isScoped:j,layerRank:xo.indexOf(m.layer),relevance:e.query?Sa(m,e.query):0,scopeSpecificity:S}});E.sort((m,S)=>m.isScoped!==S.isScoped?S.isScoped-m.isScoped:m.layerRank!==S.layerRank?m.layerRank-S.layerRank:S.relevance!==m.relevance?S.relevance-m.relevance:w?m.scopeSpecificity-S.scopeSpecificity:S.scopeSpecificity-m.scopeSpecificity);let p;if(c){let m=E.slice(0,c);if(i&&c>=a){let S=new Set(m.map(k=>k.memory.layer)),j=E.slice(c);for(let k of xo)if(!S.has(k)){let H=j.filter(I=>I.memory.layer===k);if(H.length>0){let I=new Map;for(let x of m)I.set(x.memory.layer,(I.get(x.memory.layer)||0)+1);let ce=!1;for(let x=m.length-1;x>=0;x--){let W=m[x].memory.layer;if((I.get(W)||0)>1){m[x]=H[0],I.set(W,(I.get(W)||0)-1),S.add(k),ce=!0;break}}ce||(m[m.length-1]=H[0],S.add(k))}}}p=m.map(S=>S.memory)}else p=E.map(m=>m.memory);let R=p.map(m=>m.id);return R.length>0&&n.recordRecall(R),Oo(t??null,e,p,Array.from(y),h),Z("recall",`exit candidates=${f.length} matched_scopes=${y.size} returned=${p.length} duration=${(performance.now()-r).toFixed(1)}ms`),{memories:p,matched_scopes:Array.from(y)}}var De=g(require("path")),Tr=g(require("fs")),At=g(J()),v=At.default.hex("#00c2cb"),ue={preferences:"Preferences",technical:"Technical Context",area_context:"Area Context",guidelines:"Guidelines"},fe=["preferences","technical","area_context","guidelines"];function Ea(n){let e=De.default.resolve(n),t=De.default.parse(e).root;for(;e!==t;){if(Tr.default.existsSync(De.default.join(e,".aide")))return e;e=De.default.dirname(e)}return Tr.default.existsSync(De.default.join(t,".aide"))?t:null}function M(){let n=Ea(process.cwd());return n||(console.error(At.default.red("No .aide/ directory found. Run `aide-memory init` first.")),process.exit(1)),n}function Tt(n){let e=new Map;for(let t of n)e.has(t.layer)||e.set(t.layer,[]),e.get(t.layer).push(t);return Array.from(e.entries())}function Fe(n){let e=` [${n.id}] ${n.what}`;return n.contributor&&(e+=v(` (from ${n.contributor})`)),n.scope&&n.scope!=="project"&&(e+=At.default.gray(` [${n.scope}]`)),e}function No(n){let e=M(),t=new A({projectRoot:e});try{let r=Mo(t,{paths:[n]});if(r.memories.length===0){console.log(Mt.default.gray("No memories found for this area."));return}console.log(Mt.default.white(`Recalled ${r.memories.length} memories for "${n}":
207
+ `));let o=Tt(r.memories);for(let[s,i]of o){console.log(v.bold(`## ${ue[s]??s}`));for(let a of i)console.log(Fe(a)),a.why&&console.log(Mt.default.gray(` Why: ${a.why}`));console.log()}}finally{t.close()}}var as=g(J());K();Ce();ne();function cs(n,e){fe.includes(e.layer)||(console.error(as.default.red(`Invalid layer "${e.layer}". Must be one of: ${fe.join(", ")}`)),process.exit(1));let t=M(),r=new A({projectRoot:t});try{let o=r.add({layer:e.layer,what:n,why:e.why,scope:e.scope,context_label:e.tags,contributor:e.contributor});if(console.log(v(`Stored memory (id: ${o.id}):`)),console.log(` Layer: ${o.layer}`),console.log(` What: ${o.what}`),o.scope&&console.log(` Scope: ${o.scope}`),o.why&&console.log(` Why: ${o.why}`),o.contributor&&console.log(` From: ${o.contributor}`),o.context_label&&console.log(` Tags: ${o.context_label}`),Ae(o))try{oe(G(),t)}catch{}}finally{r.close()}}var at=g(J());K();Ce();ne();function ls(n,e){let t=parseInt(n,10);isNaN(t)&&(console.error(at.default.red(`Invalid memory ID: "${n}". Must be a number.`)),process.exit(1));let r=M(),o=new A({projectRoot:r});try{let s=o.get(t);s||(console.error(at.default.red(`Memory ${t} not found.`)),process.exit(1));let i={};e.what!==void 0&&(i.what=e.what),e.why!==void 0&&(i.why=e.why),e.scope!==void 0&&(i.scope=e.scope),e.tags!==void 0&&(i.context_label=e.tags),Object.keys(i).length===0&&(console.error(at.default.yellow("No changes specified. Use --what, --why, --scope, or --tags.")),process.exit(1));let a=o.update(t,i);if(a||(console.error(at.default.red(`Failed to update memory ${t}.`)),process.exit(1)),console.log(v(`Updated memory (id: ${a.id}):`)),console.log(` Layer: ${a.layer}`),console.log(` What: ${a.what}`),a.scope&&console.log(` Scope: ${a.scope}`),a.why&&console.log(` Why: ${a.why}`),Ae(s)||Ae(a))try{oe(G(),r)}catch{}}finally{o.close()}}var Xr=g(J());K();Ce();ne();function us(n){let e=parseInt(n,10);isNaN(e)&&(console.error(Xr.default.red(`Invalid memory ID: "${n}". Must be a number.`)),process.exit(1));let t=M(),r=new A({projectRoot:t});try{let o=r.get(e);if(o||(console.error(Xr.default.red(`Memory ${e} not found.`)),process.exit(1)),r.remove(e),console.log(v(`Deleted memory ${e}: "${o.what}"`)),Ae(o))try{oe(G(),t)}catch{}}finally{r.close()}}var Gt=g(J());K();function ds(n,e){let t=M(),r=new A({projectRoot:t});try{let o=r.search(n,{layer:e.layer,limit:e.limit?parseInt(e.limit,10):50});if(o.length===0){console.log(Gt.default.gray(`No memories found matching "${n}".`));return}console.log(Gt.default.white(`Found ${o.length} matching "${n}":
208
+ `));let s=Tt(o);for(let[i,a]of s){console.log(v.bold(` ${ue[i]??i}`));for(let c of a)console.log(Fe(c)),c.why&&console.log(Gt.default.gray(` Why: ${c.why}`));console.log()}}finally{r.close()}}var ct=g(J());K();function ps(n){n.layer&&!fe.includes(n.layer)&&(console.error(ct.default.red(`Invalid layer "${n.layer}". Must be one of: ${fe.join(", ")}`)),process.exit(1));let e=M(),t=new A({projectRoot:e});try{let r=t.list({layer:n.layer,scope:n.scope,limit:n.limit?parseInt(n.limit,10):void 0});if(n.contributor&&(r=r.filter(s=>s.contributor===n.contributor)),n.tag){let s=n.tag.toLowerCase();r=r.filter(i=>i.context_label?.toLowerCase().includes(s))}if(r.length===0){console.log(ct.default.gray("No memories found."));return}let o=t.count();console.log(ct.default.white(`Showing ${r.length} of ${o} memories:
209
+ `));for(let s of r){let i=Fe(s);i+=ct.default.gray(` | recalled ${s.recalled_count}x`),console.log(i)}}finally{t.close()}}var ms=g(J());K();function fs(){let n=M(),e=new A({projectRoot:n});try{let t=e.count();console.log(ms.default.white.bold(`Memory Statistics
210
+ `)),console.log(` Total memories: ${t}`),console.log(),console.log(v.bold(" By Layer:"));for(let a of fe){let c=e.count({layer:a});console.log(` ${ue[a]}: ${c}`)}console.log();let r=e.list(),s=[...r].sort((a,c)=>c.recalled_count-a.recalled_count).filter(a=>a.recalled_count>0).slice(0,5);if(s.length>0){console.log(v.bold(" Most Recalled:"));for(let a of s)console.log(` [${a.id}] ${a.what} (${a.recalled_count}x)`);console.log()}let i=new Map;for(let a of r)i.set(a.source,(i.get(a.source)??0)+1);if(i.size>0){console.log(v.bold(" By Source:"));for(let[a,c]of i)console.log(` ${a}: ${c}`)}}finally{e.close()}}var hs=g(require("path")),lt=g(require("fs")),N=g(J());function gs(n){let e=M(),t=hs.default.join(e,".aide","recall-log.jsonl");if(n.clear){lt.default.existsSync(t)?(lt.default.unlinkSync(t),console.log(v("Recall log cleared."))):console.log(N.default.yellow("No recall log to clear."));return}if(!lt.default.existsSync(t)){console.log(N.default.yellow("No recall log found. Recalls will be logged after the next aide_recall call.")),console.log(N.default.gray(` Expected at: ${t}`));return}let r=lt.default.readFileSync(t,"utf-8").trim();if(!r){console.log(N.default.yellow("Recall log is empty."));return}let o=r.split(`
197
211
  `),s=n.last?parseInt(n.last,10):o.length,i=o.slice(-s).map(p=>{try{return JSON.parse(p)}catch{return null}}).filter(Boolean);if(i.length===0){console.log(N.default.yellow("No valid recall log entries found."));return}let a=i.filter(p=>!p.event),c=i.filter(p=>p.event);console.log(N.default.white.bold(`Event Log \u2014 ${i.length} event(s)
198
- `));let l=0,u=0;for(let p of i){let x=new Date(p.timestamp).toLocaleString();if(p.event&&p.memory){u++;let f=p.event==="memory_stored"?v("STORED"):p.event==="memory_updated"?N.default.yellow("UPDATED"):N.default.red("DELETED");console.log(`${f} ${N.default.gray(`(${x})`)}`),console.log(` [${p.memory.id}] ${N.default.white(p.memory.what)}`);let E=le[p.memory.layer]??p.memory.layer;console.log(N.default.gray(` Layer: ${E} | Scope: ${p.memory.scope??"project-wide"}`)),p.memory.why&&console.log(N.default.gray(` Why: ${p.memory.why}`))}else if(p.query&&p.memories_returned)if(l++,console.log(v.bold(`\u2500\u2500 Recall #${l} `)+N.default.gray(`(${x})`)),console.log(N.default.gray(` Query paths: ${p.query.paths.length>0?p.query.paths.join(", "):"(none)"}`)),p.query.text&&console.log(N.default.gray(` Query text: ${p.query.text}`)),p.query.layers&&console.log(N.default.gray(` Layers: ${p.query.layers.join(", ")}`)),console.log(N.default.gray(` Matched scopes: ${p.matched_scopes&&p.matched_scopes.length>0?p.matched_scopes.join(", "):"(none)"}`)),console.log(),p.memories_returned.length===0)console.log(N.default.yellow(" No memories returned."));else{console.log(N.default.white(` ${p.memories_returned.length} memor${p.memories_returned.length===1?"y":"ies"} returned:`)),console.log();for(let f of p.memories_returned){let E=le[f.layer]??f.layer;console.log(` ${v("\u2713")} [${f.id}] ${N.default.white(f.what)}`),console.log(N.default.gray(` Layer: ${E} | Scope: ${f.scope??"project-wide"} | Recalled: ${f.recalled_count}x`)),f.tags.length>0&&console.log(N.default.gray(` Tags: ${f.tags.join(", ")}`))}}console.log()}let d=a.length,m=a.reduce((p,x)=>p+(x.count??0),0),w=a.filter(p=>(p.count??0)===0).length,g=c.filter(p=>p.event==="memory_stored").length,_=c.filter(p=>p.event==="memory_updated").length,S=c.filter(p=>p.event==="memory_deleted").length;console.log(N.default.white.bold("Summary")),console.log(` Recall events: ${d}`),console.log(` Total memories returned: ${m}`),console.log(` Empty recalls (0 results): ${w}`),d>0&&console.log(` Avg memories per recall: ${(m/d).toFixed(1)}`),console.log(` Memories stored: ${g}`),console.log(` Memories updated: ${_}`),console.log(` Memories deleted: ${S}`)}var se=h(V()),Xr=h(require("path")),Ue=h(require("fs"));ot();Ze();Ft();Re();ne();function hs(n){return Xr.default.join(n,".aide","config.json")}function gs(n){if(!Ue.default.existsSync(n))return{};let e=Ue.default.readFileSync(n,"utf-8");return JSON.parse(e)}function Ya(n,e){let t=Xr.default.dirname(n);Ue.default.existsSync(t)||Ue.default.mkdirSync(t,{recursive:!0}),Ue.default.writeFileSync(n,JSON.stringify(e,null,2)+`
199
- `)}function ys(n,e){let t=e.split("."),r=n;for(let o of t){if(r==null||typeof r!="object")return;r=r[o]}return r}function Ka(n,e,t){let r=e.split("."),o=n;for(let s=0;s<r.length-1;s++){let i=r[s];(o[i]===void 0||typeof o[i]!="object")&&(o[i]={}),o=o[i]}o[r[r.length-1]]=t}function za(n){if(n==="true")return!0;if(n==="false")return!1;if(n==="null")return null;let e=Number(n);if(!isNaN(e)&&n.trim()!=="")return e;let t=n.trim();if(t.startsWith("[")&&t.endsWith("]")||t.startsWith("{")&&t.endsWith("}"))try{return JSON.parse(t)}catch{}return n}function Qa(){let n=new Set;for(let r of Object.keys(Se()))n.add(r);let t=[{obj:he.defaults(),prefix:""}];for(;t.length>0;){let{obj:r,prefix:o}=t.pop();if(r==null||typeof r!="object"||Array.isArray(r)){o&&n.add(o);continue}for(let[s,i]of Object.entries(r)){let a=o?`${o}.${s}`:s;i!==null&&typeof i=="object"&&!Array.isArray(i)?t.push({obj:i,prefix:a}):n.add(a)}}return Array.from(n).sort()}function Za(n){let e=Qa();if(e.includes(n))return{ok:!0};let t=n.toLowerCase(),r=t.split(".")[0],o=e.filter(c=>c.toLowerCase().startsWith(r)),s=e.filter(c=>c.toLowerCase().includes(t)),i=Array.from(new Set([...o,...s])).slice(0,10),a=[];if(a.push(`Unknown config key: "${n}".`),i.length>0){a.push("Did you mean one of:");for(let c of i)a.push(` - ${c}`)}return a.push(""),a.push(`Valid keys: ${e.join(", ")}`),{ok:!1,message:a.join(`
200
- `)}}function bs(n,e){if(n==="list"&&e===void 0){ec();return}let t=M(),r=hs(t),o=gs(r),s=Za(n);if(!s.ok){console.error(se.default.red(s.message)),process.exitCode=1;return}if(e===void 0){let i=ys(o,n);console.log(i===void 0?se.default.gray("(not set)"):typeof i=="object"?JSON.stringify(i,null,2):String(i))}else{let i=za(e);Ka(o,n,i),Ya(r,o),console.log(v(`Set ${n} = ${JSON.stringify(i)}`)),tc(t,n,i)}}function ec(){let n=M(),e=hs(n),t=gs(e),r=Se(),o=Object.keys(r).filter(s=>r[s].public===!0).sort();if(o.length===0){console.log(se.default.gray("(no public settings registered)"));return}console.log(v("aide-memory \xB7 configurable settings")),console.log("");for(let s of o){let i=r[s],a=ys(t,s),c=a!==void 0,l=typeof i.value=="object"?JSON.stringify(i.value):String(i.value),u=c?typeof a=="object"?JSON.stringify(a):String(a):se.default.gray("(default)");if(console.log(se.default.bold(s)),console.log(` current: ${c?se.default.cyan(u):u}`),console.log(` default: ${se.default.gray(l)}`),i.description){let d=i.description.split(`
201
- `).map(m=>` ${m}`).join(`
202
- `);console.log(se.default.dim(d))}console.log("")}console.log(se.default.gray("Set a value: aide-memory config <key> <value> \u2022 Read: aide-memory config <key>"))}function tc(n,e,t){if(new Set(["memories.hideFromGrep"]).has(e)){let s=Jt(n);for(let i of s)console.log(v(i))}if(e.startsWith("injection.")||e==="memories.softening.threshold")try{let s=oe(q(),n);for(let i of s)i.written&&console.log(v(`regenerated ${i.dest}`)),i.budgetWarning&&console.warn(v(i.budgetWarning))}catch(s){console.warn(v(`rules regen skipped: ${s.message}`))}}var Gt=h(V());Y();var ie=h(require("path")),Z=h(require("fs")),rc={preferences:"preferences",technical:"technical",area_context:"area_context",guidelines:"guidelines"},ct=class{constructor(e){this.store=e,this.db=e.db;let t=e.memoriesPath;if(!t)throw new Error("MemorySync requires a store in file-per-memory mode (use { projectRoot } constructor)");this.memoriesDir=t}importFromFiles(){let e={imported:0,updated:0,removed:0,conflicts:[],errors:[]},t=this.collectJsonFiles(),r=new Set;for(let s of t)if(!this.isPersonalPreference(s))try{let i=Z.default.readFileSync(s,"utf-8"),a=JSON.parse(i);if(!this.isValidMemoryFile(a)){e.errors.push(`Malformed file: ${ie.default.relative(this.memoriesDir,s)}`);continue}r.add(a.uuid);let c=this.getByUuid(a.uuid);if(c){if(c.updated_at>a.updated_at){e.conflicts.push({uuid:a.uuid,reason:"local edits would be overwritten",localUpdatedAt:c.updated_at,incomingUpdatedAt:a.updated_at});continue}if(c.updated_at===a.updated_at)continue;this.updateFromFile(c.id,a),e.updated++}else this.insertFromFile(a),e.imported++}catch(i){let a=ie.default.relative(this.memoriesDir,s);e.errors.push(`Error reading ${a}: ${i instanceof Error?i.message:String(i)}`)}let o=this.getAllUuids();for(let s of o)if(!r.has(s.uuid)){if(s.layer==="preferences"&&s.shared===0)continue;this.deleteByUuid(s.uuid),e.removed++}return e}exportToFiles(){let e={imported:0,updated:0,removed:0,conflicts:[],errors:[]},t=this.store.list();for(let r of t)try{let o=this.getMemoryFilePath(r.uuid,r.layer,r.shared);if(Z.default.existsSync(o))continue;let s=ie.default.dirname(o);Z.default.existsSync(s)||Z.default.mkdirSync(s,{recursive:!0});let i={uuid:r.uuid,layer:r.layer,what:r.what,why:r.why,scope:r.scope,context_label:r.context_label,contributor:r.contributor,tags:r.tags,source:r.source,shared:r.shared,generated_by:r.generated_by,derived_from:r.derived_from,created_at:r.created_at,updated_at:r.updated_at},a=o+".tmp";Z.default.writeFileSync(a,JSON.stringify(i,null,2)+`
203
- `,"utf-8"),Z.default.renameSync(a,o),e.imported++}catch(o){e.errors.push(`Error exporting ${r.uuid}: ${o instanceof Error?o.message:String(o)}`)}return e}syncFromGit(){let e={imported:0,updated:0,removed:0,conflicts:[],errors:[]},t=this.collectJsonFiles(),r=new Set;for(let s of t)if(!this.isPersonalPreference(s))try{let i=Z.default.readFileSync(s,"utf-8"),a=JSON.parse(i);if(!this.isValidMemoryFile(a)){e.errors.push(`Malformed file: ${ie.default.relative(this.memoriesDir,s)}`);continue}r.add(a.uuid);let c=this.getByUuid(a.uuid);c?a.updated_at>c.updated_at?(this.updateFromFile(c.id,a),e.updated++):a.updated_at<c.updated_at&&e.conflicts.push({uuid:a.uuid,reason:"local edits would be overwritten",localUpdatedAt:c.updated_at,incomingUpdatedAt:a.updated_at}):(this.insertFromFile(a),e.imported++)}catch(i){let a=ie.default.relative(this.memoriesDir,s);e.errors.push(`Error reading ${a}: ${i instanceof Error?i.message:String(i)}`)}let o=this.getAllUuids();for(let s of o)if(!r.has(s.uuid)){if(s.layer==="preferences"&&s.shared===0)continue;this.deleteByUuid(s.uuid),e.removed++}return e}getByUuid(e){return this.db.prepare("SELECT id, updated_at, layer, shared FROM memories WHERE uuid = ?").get(e)}getAllUuids(){return this.db.prepare("SELECT uuid, layer, shared FROM memories").all()}insertFromFile(e){this.db.prepare(`
212
+ `));let l=0,u=0;for(let p of i){let R=new Date(p.timestamp).toLocaleString();if(p.event&&p.memory){u++;let m=p.event==="memory_stored"?v("STORED"):p.event==="memory_updated"?N.default.yellow("UPDATED"):N.default.red("DELETED");console.log(`${m} ${N.default.gray(`(${R})`)}`),console.log(` [${p.memory.id}] ${N.default.white(p.memory.what)}`);let S=ue[p.memory.layer]??p.memory.layer;console.log(N.default.gray(` Layer: ${S} | Scope: ${p.memory.scope??"project-wide"}`)),p.memory.why&&console.log(N.default.gray(` Why: ${p.memory.why}`))}else if(p.query&&p.memories_returned)if(l++,console.log(v.bold(`\u2500\u2500 Recall #${l} `)+N.default.gray(`(${R})`)),console.log(N.default.gray(` Query paths: ${p.query.paths.length>0?p.query.paths.join(", "):"(none)"}`)),p.query.text&&console.log(N.default.gray(` Query text: ${p.query.text}`)),p.query.layers&&console.log(N.default.gray(` Layers: ${p.query.layers.join(", ")}`)),console.log(N.default.gray(` Matched scopes: ${p.matched_scopes&&p.matched_scopes.length>0?p.matched_scopes.join(", "):"(none)"}`)),console.log(),p.memories_returned.length===0)console.log(N.default.yellow(" No memories returned."));else{console.log(N.default.white(` ${p.memories_returned.length} memor${p.memories_returned.length===1?"y":"ies"} returned:`)),console.log();for(let m of p.memories_returned){let S=ue[m.layer]??m.layer;console.log(` ${v("\u2713")} [${m.id}] ${N.default.white(m.what)}`),console.log(N.default.gray(` Layer: ${S} | Scope: ${m.scope??"project-wide"} | Recalled: ${m.recalled_count}x`)),m.tags.length>0&&console.log(N.default.gray(` Tags: ${m.tags.join(", ")}`))}}console.log()}let d=a.length,f=a.reduce((p,R)=>p+(R.count??0),0),y=a.filter(p=>(p.count??0)===0).length,h=c.filter(p=>p.event==="memory_stored").length,w=c.filter(p=>p.event==="memory_updated").length,E=c.filter(p=>p.event==="memory_deleted").length;console.log(N.default.white.bold("Summary")),console.log(` Recall events: ${d}`),console.log(` Total memories returned: ${f}`),console.log(` Empty recalls (0 results): ${y}`),d>0&&console.log(` Avg memories per recall: ${(f/d).toFixed(1)}`),console.log(` Memories stored: ${h}`),console.log(` Memories updated: ${w}`),console.log(` Memories deleted: ${E}`)}var se=g(J()),Yr=g(require("path")),Ve=g(require("fs"));it();tt();Lt();Ce();ne();function ys(n){return Yr.default.join(n,".aide","config.json")}function bs(n){if(!Ve.default.existsSync(n))return{};let e=Ve.default.readFileSync(n,"utf-8");return JSON.parse(e)}function za(n,e){let t=Yr.default.dirname(n);Ve.default.existsSync(t)||Ve.default.mkdirSync(t,{recursive:!0}),Ve.default.writeFileSync(n,JSON.stringify(e,null,2)+`
213
+ `)}function _s(n,e){let t=e.split("."),r=n;for(let o of t){if(r==null||typeof r!="object")return;r=r[o]}return r}function Qa(n,e,t){let r=e.split("."),o=n;for(let s=0;s<r.length-1;s++){let i=r[s];(o[i]===void 0||typeof o[i]!="object")&&(o[i]={}),o=o[i]}o[r[r.length-1]]=t}function Za(n){if(n==="true")return!0;if(n==="false")return!1;if(n==="null")return null;let e=Number(n);if(!isNaN(e)&&n.trim()!=="")return e;let t=n.trim();if(t.startsWith("[")&&t.endsWith("]")||t.startsWith("{")&&t.endsWith("}"))try{return JSON.parse(t)}catch{}return n}function ec(){let n=new Set;for(let r of Object.keys(Se()))n.add(r);let t=[{obj:he.defaults(),prefix:""}];for(;t.length>0;){let{obj:r,prefix:o}=t.pop();if(r==null||typeof r!="object"||Array.isArray(r)){o&&n.add(o);continue}for(let[s,i]of Object.entries(r)){let a=o?`${o}.${s}`:s;i!==null&&typeof i=="object"&&!Array.isArray(i)?t.push({obj:i,prefix:a}):n.add(a)}}return Array.from(n).sort()}function tc(n){let e=ec();if(e.includes(n))return{ok:!0};let t=n.toLowerCase(),r=t.split(".")[0],o=e.filter(c=>c.toLowerCase().startsWith(r)),s=e.filter(c=>c.toLowerCase().includes(t)),i=Array.from(new Set([...o,...s])).slice(0,10),a=[];if(a.push(`Unknown config key: "${n}".`),i.length>0){a.push("Did you mean one of:");for(let c of i)a.push(` - ${c}`)}return a.push(""),a.push(`Valid keys: ${e.join(", ")}`),{ok:!1,message:a.join(`
214
+ `)}}function ws(n,e){if(n==="list"&&e===void 0){rc();return}let t=M(),r=ys(t),o=bs(r),s=tc(n);if(!s.ok){console.error(se.default.red(s.message)),process.exitCode=1;return}if(e===void 0){let i=_s(o,n);console.log(i===void 0?se.default.gray("(not set)"):typeof i=="object"?JSON.stringify(i,null,2):String(i))}else{let i=Za(e);Qa(o,n,i),za(r,o),console.log(v(`Set ${n} = ${JSON.stringify(i)}`)),nc(t,n,i)}}function rc(){let n=M(),e=ys(n),t=bs(e),r=Se(),o=Object.keys(r).filter(s=>r[s].public===!0).sort();if(o.length===0){console.log(se.default.gray("(no public settings registered)"));return}console.log(v("aide-memory \xB7 configurable settings")),console.log("");for(let s of o){let i=r[s],a=_s(t,s),c=a!==void 0,l=typeof i.value=="object"?JSON.stringify(i.value):String(i.value),u=c?typeof a=="object"?JSON.stringify(a):String(a):se.default.gray("(default)");if(console.log(se.default.bold(s)),console.log(` current: ${c?se.default.cyan(u):u}`),console.log(` default: ${se.default.gray(l)}`),i.description){let d=i.description.split(`
215
+ `).map(f=>` ${f}`).join(`
216
+ `);console.log(se.default.dim(d))}console.log("")}console.log(se.default.gray("Set a value: aide-memory config <key> <value> \u2022 Read: aide-memory config <key>"))}function nc(n,e,t){if(new Set(["memories.hideFromGrep"]).has(e)){let s=qt(n);for(let i of s)console.log(v(i))}if(e.startsWith("injection.")||e==="memories.softening.threshold")try{let s=oe(G(),n);for(let i of s)i.written&&console.log(v(`regenerated ${i.dest}`)),i.budgetWarning&&console.warn(v(i.budgetWarning))}catch(s){console.warn(v(`rules regen skipped: ${s.message}`))}}var Xt=g(J());K();var ie=g(require("path")),ee=g(require("fs")),oc={preferences:"preferences",technical:"technical",area_context:"area_context",guidelines:"guidelines"},ut=class{constructor(e){this.store=e,this.db=e.db;let t=e.memoriesPath;if(!t)throw new Error("MemorySync requires a store in file-per-memory mode (use { projectRoot } constructor)");this.memoriesDir=t}importFromFiles(){let e={imported:0,updated:0,removed:0,conflicts:[],errors:[]},t=this.collectJsonFiles(),r=new Set;for(let s of t)if(!this.isPersonalPreference(s))try{let i=ee.default.readFileSync(s,"utf-8"),a=JSON.parse(i);if(!this.isValidMemoryFile(a)){e.errors.push(`Malformed file: ${ie.default.relative(this.memoriesDir,s)}`);continue}r.add(a.uuid);let c=this.getByUuid(a.uuid);if(c){if(c.updated_at>a.updated_at){e.conflicts.push({uuid:a.uuid,reason:"local edits would be overwritten",localUpdatedAt:c.updated_at,incomingUpdatedAt:a.updated_at});continue}if(c.updated_at===a.updated_at)continue;this.updateFromFile(c.id,a),e.updated++}else this.insertFromFile(a),e.imported++}catch(i){let a=ie.default.relative(this.memoriesDir,s);e.errors.push(`Error reading ${a}: ${i instanceof Error?i.message:String(i)}`)}let o=this.getAllUuids();for(let s of o)if(!r.has(s.uuid)){if(s.layer==="preferences"&&s.shared===0)continue;this.deleteByUuid(s.uuid),e.removed++}return e}exportToFiles(){let e={imported:0,updated:0,removed:0,conflicts:[],errors:[]},t=this.store.list();for(let r of t)try{let o=this.getMemoryFilePath(r.uuid,r.layer,r.shared);if(ee.default.existsSync(o))continue;let s=ie.default.dirname(o);ee.default.existsSync(s)||ee.default.mkdirSync(s,{recursive:!0});let i={uuid:r.uuid,layer:r.layer,what:r.what,why:r.why,scope:r.scope,context_label:r.context_label,contributor:r.contributor,tags:r.tags,source:r.source,shared:r.shared,generated_by:r.generated_by,derived_from:r.derived_from,created_at:r.created_at,updated_at:r.updated_at},a=o+".tmp";ee.default.writeFileSync(a,JSON.stringify(i,null,2)+`
217
+ `,"utf-8"),ee.default.renameSync(a,o),e.imported++}catch(o){e.errors.push(`Error exporting ${r.uuid}: ${o instanceof Error?o.message:String(o)}`)}return e}syncFromGit(){let e={imported:0,updated:0,removed:0,conflicts:[],errors:[]},t=this.collectJsonFiles(),r=new Set;for(let s of t)if(!this.isPersonalPreference(s))try{let i=ee.default.readFileSync(s,"utf-8"),a=JSON.parse(i);if(!this.isValidMemoryFile(a)){e.errors.push(`Malformed file: ${ie.default.relative(this.memoriesDir,s)}`);continue}r.add(a.uuid);let c=this.getByUuid(a.uuid);c?a.updated_at>c.updated_at?(this.updateFromFile(c.id,a),e.updated++):a.updated_at<c.updated_at&&e.conflicts.push({uuid:a.uuid,reason:"local edits would be overwritten",localUpdatedAt:c.updated_at,incomingUpdatedAt:a.updated_at}):(this.insertFromFile(a),e.imported++)}catch(i){let a=ie.default.relative(this.memoriesDir,s);e.errors.push(`Error reading ${a}: ${i instanceof Error?i.message:String(i)}`)}let o=this.getAllUuids();for(let s of o)if(!r.has(s.uuid)){if(s.layer==="preferences"&&s.shared===0)continue;this.deleteByUuid(s.uuid),e.removed++}return e}getByUuid(e){return this.db.prepare("SELECT id, updated_at, layer, shared FROM memories WHERE uuid = ?").get(e)}getAllUuids(){return this.db.prepare("SELECT uuid, layer, shared FROM memories").all()}insertFromFile(e){this.db.prepare(`
204
218
  INSERT INTO memories (uuid, layer, what, why, scope, context_label, contributor,
205
219
  tags, source, shared, generated_by, derived_from, created_at, updated_at,
206
220
  recalled_count, last_recalled_at)
@@ -212,26 +226,26 @@ aide-memory v${m.latestVersion} is available (current: v${u}). Tell the user to
212
226
  generated_by = ?, derived_from = ?,
213
227
  created_at = ?, updated_at = ?
214
228
  WHERE id = ?
215
- `).run(t.layer,t.what,t.why??null,t.scope??null,t.context_label??null,t.contributor,JSON.stringify(t.tags??[]),t.source??"import",t.shared?1:0,t.generated_by?JSON.stringify(t.generated_by):null,t.derived_from?JSON.stringify(t.derived_from):null,t.created_at,t.updated_at,e)}deleteByUuid(e){this.db.prepare("DELETE FROM memories WHERE uuid = ?").run(e)}isPersonalPreference(e){return ie.default.relative(this.memoriesDir,e).replace(/\\/g,"/").startsWith("preferences/personal/")}isValidMemoryFile(e){return e&&typeof e=="object"&&typeof e.uuid=="string"&&typeof e.layer=="string"&&typeof e.what=="string"&&typeof e.contributor=="string"&&typeof e.created_at=="string"&&typeof e.updated_at=="string"}getMemoryFilePath(e,t,r){let o;return t==="preferences"?o=ie.default.join("preferences",r?"shared":"personal"):o=rc[t],ie.default.join(this.memoriesDir,o,`${e}.json`)}collectJsonFiles(){if(!Z.default.existsSync(this.memoriesDir))return[];let e=[],t=r=>{if(!Z.default.existsSync(r))return;let o=Z.default.readdirSync(r,{withFileTypes:!0});for(let s of o){let i=ie.default.join(r,s.name);s.isDirectory()?t(i):s.name.endsWith(".json")&&!s.name.endsWith(".tmp")&&e.push(i)}};return t(this.memoriesDir),e}};Re();ne();function ws(n,e,t=!1){let r=[];e.imported>0&&r.push(`${e.imported} ${t?"exported":"imported"}`),e.updated>0&&r.push(`${e.updated} updated`),e.removed>0&&r.push(`${e.removed} removed`),r.length>0?console.log(v(`${n} complete: ${r.join(", ")}.`)):console.log(Gt.default.gray(`${n}: everything up to date.`));for(let o of e.conflicts)console.log(Gt.default.yellow(` Conflict: memory ${o.uuid} has local edits newer than incoming file. Keeping newer version.`));for(let o of e.errors)console.log(Gt.default.yellow(` ${o}`))}function _s(){let n=M(),e=new A({projectRoot:n});try{let r=new ct(e).importFromFiles();if(ws("Import",r),r.imported>0||r.updated>0)try{oe(q(),n)}catch{}}finally{e.close()}}function Ss(){let n=M(),e=new A({projectRoot:n});try{let r=new ct(e).exportToFiles();ws("Export",r,!0)}finally{e.close()}}var Be=h(require("fs")),Xt=h(require("path")),Yt=h(V());function nc(n){let e=n.match(/^(\d+)\s*([smhd])$/);if(!e)throw new Error(`Invalid duration: ${n}. Use formats like "7d", "24h", "30m".`);let t=parseInt(e[1],10),r=e[2];return t*{s:1e3,m:6e4,h:36e5,d:864e5}[r]}function Es(n={}){let e=M(),t=Xt.default.join(e,".aide","cache");if(!Be.default.existsSync(t)){console.log(Yt.default.gray("No cache directory \u2014 nothing to clean."));return}let r=n.all?0:nc(n.olderThan||"7d"),o=Date.now()-r,s=["recalled-paths-","searched-queries-","correction-pending-","recalled-ids-"],i=Be.default.readdirSync(t),a=[];for(let c of i){if(!s.some(d=>c.startsWith(d)))continue;let l=Xt.default.join(t,c);Be.default.statSync(l).mtimeMs<o&&a.push(l)}if(a.length===0){console.log(Yt.default.gray("No stale tracking files found."));return}if(n.dryRun){console.log(v(`Would delete ${a.length} stale file(s):`));for(let c of a){let l=Be.default.statSync(c),u=Math.floor((Date.now()-l.mtimeMs)/36e5);console.log(Yt.default.gray(` ${Xt.default.basename(c)} (${u}h old)`))}return}for(let c of a)Be.default.unlinkSync(c);console.log(v(`Cleaned up ${a.length} stale tracking file(s).`))}var Yr=h(V());function vs(){console.log(Yr.default.yellow("Migration is not yet implemented. Coming soon.")),console.log(Yr.default.gray("This command will migrate from the legacy memory.db format."))}var Ae=h(V());ot();function ks(n){let e=process.cwd();if(n.reset){let r=require("path").join(e,".aide","config.json"),o=require("fs");o.existsSync(r)&&(o.unlinkSync(r),console.log(v("Config reset to factory defaults."))),n.force=!0}let t={updateRules:n.updateRules,force:n.force};qr(e,t).then(r=>{if(n.updateRules?console.log(v("Rules files updated.")):console.log(v("Project initialized for aide-memory.")),r.created.length>0){console.log(Ae.default.white(`
216
- Created:`));for(let o of r.created)console.log(v(` + ${o}`))}if(r.skipped.length>0){console.log(Ae.default.gray(`
217
- Skipped (already exists):`));for(let o of r.skipped)console.log(Ae.default.gray(` - ${o}`))}if(r.warnings.length>0){console.log(Ae.default.yellow(`
218
- Warnings:`));for(let o of r.warnings)console.log(Ae.default.yellow(` ! ${o}`))}}).catch(r=>{console.error(Ae.default.red(`Init failed: ${r.message}`)),process.exit(1)})}var z=h(require("fs")),we=h(require("path")),Ks=require("child_process");ne();async function oc(){return new Promise(n=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>e+=t),process.stdin.on("end",()=>n(e)),process.stdin.isTTY&&n("")})}async function xs(){let n=await oc();if(!n||!n.trim())return{};try{return JSON.parse(n)}catch{return{}}}function Os(n){let t=Le().translateOutput(n);t&&process.stdout.write(t)}function ue(n,e,t){Os({kind:"additionalContext",event:n,context:e,systemMessage:t})}function Ve(n,e,t){Os({kind:"block",reason:n,systemMessage:e,event:t})}ne();_t();var P=h(require("fs")),Ps=h(require("os")),U=h(require("path"));Rr();Y();var C=h(require("fs")),ye=h(require("path"));function Te(n){return ye.join(n,".aide","cache")}function We(n){let e=Te(n);try{C.mkdirSync(e,{recursive:!0})}catch{}return e}function Kt(n,e){return ye.join(Te(n),`recalled-paths-${e}.txt`)}function Rs(n,e){return ye.join(Te(n),`searched-queries-${e}.txt`)}function Kr(n,e){return ye.join(Te(n),`correction-pending-${e}.txt`)}function Cs(n,e){return ye.join(Te(n),`stop-count-${e}.txt`)}function As(n,e){return ye.join(Te(n),`stop-followup-pending-${e}.txt`)}function zr(n,e){let t=Kt(n,e);if(!C.existsSync(t))return[];try{let o=C.readFileSync(t,"utf8").split(`
219
- `).filter(i=>i.startsWith("ids|"));return o.length===0?[]:o[o.length-1].slice(4).split(",").map(i=>i.trim()).filter(Boolean)}catch{return[]}}function Qr(n,e,t){let r=Kt(n,e);if(!C.existsSync(r))return!1;try{return C.readFileSync(r,"utf8").split(`
220
- `).some(s=>s===`file|${t}`)}catch{return!1}}function lt(n,e,t,r){We(n);let o=Kt(n,e);try{C.appendFileSync(o,`${t}|${r}
221
- `)}catch{}}function Zr(n,e,t){We(n);let r=Kt(n,e),o=[],s=[];if(C.existsSync(r))try{let l=C.readFileSync(r,"utf8");for(let u of l.split(`
229
+ `).run(t.layer,t.what,t.why??null,t.scope??null,t.context_label??null,t.contributor,JSON.stringify(t.tags??[]),t.source??"import",t.shared?1:0,t.generated_by?JSON.stringify(t.generated_by):null,t.derived_from?JSON.stringify(t.derived_from):null,t.created_at,t.updated_at,e)}deleteByUuid(e){this.db.prepare("DELETE FROM memories WHERE uuid = ?").run(e)}isPersonalPreference(e){return ie.default.relative(this.memoriesDir,e).replace(/\\/g,"/").startsWith("preferences/personal/")}isValidMemoryFile(e){return e&&typeof e=="object"&&typeof e.uuid=="string"&&typeof e.layer=="string"&&typeof e.what=="string"&&typeof e.contributor=="string"&&typeof e.created_at=="string"&&typeof e.updated_at=="string"}getMemoryFilePath(e,t,r){let o;return t==="preferences"?o=ie.default.join("preferences",r?"shared":"personal"):o=oc[t],ie.default.join(this.memoriesDir,o,`${e}.json`)}collectJsonFiles(){if(!ee.default.existsSync(this.memoriesDir))return[];let e=[],t=r=>{if(!ee.default.existsSync(r))return;let o=ee.default.readdirSync(r,{withFileTypes:!0});for(let s of o){let i=ie.default.join(r,s.name);s.isDirectory()?t(i):s.name.endsWith(".json")&&!s.name.endsWith(".tmp")&&e.push(i)}};return t(this.memoriesDir),e}};Ce();ne();function Ss(n,e,t=!1){let r=[];e.imported>0&&r.push(`${e.imported} ${t?"exported":"imported"}`),e.updated>0&&r.push(`${e.updated} updated`),e.removed>0&&r.push(`${e.removed} removed`),r.length>0?console.log(v(`${n} complete: ${r.join(", ")}.`)):console.log(Xt.default.gray(`${n}: everything up to date.`));for(let o of e.conflicts)console.log(Xt.default.yellow(` Conflict: memory ${o.uuid} has local edits newer than incoming file. Keeping newer version.`));for(let o of e.errors)console.log(Xt.default.yellow(` ${o}`))}function Es(){let n=M(),e=new A({projectRoot:n});try{let r=new ut(e).importFromFiles();if(Ss("Import",r),r.imported>0||r.updated>0)try{oe(G(),n)}catch{}}finally{e.close()}}function vs(){let n=M(),e=new A({projectRoot:n});try{let r=new ut(e).exportToFiles();Ss("Export",r,!0)}finally{e.close()}}var We=g(require("fs")),Yt=g(require("path")),Kt=g(J());function sc(n){let e=n.match(/^(\d+)\s*([smhd])$/);if(!e)throw new Error(`Invalid duration: ${n}. Use formats like "7d", "24h", "30m".`);let t=parseInt(e[1],10),r=e[2];return t*{s:1e3,m:6e4,h:36e5,d:864e5}[r]}function ks(n={}){let e=M(),t=Yt.default.join(e,".aide","cache");if(!We.default.existsSync(t)){console.log(Kt.default.gray("No cache directory \u2014 nothing to clean."));return}let r=n.all?0:sc(n.olderThan||"7d"),o=Date.now()-r,s=["recalled-paths-","searched-queries-","correction-pending-","recalled-ids-"],i=We.default.readdirSync(t),a=[];for(let c of i){if(!s.some(d=>c.startsWith(d)))continue;let l=Yt.default.join(t,c);We.default.statSync(l).mtimeMs<o&&a.push(l)}if(a.length===0){console.log(Kt.default.gray("No stale tracking files found."));return}if(n.dryRun){console.log(v(`Would delete ${a.length} stale file(s):`));for(let c of a){let l=We.default.statSync(c),u=Math.floor((Date.now()-l.mtimeMs)/36e5);console.log(Kt.default.gray(` ${Yt.default.basename(c)} (${u}h old)`))}return}for(let c of a)We.default.unlinkSync(c);console.log(v(`Cleaned up ${a.length} stale tracking file(s).`))}var Kr=g(J());function xs(){console.log(Kr.default.yellow("Migration is not yet implemented. Coming soon.")),console.log(Kr.default.gray("This command will migrate from the legacy memory.db format."))}var Te=g(J());it();function Os(n){let e=process.cwd();if(n.reset){let r=require("path").join(e,".aide","config.json"),o=require("fs");o.existsSync(r)&&(o.unlinkSync(r),console.log(v("Config reset to factory defaults."))),n.force=!0}let t={updateRules:n.updateRules,force:n.force};Gr(e,t).then(r=>{if(n.updateRules?console.log(v("Rules files updated.")):console.log(v("Project initialized for aide-memory.")),r.created.length>0){console.log(Te.default.white(`
230
+ Created:`));for(let o of r.created)console.log(v(` + ${o}`))}if(r.skipped.length>0){console.log(Te.default.gray(`
231
+ Skipped (already exists):`));for(let o of r.skipped)console.log(Te.default.gray(` - ${o}`))}if(r.warnings.length>0){console.log(Te.default.yellow(`
232
+ Warnings:`));for(let o of r.warnings)console.log(Te.default.yellow(` ! ${o}`))}}).catch(r=>{console.error(Te.default.red(`Init failed: ${r.message}`)),process.exit(1)})}var Q=g(require("fs")),_e=g(require("path")),Qs=require("child_process");ne();async function ic(){return new Promise(n=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>e+=t),process.stdin.on("end",()=>n(e)),process.stdin.isTTY&&n("")})}async function Rs(){let n=await ic();if(!n||!n.trim())return{};try{return JSON.parse(n)}catch{return{}}}function Cs(n){let t=Re().translateOutput(n);t&&process.stdout.write(t)}function de(n,e,t){Cs({kind:"additionalContext",event:n,context:e,systemMessage:t})}function Je(n,e,t){Cs({kind:"block",reason:n,systemMessage:e,event:t})}ne();Et();var L=g(require("fs")),Hs=g(require("os")),V=g(require("path"));Cr();K();var C=g(require("fs")),ye=g(require("path"));function Me(n){return ye.join(n,".aide","cache")}function qe(n){let e=Me(n);try{C.mkdirSync(e,{recursive:!0})}catch{}return e}function zt(n,e){return ye.join(Me(n),`recalled-paths-${e}.txt`)}function As(n,e){return ye.join(Me(n),`searched-queries-${e}.txt`)}function zr(n,e){return ye.join(Me(n),`correction-pending-${e}.txt`)}function Ts(n,e){return ye.join(Me(n),`stop-count-${e}.txt`)}function Ms(n,e){return ye.join(Me(n),`stop-followup-pending-${e}.txt`)}function Qr(n,e){let t=zt(n,e);if(!C.existsSync(t))return[];try{let o=C.readFileSync(t,"utf8").split(`
233
+ `).filter(i=>i.startsWith("ids|"));return o.length===0?[]:o[o.length-1].slice(4).split(",").map(i=>i.trim()).filter(Boolean)}catch{return[]}}function Zr(n,e,t){let r=zt(n,e);if(!C.existsSync(r))return!1;try{return C.readFileSync(r,"utf8").split(`
234
+ `).some(s=>s===`file|${t}`)}catch{return!1}}function dt(n,e,t,r){qe(n);let o=zt(n,e);try{C.appendFileSync(o,`${t}|${r}
235
+ `)}catch{}}function en(n,e,t){qe(n);let r=zt(n,e),o=[],s=[];if(C.existsSync(r))try{let l=C.readFileSync(r,"utf8");for(let u of l.split(`
222
236
  `))u.startsWith("ids|")?s=u.slice(4).split(",").map(d=>d.trim()).filter(Boolean):u.length>0&&o.push(u)}catch{}let i=new Set([...s,...t.map(l=>l.trim()).filter(Boolean)]),a=Array.from(i).sort((l,u)=>Number(l)-Number(u)),c=o.join(`
223
237
  `)+(o.length>0?`
224
238
  `:"")+`ids|${a.join(",")}
225
- `;try{C.writeFileSync(r,c)}catch{}}function Ts(n,e,t){let r=Rs(n,e);if(!C.existsSync(r))return!1;try{return C.readFileSync(r,"utf8").split(`
226
- `).some(s=>s===t)}catch{return!1}}function Ms(n,e,t){We(n);let r=Rs(n,e);try{C.appendFileSync(r,`${t}
227
- `)}catch{}}function en(n,e){let t=Te(n),r=[`recalled-paths-${e}.txt`,`searched-queries-${e}.txt`,`correction-pending-${e}.txt`,`compact-pending-${e}.txt`,`stop-count-${e}.txt`,`stop-followup-pending-${e}.txt`];for(let o of r)try{C.unlinkSync(ye.join(t,o))}catch{}}function Ns(n,e){let t=Cs(n,e);if(!C.existsSync(t))return 0;try{let r=C.readFileSync(t,"utf8").trim(),o=parseInt(r,10);return Number.isFinite(o)?o:0}catch{return 0}}function $s(n,e,t){We(n);try{C.writeFileSync(Cs(n,e),String(t))}catch{}}function tn(n,e){We(n);try{C.writeFileSync(As(n,e),"1")}catch{}}function js(n,e){let t=As(n,e);if(!C.existsSync(t))return!1;try{C.unlinkSync(t)}catch{}return!0}function Is(n,e){return C.existsSync(Kr(n,e))}function Ds(n,e,t){We(n);try{C.writeFileSync(Kr(n,e),t)}catch{}}function rn(n,e){try{C.unlinkSync(Kr(n,e))}catch{}}function nn(n){return(n||"").toLowerCase().trim()}ne();var ut=h(require("fs")),be=h(require("path"));Y();var on=new Set(["the","this","that","from","with","into","for","and","but","not","all","are","was","were","been","have","has","had","will","can","should","would","could","may","must","use","used","using","also","when","what","how","why","who","which","where","then","than","each","every","some","any","does","done","only","just","more","most","very","same","other","after","before","about","between","IMPORTANT","COMPLETE","DONE","TODO","NOTE","PENDING","NEW","OLD","TRUE","FALSE","YES","NO","NEVER","ALWAYS"]);function Fs(n){let e={},t=n.match(/[a-zA-Z]+-[a-zA-Z]+(?:-[a-zA-Z]+)*/g)||[];for(let o of t){let s=o.toLowerCase();on.has(s)||(e[s]=(e[s]||0)+1)}let r=n.split(/[.\n]+/);for(let o of r){let s=o.trim().split(/\s+/).slice(1);for(let i of s)if(/^[A-Z][a-z]{2,}/.test(i)){let a=i.replace(/[^a-zA-Z]/g,"");a.length>2&&!on.has(a)&&!on.has(a.toUpperCase())&&(e[a]=(e[a]||0)+1)}}return e}function sn(n,e){let t=be.join(n,".aide");if(!ut.existsSync(t))return null;let r=e.endsWith("/"),o=n,s=e;try{o=ut.realpathSync(n)}catch{}try{s=ut.realpathSync(e)}catch{}let i=e;be.isAbsolute(s)&&s.startsWith(o)&&(i=be.relative(o,s)),r&&!i.endsWith("/")&&(i=i+"/");let a=new A({projectRoot:n});try{let c=a.list(),l=Co(c,i,n),u=0;for(let O of c)(!O.scope||O.scope==="project")&&u++;let d=l.memories;if(d.length===0)return null;let m=l.layers,w=l.count,g=l.ids,_=0,S=0;for(let O of d){let B=O.scope||"";B.endsWith("/")||B.endsWith("/**")||B.endsWith("/*")?S++:_++}let p=c.length,x={},f={};for(let O of d){let B=[O.what,O.why||"",O.context_label||""].join(" "),pe=Fs(B);for(let[Me,zt]of Object.entries(pe))x[Me]=(x[Me]||0)+zt;f[O.layer]||(f[O.layer]=""),f[O.layer]+=" "+B}let E=Object.entries(x).sort((O,B)=>B[1]-O[1]).slice(0,8).map(([O])=>O),T=new Set(E),k={};for(let[O,B]of Object.entries(f)){let pe=Fs(B);k[O]=Object.entries(pe).sort((Me,zt)=>zt[1]-Me[1]).slice(0,2).map(([Me])=>Me)}let re=[];for(let[,O]of Object.entries(k))if(!O.some(pe=>T.has(pe))&&O.length>0)for(let pe of O)!T.has(pe)&&re.length<2&&re.push(pe);let J=[...E,...re],de=null;if(i&&!i.endsWith("/")&&i.includes("/")){let O=be.dirname(i);O&&O!=="."&&(de=O+"/")}return{count:d.length,scoped_count:w,scoped_ids:g,project_count:u,total_memories:p,layers:m,file_count:_,dir_count:S,topics:J,per_layer_topics:k,suggested_path:de}}finally{a.close()}}Tr();function ee(n){return n.cwd?n.cwd:process.cwd()}function te(n){return n.session_id||"default"}var sc=xt;function Je(n){return K(n,"hooks.visible")!==!1}var ic="\x1B[38;2;0;194;203m",ac="\x1B[0m",ae=`${ic}aide-memory \xB7 ${ac}`;function K(n,e){let t=sc[e];if(!t)return;let r=t.value;if(t.public!==!0)return r;let o=U.join(n,".aide","config.json");if(!P.existsSync(o))return r;let s;try{s=JSON.parse(P.readFileSync(o,"utf8"))}catch{return r}let i=e.split("."),a=s;for(let c of i){if(a==null||typeof a!="object"||Array.isArray(a)||!Object.prototype.hasOwnProperty.call(a,c))return r;a=a[c]}return a}async function Ls(n){let e=n.tool_input?.file_path;if(!e||!P.existsSync(e))return;if(e.includes(".aide/memories/")){ue("PreToolUse","memory_file_direct_read: You are reading a raw memory file. Use aide_recall for structured context.");return}let t=ee(n),r=te(n),o=U.isAbsolute(e)?e:U.resolve(t,e),s=K(t,"hooks.read.maxBlocks");if(s===0||s==="0")return;let i=sn(t,o);if(!i||i.count===0||i.scoped_count===0||i.scoped_ids.length===0)return;let a=zr(t,r),c=new Set(a.map(String)),l=[],u=0;for(let f of i.scoped_ids)c.has(String(f))?u++:l.push(String(f));let d=Qr(t,r,o);if(lt(t,r,"file",o),u===i.scoped_ids.length)return;let m=i.scoped_ids.length-u,w=Number(K(t,"memories.softening.threshold")??10),g=i.total_memories<w,_;if(u===0){let f=Object.entries(i.layers).map(([T,k])=>`${k} ${T}`).join(", "),E=(i.topics||[]).join(", ");E?_=`${i.scoped_count} memories for ${o} (${f}) \u2014 topics: ${E}. Call aide_recall({paths: ['${o}']}).`:_=`${i.scoped_count} memories for ${o}. Call aide_recall({paths: ['${o}']}).`}else _=`${m} memories for ${o} not yet recalled. Call aide_recall({ids: [${l.join(",")}]}).`;let S=Je(t),p=S?`${ae}prompting aide_recall \u2014 additional scoped memories not yet recalled`:void 0,x=S?`${ae}prompting aide_recall \u2014 scoped memories not recalled yet (expected flow)`:void 0;g||d?ue("PreToolUse",_,p):Ve(_,x)}async function Hs(n){let e=n.tool_input?.file_path;if(!e||!P.existsSync(e))return;let t=ee(n),r=te(n),o=U.isAbsolute(e)?e:U.resolve(t,e),s=K(t,"hooks.edit.maxBlocks");if(s===0||s==="0")return;let i=sn(t,o);if(!i||i.count===0||i.scoped_count===0||i.scoped_ids.length===0)return;let a=zr(t,r),c=new Set(a.map(String)),l=[],u=0;for(let f of i.scoped_ids)c.has(String(f))?u++:l.push(String(f));let d=Qr(t,r,o);if(lt(t,r,"file",o),u===i.scoped_ids.length)return;let m=i.scoped_ids.length-u,w=Number(K(t,"memories.softening.threshold")??10),g=i.total_memories<w,_;u===0?_=`${i.scoped_count} memories for ${o}. Call aide_recall({paths: ['${o}']}) before editing.`:_=`${m} memories for ${o} not yet recalled. Call aide_recall({ids: [${l.join(",")}]}) before editing.`;let S=Je(t),p=S?`${ae}prompting aide_recall \u2014 additional scoped memories not yet recalled`:void 0,x=S?`${ae}prompting aide_recall \u2014 scoped memories not recalled yet (expected flow)`:void 0;g||d?ue("PreToolUse",_,p):Ve(_,x)}async function Us(n){let e=n.tool_input?.pattern;if(!e)return;let t=ee(n),r=te(n),o=K(t,"hooks.search.mode");if(o==="off")return;let s=U.join(t,".aide");if(!P.existsSync(s))return;let i=0,a=[],c=new A({projectRoot:t});try{let _=c.list(),S=e.toLowerCase(),p=_.filter(x=>{let f=(x.what||"").toLowerCase(),E=(x.why||"").toLowerCase();return f.includes(S)||E.includes(S)});if(i=p.length,i===0)return;a=p.slice(0,3).map(x=>{let f=x.what||"";return f.length>30?f.slice(0,30)+"...":f})}finally{c.close()}if(i===0)return;let l=a.join(", "),u=nn(e),d=Ts(t,r,u),w=Je(t)?`${ae}prompting aide_search for "${e}" \u2014 ${i} matching ${i===1?"memory":"memories"}`:void 0;if(d){ue("PreToolUse",`${i} aide memories match '${e}' (${l}). Call aide_search({keyword: '${e}'}).`,w);return}let g=`${i} aide memories match '${e}' (${l}). Call aide_search({keyword: '${e}'}).`;o==="block"?Ve(g,w):ue("PreToolUse",g,w)}var cc=new RegExp("(no[, ]+(don'?t|do not|can'?t|won'?t|isn'?t|wasn'?t|weren'?t|shouldn'?t|didn'?t|couldn'?t|wouldn'?t|mustn'?t|haven'?t|hadn'?t|aren'?t|use|instead|that'?s wrong)|no[, ]+(we|I|it|you)\\s+(use|go with|prefer|want|need|should)|no[, ]+try\\s+.+\\s+instead|actually[, ]|wrong[, ]|not like that|use .+ instead|don'?t use|stop using|I told you|I said)","i"),lc=new RegExp("(let'?s (use|go with)|we should|go with|the approach is|decided to|decision is|we'?re going|from now on)","i"),uc=new RegExp("(I prefer|always use|never use|I like|my style is|I want you to|don'?t ever|make sure to always|I always)","i"),dc=new RegExp("^(no I mean (the|that|this|it|a|an|one|those)\\s|no (but|actually I|I think|not sure)|I don'?t (think|know|get|understand)|what I mean)","i"),pc=new RegExp("(correction (prompt|regex|pattern|hook|flag|detection)|matched correction|hooks?\\.correction|correction[- ]pending)","i");function fc(n){let e=n.replace(/```[\s\S]*?```/g,"");return e=e.replace(/`[^`\n]*`/g,""),e=e.split(`
239
+ `;try{C.writeFileSync(r,c)}catch{}}function Ns(n,e,t){let r=As(n,e);if(!C.existsSync(r))return!1;try{return C.readFileSync(r,"utf8").split(`
240
+ `).some(s=>s===t)}catch{return!1}}function $s(n,e,t){qe(n);let r=As(n,e);try{C.appendFileSync(r,`${t}
241
+ `)}catch{}}function tn(n,e){let t=Me(n),r=[`recalled-paths-${e}.txt`,`searched-queries-${e}.txt`,`correction-pending-${e}.txt`,`compact-pending-${e}.txt`,`stop-count-${e}.txt`,`stop-followup-pending-${e}.txt`];for(let o of r)try{C.unlinkSync(ye.join(t,o))}catch{}}function Is(n,e){let t=Ts(n,e);if(!C.existsSync(t))return 0;try{let r=C.readFileSync(t,"utf8").trim(),o=parseInt(r,10);return Number.isFinite(o)?o:0}catch{return 0}}function js(n,e,t){qe(n);try{C.writeFileSync(Ts(n,e),String(t))}catch{}}function rn(n,e){qe(n);try{C.writeFileSync(Ms(n,e),"1")}catch{}}function Ps(n,e){let t=Ms(n,e);if(!C.existsSync(t))return!1;try{C.unlinkSync(t)}catch{}return!0}function Ds(n,e){return C.existsSync(zr(n,e))}function Fs(n,e,t){qe(n);try{C.writeFileSync(zr(n,e),t)}catch{}}function nn(n,e){try{C.unlinkSync(zr(n,e))}catch{}}function on(n){return(n||"").toLowerCase().trim()}ne();var pt=g(require("fs")),be=g(require("path"));K();var sn=new Set(["the","this","that","from","with","into","for","and","but","not","all","are","was","were","been","have","has","had","will","can","should","would","could","may","must","use","used","using","also","when","what","how","why","who","which","where","then","than","each","every","some","any","does","done","only","just","more","most","very","same","other","after","before","about","between","IMPORTANT","COMPLETE","DONE","TODO","NOTE","PENDING","NEW","OLD","TRUE","FALSE","YES","NO","NEVER","ALWAYS"]);function Ls(n){let e={},t=n.match(/[a-zA-Z]+-[a-zA-Z]+(?:-[a-zA-Z]+)*/g)||[];for(let o of t){let s=o.toLowerCase();sn.has(s)||(e[s]=(e[s]||0)+1)}let r=n.split(/[.\n]+/);for(let o of r){let s=o.trim().split(/\s+/).slice(1);for(let i of s)if(/^[A-Z][a-z]{2,}/.test(i)){let a=i.replace(/[^a-zA-Z]/g,"");a.length>2&&!sn.has(a)&&!sn.has(a.toUpperCase())&&(e[a]=(e[a]||0)+1)}}return e}function an(n,e){let t=be.join(n,".aide");if(!pt.existsSync(t))return null;let r=e.endsWith("/"),o=n,s=e;try{o=pt.realpathSync(n)}catch{}try{s=pt.realpathSync(e)}catch{}let i=e;be.isAbsolute(s)&&s.startsWith(o)&&(i=be.relative(o,s)),r&&!i.endsWith("/")&&(i=i+"/");let a=new A({projectRoot:n});try{let c=a.list(),l=Ao(c,i,n),u=0;for(let x of c)(!x.scope||x.scope==="project")&&u++;let d=l.memories;if(d.length===0)return null;let f=l.layers,y=l.count,h=l.ids,w=0,E=0;for(let x of d){let W=x.scope||"";W.endsWith("/")||W.endsWith("/**")||W.endsWith("/*")?E++:w++}let p=c.length,R={},m={};for(let x of d){let W=[x.what,x.why||"",x.context_label||""].join(" "),pe=Ls(W);for(let[Ne,Qt]of Object.entries(pe))R[Ne]=(R[Ne]||0)+Qt;m[x.layer]||(m[x.layer]=""),m[x.layer]+=" "+W}let S=Object.entries(R).sort((x,W)=>W[1]-x[1]).slice(0,8).map(([x])=>x),j=new Set(S),k={};for(let[x,W]of Object.entries(m)){let pe=Ls(W);k[x]=Object.entries(pe).sort((Ne,Qt)=>Qt[1]-Ne[1]).slice(0,2).map(([Ne])=>Ne)}let H=[];for(let[,x]of Object.entries(k))if(!x.some(pe=>j.has(pe))&&x.length>0)for(let pe of x)!j.has(pe)&&H.length<2&&H.push(pe);let I=[...S,...H],ce=null;if(i&&!i.endsWith("/")&&i.includes("/")){let x=be.dirname(i);x&&x!=="."&&(ce=x+"/")}return{count:d.length,scoped_count:y,scoped_ids:h,project_count:u,total_memories:p,layers:f,file_count:w,dir_count:E,topics:I,per_layer_topics:k,suggested_path:ce}}finally{a.close()}}Mr();function te(n){return n.cwd?n.cwd:process.cwd()}function re(n){return n.session_id||"default"}var ac=Rt;function Ge(n){return z(n,"hooks.visible")!==!1}var cc="\x1B[38;2;0;194;203m",lc="\x1B[0m",ae=`${cc}aide-memory \xB7 ${lc}`;function z(n,e){let t=ac[e];if(!t)return;let r=t.value;if(t.public!==!0)return r;let o=V.join(n,".aide","config.json");if(!L.existsSync(o))return r;let s;try{s=JSON.parse(L.readFileSync(o,"utf8"))}catch{return r}let i=e.split("."),a=s;for(let c of i){if(a==null||typeof a!="object"||Array.isArray(a)||!Object.prototype.hasOwnProperty.call(a,c))return r;a=a[c]}return a}async function Us(n){let e=n.tool_input?.file_path;if(!e||!L.existsSync(e))return;if(e.includes(".aide/memories/")){de("PreToolUse","memory_file_direct_read: You are reading a raw memory file. Use aide_recall for structured context.");return}let t=te(n),r=re(n),o=V.isAbsolute(e)?e:V.resolve(t,e),s=z(t,"hooks.read.maxBlocks");if(s===0||s==="0")return;let i=an(t,o);if(!i||i.count===0||i.scoped_count===0||i.scoped_ids.length===0)return;let a=Qr(t,r),c=new Set(a.map(String)),l=[],u=0;for(let m of i.scoped_ids)c.has(String(m))?u++:l.push(String(m));let d=Zr(t,r,o);if(dt(t,r,"file",o),u===i.scoped_ids.length)return;let f=i.scoped_ids.length-u,y=Number(z(t,"memories.softening.threshold")??10),h=i.total_memories<y,w;if(u===0){let m=Object.entries(i.layers).map(([j,k])=>`${k} ${j}`).join(", "),S=(i.topics||[]).join(", ");S?w=`${i.scoped_count} memories for ${o} (${m}) \u2014 topics: ${S}. Call aide_recall({paths: ['${o}']}).`:w=`${i.scoped_count} memories for ${o}. Call aide_recall({paths: ['${o}']}).`}else w=`${f} memories for ${o} not yet recalled. Call aide_recall({ids: [${l.join(",")}]}).`;let E=Ge(t),p=E?`${ae}prompting aide_recall \u2014 additional scoped memories not yet recalled`:void 0,R=E?`${ae}prompting aide_recall \u2014 scoped memories not recalled yet (expected flow)`:void 0;h||d?de("PreToolUse",w,p):Je(w,R)}async function Bs(n){let e=n.tool_input?.file_path;if(!e||!L.existsSync(e))return;let t=te(n),r=re(n),o=V.isAbsolute(e)?e:V.resolve(t,e),s=z(t,"hooks.edit.maxBlocks");if(s===0||s==="0")return;let i=an(t,o);if(!i||i.count===0||i.scoped_count===0||i.scoped_ids.length===0)return;let a=Qr(t,r),c=new Set(a.map(String)),l=[],u=0;for(let m of i.scoped_ids)c.has(String(m))?u++:l.push(String(m));let d=Zr(t,r,o);if(dt(t,r,"file",o),u===i.scoped_ids.length)return;let f=i.scoped_ids.length-u,y=Number(z(t,"memories.softening.threshold")??10),h=i.total_memories<y,w;u===0?w=`${i.scoped_count} memories for ${o}. Call aide_recall({paths: ['${o}']}) before editing.`:w=`${f} memories for ${o} not yet recalled. Call aide_recall({ids: [${l.join(",")}]}) before editing.`;let E=Ge(t),p=E?`${ae}prompting aide_recall \u2014 additional scoped memories not yet recalled`:void 0,R=E?`${ae}prompting aide_recall \u2014 scoped memories not recalled yet (expected flow)`:void 0;h||d?de("PreToolUse",w,p):Je(w,R)}async function Vs(n){let e=n.tool_input?.pattern;if(!e)return;let t=te(n),r=re(n),o=z(t,"hooks.search.mode");if(o==="off")return;let s=V.join(t,".aide");if(!L.existsSync(s))return;let i=0,a=[],c=new A({projectRoot:t});try{let w=c.list(),E=e.toLowerCase(),p=w.filter(R=>{let m=(R.what||"").toLowerCase(),S=(R.why||"").toLowerCase();return m.includes(E)||S.includes(E)});if(i=p.length,i===0)return;a=p.slice(0,3).map(R=>{let m=R.what||"";return m.length>30?m.slice(0,30)+"...":m})}finally{c.close()}if(i===0)return;let l=a.join(", "),u=on(e),d=Ns(t,r,u),y=Ge(t)?`${ae}prompting aide_search for "${e}" \u2014 ${i} matching ${i===1?"memory":"memories"}`:void 0;if(d){de("PreToolUse",`${i} aide memories match '${e}' (${l}). Call aide_search({keyword: '${e}'}).`,y);return}let h=`${i} aide memories match '${e}' (${l}). Call aide_search({keyword: '${e}'}).`;o==="block"?Je(h,y):de("PreToolUse",h,y)}var uc=new RegExp("(no[, ]+(don'?t|do not|can'?t|won'?t|isn'?t|wasn'?t|weren'?t|shouldn'?t|didn'?t|couldn'?t|wouldn'?t|mustn'?t|haven'?t|hadn'?t|aren'?t|use|instead|that'?s wrong)|no[, ]+(we|I|it|you)\\s+(use|go with|prefer|want|need|should)|no[, ]+try\\s+.+\\s+instead|actually[, ]|wrong[, ]|not like that|use .+ instead|don'?t use|stop using|I told you|I said)","i"),dc=new RegExp("(let'?s (use|go with)|we should|go with|the approach is|decided to|decision is|we'?re going|from now on)","i"),pc=new RegExp("(I prefer|always use|never use|I like|my style is|I want you to|don'?t ever|make sure to always|I always)","i"),mc=new RegExp("^(no I mean (the|that|this|it|a|an|one|those)\\s|no (but|actually I|I think|not sure)|I don'?t (think|know|get|understand)|what I mean)","i"),fc=new RegExp("(correction (prompt|regex|pattern|hook|flag|detection)|matched correction|hooks?\\.correction|correction[- ]pending)","i");function hc(n){let e=n.replace(/```[\s\S]*?```/g,"");return e=e.replace(/`[^`\n]*`/g,""),e=e.split(`
228
242
  `).filter(t=>!/^\s*["'`]/.test(t)).join(`
229
- `),e}var mc="Your prompt may contain a correction or convention worth persisting. If something here applies to future work in this project \u2014 across preferences (how you work), technical (stack facts, why-decisions), area_context (decisions for this code area), or guidelines (team rules) \u2014 call aide_remember on the matching layer. Otherwise respond as normal.";async function Bs(n){let e=n.prompt||"";if(!e||e.trim().split(/\s+/).filter(Boolean).length<3||dc.test(e)||pc.test(e))return;let r=ee(n),o=te(n);if(K(r,"hooks.correction.enabled")===!1)return;let i=fc(e),a=null;if(cc.test(i)?a="correction":lc.test(i)?a="decision":uc.test(i)&&(a="preference"),!a)return;let l=Je(r)?`${ae}possible ${a} detected \u2014 consider aide_remember`:void 0;ue("UserPromptSubmit",mc,l);let u=K(r,"hooks.correction.escalate");(u==="soft"||u==="block")&&Ds(r,o,a)}function hc(n){return n?typeof n=="string"?n:Array.isArray(n)?n.map(e=>typeof e=="object"&&e?.text?e.text:"").join(`
230
- `):typeof n=="object"&&n.text?n.text:"":""}async function Vs(n){let e=hc(n.tool_response);if(!e)return;let t=ee(n),r=te(n),o=e.match(/\[(\d+)\]/g)||[],s=Array.from(new Set(o.map(i=>i.slice(1,-1))));s.length!==0&&Zr(t,r,s)}var gc="Anything from this turn worth persisting for future sessions in this project? Could touch preferences, technical, area_context, or guidelines. If yes, call aide_remember on the matching layer. Otherwise stop.",yc="A correction or convention from this turn was detected but no memory was stored. If it applies to future work \u2014 preferences, technical, area_context, or guidelines \u2014 call aide_remember on the matching layer. Otherwise stop.";async function Ws(n){if(n.stop_hook_active)return;let e=ee(n),t=te(n),r=Le().id==="cursor";if(r&&js(e,t))return;let s=Ns(e,t)+1;$s(e,t,s);let i=Je(e),a=K(e,"hooks.correction.escalate"),c=K(e,"hooks.stop.mode");if(Is(e,t)&&(rn(e,t),a==="block")){let m=i?`${ae}correction from this turn not yet stored \u2014 prompting aide_remember`:void 0;r&&tn(e,t),Ve(yc,m,"stop");return}if(c==="off")return;let l=K(e,"hooks.stop.schedule")||[],u=!1;if(!Array.isArray(l)||l.length===0)s%5===0&&(u=!0);else{let m=0,w=!1;for(let g of l){let _=g.every??5;g.until===void 0||g.until===null?w||((s-m)%_===0&&(u=!0),w=!0):s<=g.until&&!w&&((s-m)%_===0&&(u=!0),w=!0),g.until!==void 0&&g.until!==null&&(m=g.until)}}if(!u)return;let d=i?`${ae}checkpoint \u2014 anything worth remembering?`:void 0;r&&tn(e,t),Ve(gc,d,"stop")}async function Js(n){let e=ee(n),t=te(n);K(e,"hooks.precompact.mode")!=="off"&&en(e,t)}async function qs(n){let e=ee(n),t=te(n),r=U.join(e,".aide");if(!P.existsSync(r))return;try{let _=U.join(e,".mcp.json");if(P.existsSync(_)){let p=JSON.parse(P.readFileSync(_,"utf8"))?.mcpServers?.["aide-memory"]?.args?.[0];if(p&&!P.existsSync(p)){let x=`aide-memory: MCP server path not found (${p}). This can happen after a Node version change or cache clean. Fix: run "npx aide-memory init" or "npm install -g aide-memory && aide-memory init"`;process.stderr.write(`[AIDE_HEALTH] ${x}
231
- `),ue("SessionStart",x);return}}}catch{}let o="",s="";try{let{findPackageRoot:_}=($t(),Zt(No)),S=_();if(!P.existsSync(U.resolve(S,"src","cli"))){let p=U.join(S,"package.json"),x=JSON.parse(P.readFileSync(p,"utf8")).version,f=U.join(Ps.homedir(),".aide","update-check.json");if(P.existsSync(f)){let E=JSON.parse(P.readFileSync(f,"utf8"));if(E.latestVersion&&E.latestVersion!==x){let T=x.replace(/^v/,"").split(".").map(Number),k=E.latestVersion.replace(/^v/,"").split(".").map(Number);(k[0]>T[0]||k[0]===T[0]&&k[1]>T[1]||k[0]===T[0]&&k[1]===T[1]&&k[2]>T[2])&&(o=`aide-memory v${E.latestVersion} is available (current: v${x}). Run \`npm update -g aide-memory\` to upgrade.`,s=`${ae}update available: v${E.latestVersion}`)}}}}catch{}let i=n.source;if(i==="resume")return;(i==="clear"||i==="compact")&&en(e,t);let a=new A({projectRoot:e}),c="",l=[];try{let _=Mt(e,a);c=_.content,l=_.injectedIds}finally{a.close()}if(!c&&!o)return;l.length>0&&Zr(e,t,l.map(String));let u=Je(e),d=l.length,m=[];u&&d>0&&m.push(`${ae}injected ${d} ${d===1?"memory":"memories"} at session start`),s&&m.push(s);let w=m.length>0?m.join(`
232
- `):void 0,g=o?`${o}
243
+ `),e}var gc="Your prompt may contain a correction or convention worth persisting. If something here applies to future work in this project \u2014 across preferences (how you work), technical (stack facts, why-decisions), area_context (decisions for this code area), or guidelines (team rules) \u2014 call aide_remember on the matching layer. Otherwise respond as normal.";async function Ws(n){let e=n.prompt||"";if(!e||e.trim().split(/\s+/).filter(Boolean).length<3||mc.test(e)||fc.test(e))return;let r=te(n),o=re(n);if(z(r,"hooks.correction.enabled")===!1)return;let i=hc(e),a=null;if(uc.test(i)?a="correction":dc.test(i)?a="decision":pc.test(i)&&(a="preference"),!a)return;let l=Ge(r)?`${ae}possible ${a} detected \u2014 consider aide_remember`:void 0;de("UserPromptSubmit",gc,l);let u=z(r,"hooks.correction.escalate");(u==="soft"||u==="block")&&Fs(r,o,a)}function yc(n){return n?typeof n=="string"?n:Array.isArray(n)?n.map(e=>typeof e=="object"&&e?.text?e.text:"").join(`
244
+ `):typeof n=="object"&&n.text?n.text:"":""}async function Js(n){let e=yc(n.tool_response);if(!e)return;let t=te(n),r=re(n),o=e.match(/\[(\d+)\]/g)||[],s=Array.from(new Set(o.map(i=>i.slice(1,-1))));s.length!==0&&en(t,r,s)}var bc="Anything from this turn worth persisting for future sessions in this project? Could touch preferences, technical, area_context, or guidelines. If yes, call aide_remember on the matching layer. Otherwise stop.",_c="A correction or convention from this turn was detected but no memory was stored. If it applies to future work \u2014 preferences, technical, area_context, or guidelines \u2014 call aide_remember on the matching layer. Otherwise stop.";async function qs(n){if(n.stop_hook_active)return;let e=te(n),t=re(n),r=Re().id==="cursor";if(r&&Ps(e,t))return;let s=Is(e,t)+1;js(e,t,s);let i=Ge(e),a=z(e,"hooks.correction.escalate"),c=z(e,"hooks.stop.mode");if(Ds(e,t)&&(nn(e,t),a==="block")){let f=i?`${ae}correction from this turn not yet stored \u2014 prompting aide_remember`:void 0;r&&rn(e,t),Je(_c,f,"stop");return}if(c==="off")return;let l=z(e,"hooks.stop.schedule")||[],u=!1;if(!Array.isArray(l)||l.length===0)s%5===0&&(u=!0);else{let f=0,y=!1;for(let h of l){let w=h.every??5;h.until===void 0||h.until===null?y||((s-f)%w===0&&(u=!0),y=!0):s<=h.until&&!y&&((s-f)%w===0&&(u=!0),y=!0),h.until!==void 0&&h.until!==null&&(f=h.until)}}if(!u)return;let d=i?`${ae}checkpoint \u2014 anything worth remembering?`:void 0;r&&rn(e,t),Je(bc,d,"stop")}async function Gs(n){let e=te(n),t=re(n);z(e,"hooks.precompact.mode")!=="off"&&tn(e,t)}async function Xs(n){let e=te(n),t=re(n),r=V.join(e,".aide");if(!L.existsSync(r))return;try{let p=V.join(e,".mcp.json");if(L.existsSync(p)){let m=JSON.parse(L.readFileSync(p,"utf8"))?.mcpServers?.["aide-memory"]?.args?.[0];if(m&&!L.existsSync(m)){let S=`aide-memory: MCP server path not found (${m}). This can happen after a Node version change or cache clean. Fix: run "npx aide-memory init" or "npm install -g aide-memory && aide-memory init"`;process.stderr.write(`[AIDE_HEALTH] ${S}
245
+ `),de("SessionStart",S);return}}}catch{}let o="",s="";try{let{findPackageRoot:p}=(jt(),er($o)),R=p();if(!L.existsSync(V.resolve(R,"src","cli"))){let m=V.join(R,"package.json"),S=JSON.parse(L.readFileSync(m,"utf8")).version,j=V.join(Hs.homedir(),".aide","update-check.json");if(L.existsSync(j)){let k=JSON.parse(L.readFileSync(j,"utf8"));if(k.latestVersion&&k.latestVersion!==S){let H=S.replace(/^v/,"").split(".").map(Number),I=k.latestVersion.replace(/^v/,"").split(".").map(Number);(I[0]>H[0]||I[0]===H[0]&&I[1]>H[1]||I[0]===H[0]&&I[1]===H[1]&&I[2]>H[2])&&(o=`aide-memory v${k.latestVersion} is available (current: v${S}). Run \`npm update -g aide-memory\` to upgrade.`,s=`${ae}update available: v${k.latestVersion}`)}}}}catch{}let i=n.source;if(i==="resume")return;(i==="clear"||i==="compact")&&tn(e,t);let a=new A({projectRoot:e}),c="",l=[];try{let p=$t(e,a);c=p.content,l=p.injectedIds}finally{a.close()}let d=Re().id==="devin"?wc:"";if(!c&&!o&&!d)return;l.length>0&&en(e,t,l.map(String));let f=Ge(e),y=l.length,h=[];f&&y>0&&h.push(`${ae}injected ${y} ${y===1?"memory":"memories"} at session start`),s&&h.push(s);let w=h.length>0?h.join(`
246
+ `):void 0,E=[o,d,c].filter(Boolean).join(`
233
247
 
234
- ${c}`:c;ue("SessionStart",g,w)}async function Gs(n){let e=n.tool_input?.paths;if(!e||!Array.isArray(e)||e.length===0)return;let t=ee(n),r=te(n);for(let o of e){let s=U.isAbsolute(o)?o:U.join(t,o),i=s.endsWith("/"),a=s.endsWith("/**"),c=s.endsWith("/*"),l=!1,u=s;if(i)l=!0;else if(a)l=!0,u=s.slice(0,-3);else if(c)l=!0,u=s.slice(0,-2);else try{P.statSync(s).isDirectory()&&(l=!0)}catch{}l?(u.endsWith("/")||(u=u+"/"),lt(t,r,"dir",u)):lt(t,r,"file",s)}}async function Xs(n){let e=ee(n),t=te(n);rn(e,t)}async function Ys(n){let e=n.tool_input?.keyword;if(!e)return;let t=ee(n),r=te(n),o=nn(e);Ms(t,r,o)}function bc(n){try{let e=n.cwd;if(!e)return;let t=we.join(e,".aide","config.json"),r=we.join(e,".aide","cache","config-mtime.txt");if(!z.existsSync(t))return;let o=String(z.statSync(t).mtimeMs),s="";try{s=z.readFileSync(r,"utf8").trim()}catch{}if(o===s)return;z.mkdirSync(we.dirname(r),{recursive:!0}),z.writeFileSync(r,o,"utf8");try{let i=process.argv[1]&&/aide-memory(?:\.js)?$/.test(process.argv[1])?process.argv[1]:we.resolve(__dirname,"..","..","cli","aide-memory.js");if(!z.existsSync(i)){let c=we.resolve(__dirname,"..","..","cli","aide-memory.js");z.existsSync(c)&&(i=c)}(0,Ks.spawn)(process.execPath,[i,"internal-resync",e],{detached:!0,stdio:"ignore",cwd:e}).unref()}catch{}}catch{}}var wc={"pre-read":Ls,"pre-edit":Hs,"pre-search":Us,"pre-prompt":Bs,"post-tool-use-recall":Vs,stop:Ws,"pre-compact":Js,"session-start":qs,"pre-recall":Gs,"post-remember":Xs,"post-search":Ys};async function zs(n){let e=wc[n];if(!e){_e(`aide-memory hook: unknown event "${n}"`,"check .claude/settings.json or .cursor/hooks.json command lines");return}let t=performance.now();try{let r=await xs(),o=Le(),s=o.translateInput(r);if(bc(s),Q("hooks",`enter hook=${n} adapter=${o.id} cwd=${s.cwd??""} session=${s.session_id??""} file=${s.tool_input?.file_path??""}`),oo("hooks")){let i=process.stdout.write.bind(process.stdout),a="";process.stdout.write=(c,...l)=>{try{a+=typeof c=="string"?c:String(c)}catch{}return i(c,...l)};try{await e(s)}finally{process.stdout.write=i,Q("hooks",`exit hook=${n} duration=${(performance.now()-t).toFixed(1)}ms stdout-len=${a.length} stdout-head=${JSON.stringify(a.slice(0,200))}`)}}else await e(s),Q("hooks",`exit hook=${n} duration=${(performance.now()-t).toFixed(1)}ms`)}catch(r){let o=r,s=o?.message??String(r);/NODE_MODULE_VERSION|node-loader|wrong ELF class|invalid ELF header|dlopen/i.test(s)?_e(`aide-memory hook=${n}: native binding load failed (${s})`,"reinstall aide-memory or run `npm rebuild libsql` in the install dir"):/ENOENT|MODULE_NOT_FOUND/i.test(s)?_e(`aide-memory hook=${n}: missing file/module (${s})`,"reinstall aide-memory \u2014 dist/ may be incomplete"):_e(`aide-memory hook=${n} threw: ${s}`),Q("hooks",`error hook=${n} duration=${(performance.now()-t).toFixed(1)}ms class=${o?.name??"Error"}`)}}async function Qs(n){await zs(n),process.exit(0)}var si=h(require("fs")),ii=h(require("path"));var ei=h(require("https")),qe=h(require("fs")),an=h(require("path")),ti=h(require("os")),_c="https://registry.npmjs.org/aide-memory/latest",Sc=1440*60*1e3;function ri(){return an.default.join(ti.default.homedir(),".aide","update-check.json")}function Ec(){let n=ri();try{if(!qe.default.existsSync(n))return null;let e=qe.default.readFileSync(n,"utf-8");return JSON.parse(e)}catch{return null}}function vc(n){let e=ri();try{let t=an.default.dirname(e);qe.default.existsSync(t)||qe.default.mkdirSync(t,{recursive:!0}),qe.default.writeFileSync(e,JSON.stringify(n),"utf-8")}catch{}}function kc(){return new Promise(n=>{let e=ei.default.get(_c,{timeout:5e3},t=>{if(t.statusCode!==200){t.resume(),n(null);return}let r="";t.on("data",o=>{r+=o.toString()}),t.on("end",()=>{try{let o=JSON.parse(r);n(o.version??null)}catch{n(null)}})});e.on("error",()=>n(null)),e.on("timeout",()=>{e.destroy(),n(null)})})}function Zs(n,e){let t=s=>{let i=s.replace(/^v/,"").split(".").map(Number);return{major:i[0]||0,minor:i[1]||0,patch:i[2]||0}},r=t(n),o=t(e);return o.major!==r.major?o.major>r.major:o.minor!==r.minor?o.minor>r.minor:o.patch>r.patch}function xc(){try{if(process.env.AIDE_MEMORY_FORCE_REGISTRY_CHECK==="1")return!1;let n=require("fs"),t=require("path").resolve(__dirname,"..","..","src","cli");return n.existsSync(t)}catch{return!1}}async function ni(n){if(xc())return null;try{let e=Ec();if(e&&Date.now()-e.lastCheck<Sc)return e.latestVersion&&Zs(n,e.latestVersion)?e.latestVersion:null;let t=await kc();return vc({lastCheck:Date.now(),latestVersion:t}),t&&Zs(n,t)?t:null}catch{return null}}function oi(n,e){console.error(`
248
+ `);de("SessionStart",E,w)}var wc='This project uses aide-memory for persistent, cross-session context (managed via an MCP server + hooks). When an aide-memory hook nudges you \u2014 e.g. "N memories for this path. Call aide_recall(...)", a correction hint, or the Stop checkpoint \u2014 follow it. For how aide-memory works (when to call aide_recall / aide_remember / aide_search, the memory layers, and how to format a memory), use the `aide-memory` skill. Memory management is invisible to the user \u2014 do not mention aide-memory unless asked.';async function Ys(n){let e=n.tool_input?.paths;if(!e||!Array.isArray(e)||e.length===0)return;let t=te(n),r=re(n);for(let o of e){let s=V.isAbsolute(o)?o:V.join(t,o),i=s.endsWith("/"),a=s.endsWith("/**"),c=s.endsWith("/*"),l=!1,u=s;if(i)l=!0;else if(a)l=!0,u=s.slice(0,-3);else if(c)l=!0,u=s.slice(0,-2);else try{L.statSync(s).isDirectory()&&(l=!0)}catch{}l?(u.endsWith("/")||(u=u+"/"),dt(t,r,"dir",u)):dt(t,r,"file",s)}}async function Ks(n){let e=te(n),t=re(n);nn(e,t)}async function zs(n){let e=n.tool_input?.keyword;if(!e)return;let t=te(n),r=re(n),o=on(e);$s(t,r,o)}function Sc(n){try{let e=n.cwd;if(!e)return;let t=_e.join(e,".aide","config.json"),r=_e.join(e,".aide","cache","config-mtime.txt");if(!Q.existsSync(t))return;let o=String(Q.statSync(t).mtimeMs),s="";try{s=Q.readFileSync(r,"utf8").trim()}catch{}if(o===s)return;Q.mkdirSync(_e.dirname(r),{recursive:!0}),Q.writeFileSync(r,o,"utf8");try{let i=process.argv[1]&&/aide-memory(?:\.js)?$/.test(process.argv[1])?process.argv[1]:_e.resolve(__dirname,"..","..","cli","aide-memory.js");if(!Q.existsSync(i)){let c=_e.resolve(__dirname,"..","..","cli","aide-memory.js");Q.existsSync(c)&&(i=c)}(0,Qs.spawn)(process.execPath,[i,"internal-resync",e],{detached:!0,stdio:"ignore",cwd:e}).unref()}catch{}}catch{}}var Ec={"pre-read":Us,"pre-edit":Bs,"pre-search":Vs,"pre-prompt":Ws,"post-tool-use-recall":Js,stop:qs,"pre-compact":Gs,"session-start":Xs,"pre-recall":Ys,"post-remember":Ks,"post-search":zs};async function Zs(n){let e=Ec[n];if(!e){we(`aide-memory hook: unknown event "${n}"`,"check .claude/settings.json or .cursor/hooks.json command lines");return}let t=performance.now();try{let r=await Rs(),o=Re(),s=o.translateInput(r);if(Sc(s),Z("hooks",`enter hook=${n} adapter=${o.id} cwd=${s.cwd??""} session=${s.session_id??""} file=${s.tool_input?.file_path??""}`),so("hooks")){let i=process.stdout.write.bind(process.stdout),a="";process.stdout.write=(c,...l)=>{try{a+=typeof c=="string"?c:String(c)}catch{}return i(c,...l)};try{await e(s)}finally{process.stdout.write=i,Z("hooks",`exit hook=${n} duration=${(performance.now()-t).toFixed(1)}ms stdout-len=${a.length} stdout-head=${JSON.stringify(a.slice(0,200))}`)}}else await e(s),Z("hooks",`exit hook=${n} duration=${(performance.now()-t).toFixed(1)}ms`)}catch(r){let o=r,s=o?.message??String(r);/NODE_MODULE_VERSION|node-loader|wrong ELF class|invalid ELF header|dlopen/i.test(s)?we(`aide-memory hook=${n}: native binding load failed (${s})`,"reinstall aide-memory or run `npm rebuild libsql` in the install dir"):/ENOENT|MODULE_NOT_FOUND/i.test(s)?we(`aide-memory hook=${n}: missing file/module (${s})`,"reinstall aide-memory \u2014 dist/ may be incomplete"):we(`aide-memory hook=${n} threw: ${s}`),Z("hooks",`error hook=${n} duration=${(performance.now()-t).toFixed(1)}ms class=${o?.name??"Error"}`)}}async function ei(n){await Zs(n),process.exit(0)}var ai=g(require("fs")),ci=g(require("path"));var ri=g(require("https")),Xe=g(require("fs")),cn=g(require("path")),ni=g(require("os")),vc="https://registry.npmjs.org/aide-memory/latest",kc=1440*60*1e3;function oi(){return cn.default.join(ni.default.homedir(),".aide","update-check.json")}function xc(){let n=oi();try{if(!Xe.default.existsSync(n))return null;let e=Xe.default.readFileSync(n,"utf-8");return JSON.parse(e)}catch{return null}}function Oc(n){let e=oi();try{let t=cn.default.dirname(e);Xe.default.existsSync(t)||Xe.default.mkdirSync(t,{recursive:!0}),Xe.default.writeFileSync(e,JSON.stringify(n),"utf-8")}catch{}}function Rc(){return new Promise(n=>{let e=ri.default.get(vc,{timeout:5e3},t=>{if(t.statusCode!==200){t.resume(),n(null);return}let r="";t.on("data",o=>{r+=o.toString()}),t.on("end",()=>{try{let o=JSON.parse(r);n(o.version??null)}catch{n(null)}})});e.on("error",()=>n(null)),e.on("timeout",()=>{e.destroy(),n(null)})})}function ti(n,e){let t=s=>{let i=s.replace(/^v/,"").split(".").map(Number);return{major:i[0]||0,minor:i[1]||0,patch:i[2]||0}},r=t(n),o=t(e);return o.major!==r.major?o.major>r.major:o.minor!==r.minor?o.minor>r.minor:o.patch>r.patch}function Cc(){try{if(process.env.AIDE_MEMORY_FORCE_REGISTRY_CHECK==="1")return!1;let n=require("fs"),t=require("path").resolve(__dirname,"..","..","src","cli");return n.existsSync(t)}catch{return!1}}async function si(n){if(Cc())return null;try{let e=xc();if(e&&Date.now()-e.lastCheck<kc)return e.latestVersion&&ti(n,e.latestVersion)?e.latestVersion:null;let t=await Rc();return Oc({lastCheck:Date.now(),latestVersion:t}),t&&ti(n,t)?t:null}catch{return null}}function ii(n,e){console.error(`
235
249
  aide-memory v${e} available (current: v${n}).
236
250
  Run \`npm update -g aide-memory\` to update.
237
- `)}Ft();var cn=JSON.parse(si.readFileSync(ii.join(__dirname,"..","..","package.json"),"utf8"));function ai(){let n=new vn;n.name("aide-memory").description("AIDE Memory \u2014 persistent context for AI coding agents").version(cn.version),n.command("recall").description("Recall memories for a file/directory path").argument("<path>","File or directory path to recall context for").action(t=>{Mo(t)}),n.command("remember").description("Store a new memory").argument("<what>","The knowledge to remember").requiredOption("--layer <layer>","Memory layer: preferences, technical, area_context, guidelines").option("--scope <scope>",'Glob pattern for the code area (e.g. "src/components/**")').option("--tags <tags>","Comma-separated tags / context label").option("--why <why>","Context for why this is worth remembering").option("--contributor <contributor>","Who this knowledge came from").action((t,r)=>{is(t,r)}),n.command("update").description("Update an existing memory").argument("<id>","Memory ID to update").option("--what <what>","New content").option("--why <why>","New reason").option("--scope <scope>","New scope").option("--tags <tags>","New tags / context label").action((t,r)=>{as(t,r)}),n.command("forget").description("Delete a memory").argument("<id>","Memory ID to delete").action(t=>{cs(t)}),n.command("search").description("Search memories by keyword").argument("<query>","Text to search for").option("--layer <layer>","Filter by layer").option("--limit <limit>","Max results (default 50)").action((t,r)=>{ls(t,r)}),n.command("list").description("List memories").option("--layer <layer>","Filter by layer").option("--scope <scope>","Filter by scope").option("--contributor <contributor>","Filter by contributor").option("--limit <limit>","Max results").option("--tag <tag>","Filter by tag / context label").action(t=>{us(t)}),n.command("stats").description("Show memory analytics summary").action(()=>{ps()}),n.command("recall-log").description("Show detailed recall history (which memories were returned per recall event)").option("--last <n>","Show only the last N recall events").option("--clear","Clear the recall log").action(t=>{ms(t)}),n.command("config").description("Get or set configuration (dot-notation keys). Use `aide-memory config list` to enumerate all public settings with current value + description.").argument("<key>",'Configuration key (e.g. hooks.visible) or "list" to enumerate all public settings').argument("[value]","Value to set (omit to read)").action((t,r)=>{bs(t,r)});let e=n.command("sync").description("Synchronize between JSON files and SQLite cache");return e.command("import").description("Rebuild SQLite cache from JSON memory files").action(()=>{_s()}),e.command("export").description("Export memories to JSON files").action(()=>{Ss()}),n.command("migrate").description("Migrate from legacy memory.db format").action(()=>{vs()}),n.command("cleanup").description("Remove stale session tracking files from .aide/cache/").option("--older-than <duration>",'TTL for cleanup (e.g. "7d", "24h", "30m")',"7d").option("--all","Remove all tracking files regardless of age").option("--dry-run","Show what would be deleted without actually deleting").action(t=>{Es(t)}),n.command("init").description("Initialize a new .aide/ project").option("--update-rules","Only refresh rules files (idempotent)").option("--force","Update all config to current version (merges, preserves user settings)").option("--reset","Reset config to factory defaults (does not delete memories)").action(t=>{ks(t)}),n.command("hook <name>").description("Internal: dispatch a Claude Code hook (called by shell shims)").action(t=>{Qs(t)}),n.command("internal-resync <projectRoot>",{hidden:!0}).description("Internal: resync derived artifacts (spawned by hooks on config drift)").action(t=>{try{let{resyncDerivedArtifacts:r}=(ot(),Zt(ns));r(t)}catch{}process.exit(0)}),n}if(require.main===module){ai().parse(process.argv);try{let e=process.cwd();new he(e).get("updates.check")&&ni(cn.version).then(r=>{r&&oi(cn.version,r)}).catch(()=>{})}catch{}}0&&(module.exports={createProgram});
251
+ `)}Lt();var ln=JSON.parse(ai.readFileSync(ci.join(__dirname,"..","..","package.json"),"utf8"));function li(){let n=new kn;n.name("aide-memory").description("AIDE Memory \u2014 persistent context for AI coding agents").version(ln.version),n.command("recall").description("Recall memories for a file/directory path").argument("<path>","File or directory path to recall context for").action(t=>{No(t)}),n.command("remember").description("Store a new memory").argument("<what>","The knowledge to remember").requiredOption("--layer <layer>","Memory layer: preferences, technical, area_context, guidelines").option("--scope <scope>",'Glob pattern for the code area (e.g. "src/components/**")').option("--tags <tags>","Comma-separated tags / context label").option("--why <why>","Context for why this is worth remembering").option("--contributor <contributor>","Who this knowledge came from").action((t,r)=>{cs(t,r)}),n.command("update").description("Update an existing memory").argument("<id>","Memory ID to update").option("--what <what>","New content").option("--why <why>","New reason").option("--scope <scope>","New scope").option("--tags <tags>","New tags / context label").action((t,r)=>{ls(t,r)}),n.command("forget").description("Delete a memory").argument("<id>","Memory ID to delete").action(t=>{us(t)}),n.command("search").description("Search memories by keyword").argument("<query>","Text to search for").option("--layer <layer>","Filter by layer").option("--limit <limit>","Max results (default 50)").action((t,r)=>{ds(t,r)}),n.command("list").description("List memories").option("--layer <layer>","Filter by layer").option("--scope <scope>","Filter by scope").option("--contributor <contributor>","Filter by contributor").option("--limit <limit>","Max results").option("--tag <tag>","Filter by tag / context label").action(t=>{ps(t)}),n.command("stats").description("Show memory analytics summary").action(()=>{fs()}),n.command("recall-log").description("Show detailed recall history (which memories were returned per recall event)").option("--last <n>","Show only the last N recall events").option("--clear","Clear the recall log").action(t=>{gs(t)}),n.command("config").description("Get or set configuration (dot-notation keys). Use `aide-memory config list` to enumerate all public settings with current value + description.").argument("<key>",'Configuration key (e.g. hooks.visible) or "list" to enumerate all public settings').argument("[value]","Value to set (omit to read)").action((t,r)=>{ws(t,r)});let e=n.command("sync").description("Synchronize between JSON files and SQLite cache");return e.command("import").description("Rebuild SQLite cache from JSON memory files").action(()=>{Es()}),e.command("export").description("Export memories to JSON files").action(()=>{vs()}),n.command("migrate").description("Migrate from legacy memory.db format").action(()=>{xs()}),n.command("cleanup").description("Remove stale session tracking files from .aide/cache/").option("--older-than <duration>",'TTL for cleanup (e.g. "7d", "24h", "30m")',"7d").option("--all","Remove all tracking files regardless of age").option("--dry-run","Show what would be deleted without actually deleting").action(t=>{ks(t)}),n.command("init").description("Initialize a new .aide/ project").option("--update-rules","Only refresh rules files (idempotent)").option("--force","Update all config to current version (merges, preserves user settings)").option("--reset","Reset config to factory defaults (does not delete memories)").action(t=>{Os(t)}),n.command("hook <name>").description("Internal: dispatch a Claude Code hook (called by shell shims)").action(t=>{ei(t)}),n.command("internal-resync <projectRoot>",{hidden:!0}).description("Internal: resync derived artifacts (spawned by hooks on config drift)").action(t=>{try{let{resyncDerivedArtifacts:r}=(it(),er(ss));r(t)}catch{}process.exit(0)}),n}if(require.main===module){li().parse(process.argv);try{let e=process.cwd();new he(e).get("updates.check")&&si(ln.version).then(r=>{r&&ii(ln.version,r)}).catch(()=>{})}catch{}}0&&(module.exports={createProgram});