@r5n/ariadne 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +24 -6
  2. package/dist/cli.js +240 -210
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,257 +1,287 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
- import{homedir as v2}from"os";import{join as x2}from"path";class dt extends Error{_tag="Cancel";constructor(t="Operation cancelled"){super(t)}}function j(t){return t}function pl(t){return t==null?[]:Array.isArray(t)?t:[t]}function Bb(t,e,n,r){var o,s=t[e],i=~r.string.indexOf(e)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~r.boolean.indexOf(e)?n==="false"?!1:n==="true"||(t._.push((o=+n,o*0===0)?o:n),!!n):(o=+n,o*0===0)?o:n;t[e]=s==null?i:Array.isArray(s)?s.concat(i):[s,i]}function gl(t,e){t=t||[],e=e||{};var n,r,o,s,i,a={_:[]},c=0,l=0,u=0,d=t.length;let p=e.alias!==void 0,m=e.unknown!==void 0,f=e.default!==void 0;if(e.alias=e.alias||{},e.string=pl(e.string),e.boolean=pl(e.boolean),p)for(n in e.alias){r=e.alias[n]=pl(e.alias[n]);for(c=0;c<r.length;c++)(e.alias[r[c]]=r.concat(n)).splice(c,1)}for(c=e.boolean.length;c-- >0;){r=e.alias[e.boolean[c]]||[];for(l=r.length;l-- >0;)e.boolean.push(r[l])}for(c=e.string.length;c-- >0;){r=e.alias[e.string[c]]||[];for(l=r.length;l-- >0;)e.string.push(r[l])}if(f){for(n in e.default)if(s=typeof e.default[n],r=e.alias[n]=e.alias[n]||[],e[s]!==void 0){e[s].push(n);for(c=0;c<r.length;c++)e[s].push(r[c])}}let y=m?Object.keys(e.alias):[];for(c=0;c<d;c++){if(o=t[c],o==="--"){a._=a._.concat(t.slice(++c));break}for(l=0;l<o.length;l++)if(o.charCodeAt(l)!==45)break;if(l===0)a._.push(o);else if(o.substring(l,l+3)==="no-"){if(s=o.substring(l+3),m&&!~y.indexOf(s))return e.unknown(o);a[s]=!1}else{for(u=l+1;u<o.length;u++)if(o.charCodeAt(u)===61)break;s=o.substring(l,u),i=o.substring(++u)||(c+1===d||(""+t[c+1]).charCodeAt(0)===45||t[++c]),r=l===2?[s]:s;for(u=0;u<r.length;u++){if(s=r[u],m&&!~y.indexOf(s))return e.unknown("-".repeat(l)+s);Bb(a,s,u+1<r.length||i,e)}}}if(f){for(n in e.default)if(a[n]===void 0)a[n]=e.default[n]}if(p)for(n in a){r=e.alias[n]||[];while(r.length>0)a[r.shift()]=a[n]}return a}var Ut=0,_o=1,Sg=2,Tg=255;function zs(t){return Number.isInteger(t)&&t>=0&&t<=255}class g extends Error{hint;exitCode;_tag;constructor(t,e,n=1,r={}){super(t,"cause"in r?{cause:r.cause}:void 0);this.hint=e;this.exitCode=n;this._tag=r.tag??"Exit"}}class T extends g{constructor(t,e,n={}){super(t,e,2,{...n,tag:n.tag??"UsageError"})}}var $g=1,Wb=2,Qs="--",bg="-",bn="no-",Vb=new Set(["false","true"]),Do=/^--([^=]+)(?:=(.*))?$/s,Lo=/^-([^-=][^=]*)(?:=(.*))?$/s,hl=/^(?:---|-no-|-_|-[^-=][^=]*_)/,Jb="_",Po="\x00";function xe(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Ir(t){let e={alias:{},boolean:[],default:{},string:[]};for(let[n,r]of Object.entries(t)){if(r.type==="boolean")e.boolean.push(n);else e.string.push(n);if(r.alias)e.alias[r.alias]=n;let o=xe(n);if(o!==n)e.alias[o]=n;if(r.default!==void 0)e.default[n]=r.default}return e}function Zs(t,e){let n={};for(let[i,a]of Object.entries(e.alias))n[a]=[...n[a]??[],i];let{_:r,...o}=gl(ri(t,qb),{alias:n,boolean:[...e.boolean],default:{...e.default},string:[...e.string]}),s=Object.entries(o).map(([i,a])=>[ml(i),ml(a)]);return{...Object.fromEntries(s),_:r.map(ml)}}function qb(t){if(t===bg)return`${Po}${t}`;let e=Do.exec(t);if(hl.test(t)||Yb(e?.[1]))return`--${Po}${t}`;return(e?e[2]:Lo.exec(t)?.[2])===""?`${t}${Po}`:t}function Yb(t){if(t===void 0)return!1;let e=t.startsWith(bn)?t.slice(bn.length):t;return e===Jb||e in Object.prototype}function ml(t){return typeof t==="string"&&t.startsWith(Po)?t.slice(Po.length):t}function No(t,e){return Object.hasOwn(e.alias,t)?e.alias[t]??t:t}function Rr(t,e){if(Object.hasOwn(e,t))return`--${xe(t)}`;let n=Object.entries(e).find(([,r])=>r.alias===t)?.[0];if(n)return`--${xe(n)}`;return t.length===$g?`-${t}`:`--${t}`}function ti(t,e,n,r){let{alias:o}=Ir(e),s=Object.keys(t).find((i)=>!Object.hasOwn(e,i)&&!Object.hasOwn(o,i));if(s!==void 0)throw new T(`Unknown option: ${Xb(s,r)}`,n)}function Xb(t,e){if(t.startsWith("-"))return t;let n=e.indexOf(Qs);for(let r of n<0?e:e.slice(0,n)){let o=Do.exec(r)?.[1];if(o===t||r===`--${bn}${t}`)return`--${o}`;if(o===void 0&&Lo.exec(r)?.[1]?.includes(t))return`-${t}`}return Rr(t,{})}function vg(t,e){for(let[r,o]of Object.entries(t))if(Array.isArray(o))throw new T(`${Rr(r,e)} can only be provided once`);let n={...t};for(let[r,o]of Object.entries(e)){let s=t[r];if(s===void 0)continue;if(o.type==="string"&&typeof s==="boolean")throw xg(Rr(r,e));if(o.type!=="number")continue;let i=Number(s);if(typeof s==="boolean"||typeof s==="string"&&s.trim().length===0||!Number.isFinite(i)){let a=Rr(r,e);throw new T(`Invalid number for ${a}: "${s}"`,`Use ${a}=<number> with a finite numeric value`)}n[r]=i}return n}function xg(t){return new T(`${t} needs a value`,`Use ${t}=<value>`)}function ei(t,e){let n=Ir(e),r=kl([...t],n),o=Zs(r,n)._[0],s=o===void 0?-1:r.indexOf(o);return{before:s>=0?t.slice(0,s):[...t],command:o,restArgs:s>=0?t.slice(s+1):[]}}function Ag(t,e){let n=Ir(e);for(let r=0;r<t.length;r+=1){let o=t[r]??"";if(o===Qs)return-1;if(o===bg||!o.startsWith("-"))return r;if(zb(o,n,e))r+=1}return-1}function zb(t,e,n){if(t.startsWith(`--${bn}`))return!1;let r=Do.exec(t),o=r??Lo.exec(t);if(!o||o[2]!==void 0)return!1;let s=r?o[1]??"":o[1]?.at(-1)??"",i=n[No(s,e)]?.type;return i==="string"||i==="number"}function yl(t,e,n=e){let r=Ir(e),{before:o,command:s,restArgs:i}=ei(t,e),a=Ir(n);fl(o,r,e,!0),fl(t,a,n,!0);let{_:c,...l}=Zs(Cg(o,r,e),r);ti(l,e,"Place command options after the command name",o);let{_:u,...d}=Zs(kl(i,a),a),p=vg({...Eg(l,e,r),...Eg(d,n,a)},e);return{command:s,flags:p,restArgs:i}}function Eg(t,e,n){return Object.fromEntries(Object.entries(t).filter(([r])=>Object.hasOwn(e,r)||Object.hasOwn(n.alias,r)))}function ni(t,e){return Object.fromEntries(Object.keys(e).flatMap((n)=>{let r=t[n];return r===void 0?[]:[[n,r]]}))}function Mo(t,e={}){let n=Ir(e),r=Zb(t,n);fl(r,n,e);let o=Zs(Cg(r,n,e),n),{_:s,...i}=o;return{args:vg(i,e),rawPositionals:s.map(String)}}function fl(t,e,n,r=!1){let o=new Set;for(let s of t){if(s===Qs)break;let i=s.match(/^-+/)?.[0];if(!i||hl.test(s))continue;let a=s.slice(i.length),c=a.split("=",$g)[0]??"",l=a.startsWith(bn)?[a.slice(bn.length)]:i.length===Wb?[c]:[...c];for(let u of l){let d=No(u,e);if(r&&!Object.hasOwn(n,d))continue;if(o.has(d))throw new T(`${Rr(d,n)} can only be provided once`);o.add(d)}}}function ri(t,e){let n=t.indexOf(Qs);return t.map((r,o)=>n>=0&&o>=n?r:e(r,t[o+1]))}function kl(t,e){return ri(t,(n)=>{let r=Do.exec(n)??Lo.exec(n);if(!r||r[2]!==void 0||n.startsWith(`--${bn}`))return n;let o=n.startsWith("--")?r[1]??"":r[1]?.at(-1)??"";return e.boolean.includes(No(o,e))?`${n}=true`:n})}function Cg(t,e,n){let r=(i)=>n[No(i,e)]?.type,o=(i)=>i!==void 0&&!i.startsWith("-"),s=ri(t,(i,a)=>{let c=Do.exec(i),l=c?null:Lo.exec(i);if(i.startsWith(`--${bn}`)||hl.test(i))return i;let u=c?[c[1]??""]:[...l?.[1]??""],d=c?c[2]:l?.[2];for(let[p,m]of u.entries()){let f=r(m),y=p===u.length-1,S=Rr(No(m,e),n),R=!y||d===void 0&&!o(a);if(f==="string"&&(R||d===""))throw xg(S);if(f==="number"&&R)throw new T(`${S} needs a value`,`Use ${S}=<number>`);if(f==="boolean"&&y&&d!==void 0&&!Vb.has(d))throw new T(`Invalid value for ${S}: "${d}"`,`Use ${S}=true or ${S}=false`)}return i});return kl(s,e)}function Zb(t,e){return ri(t,(n)=>n.replace(/^--(no-[^=]+)(=.*)?$/,(r,o,s)=>{let i=e.alias[o];return i&&e.boolean.includes(i)?`--${i}${s??""}`:r}))}function oi(t,e){let n={},r=Object.entries(e);for(let[o,[s,i]]of r.entries())n[s]=i.variadic?t.slice(o):t[o];return n}function si(t,e){for(let[n,r]of Object.entries(e)){if(!r.required)continue;let o=t[n];if(Array.isArray(o)?o.length===0:!o)return`Missing required argument: <${n}${r.variadic?"...":""}>`}return null}function Rg(t,e){let n=Object.values(e);if(n.some((r)=>r.variadic))return;return t[n.length]}var Qb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,tv=new Set(["help","json"]),ev=/^[a-zA-Z0-9]$/,nv=new Set(["h","j"]);function ii(){return(t)=>{let e={args:t.args??{},description:t.description,examples:t.examples??[],json:t.json??!1,name:t.name,passthrough:t.passthrough??!1,positionals:t.positionals??{},prompts:t.prompts??!1,run:t.run,strict:t.strict??!0,subcommands:t.subcommands??[]};return rv(e),Object.freeze(e)}}function ai(t,e){let n=wl(e.map((r)=>r.name));if(n!==void 0)throw Error(`${t} has more than one command named "${n}"`)}function rv(t){let e=`Command "${t.name}"`;if(!Qb.test(t.name))throw Error(`${e} must be named with a lower-case word such as "list" or "dry-run"`);if(!t.run&&t.subcommands.length===0)throw Error(`${e} needs run or subcommands`);for(let[u,d]of Object.entries(t.args)){if(tv.has(xe(u)))throw Error(`${e} cannot define the option "${u}": --${xe(u)} is a global flag`);if(d.alias!==void 0&&nv.has(d.alias))throw Error(`${e} cannot give "${u}" the alias -${d.alias}: it belongs to a global flag`)}let n=Object.keys(t.args).map(xe),r=wl(n);if(r!==void 0)throw Error(`${e} has more than one option named --${r}`);let o=Object.values(t.args).flatMap((u)=>u.alias??[]),s=o.find((u)=>!ev.test(u));if(s!==void 0)throw Error(`${e} uses the alias "${s}": an alias is one letter or digit`);let i=o.find((u)=>n.includes(u));if(i!==void 0)throw Error(`${e} uses the alias -${i}, which is also an option's name`);let a=wl(o);if(a!==void 0)throw Error(`${e} uses the alias -${a} more than once`);let c=Object.keys(t.positionals),l=c.find((u)=>t.positionals[u]?.variadic);if(l!==void 0&&l!==c.at(-1))throw Error(`${e} declares the variadic positional "${l}" before other positionals`);if(t.passthrough&&(!t.run||l===void 0))throw Error(`${e} uses passthrough, which needs run and a variadic last positional`);ai(e,t.subcommands)}function wl(t){return t.find((e,n)=>t.indexOf(e)!==n)}function at(t){return t}import{Console as gv}from"console";import{Writable as mv}from"stream";import{format as fv,stripVTControlCharacters as hv}from"util";var vn={active:!1};var ov=new Set(["0","false"]);function jo(t){if(process.env.NO_COLOR)return!1;let e=process.env.FORCE_COLOR;if(e!==void 0)return!ov.has(e);return t?.isTTY===!0}var sv=jo(process.stdout),_g=["black","blue","cyan","gray","green","magenta","red","white","yellow"],iv=["bold","dim","italic","underline","reset"],Pg={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},av={black:"\x1B[30m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",green:"\x1B[32m",magenta:"\x1B[35m",red:"\x1B[31m",white:"\x1B[37m",yellow:"\x1B[33m"},cv={black:"\x1B[40m",blue:"\x1B[44m",cyan:"\x1B[46m",gray:"\x1B[100m",green:"\x1B[42m",magenta:"\x1B[45m",red:"\x1B[41m",white:"\x1B[47m",yellow:"\x1B[43m"},Ig={"\x1B[30m":"\x1B[90m","\x1B[31m":"\x1B[91m","\x1B[32m":"\x1B[92m","\x1B[33m":"\x1B[93m","\x1B[34m":"\x1B[94m","\x1B[35m":"\x1B[95m","\x1B[36m":"\x1B[96m","\x1B[37m":"\x1B[97m"};function ci(t){return(e)=>sv&&!vn.active?`${t}${e}${Pg.reset}`:e}function lv(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<32&&n!==27)return!1}return!0}function Og({bright:t=!1,color:e}){let n=Bun.color(e,"ansi"),r=typeof n==="string"&&n.length>0&&lv(n)?n:av[e];if(!r)return"";return t&&r in Ig?Ig[r]:r}var uv=_g.reduce((t,e)=>{let n=Og({color:e});if(n)t[e]=ci(n);let r=Og({bright:!0,color:e});if(r)t[`${e}Bright`]=ci(r);return t},{}),dv=iv.reduce((t,e)=>(t[e]=ci(Pg[e]),t),{}),pv=_g.reduce((t,e)=>{let n=cv[e];if(n){let r=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[r]=ci(n)}return t},{}),k={...uv,...dv,...pv};var yv=2,Lg=["clear","count","countReset","debug","dir","dirxml","group","groupCollapsed","groupEnd","info","log","table"],kv=[...Lg,"trace","write"],wv=1,Sv="EPIPE",Tv="EIO",rt={closedStreams:new Set,documentWritten:!1,jsonRuns:0,outputGuarded:!1,restoreStdout:void 0,sealed:!1,stdoutClosed:!1,stdoutWrite:void 0};function Fo(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Jn(t){return Fo()&&!vn.active&&t?.json!==!0}function Mg(){return vn.active}function xn(t){let e=JSON.stringify(t??null,null,yv);if(e===void 0)throw TypeError("JSON cannot represent the value");return`${e}
4
- `}function jg(){return rt.documentWritten}function Fg(){rt.sealed=!0}function rn(t){if(rt.documentWritten=!0,rt.sealed||rt.stdoutClosed)return;let e=rt.stdoutWrite??process.stdout.write;try{e.call(process.stdout,t)}catch(n){if(!li(n,process.stdout))throw n;rt.stdoutClosed=!0}}function Gg(){if(rt.outputGuarded)return;rt.outputGuarded=!0,process.stdout.write=Ng(process.stdout.write,!0),console.write=Ng(console.write,0),process.stdout.on("error",(t)=>{if(!li(t,process.stdout))throw t;rt.stdoutClosed=!0}),process.stderr.on("error",(t)=>{if(!li(t,process.stderr))throw t});for(let t of[process.stdout,process.stderr])t.once("close",()=>rt.closedStreams.add(t))}function Ng(t,e){let n=(r)=>{let o=r.at(-1);if(typeof o==="function")queueMicrotask(()=>o());return e};return function(...o){if(rt.stdoutClosed)return n(o);try{return t.apply(this,o)}catch(s){if(!li(s,process.stdout))throw s;return rt.stdoutClosed=!0,n(o)}}}function li(t,e){if(!(t instanceof Error))return!1;let n=Reflect.get(t,"code");return n===Sv||n===Tv&&e.isTTY===!0}function ui(){let t=jo(process.stderr);return new mv({decodeStrings:!1,write(e,n,r){process.stderr.write(t?e:hv(e)),r()}})}async function Hg(t,e){if(!t)return e();rt.jsonRuns+=1,rt.restoreStdout??=Ev(),vn.active=!0;try{return await e()}finally{if(rt.jsonRuns-=1,vn.active=rt.jsonRuns>0,!vn.active&&!rt.outputGuarded)rt.restoreStdout?.(),rt.restoreStdout=void 0}}async function Ug(t){let e=Promise.all([rt.stdoutClosed?void 0:Dg(process.stdout),Dg(process.stderr)]);await(t===void 0?e:Promise.race([e,Bun.sleep(t)]))}function Dg(t){if(t.writableFinished||rt.closedStreams.has(t))return Promise.resolve();return new Promise((e)=>{t.once("close",e),t.once("finish",e),t.once("error",()=>e()),t.end(()=>e())})}function Ev(){let t=process.stdout.write,e=new gv({stderr:process.stderr,stdout:process.stderr}),n=Object.fromEntries(kv.map((o)=>[o,console[o]])),r=Object.fromEntries(Lg.map((o)=>[o,e[o].bind(e)]));return rt.stdoutWrite=t,process.stdout.write=process.stderr.write.bind(process.stderr),Object.assign(console,r,{trace:$v(e),write:bv}),()=>{process.stdout.write=t,Object.assign(console,n),rt.stdoutWrite=void 0}}function $v(t){let e=(...n)=>{let r={};Error.captureStackTrace(r,e);let o=r.stack?.split(`
5
- `).slice(wv)??[];t.error([`Trace: ${fv(...n)}`,...o].join(`
6
- `))};return e}function bv(...t){let e=Buffer.concat(t.map(vv));return process.stderr.write(e),e.byteLength}function vv(t){if(typeof t==="string")return Buffer.from(t);return ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t)}var ae={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"},json:{alias:"j",description:"Write one JSON document to stdout",type:"boolean"}},Or={help:ae.help,json:ae.json},qn="help",di={[Ut]:"success",[_o]:"failure",[Sg]:"usage error"};import{stripVTControlCharacters as Dl}from"util";import{styleText as Fv}from"util";import{stdout as rm,stdin as Gv}from"process";import Hv from"readline";var Kg=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let n=0;t.lastIndex=0;while(t.test(e))n+=1;return e.length-n}})(),Bg=(t)=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Wg=(t)=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var xv=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Av=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Vg=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Cv=/\t{1,1000}/y,Jg=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,Rv=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Iv=/\p{M}+/gu,Ov={limit:1/0,ellipsis:""},qg=(t,e={},n={})=>{let r=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?qg(o,Ov,n).width:0),i=0,a=n.controlWidth??0,c=n.tabWidth??8,l=n.emojiWidth??2,u=2,d=n.regularWidth??1,p=n.wideWidth??2,m=[[Rv,d],[xv,0],[Av,a],[Cv,c],[Jg,l],[Vg,p]],f=0,y=0,S=t.length,R=0,v=!1,H=S,J=Math.max(0,r-s),N=0,U=0,_=0,A=0;t:while(!0){if(U>N||y>=S&&y>f){let B=t.slice(N,U)||t.slice(f,y);R=0;for(let Dt of B.replaceAll(Iv,"")){let Yt=Dt.codePointAt(0)||0;if(Bg(Yt))A=2;else if(Wg(Yt))A=p;else A=d;if(_+A>J)H=Math.min(H,Math.max(N,f)+R);if(_+A>r){v=!0;break t}R+=Dt.length,_+=A}N=U=0}if(y>=S)break t;for(let B=0,Dt=m.length;B<Dt;B++){let[Yt,wg]=m[B];if(Yt.lastIndex=y,Yt.test(t)){if(R=Yt===Vg?Kg(t.slice(y,Yt.lastIndex)):Yt===Jg?1:Yt.lastIndex-y,A=R*wg,_+A>J)H=Math.min(H,y+Math.floor((J-_)/wg));if(_+A>r){v=!0;break t}_+=A,N=f,U=y,y=f=Yt.lastIndex;continue t}}y+=1}return{width:v?J:_,index:v?H:S,truncated:v,ellipsed:v&&r>=s}},Yg=qg;var _v={limit:1/0,ellipsis:"",ellipsisWidth:0},Pv=(t,e={})=>Yg(t,_v,e).width,xt=Pv;var pi="\x1B",tm="\x9B",Nv=39,Tl="\x07",em="[",Dv="]",nm="m",El=`${Dv}8;;`,Xg=new RegExp(`(?:\\${em}(?<code>\\d+)m|\\${El}(?<uri>.*)${Tl})`,"y"),zg=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},Zg=(t)=>`${pi}${em}${t}${nm}`,Qg=(t)=>`${pi}${El}${t}${Tl}`,Sl=(t,e,n)=>{let r=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:xt(i),c=r.next(),l=r.next(),u=0;while(!c.done){let d=c.value,p=xt(d);if(a+p<=n)t[t.length-1]+=d;else t.push(d),a=0;if(d===pi||d===tm)o=!0,s=e.startsWith(El,u+1);if(o){if(s){if(d===Tl)o=!1,s=!1}else if(d===nm)o=!1}else if(a+=p,a===n&&!l.done)t.push(""),a=0;c=l,l=r.next(),u+=d.length}if(i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1)t[t.length-2]+=t.pop()},Lv=(t)=>{let e=t.split(" "),n=e.length;while(n){if(xt(e[n-1]))break;n--}if(n===e.length)return t;return e.slice(0,n).join(" ")+e.slice(n).join("")},Mv=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let r="",o,s,i=t.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let p=i[d];if(n.trim!==!1){let f=a.at(-1)??"",y=f.trimStart();if(f.length!==y.length)a[a.length-1]=y,c=xt(y)}if(d!==0){if(c>=e&&(n.wordWrap===!1||n.trim===!1))a.push(""),c=0;if(c||n.trim===!1)a[a.length-1]+=" ",c++}let m=xt(p);if(n.hard&&m>e){let f=e-c,y=1+Math.floor((m-f-1)/e);if(Math.floor((m-1)/e)<y)a.push("");Sl(a,p,e),c=xt(a.at(-1)??"");continue}if(c+m>e&&c&&m){if(n.wordWrap===!1&&c<e){Sl(a,p,e),c=xt(a.at(-1)??"");continue}a.push(""),c=0}if(c+m>e&&n.wordWrap===!1){Sl(a,p,e),c=xt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=m}if(n.trim!==!1)a=a.map((d)=>Lv(d));let l=a.join(`
7
- `),u=!1;for(let d=0;d<l.length;d++){let p=l[d];if(r+=p,!u){if(u=p>="\uD800"&&p<="\uDBFF",u)continue}else u=!1;if(p===pi||p===tm){Xg.lastIndex=d+1;let f=Xg.exec(l)?.groups;if(f?.code!==void 0){let y=Number.parseFloat(f.code);o=y===Nv?void 0:y}else if(f?.uri!==void 0)s=f.uri.length===0?void 0:f.uri}if(l[d+1]===`
8
- `){if(s)r+=Qg("");let m=o?zg(o):void 0;if(o&&m)r+=Zg(m)}else if(p===`
9
- `){if(o&&zg(o))r+=Zg(o);if(s)r+=Qg(s)}}return r},jv=/\r?\n/;function An(t,e,n){return String(t).normalize().split(jv).map((r)=>Mv(r,e,n)).join(`
10
- `)}var ce={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let n="";if(t<0)n+=`\x1B[${-t}D`;else if(t>0)n+=`\x1B[${t}C`;if(e<0)n+=`\x1B[${-e}A`;else if(e>0)n+=`\x1B[${e}B`;return n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"};var Go={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?ce.up():"");if(t)e+=ce.left;return e}};function Yn(t,e,n){if(!n.some((i)=>!i.disabled))return t;let r=t+e,o=Math.max(n.length-1,0),s=r<0?o:r>o?0:r;return n[s]?.disabled?Yn(s,e<0?-1:1,n):s}var Uv=["up","down","left","right","space","enter","cancel"],Kv=["January","February","March","April","May","June","July","August","September","October","November","December"],At={actions:new Set(Uv),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,accessible:void 0,date:{monthNames:[...Kv],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function om(t){if(t!==void 0)return t;if(At.accessible!==void 0)return At.accessible;let e=process.env.ACCESSIBLE;return e!==void 0&&e!==""&&e!=="0"&&e!=="false"}function sm(t,e){if(typeof t=="string")return At.aliases.get(t)===e;for(let n of t)if(n!==void 0&&sm(n,e))return!0;return!1}function Bv(t,e){if(t===e)return;let n=t.split(`
3
+ import{homedir as c5}from"os";import{join as l5}from"path";class vt extends Error{_tag="Cancel";constructor(t="Operation cancelled"){super(t)}}function j(t){return t}function ru(t){return t==null?[]:Array.isArray(t)?t:[t]}function oA(t,e,n,r){var o,s=t[e],i=~r.string.indexOf(e)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~r.boolean.indexOf(e)?n==="false"?!1:n==="true"||(t._.push((o=+n,o*0===0)?o:n),!!n):(o=+n,o*0===0)?o:n;t[e]=s==null?i:Array.isArray(s)?s.concat(i):[s,i]}function ou(t,e){t=t||[],e=e||{};var n,r,o,s,i,a={_:[]},c=0,l=0,u=0,d=t.length;let p=e.alias!==void 0,g=e.unknown!==void 0,f=e.default!==void 0;if(e.alias=e.alias||{},e.string=ru(e.string),e.boolean=ru(e.boolean),p)for(n in e.alias){r=e.alias[n]=ru(e.alias[n]);for(c=0;c<r.length;c++)(e.alias[r[c]]=r.concat(n)).splice(c,1)}for(c=e.boolean.length;c-- >0;){r=e.alias[e.boolean[c]]||[];for(l=r.length;l-- >0;)e.boolean.push(r[l])}for(c=e.string.length;c-- >0;){r=e.alias[e.string[c]]||[];for(l=r.length;l-- >0;)e.string.push(r[l])}if(f){for(n in e.default)if(s=typeof e.default[n],r=e.alias[n]=e.alias[n]||[],e[s]!==void 0){e[s].push(n);for(c=0;c<r.length;c++)e[s].push(r[c])}}let y=g?Object.keys(e.alias):[];for(c=0;c<d;c++){if(o=t[c],o==="--"){a._=a._.concat(t.slice(++c));break}for(l=0;l<o.length;l++)if(o.charCodeAt(l)!==45)break;if(l===0)a._.push(o);else if(o.substring(l,l+3)==="no-"){if(s=o.substring(l+3),g&&!~y.indexOf(s))return e.unknown(o);a[s]=!1}else{for(u=l+1;u<o.length;u++)if(o.charCodeAt(u)===61)break;s=o.substring(l,u),i=o.substring(++u)||(c+1===d||(""+t[c+1]).charCodeAt(0)===45||t[++c]),r=l===2?[s]:s;for(u=0;u<r.length;u++){if(s=r[u],g&&!~y.indexOf(s))return e.unknown("-".repeat(l)+s);oA(a,s,u+1<r.length||i,e)}}}if(f){for(n in e.default)if(a[n]===void 0)a[n]=e.default[n]}if(p)for(n in a){r=e.alias[n]||[];while(r.length>0)a[r.shift()]=a[n]}return a}var zt=0,ss=1,Tm=2,xm=255;function Ii(t){return Number.isInteger(t)&&t>=0&&t<=255}class m extends Error{hint;exitCode;_tag;constructor(t,e,n=1,r={}){super(t,"cause"in r?{cause:r.cause}:void 0);this.hint=e;this.exitCode=n;this._tag=r.tag??"Exit"}}class v extends m{constructor(t,e,n={}){super(t,e,2,{...n,tag:n.tag??"UsageError"})}}var Cm=1,sA=2,_i="--",Rm="-",Fn="no-",iA=new Set(["false","true"]),cs=/^--([^=]+)(?:=(.*))?$/s,ls=/^-([^-=][^=]*)(?:=(.*))?$/s,au=/^(?:---|-no-|-_|-[^-=][^=]*_)/,aA="_",is="\x00";function Me(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Zr(t){let e={alias:{},boolean:[],default:{},string:[]};for(let[n,r]of Object.entries(t)){if(r.type==="boolean")e.boolean.push(n);else e.string.push(n);if(r.alias)e.alias[r.alias]=n;let o=Me(n);if(o!==n)e.alias[o]=n;if(r.default!==void 0)e.default[n]=r.default}return e}function Oi(t,e){let n={};for(let[i,a]of Object.entries(e.alias))n[a]=[...n[a]??[],i];let{_:r,...o}=ou(Li(t,cA),{alias:n,boolean:[...e.boolean],default:{...e.default},string:[...e.string]}),s=Object.entries(o).map(([i,a])=>[su(i),su(a)]);return{...Object.fromEntries(s),_:r.map(su)}}function cA(t){if(t===Rm)return`${is}${t}`;let e=cs.exec(t);if(au.test(t)||lA(e?.[1]))return`--${is}${t}`;return(e?e[2]:ls.exec(t)?.[2])===""?`${t}${is}`:t}function lA(t){if(t===void 0)return!1;let e=t.startsWith(Fn)?t.slice(Fn.length):t;return e===aA||e in Object.prototype}function su(t){return typeof t==="string"&&t.startsWith(is)?t.slice(is.length):t}function as(t,e){return Object.hasOwn(e.alias,t)?e.alias[t]??t:t}function zr(t,e){if(Object.hasOwn(e,t))return`--${Me(t)}`;let n=Object.entries(e).find(([,r])=>r.alias===t)?.[0];if(n)return`--${Me(n)}`;return t.length===Cm?`-${t}`:`--${t}`}function Pi(t,e,n,r){let{alias:o}=Zr(e),s=Object.keys(t).find((i)=>!Object.hasOwn(e,i)&&!Object.hasOwn(o,i));if(s!==void 0)throw new v(`Unknown option: ${uA(s,r)}`,n)}function uA(t,e){if(t.startsWith("-"))return t;let n=e.indexOf(_i);for(let r of n<0?e:e.slice(0,n)){let o=cs.exec(r)?.[1];if(o===t||r===`--${Fn}${t}`)return`--${o}`;if(o===void 0&&ls.exec(r)?.[1]?.includes(t))return`-${t}`}return zr(t,{})}function Im(t,e){for(let[r,o]of Object.entries(t))if(Array.isArray(o))throw new v(`${zr(r,e)} can only be provided once`);let n={...t};for(let[r,o]of Object.entries(e)){let s=t[r];if(s===void 0)continue;if(o.type==="string"&&typeof s==="boolean")throw Om(zr(r,e));if(o.type!=="number")continue;let i=Number(s);if(typeof s==="boolean"||typeof s==="string"&&s.trim().length===0||!Number.isFinite(i)){let a=zr(r,e);throw new v(`Invalid number for ${a}: "${s}"`,`Use ${a}=<number> with a finite numeric value`)}n[r]=i}return n}function Om(t){return new v(`${t} needs a value`,`Use ${t}=<value>`)}function Ni(t,e){let n=Zr(e),r=lu([...t],n),o=Oi(r,n)._[0],s=o===void 0?-1:r.indexOf(o);return{before:s>=0?t.slice(0,s):[...t],command:o,restArgs:s>=0?t.slice(s+1):[]}}function _m(t,e){let n=Zr(e);for(let r=0;r<t.length;r+=1){let o=t[r]??"";if(o===_i)return-1;if(o===Rm||!o.startsWith("-"))return r;if(dA(o,n,e))r+=1}return-1}function dA(t,e,n){if(t.startsWith(`--${Fn}`))return!1;let r=cs.exec(t),o=r??ls.exec(t);if(!o||o[2]!==void 0)return!1;let s=r?o[1]??"":o[1]?.at(-1)??"",i=n[as(s,e)]?.type;return i==="string"||i==="number"}function cu(t,e,n=e){let r=Zr(e),{before:o,command:s,restArgs:i}=Ni(t,e),a=Zr(n);iu(o,r,e,!0),iu(t,a,n,!0);let{_:c,...l}=Oi(Pm(o,r,e),r);Pi(l,e,"Place command options after the command name",o);let{_:u,...d}=Oi(lu(i,a),a),p=Im({...Am(l,e,r),...Am(d,n,a)},e);return{command:s,flags:p,restArgs:i}}function Am(t,e,n){return Object.fromEntries(Object.entries(t).filter(([r])=>Object.hasOwn(e,r)||Object.hasOwn(n.alias,r)))}function Di(t,e){return Object.fromEntries(Object.keys(e).flatMap((n)=>{let r=t[n];return r===void 0?[]:[[n,r]]}))}function us(t,e={}){let n=Zr(e),r=pA(t,n);iu(r,n,e);let o=Oi(Pm(r,n,e),n),{_:s,...i}=o;return{args:Im(i,e),rawPositionals:s.map(String)}}function iu(t,e,n,r=!1){let o=new Set;for(let s of t){if(s===_i)break;let i=s.match(/^-+/)?.[0];if(!i||au.test(s))continue;let a=s.slice(i.length),c=a.split("=",Cm)[0]??"",l=a.startsWith(Fn)?[a.slice(Fn.length)]:i.length===sA?[c]:[...c];for(let u of l){let d=as(u,e);if(r&&!Object.hasOwn(n,d))continue;if(o.has(d))throw new v(`${zr(d,n)} can only be provided once`);o.add(d)}}}function Li(t,e){let n=t.indexOf(_i);return t.map((r,o)=>n>=0&&o>=n?r:e(r,t[o+1]))}function lu(t,e){return Li(t,(n)=>{let r=cs.exec(n)??ls.exec(n);if(!r||r[2]!==void 0||n.startsWith(`--${Fn}`))return n;let o=n.startsWith("--")?r[1]??"":r[1]?.at(-1)??"";return e.boolean.includes(as(o,e))?`${n}=true`:n})}function Pm(t,e,n){let r=(i)=>n[as(i,e)]?.type,o=(i)=>i!==void 0&&!i.startsWith("-"),s=Li(t,(i,a)=>{let c=cs.exec(i),l=c?null:ls.exec(i);if(i.startsWith(`--${Fn}`)||au.test(i))return i;let u=c?[c[1]??""]:[...l?.[1]??""],d=c?c[2]:l?.[2];for(let[p,g]of u.entries()){let f=r(g),y=p===u.length-1,S=zr(as(g,e),n),I=!y||d===void 0&&!o(a);if(f==="string"&&(I||d===""))throw Om(S);if(f==="number"&&I)throw new v(`${S} needs a value`,`Use ${S}=<number>`);if(f==="boolean"&&y&&d!==void 0&&!iA.has(d))throw new v(`Invalid value for ${S}: "${d}"`,`Use ${S}=true or ${S}=false`)}return i});return lu(s,e)}function pA(t,e){return Li(t,(n)=>n.replace(/^--(no-[^=]+)(=.*)?$/,(r,o,s)=>{let i=e.alias[o];return i&&e.boolean.includes(i)?`--${i}${s??""}`:r}))}function Mi(t,e){let n={},r=Object.entries(e);for(let[o,[s,i]]of r.entries())n[s]=i.variadic?t.slice(o):t[o];return n}function ji(t,e){for(let[n,r]of Object.entries(e)){if(!r.required)continue;let o=t[n];if(Array.isArray(o)?o.length===0:!o)return`Missing required argument: <${n}${r.variadic?"...":""}>`}return null}function Nm(t,e){let n=Object.values(e);if(n.some((r)=>r.variadic))return;return t[n.length]}var gA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,mA=new Set(["help","json"]),fA=/^[a-zA-Z0-9]$/,hA=new Set(["h","j"]);function Fi(){return(t)=>{let e={args:t.args??{},description:t.description,examples:t.examples??[],json:t.json??!1,name:t.name,passthrough:t.passthrough??!1,positionals:t.positionals??{},prompts:t.prompts??!1,run:t.run,strict:t.strict??!0,subcommands:t.subcommands??[]};return yA(e),Object.freeze(e)}}function Gi(t,e){let n=uu(e.map((r)=>r.name));if(n!==void 0)throw Error(`${t} has more than one command named "${n}"`)}function yA(t){let e=`Command "${t.name}"`;if(!gA.test(t.name))throw Error(`${e} must be named with a lower-case word such as "list" or "dry-run"`);if(!t.run&&t.subcommands.length===0)throw Error(`${e} needs run or subcommands`);for(let[u,d]of Object.entries(t.args)){if(mA.has(Me(u)))throw Error(`${e} cannot define the option "${u}": --${Me(u)} is a global flag`);if(d.alias!==void 0&&hA.has(d.alias))throw Error(`${e} cannot give "${u}" the alias -${d.alias}: it belongs to a global flag`)}let n=Object.keys(t.args).map(Me),r=uu(n);if(r!==void 0)throw Error(`${e} has more than one option named --${r}`);let o=Object.values(t.args).flatMap((u)=>u.alias??[]),s=o.find((u)=>!fA.test(u));if(s!==void 0)throw Error(`${e} uses the alias "${s}": an alias is one letter or digit`);let i=o.find((u)=>n.includes(u));if(i!==void 0)throw Error(`${e} uses the alias -${i}, which is also an option's name`);let a=uu(o);if(a!==void 0)throw Error(`${e} uses the alias -${a} more than once`);let c=Object.keys(t.positionals),l=c.find((u)=>t.positionals[u]?.variadic);if(l!==void 0&&l!==c.at(-1))throw Error(`${e} declares the variadic positional "${l}" before other positionals`);if(t.passthrough&&(!t.run||l===void 0))throw Error(`${e} uses passthrough, which needs run and a variadic last positional`);Gi(e,t.subcommands)}function uu(t){return t.find((e,n)=>t.indexOf(e)!==n)}function st(t){return t}import{Console as AA}from"console";import{Writable as CA}from"stream";import{format as RA,stripVTControlCharacters as IA}from"util";var Gn={active:!1};var kA=new Set(["0","false"]);function ds(t){if(process.env.NO_COLOR)return!1;let e=process.env.FORCE_COLOR;if(e!==void 0)return!kA.has(e);return t?.isTTY===!0}var wA=ds(process.stdout),Mm=["black","blue","cyan","gray","green","magenta","red","white","yellow"],SA=["bold","dim","italic","underline","reset"],jm={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},vA={black:"\x1B[30m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",green:"\x1B[32m",magenta:"\x1B[35m",red:"\x1B[31m",white:"\x1B[37m",yellow:"\x1B[33m"},bA={black:"\x1B[40m",blue:"\x1B[44m",cyan:"\x1B[46m",gray:"\x1B[100m",green:"\x1B[42m",magenta:"\x1B[45m",red:"\x1B[41m",white:"\x1B[47m",yellow:"\x1B[43m"},Dm={"\x1B[30m":"\x1B[90m","\x1B[31m":"\x1B[91m","\x1B[32m":"\x1B[92m","\x1B[33m":"\x1B[93m","\x1B[34m":"\x1B[94m","\x1B[35m":"\x1B[95m","\x1B[36m":"\x1B[96m","\x1B[37m":"\x1B[97m"};function Hi(t){return(e)=>wA&&!Gn.active?`${t}${e}${jm.reset}`:e}function EA(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<32&&n!==27)return!1}return!0}function Lm({bright:t=!1,color:e}){let n=Bun.color(e,"ansi"),r=typeof n==="string"&&n.length>0&&EA(n)?n:vA[e];if(!r)return"";return t&&r in Dm?Dm[r]:r}var $A=Mm.reduce((t,e)=>{let n=Lm({color:e});if(n)t[e]=Hi(n);let r=Lm({bright:!0,color:e});if(r)t[`${e}Bright`]=Hi(r);return t},{}),TA=SA.reduce((t,e)=>(t[e]=Hi(jm[e]),t),{}),xA=Mm.reduce((t,e)=>{let n=bA[e];if(n){let r=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[r]=Hi(n)}return t},{}),w={...$A,...TA,...xA};var OA=2,Hm=["clear","count","countReset","debug","dir","dirxml","group","groupCollapsed","groupEnd","info","log","table"],_A=[...Hm,"trace","write"],PA=1,NA="EPIPE",DA="EIO",dt={closedStreams:new Set,documentWritten:!1,jsonRuns:0,outputGuarded:!1,restoreStdout:void 0,sealed:!1,stdoutClosed:!1,stdoutWrite:void 0};function ps(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function ur(t){return ps()&&!Gn.active&&t?.json!==!0}function Um(){return Gn.active}function Hn(t){let e=JSON.stringify(t??null,null,OA);if(e===void 0)throw TypeError("JSON cannot represent the value");return`${e}
4
+ `}function Km(){return dt.documentWritten}function Bm(){dt.sealed=!0}function wn(t){if(dt.documentWritten=!0,dt.sealed||dt.stdoutClosed)return;let e=dt.stdoutWrite??process.stdout.write;try{e.call(process.stdout,t)}catch(n){if(!Ui(n,process.stdout))throw n;dt.stdoutClosed=!0}}function Vm(){if(dt.outputGuarded)return;dt.outputGuarded=!0,process.stdout.write=Fm(process.stdout.write,!0),console.write=Fm(console.write,0),process.stdout.on("error",(t)=>{if(!Ui(t,process.stdout))throw t;dt.stdoutClosed=!0}),process.stderr.on("error",(t)=>{if(!Ui(t,process.stderr))throw t});for(let t of[process.stdout,process.stderr])t.once("close",()=>dt.closedStreams.add(t))}function Fm(t,e){let n=(r)=>{let o=r.at(-1);if(typeof o==="function")queueMicrotask(()=>o());return e};return function(...o){if(dt.stdoutClosed)return n(o);try{return t.apply(this,o)}catch(s){if(!Ui(s,process.stdout))throw s;return dt.stdoutClosed=!0,n(o)}}}function Ui(t,e){if(!(t instanceof Error))return!1;let n=Reflect.get(t,"code");return n===NA||n===DA&&e.isTTY===!0}function Ki(){let t=ds(process.stderr);return new CA({decodeStrings:!1,write(e,n,r){process.stderr.write(t?e:IA(e)),r()}})}async function Wm(t,e){if(!t)return e();dt.jsonRuns+=1,dt.restoreStdout??=LA(),Gn.active=!0;try{return await e()}finally{if(dt.jsonRuns-=1,Gn.active=dt.jsonRuns>0,!Gn.active&&!dt.outputGuarded)dt.restoreStdout?.(),dt.restoreStdout=void 0}}async function Jm(t){let e=Promise.all([dt.stdoutClosed?void 0:Gm(process.stdout),Gm(process.stderr)]);await(t===void 0?e:Promise.race([e,Bun.sleep(t)]))}function Gm(t){if(t.writableFinished||dt.closedStreams.has(t))return Promise.resolve();return new Promise((e)=>{t.once("close",e),t.once("finish",e),t.once("error",()=>e()),t.end(()=>e())})}function LA(){let t=process.stdout.write,e=new AA({stderr:process.stderr,stdout:process.stderr}),n=Object.fromEntries(_A.map((o)=>[o,console[o]])),r=Object.fromEntries(Hm.map((o)=>[o,e[o].bind(e)]));return dt.stdoutWrite=t,process.stdout.write=process.stderr.write.bind(process.stderr),Object.assign(console,r,{trace:MA(e),write:jA}),()=>{process.stdout.write=t,Object.assign(console,n),dt.stdoutWrite=void 0}}function MA(t){let e=(...n)=>{let r={};Error.captureStackTrace(r,e);let o=r.stack?.split(`
5
+ `).slice(PA)??[];t.error([`Trace: ${RA(...n)}`,...o].join(`
6
+ `))};return e}function jA(...t){let e=Buffer.concat(t.map(FA));return process.stderr.write(e),e.byteLength}function FA(t){if(typeof t==="string")return Buffer.from(t);return ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t)}var Se={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"},json:{alias:"j",description:"Write one JSON document to stdout",type:"boolean"}},Qr={help:Se.help,json:Se.json},dr="help",Bi={[zt]:"success",[ss]:"failure",[Tm]:"usage error"};import{stripVTControlCharacters as xu}from"util";import{styleText as QA}from"util";import{stdout as lf,stdin as tC}from"process";import eC from"readline";var qm=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let n=0;t.lastIndex=0;while(t.test(e))n+=1;return e.length-n}})(),Ym=(t)=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Xm=(t)=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var GA=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,HA=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,zm=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,UA=/\t{1,1000}/y,Zm=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,KA=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,BA=/\p{M}+/gu,VA={limit:1/0,ellipsis:""},Qm=(t,e={},n={})=>{let r=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?Qm(o,VA,n).width:0),i=0,a=n.controlWidth??0,c=n.tabWidth??8,l=n.emojiWidth??2,u=2,d=n.regularWidth??1,p=n.wideWidth??2,g=[[KA,d],[GA,0],[HA,a],[UA,c],[Zm,l],[zm,p]],f=0,y=0,S=t.length,I=0,C=!1,q=S,G=Math.max(0,r-s),N=0,H=0,A=0,R=0;t:while(!0){if(H>N||y>=S&&y>f){let B=t.slice(N,H)||t.slice(f,y);I=0;for(let _t of B.replaceAll(BA,"")){let Q=_t.codePointAt(0)||0;if(Ym(Q))R=2;else if(Xm(Q))R=p;else R=d;if(A+R>G)q=Math.min(q,Math.max(N,f)+I);if(A+R>r){C=!0;break t}I+=_t.length,A+=R}N=H=0}if(y>=S)break t;for(let B=0,_t=g.length;B<_t;B++){let[Q,Xr]=g[B];if(Q.lastIndex=y,Q.test(t)){if(I=Q===zm?qm(t.slice(y,Q.lastIndex)):Q===Zm?1:Q.lastIndex-y,R=I*Xr,A+R>G)q=Math.min(q,y+Math.floor((G-A)/Xr));if(A+R>r){C=!0;break t}A+=R,N=f,H=y,y=f=Q.lastIndex;continue t}}y+=1}return{width:C?G:A,index:C?q:S,truncated:C,ellipsed:C&&r>=s}},tf=Qm;var WA={limit:1/0,ellipsis:"",ellipsisWidth:0},JA=(t,e={})=>tf(t,WA,e).width,Lt=JA;var Vi="\x1B",sf="\x9B",qA=39,pu="\x07",af="[",YA="]",cf="m",gu=`${YA}8;;`,ef=new RegExp(`(?:\\${af}(?<code>\\d+)m|\\${gu}(?<uri>.*)${pu})`,"y"),nf=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},rf=(t)=>`${Vi}${af}${t}${cf}`,of=(t)=>`${Vi}${gu}${t}${pu}`,du=(t,e,n)=>{let r=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:Lt(i),c=r.next(),l=r.next(),u=0;while(!c.done){let d=c.value,p=Lt(d);if(a+p<=n)t[t.length-1]+=d;else t.push(d),a=0;if(d===Vi||d===sf)o=!0,s=e.startsWith(gu,u+1);if(o){if(s){if(d===pu)o=!1,s=!1}else if(d===cf)o=!1}else if(a+=p,a===n&&!l.done)t.push(""),a=0;c=l,l=r.next(),u+=d.length}if(i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1)t[t.length-2]+=t.pop()},XA=(t)=>{let e=t.split(" "),n=e.length;while(n){if(Lt(e[n-1]))break;n--}if(n===e.length)return t;return e.slice(0,n).join(" ")+e.slice(n).join("")},zA=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let r="",o,s,i=t.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let p=i[d];if(n.trim!==!1){let f=a.at(-1)??"",y=f.trimStart();if(f.length!==y.length)a[a.length-1]=y,c=Lt(y)}if(d!==0){if(c>=e&&(n.wordWrap===!1||n.trim===!1))a.push(""),c=0;if(c||n.trim===!1)a[a.length-1]+=" ",c++}let g=Lt(p);if(n.hard&&g>e){let f=e-c,y=1+Math.floor((g-f-1)/e);if(Math.floor((g-1)/e)<y)a.push("");du(a,p,e),c=Lt(a.at(-1)??"");continue}if(c+g>e&&c&&g){if(n.wordWrap===!1&&c<e){du(a,p,e),c=Lt(a.at(-1)??"");continue}a.push(""),c=0}if(c+g>e&&n.wordWrap===!1){du(a,p,e),c=Lt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=g}if(n.trim!==!1)a=a.map((d)=>XA(d));let l=a.join(`
7
+ `),u=!1;for(let d=0;d<l.length;d++){let p=l[d];if(r+=p,!u){if(u=p>="\uD800"&&p<="\uDBFF",u)continue}else u=!1;if(p===Vi||p===sf){ef.lastIndex=d+1;let f=ef.exec(l)?.groups;if(f?.code!==void 0){let y=Number.parseFloat(f.code);o=y===qA?void 0:y}else if(f?.uri!==void 0)s=f.uri.length===0?void 0:f.uri}if(l[d+1]===`
8
+ `){if(s)r+=of("");let g=o?nf(o):void 0;if(o&&g)r+=rf(g)}else if(p===`
9
+ `){if(o&&nf(o))r+=rf(o);if(s)r+=of(s)}}return r},ZA=/\r?\n/;function Un(t,e,n){return String(t).normalize().split(ZA).map((r)=>zA(r,e,n)).join(`
10
+ `)}var ve={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let n="";if(t<0)n+=`\x1B[${-t}D`;else if(t>0)n+=`\x1B[${t}C`;if(e<0)n+=`\x1B[${-e}A`;else if(e>0)n+=`\x1B[${e}B`;return n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"};var gs={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?ve.up():"");if(t)e+=ve.left;return e}};function pr(t,e,n){if(!n.some((i)=>!i.disabled))return t;let r=t+e,o=Math.max(n.length-1,0),s=r<0?o:r>o?0:r;return n[s]?.disabled?pr(s,e<0?-1:1,n):s}var nC=["up","down","left","right","space","enter","cancel"],rC=["January","February","March","April","May","June","July","August","September","October","November","December"],Mt={actions:new Set(nC),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,accessible:void 0,date:{monthNames:[...rC],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function uf(t){if(t!==void 0)return t;if(Mt.accessible!==void 0)return Mt.accessible;let e=process.env.ACCESSIBLE;return e!==void 0&&e!==""&&e!=="0"&&e!=="false"}function df(t,e){if(typeof t=="string")return Mt.aliases.get(t)===e;for(let n of t)if(n!==void 0&&df(n,e))return!0;return!1}function oC(t,e){if(t===e)return;let n=t.split(`
11
11
  `),r=e.split(`
12
- `),o=Math.max(n.length,r.length),s=[];for(let i=0;i<o;i++)n[i]!==r[i]&&s.push(i);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:o}}var fW=globalThis.process.platform.startsWith("win"),mi=Symbol("clack:cancel");function fi(t){return t===mi}function gi(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var _r=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,$l=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function on(t,e,n,r=n,o=n,s){let i=_r(t??rm),a=xt(n);return An(e,i-a,{hard:!0,trim:!1}).split(`
12
+ `),o=Math.max(n.length,r.length),s=[];for(let i=0;i<o;i++)n[i]!==r[i]&&s.push(i);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:o}}var Z5=globalThis.process.platform.startsWith("win"),Ji=Symbol("clack:cancel");function qi(t){return t===Ji}function Wi(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var to=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,mu=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function Sn(t,e,n,r=n,o=n,s){let i=to(t??lf),a=Lt(n);return Un(e,i-a,{hard:!0,trim:!1}).split(`
13
13
  `).map((c,l,u)=>{let d=s?s(c,l):c;return l===0?`${r}${d}`:l===u.length-1?`${o}${d}`:`${n}${d}`}).join(`
14
- `)}function im(t,e){if("~standard"in t){let n=t["~standard"].validate(e);return n instanceof Promise?n.then((r)=>r.issues?.at(0)?.message):n.issues?.at(0)?.message}return t(e)}var hi=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return om(this.opts.accessible)}constructor(e,n=!0){let{input:r=Gv,output:o=rm,render:s,signal:i,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=s.bind(this),this._track=n,this._abortSignal=i,this.input=r,this.output=o}unsubscribe(){this._subscribers.clear()}setSubscriber(e,n){let r=this._subscribers.get(e)??[];r.push(n),this._subscribers.set(e,r)}on(e,n){this.setSubscriber(e,{cb:n})}once(e,n){this.setSubscriber(e,{cb:n,once:!0})}emit(e,...n){let r=this._subscribers.get(e)??[],o=[];for(let s of r)s.cb(...n),s.once&&o.push(()=>r.splice(r.indexOf(s),1));for(let s of o)s()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(mi);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Hv.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),gi(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(ce.show),this.output.off("resize",this.render),gi(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(ce.show),this.output.off("resize",this.render),gi(this.input,!1),e(mi)})})}_isActionKey(e,n){return e==="\t"}_shouldSubmit(e,n){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,n){this.userInput=e??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress(e,n){if(this.state!=="validating"){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(e,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&At.aliases.has(n.name)&&this.emit("cursor",At.aliases.get(n.name)),At.actions.has(n.name)&&this.emit("cursor",n.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,n),n?.name==="return"&&this._shouldSubmit(e,n)){if(this.opts.validate){let r=im(this.opts.validate,this.value),o;r instanceof Promise?(this.state="validating",this.render(),o=await r):o=r,o&&(this.error=o instanceof Error?o.message:o,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}sm([e,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
15
- `),gi(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=An(this._prevFrame,_r(this.output),{hard:!0,trim:!1}).split(`
16
- `).length-1;this.output.write(ce.move(-999,e*-1))}render(){let e=An(this._render(this)??"",_r(this.output),{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(ce.hide);else{let n=Bv(this._prevFrame,e),r=$l(this.output);if(this.restoreCursor(),n){let o=Math.max(0,n.numLinesAfter-r),s=Math.max(0,n.numLinesBefore-r),i=n.lines.find((a)=>a>=o);if(i===void 0){this._prevFrame=e;return}if(n.lines.length===1){this.output.write(ce.move(0,i-s)),this.output.write(Go.lines(1));let a=e.split(`
17
- `);this.output.write(a[i]),this._prevFrame=e,this.output.write(ce.move(0,a.length-i-1));return}else if(n.lines.length>1){if(o<s)i=o;else{let c=i-s;c>0&&this.output.write(ce.move(0,c))}this.output.write(Go.down());let a=e.split(`
14
+ `)}function pf(t,e){if("~standard"in t){let n=t["~standard"].validate(e);return n instanceof Promise?n.then((r)=>r.issues?.at(0)?.message):n.issues?.at(0)?.message}return t(e)}var Yi=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return uf(this.opts.accessible)}constructor(e,n=!0){let{input:r=tC,output:o=lf,render:s,signal:i,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=s.bind(this),this._track=n,this._abortSignal=i,this.input=r,this.output=o}unsubscribe(){this._subscribers.clear()}setSubscriber(e,n){let r=this._subscribers.get(e)??[];r.push(n),this._subscribers.set(e,r)}on(e,n){this.setSubscriber(e,{cb:n})}once(e,n){this.setSubscriber(e,{cb:n,once:!0})}emit(e,...n){let r=this._subscribers.get(e)??[],o=[];for(let s of r)s.cb(...n),s.once&&o.push(()=>r.splice(r.indexOf(s),1));for(let s of o)s()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Ji);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=eC.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Wi(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(ve.show),this.output.off("resize",this.render),Wi(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(ve.show),this.output.off("resize",this.render),Wi(this.input,!1),e(Ji)})})}_isActionKey(e,n){return e==="\t"}_shouldSubmit(e,n){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,n){this.userInput=e??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress(e,n){if(this.state!=="validating"){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(e,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&Mt.aliases.has(n.name)&&this.emit("cursor",Mt.aliases.get(n.name)),Mt.actions.has(n.name)&&this.emit("cursor",n.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,n),n?.name==="return"&&this._shouldSubmit(e,n)){if(this.opts.validate){let r=pf(this.opts.validate,this.value),o;r instanceof Promise?(this.state="validating",this.render(),o=await r):o=r,o&&(this.error=o instanceof Error?o.message:o,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}df([e,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
15
+ `),Wi(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Un(this._prevFrame,to(this.output),{hard:!0,trim:!1}).split(`
16
+ `).length-1;this.output.write(ve.move(-999,e*-1))}render(){let e=Un(this._render(this)??"",to(this.output),{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(ve.hide);else{let n=oC(this._prevFrame,e),r=mu(this.output);if(this.restoreCursor(),n){let o=Math.max(0,n.numLinesAfter-r),s=Math.max(0,n.numLinesBefore-r),i=n.lines.find((a)=>a>=o);if(i===void 0){this._prevFrame=e;return}if(n.lines.length===1){this.output.write(ve.move(0,i-s)),this.output.write(gs.lines(1));let a=e.split(`
17
+ `);this.output.write(a[i]),this._prevFrame=e,this.output.write(ve.move(0,a.length-i-1));return}else if(n.lines.length>1){if(o<s)i=o;else{let c=i-s;c>0&&this.output.write(ve.move(0,c))}this.output.write(gs.down());let a=e.split(`
18
18
  `).slice(i);this.output.write(a.join(`
19
- `)),this._prevFrame=e;return}}this.output.write(Go.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};class bl extends hi{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(e)=>{this.output.write(ce.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class vl extends hi{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((t)=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,e=this.value!==void 0&&this.value.length===t.length;this.value=e?[]:t.map((n)=>n.value)}toggleInvert(){let t=this.value;if(!t)return;let e=this._enabledOptions.filter((n)=>!t.includes(n.value));this.value=e.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter((e)=>e!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let e=Math.max(this.options.findIndex(({value:n})=>n===t.cursorAt),0);this.cursor=this.options[e]?.disabled?Yn(e,1,this.options):e,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert(),r.name===void 0&&n==="\u3000"&&this.toggleValue()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=Yn(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Yn(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var am=class extends hi{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let n=this.options.findIndex(({value:o})=>o===e.initialValue),r=n===-1?0:n;this.cursor=this.options[r]?.disabled?Yn(r,1,this.options):r,this.changeValue(),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=Yn(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=Yn(this.cursor,1,this.options);break}this.changeValue()})}};class xl extends hi{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let e=t.slice(0,this.cursor),n=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return`${e}${Fv("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",(e)=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as h,stripVTControlCharacters as AW}from"util";import le from"process";function Wv(){if(le.platform!=="win32")return le.env.TERM!=="linux";return Boolean(le.env.CI)||Boolean(le.env.WT_SESSION)||Boolean(le.env.TERMINUS_SUBLIME)||le.env.ConEmuTask==="{cmd::Cmder}"||le.env.TERM_PROGRAM==="Terminus-Sublime"||le.env.TERM_PROGRAM==="vscode"||le.env.TERM==="xterm-256color"||le.env.TERM==="alacritty"||le.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Rl=Wv(),gm=()=>process.env.CI==="true";var z=(t,e)=>Rl?t:e,cm=z("\u25C6","*"),Il=z("\u25A0","x"),Ol=z("\u25B2","x"),Uo=z("\u25C7","o"),Vv=z("\u250C","T"),G=z("\u2502","|"),Ge=z("\u2514","\u2014"),_W=z("\u2510","T"),PW=z("\u2518","\u2014"),Al=z("\u25CF",">"),ki=z("\u25CB"," "),Jv=z("\u25FB","[\u2022]"),lm=z("\u25FC","[+]"),um=z("\u25FB","[ ]"),NW=z("\u25AA","\u2022"),dm=z("\u2500","-"),qv=z("\u256E","+"),Yv=z("\u251C","+"),Xv=z("\u256F","+"),zv=z("\u2570","+"),DW=z("\u256D","+"),Zv=z("\u25CF","\u2022"),Qv=z("\u25C6","*"),tx=z("\u25B2","!"),ex=z("\u25A0","x"),wi=(t)=>{switch(t){case"initial":case"active":return h("cyan",cm);case"cancel":return h("red",Il);case"error":return h("yellow",Ol);case"submit":return h("green",Uo);case"validating":return h("dim",cm)}},mm=(t)=>{switch(t){case"initial":case"active":return h("cyan",G);case"cancel":return h("red",G);case"error":return h("yellow",G);case"submit":return h("green",G)}};function fm(t,e,n){let r=n?`${h("cyan",G)} `:"",o=on(t,e.join(" \u2022 "),r).split(`
20
- `);return n&&o.push(h("cyan",Ge)),o}var pm=(t,e,n,r,o,s=!1)=>{let i=e,a=0;if(s)for(let c=r-1;c>=n;c--){let l=t[c];if(l&&(i-=l.length),a++,i<=o)break}else for(let c=n;c<r;c++){let l=t[c];if(l&&(i-=l.length),a++,i<=o)break}return{lineCount:i,removals:a}},Cl=({cursor:t,options:e,style:n,output:r=process.stdout,maxItems:o=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:i=4})=>{let a=_r(r)-s,c=$l(r),l=h("dim","..."),u=Math.max(c-i,0),d=Math.max(Math.min(o,u),5),p=0;t>=d-3&&(p=Math.max(Math.min(t-d+3,e.length-d),0));let m=d<e.length&&p>0,f=d<e.length&&p+d<e.length,y=Math.min(p+d,e.length),S=[],R=0;m&&R++,f&&R++;let v=p+(m?1:0),H=y-(f?1:0);for(let N=v;N<H;N++){let U=e[N],_=U!==void 0?n(U,N===t):"",A=An(_,a,{hard:!0,trim:!1}).split(`
21
- `);S.push(A),R+=A.length}if(R>u){let N=0,U=0,_=R,A=t-v,B=u,Dt=()=>pm(S,_,0,A,B),Yt=()=>pm(S,_,A+1,S.length,B,!0);m?({lineCount:_,removals:N}=Dt(),_>B&&(f||(B-=1),{lineCount:_,removals:U}=Yt())):(f||(B-=1),{lineCount:_,removals:U}=Yt(),_>B&&(B-=1,{lineCount:_,removals:N}=Dt())),N>0&&(m=!0,S.splice(0,N)),U>0&&(f=!0,S.splice(S.length-U,U))}let J=[];m&&J.push(l);for(let N of S)for(let U of N)J.push(U);return f&&J.push(l),J};var hm=(t)=>{let e=t.active??"Yes",n=t.inactive??"No";return new bl({active:e,inactive:n,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let r=t.withGuide??At.withGuide,o=`${wi(this.state)} `,s=r?`${h("gray",G)} `:"",i=on(t.output,t.message,s,o),a=`${r?`${h("gray",G)}
19
+ `)),this._prevFrame=e;return}}this.output.write(gs.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};class fu extends Yi{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(e)=>{this.output.write(ve.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class hu extends Yi{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((t)=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,e=this.value!==void 0&&this.value.length===t.length;this.value=e?[]:t.map((n)=>n.value)}toggleInvert(){let t=this.value;if(!t)return;let e=this._enabledOptions.filter((n)=>!t.includes(n.value));this.value=e.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter((e)=>e!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let e=Math.max(this.options.findIndex(({value:n})=>n===t.cursorAt),0);this.cursor=this.options[e]?.disabled?pr(e,1,this.options):e,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert(),r.name===void 0&&n==="\u3000"&&this.toggleValue()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=pr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var gf=class extends Yi{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let n=this.options.findIndex(({value:o})=>o===e.initialValue),r=n===-1?0:n;this.cursor=this.options[r]?.disabled?pr(r,1,this.options):r,this.changeValue(),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=pr(this.cursor,1,this.options);break}this.changeValue()})}};class yu extends Yi{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let e=t.slice(0,this.cursor),n=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return`${e}${QA("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",(e)=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as h,stripVTControlCharacters as uY}from"util";import be from"process";function sC(){if(be.platform!=="win32")return be.env.TERM!=="linux";return Boolean(be.env.CI)||Boolean(be.env.WT_SESSION)||Boolean(be.env.TERMINUS_SUBLIME)||be.env.ConEmuTask==="{cmd::Cmder}"||be.env.TERM_PROGRAM==="Terminus-Sublime"||be.env.TERM_PROGRAM==="vscode"||be.env.TERM==="xterm-256color"||be.env.TERM==="alacritty"||be.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Su=sC(),wf=()=>process.env.CI==="true";var tt=(t,e)=>Su?t:e,mf=tt("\u25C6","*"),vu=tt("\u25A0","x"),bu=tt("\u25B2","x"),fs=tt("\u25C7","o"),iC=tt("\u250C","T"),U=tt("\u2502","|"),Ze=tt("\u2514","\u2014"),fY=tt("\u2510","T"),hY=tt("\u2518","\u2014"),ku=tt("\u25CF",">"),zi=tt("\u25CB"," "),aC=tt("\u25FB","[\u2022]"),ff=tt("\u25FC","[+]"),hf=tt("\u25FB","[ ]"),yY=tt("\u25AA","\u2022"),yf=tt("\u2500","-"),cC=tt("\u256E","+"),lC=tt("\u251C","+"),uC=tt("\u256F","+"),dC=tt("\u2570","+"),kY=tt("\u256D","+"),pC=tt("\u25CF","\u2022"),gC=tt("\u25C6","*"),mC=tt("\u25B2","!"),fC=tt("\u25A0","x"),Zi=(t)=>{switch(t){case"initial":case"active":return h("cyan",mf);case"cancel":return h("red",vu);case"error":return h("yellow",bu);case"submit":return h("green",fs);case"validating":return h("dim",mf)}},Sf=(t)=>{switch(t){case"initial":case"active":return h("cyan",U);case"cancel":return h("red",U);case"error":return h("yellow",U);case"submit":return h("green",U)}};function vf(t,e,n){let r=n?`${h("cyan",U)} `:"",o=Sn(t,e.join(" \u2022 "),r).split(`
20
+ `);return n&&o.push(h("cyan",Ze)),o}var kf=(t,e,n,r,o,s=!1)=>{let i=e,a=0;if(s)for(let c=r-1;c>=n;c--){let l=t[c];if(l&&(i-=l.length),a++,i<=o)break}else for(let c=n;c<r;c++){let l=t[c];if(l&&(i-=l.length),a++,i<=o)break}return{lineCount:i,removals:a}},wu=({cursor:t,options:e,style:n,output:r=process.stdout,maxItems:o=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:i=4})=>{let a=to(r)-s,c=mu(r),l=h("dim","..."),u=Math.max(c-i,0),d=Math.max(Math.min(o,u),5),p=0;t>=d-3&&(p=Math.max(Math.min(t-d+3,e.length-d),0));let g=d<e.length&&p>0,f=d<e.length&&p+d<e.length,y=Math.min(p+d,e.length),S=[],I=0;g&&I++,f&&I++;let C=p+(g?1:0),q=y-(f?1:0);for(let N=C;N<q;N++){let H=e[N],A=H!==void 0?n(H,N===t):"",R=Un(A,a,{hard:!0,trim:!1}).split(`
21
+ `);S.push(R),I+=R.length}if(I>u){let N=0,H=0,A=I,R=t-C,B=u,_t=()=>kf(S,A,0,R,B),Q=()=>kf(S,A,R+1,S.length,B,!0);g?({lineCount:A,removals:N}=_t(),A>B&&(f||(B-=1),{lineCount:A,removals:H}=Q())):(f||(B-=1),{lineCount:A,removals:H}=Q(),A>B&&(B-=1,{lineCount:A,removals:N}=_t())),N>0&&(g=!0,S.splice(0,N)),H>0&&(f=!0,S.splice(S.length-H,H))}let G=[];g&&G.push(l);for(let N of S)for(let H of N)G.push(H);return f&&G.push(l),G};var bf=(t)=>{let e=t.active??"Yes",n=t.inactive??"No";return new fu({active:e,inactive:n,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let r=t.withGuide??Mt.withGuide,o=`${Zi(this.state)} `,s=r?`${h("gray",U)} `:"",i=Sn(t.output,t.message,s,o),a=`${r?`${h("gray",U)}
22
22
  `:""}${i}
23
- `,c=this.value?e:n;switch(this.state){case"submit":{let l=r?`${h("gray",G)} `:"";return`${a}${l}${h("dim",c)}`}case"cancel":{let l=r?`${h("gray",G)} `:"";return`${a}${l}${h(["strikethrough","dim"],c)}${r?`
24
- ${h("gray",G)}`:""}`}default:{let l=r?`${h("cyan",G)} `:"",u=r?h("cyan",Ge):"";return`${a}${l}${this.value?`${h("green",Al)} ${e}`:`${h("dim",ki)} ${h("dim",e)}`}${t.vertical?r?`
25
- ${h("cyan",G)} `:`
26
- `:` ${h("dim","/")} `}${this.value?`${h("dim",ki)} ${h("dim",n)}`:`${h("green",Al)} ${n}`}
23
+ `,c=this.value?e:n;switch(this.state){case"submit":{let l=r?`${h("gray",U)} `:"";return`${a}${l}${h("dim",c)}`}case"cancel":{let l=r?`${h("gray",U)} `:"";return`${a}${l}${h(["strikethrough","dim"],c)}${r?`
24
+ ${h("gray",U)}`:""}`}default:{let l=r?`${h("cyan",U)} `:"",u=r?h("cyan",Ze):"";return`${a}${l}${this.value?`${h("green",ku)} ${e}`:`${h("dim",zi)} ${h("dim",e)}`}${t.vertical?r?`
25
+ ${h("cyan",U)} `:`
26
+ `:` ${h("dim","/")} `}${this.value?`${h("dim",zi)} ${h("dim",n)}`:`${h("green",ku)} ${n}`}
27
27
  ${u}
28
- `}}}}).prompt()};var nx=[`${h("dim","\u2191/\u2193")} to navigate`,`${h("dim","Space:")} select`,`${h("dim","Enter:")} confirm`],Ho=(t,e)=>t.split(`
28
+ `}}}}).prompt()};var hC=[`${h("dim","\u2191/\u2193")} to navigate`,`${h("dim","Space:")} select`,`${h("dim","Enter:")} confirm`],ms=(t,e)=>t.split(`
29
29
  `).map((n)=>e(n)).join(`
30
- `),ym=(t)=>{let e=(o,s)=>{let i=o.label??String(o.value);return s==="disabled"?`${h("gray",um)} ${Ho(i,(a)=>h(["strikethrough","gray"],a))}${o.hint?` ${h("dim",`(${o.hint??"disabled"})`)}`:""}`:s==="active"?`${h("cyan",Jv)} ${i}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="selected"?`${h("green",lm)} ${Ho(i,(a)=>h("dim",a))}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="cancelled"?`${Ho(i,(a)=>h(["strikethrough","dim"],a))}`:s==="active-selected"?`${h("green",lm)} ${i}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="submitted"?`${Ho(i,(a)=>h("dim",a))}`:`${h("dim",um)} ${Ho(i,(a)=>h("dim",a))}`},n=t.required??!0,r=t.showInstructions??!0;return new vl({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,validate(o){if(n&&(o===void 0||o.length===0))return`Please select at least one option.
31
- ${h("reset",h("dim",`Press ${h(["gray","bgWhite","inverse"]," space ")} to select, ${h("gray",h("bgWhite",h("inverse"," enter ")))} to submit`))}`},render(){let o=t.withGuide??At.withGuide,s=on(t.output,t.message,o?`${mm(this.state)} `:"",`${wi(this.state)} `),i=`${o?`${h("gray",G)}
30
+ `),Ef=(t)=>{let e=(o,s)=>{let i=o.label??String(o.value);return s==="disabled"?`${h("gray",hf)} ${ms(i,(a)=>h(["strikethrough","gray"],a))}${o.hint?` ${h("dim",`(${o.hint??"disabled"})`)}`:""}`:s==="active"?`${h("cyan",aC)} ${i}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="selected"?`${h("green",ff)} ${ms(i,(a)=>h("dim",a))}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="cancelled"?`${ms(i,(a)=>h(["strikethrough","dim"],a))}`:s==="active-selected"?`${h("green",ff)} ${i}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="submitted"?`${ms(i,(a)=>h("dim",a))}`:`${h("dim",hf)} ${ms(i,(a)=>h("dim",a))}`},n=t.required??!0,r=t.showInstructions??!0;return new hu({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,validate(o){if(n&&(o===void 0||o.length===0))return`Please select at least one option.
31
+ ${h("reset",h("dim",`Press ${h(["gray","bgWhite","inverse"]," space ")} to select, ${h("gray",h("bgWhite",h("inverse"," enter ")))} to submit`))}`},render(){let o=t.withGuide??Mt.withGuide,s=Sn(t.output,t.message,o?`${Sf(this.state)} `:"",`${Zi(this.state)} `),i=`${o?`${h("gray",U)}
32
32
  `:""}${s}
33
- `,a=this.value??[],c=(l,u)=>{if(l.disabled)return e(l,"disabled");let d=a.includes(l.value);return u&&d?e(l,"active-selected"):d?e(l,"selected"):e(l,u?"active":"inactive")};switch(this.state){case"submit":{let l=this.options.filter(({value:d})=>a.includes(d)).map((d)=>e(d,"submitted")).join(h("dim",", "))||h("dim","none"),u=on(t.output,l,o?`${h("gray",G)} `:"");return`${i}${u}`}case"cancel":{let l=this.options.filter(({value:d})=>a.includes(d)).map((d)=>e(d,"cancelled")).join(h("dim",", "));if(l.trim()==="")return`${i}${h("gray",G)}`;let u=on(t.output,l,o?`${h("gray",G)} `:"");return`${i}${u}${o?`
34
- ${h("gray",G)}`:""}`}case"error":{let l=o?`${h("yellow",G)} `:"",u=this.error.split(`
35
- `).map((m,f)=>f===0?`${o?`${h("yellow",Ge)} `:""}${h("yellow",m)}`:` ${m}`).join(`
33
+ `,a=this.value??[],c=(l,u)=>{if(l.disabled)return e(l,"disabled");let d=a.includes(l.value);return u&&d?e(l,"active-selected"):d?e(l,"selected"):e(l,u?"active":"inactive")};switch(this.state){case"submit":{let l=this.options.filter(({value:d})=>a.includes(d)).map((d)=>e(d,"submitted")).join(h("dim",", "))||h("dim","none"),u=Sn(t.output,l,o?`${h("gray",U)} `:"");return`${i}${u}`}case"cancel":{let l=this.options.filter(({value:d})=>a.includes(d)).map((d)=>e(d,"cancelled")).join(h("dim",", "));if(l.trim()==="")return`${i}${h("gray",U)}`;let u=Sn(t.output,l,o?`${h("gray",U)} `:"");return`${i}${u}${o?`
34
+ ${h("gray",U)}`:""}`}case"error":{let l=o?`${h("yellow",U)} `:"",u=this.error.split(`
35
+ `).map((g,f)=>f===0?`${o?`${h("yellow",Ze)} `:""}${h("yellow",g)}`:` ${g}`).join(`
36
36
  `),d=i.split(`
37
37
  `).length,p=u.split(`
38
- `).length+1;return`${i}${l}${Cl({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:l.length,rowPadding:d+p,style:c}).join(`
38
+ `).length+1;return`${i}${l}${wu({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:l.length,rowPadding:d+p,style:c}).join(`
39
39
  ${l}`)}
40
40
  ${u}
41
- `}default:{let l=o?`${h("cyan",G)} `:"",u=i.split(`
42
- `).length,d=r?fm(t.output,nx,o):o?[h("cyan",Ge)]:[],p=d.join(`
43
- `),m=d.length+1;return`${i}${l}${Cl({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:l.length,rowPadding:u+m,style:c}).join(`
41
+ `}default:{let l=o?`${h("cyan",U)} `:"",u=i.split(`
42
+ `).length,d=r?vf(t.output,hC,o):o?[h("cyan",Ze)]:[],p=d.join(`
43
+ `),g=d.length+1;return`${i}${l}${wu({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:l.length,rowPadding:u+g,style:c}).join(`
44
44
  ${l}`)}
45
45
  ${p}
46
- `}}}}).prompt()};var Lt={message:(t=[],{symbol:e=h("gray",G),secondarySymbol:n=h("gray",G),output:r=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??At.withGuide,c=a?n:"",l=a?`${e} `:"",u=a?`${n} `:"";for(let p=0;p<o;p++)i.push(c);let d=Array.isArray(t)?t:t.split(`
47
- `);if(d.length>0){let[p,...m]=d;p.length>0?i.push(`${l}${p}`):i.push(a?e:"");for(let f of m)f.length>0?i.push(`${u}${f}`):i.push(a?n:"")}r.write(`${i.join(`
46
+ `}}}}).prompt()};var Ut={message:(t=[],{symbol:e=h("gray",U),secondarySymbol:n=h("gray",U),output:r=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??Mt.withGuide,c=a?n:"",l=a?`${e} `:"",u=a?`${n} `:"";for(let p=0;p<o;p++)i.push(c);let d=Array.isArray(t)?t:t.split(`
47
+ `);if(d.length>0){let[p,...g]=d;p.length>0?i.push(`${l}${p}`):i.push(a?e:"");for(let f of g)f.length>0?i.push(`${u}${f}`):i.push(a?n:"")}r.write(`${i.join(`
48
48
  `)}
49
- `)},info:(t,e)=>{Lt.message(t,{...e,symbol:h("blue",Zv)})},success:(t,e)=>{Lt.message(t,{...e,symbol:h("green",Qv)})},step:(t,e)=>{Lt.message(t,{...e,symbol:h("green",Uo)})},warn:(t,e)=>{Lt.message(t,{...e,symbol:h("yellow",tx)})},warning:(t,e)=>{Lt.warn(t,e)},error:(t,e)=>{Lt.message(t,{...e,symbol:h("red",ex)})}},km=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??At.withGuide?`${h("gray",Ge)} `:"";n.write(`${r}${h("red",t)}
49
+ `)},info:(t,e)=>{Ut.message(t,{...e,symbol:h("blue",pC)})},success:(t,e)=>{Ut.message(t,{...e,symbol:h("green",gC)})},step:(t,e)=>{Ut.message(t,{...e,symbol:h("green",fs)})},warn:(t,e)=>{Ut.message(t,{...e,symbol:h("yellow",mC)})},warning:(t,e)=>{Ut.warn(t,e)},error:(t,e)=>{Ut.message(t,{...e,symbol:h("red",fC)})}},$f=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Mt.withGuide?`${h("gray",Ze)} `:"";n.write(`${r}${h("red",t)}
50
50
 
51
- `)},wm=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??At.withGuide?`${h("gray",Vv)} `:"";n.write(`${r}${t}
52
- `)},Sm=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??At.withGuide?`${h("gray",G)}
53
- ${h("gray",Ge)} `:"";n.write(`${r}${t}
51
+ `)},Tf=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Mt.withGuide?`${h("gray",iC)} `:"";n.write(`${r}${t}
52
+ `)},xf=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Mt.withGuide?`${h("gray",U)}
53
+ ${h("gray",Ze)} `:"";n.write(`${r}${t}
54
54
 
55
- `)};var rx=(t)=>t,ox=(t,e,n)=>{let r={hard:!0,trim:!1},o=An(t,e,r).split(`
56
- `),s=o.reduce((c,l)=>Math.max(xt(l),c),0),i=o.map(n).reduce((c,l)=>Math.max(xt(l),c),0),a=e-(i-s);return An(t,a,r)},Tm=(t="",e="",n)=>{let r=n?.output??le.stdout,o=n?.withGuide??At.withGuide,s=n?.format??rx,i=["",...ox(t,_r(r)-6,s).split(`
57
- `).map(s),""],a=xt(e),c=Math.max(i.reduce((p,m)=>{let f=xt(m);return f>p?f:p},0),a)+2,l=i.map((p)=>`${h("gray",G)} ${p}${" ".repeat(c-xt(p))}${h("gray",G)}`).join(`
58
- `),u=o?`${h("gray",G)}
59
- `:"",d=o?Yv:zv;r.write(`${u}${h("green",Uo)} ${h("reset",e)} ${h("gray",dm.repeat(Math.max(c-a-1,1))+qv)}
55
+ `)};var yC=(t)=>t,kC=(t,e,n)=>{let r={hard:!0,trim:!1},o=Un(t,e,r).split(`
56
+ `),s=o.reduce((c,l)=>Math.max(Lt(l),c),0),i=o.map(n).reduce((c,l)=>Math.max(Lt(l),c),0),a=e-(i-s);return Un(t,a,r)},Af=(t="",e="",n)=>{let r=n?.output??be.stdout,o=n?.withGuide??Mt.withGuide,s=n?.format??yC,i=["",...kC(t,to(r)-6,s).split(`
57
+ `).map(s),""],a=Lt(e),c=Math.max(i.reduce((p,g)=>{let f=Lt(g);return f>p?f:p},0),a)+2,l=i.map((p)=>`${h("gray",U)} ${p}${" ".repeat(c-Lt(p))}${h("gray",U)}`).join(`
58
+ `),u=o?`${h("gray",U)}
59
+ `:"",d=o?lC:dC;r.write(`${u}${h("green",fs)} ${h("reset",e)} ${h("gray",yf.repeat(Math.max(c-a-1,1))+cC)}
60
60
  ${l}
61
- ${h("gray",d+dm.repeat(c+2)+Xv)}
62
- `)};var LW={light:z("\u2500","-"),heavy:z("\u2501","="),block:z("\u2588","#")};var sx=[`${h("dim","\u2191/\u2193")} to navigate`,`${h("dim","Enter:")} confirm`],yi=(t,e)=>t.includes(`
61
+ ${h("gray",d+yf.repeat(c+2)+uC)}
62
+ `)};var wY={light:tt("\u2500","-"),heavy:tt("\u2501","="),block:tt("\u2588","#")};var wC=[`${h("dim","\u2191/\u2193")} to navigate`,`${h("dim","Enter:")} confirm`],Xi=(t,e)=>t.includes(`
63
63
  `)?t.split(`
64
64
  `).map((n)=>e(n)).join(`
65
- `):e(t),Em=(t)=>{let e=(r,o)=>{if(r===void 0)return"";let s=r.label??String(r.value);switch(o){case"disabled":return`${h("gray",ki)} ${yi(s,(i)=>h("gray",i))}${r.hint?` ${h("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${yi(s,(i)=>h("dim",i))}`;case"active":return`${h("green",Al)} ${s}${r.hint?` ${h("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${yi(s,(i)=>h(["strikethrough","dim"],i))}`;default:return`${h("dim",ki)} ${yi(s,(i)=>h("dim",i))}`}},n=t.showInstructions??!0;return new am({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let r=t.withGuide??At.withGuide,o=`${wi(this.state)} `,s=`${mm(this.state)} `,i=on(t.output,t.message,s,o),a=`${r?`${h("gray",G)}
65
+ `):e(t),Cf=(t)=>{let e=(r,o)=>{if(r===void 0)return"";let s=r.label??String(r.value);switch(o){case"disabled":return`${h("gray",zi)} ${Xi(s,(i)=>h("gray",i))}${r.hint?` ${h("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${Xi(s,(i)=>h("dim",i))}`;case"active":return`${h("green",ku)} ${s}${r.hint?` ${h("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${Xi(s,(i)=>h(["strikethrough","dim"],i))}`;default:return`${h("dim",zi)} ${Xi(s,(i)=>h("dim",i))}`}},n=t.showInstructions??!0;return new gf({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let r=t.withGuide??Mt.withGuide,o=`${Zi(this.state)} `,s=`${Sf(this.state)} `,i=Sn(t.output,t.message,s,o),a=`${r?`${h("gray",U)}
66
66
  `:""}${i}
67
- `;switch(this.state){case"submit":{let c=r?`${h("gray",G)} `:"",l=on(t.output,e(this.options[this.cursor],"selected"),c);return`${a}${l}`}case"cancel":{let c=r?`${h("gray",G)} `:"",l=on(t.output,e(this.options[this.cursor],"cancelled"),c);return`${a}${l}${r?`
68
- ${h("gray",G)}`:""}`}default:{let c=r?`${h("cyan",G)} `:"",l=a.split(`
69
- `).length,u=n?fm(t.output,sx,r):r?[h("cyan",Ge)]:[],d=u.join(`
70
- `),p=u.length+1;return`${a}${c}${Cl({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:c.length,rowPadding:l+p,style:(m,f)=>e(m,m.disabled?"disabled":f?"active":"inactive")}).join(`
67
+ `;switch(this.state){case"submit":{let c=r?`${h("gray",U)} `:"",l=Sn(t.output,e(this.options[this.cursor],"selected"),c);return`${a}${l}`}case"cancel":{let c=r?`${h("gray",U)} `:"",l=Sn(t.output,e(this.options[this.cursor],"cancelled"),c);return`${a}${l}${r?`
68
+ ${h("gray",U)}`:""}`}default:{let c=r?`${h("cyan",U)} `:"",l=a.split(`
69
+ `).length,u=n?vf(t.output,wC,r):r?[h("cyan",Ze)]:[],d=u.join(`
70
+ `),p=u.length+1;return`${a}${c}${wu({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:c.length,rowPadding:l+p,style:(g,f)=>e(g,g.disabled?"disabled":f?"active":"inactive")}).join(`
71
71
  ${c}`)}
72
72
  ${d}
73
- `}}}}).prompt()};var MW=`${h("gray",G)} `;var $m=(t)=>new xl({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??At.withGuide,n=`${`${e?`${h("gray",G)}
74
- `:""}${wi(this.state)} `}${t.message}
75
- `,r=t.placeholder&&t.placeholder.length>0?h("inverse",t.placeholder[0])+h("dim",t.placeholder.slice(1)):h(["inverse","hidden"],"_"),o=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"validating":{let i=e?`${h("cyan",G)} `:"",a=e?h("cyan",Ge):"",c=h("dim",o),l=h("dim","Validating...");return`${n}${i}${c}
73
+ `}}}}).prompt()};var SY=`${h("gray",U)} `;var Rf=(t)=>new yu({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??Mt.withGuide,n=`${`${e?`${h("gray",U)}
74
+ `:""}${Zi(this.state)} `}${t.message}
75
+ `,r=t.placeholder&&t.placeholder.length>0?h("inverse",t.placeholder[0])+h("dim",t.placeholder.slice(1)):h(["inverse","hidden"],"_"),o=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"validating":{let i=e?`${h("cyan",U)} `:"",a=e?h("cyan",Ze):"",c=h("dim",o),l=h("dim","Validating...");return`${n}${i}${c}
76
76
  ${a} ${l}
77
- `}case"error":{let i=this.error?` ${h("yellow",this.error)}`:"",a=e?`${h("yellow",G)} `:"",c=e?h("yellow",Ge):"";return`${n.trim()}
77
+ `}case"error":{let i=this.error?` ${h("yellow",this.error)}`:"",a=e?`${h("yellow",U)} `:"",c=e?h("yellow",Ze):"";return`${n.trim()}
78
78
  ${a}${o}
79
79
  ${c}${i}
80
- `}case"submit":{let i=s?`${e?" ":""}${h("dim",s)}`:"",a=e?h("gray",G):"";return`${n}${a}${i}`}case"cancel":{let i=s?` ${h(["strikethrough","dim"],s)}`:"",a=e?h("gray",G):"";return`${n}${a}${i}${s.trim()?`
81
- ${a}`:""}`}default:{let i=e?`${h("cyan",G)} `:"",a=e?h("cyan",Ge):"";return`${n}${i}${o}
80
+ `}case"submit":{let i=s?`${e?" ":""}${h("dim",s)}`:"",a=e?h("gray",U):"";return`${n}${a}${i}`}case"cancel":{let i=s?` ${h(["strikethrough","dim"],s)}`:"",a=e?h("gray",U):"";return`${n}${a}${i}${s.trim()?`
81
+ ${a}`:""}`}default:{let i=e?`${h("cyan",U)} `:"",a=e?h("cyan",Ze):"";return`${n}${i}${o}
82
82
  ${a}
83
- `}}}}).prompt();function bm(t=process.stdin){return t.readableEnded||t.destroyed}async function vm({edits:t,input:e=process.stdin,signal:n},r){let o=new AbortController,s=()=>o.abort(),i=(c,l)=>{if(l.sequence==="\x04"&&(!t||e.isPaused()))s()},a=r(n?AbortSignal.any([o.signal,n]):o.signal);e.on("keypress",i),e.once("end",s),e.once("close",s);try{return await a}finally{e.off("keypress",i),e.off("end",s),e.off("close",s)}}import{stripVTControlCharacters as ax}from"util";var _l=Rl?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],cx=80,lx=8,ux=3,dx="...",Pl="\r\x1B[K",px=80,gx=/\s*\n\s*/g,Ko=new Set;function Am(){for(let t of[...Ko])t.error()}function Cm({output:t=process.stdout}={}){let e=t.isTTY===!0&&!gm(),n=jo(t),r="",o=0,s=!1,i,a=(m)=>{t.write(e||n?m:ax(m))},c=()=>{let m=k.magenta(_l[o%_l.length]??""),f=".".repeat(Math.floor(o/lx)%(ux+1)),y=`${m} ${r.replace(gx," ")}${f}`;a(`${Pl}${Bun.sliceAnsi(y,0,(t.columns||px)-1)}`),o+=1},l=()=>e?c():a(`${k.magenta(_l[0]??"")} ${r}${dx}
84
- `),u=()=>(clearInterval(i),Ko.delete(p)),d=(m,f)=>{if(u())a(`${e?Pl:""}${m} ${f}
85
- `)},p={cancel(m=r){s=Ko.has(p)||s,d(k.red(Il),m)},clear(){if(u()&&e)a(Pl)},error(m=r){d(k.red(Ol),m)},get isCancelled(){return s},message(m=r){let f=xm(m);if(f===r)return;if(r=f,Ko.has(p)&&!e)l()},start(m=""){if(p.clear(),s=!1,r=xm(m),o=0,Ko.add(p),a(`${k.gray(G)}
86
- `),l(),!e)return;i=setInterval(c,cx),i.unref()},stop(m=r){d(k.green(Uo),m)}};return p}function xm(t){return t.replace(/\.+$/,"")}var fx="Pass the value as an argument or option instead";function hx(t){if(fi(t))throw new dt;return t}function yx(t){if(Jn())return;throw new T(`Cannot prompt for ${t} without a terminal`,fx)}async function Si(t,e,{edits:n=!1,hint:r}){if(yx(e.message),bm(e.input))throw new dt;return wx(r),hx(await vm({...e,edits:n},(o)=>t({...e,signal:o})))}function kx(t){return t.map((e)=>e.key?`${k.bold(e.key)} ${k.dim(e.text)}`:k.dim(e.text)).join(k.dim(" \xB7 "))}function wx(t){Lt.info(kx(t))}var Ti={confirm:[{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],multiselect:[{key:"\u2191\u2193",text:"navigate"},{key:"Space",text:"toggle"},{key:"a",text:"all"},{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],select:[{key:"\u2191\u2193",text:"navigate"},{key:"Enter",text:"select"},{key:"Esc",text:"cancel"}],text:[{key:"Enter",text:"submit"},{key:"Esc",text:"cancel"}]};async function ue(t){return Si(hm,t,{hint:Ti.confirm})}async function Nl(t){return Si($m,t,{edits:!0,hint:Ti.text})}async function Xn(t){return Si(Em,{showInstructions:!1,...t},{hint:Ti.select})}async function Ei(t){return Si(ym,{showInstructions:!1,...t},{hint:Ti.multiselect})}function zn(t){return Mg()&&t.output===void 0?{...t,output:process.stderr}:t}function Pr(t){return(e,n={})=>t(e,zn(n))}var pt={error:Pr(Lt.error),info:Pr(Lt.info),message:(t,e={})=>Lt.message(t,zn(e)),step:Pr(Lt.step),success:Pr(Lt.success),warn:Pr(Lt.warn),warning:Pr(Lt.warning)};function Zn(t,e={}){wm(t,zn(e))}function Xt(t,e={}){Sm(t,zn(e))}function Bo(t,e={}){km(t,zn(e))}function St(t,e,n={}){Tm(t,e,zn(n))}function $i(t={}){return Cm(zn(t))}import{inspect as Sx}from"util";var Tx=4;function bi(t,e=[]){if(e.length>=Tx)return[];let n=t instanceof AggregateError?t.errors:[],r=[...e,t];return[...n,...t.cause!==void 0?[t.cause]:[]].filter((s)=>!r.includes(s)).flatMap((s)=>[{hint:xi(s),message:vi(s)},...s instanceof Error?bi(s,r):[]])}function vi(t){return Ai(t instanceof Error?t.message||t.name:t)}function xi(t){return t instanceof g&&t.hint!==void 0?Ai(t.hint):void 0}function Ai(t){return typeof t==="string"?t:Sx(t,{breakLength:Number.POSITIVE_INFINITY})}var Ex="Error",$x=27,bx=new RegExp(`${String.fromCharCode($x)}\\[[\\d;]*m`,"g"),vx=9,xx=10,Ax=31,Cx=127,Rx=159,Ix=16,Ox=4;function Cn(t,{json:e}){if(Am(),Nx(t),e)rn(xn({error:_x(t)}));return Rm(t)}function _x(t){let e=Rm(t),n=Dl(vi(t));if(!(t instanceof Error))return{_tag:Ex,message:n,exitCode:e,causes:[]};let r=xi(t);return{_tag:Px(t),message:n,hint:r===void 0?void 0:Dl(r),exitCode:e,causes:bi(t).map((o)=>Dl(o.message))}}function Rm(t){if(t instanceof dt)return Ut;if(t instanceof g)return zs(t.exitCode)?t.exitCode:_o;return _o}function Px(t){let e=Reflect.get(t,"_tag");return typeof e==="string"?e:Ai(t.name)}function Nx(t){if(t instanceof dt)return;let e=ui(),n=Ci(vi(t));if(t instanceof g){let r=xi(t);if(pt.warn(k.yellow(n),{output:e}),r)pt.info(k.dim(Ci(r)),{output:e})}else pt.error(k.red(n),{output:e});if(!(t instanceof Error))return;for(let r of bi(t))if(pt.info(k.dim(`caused by: ${Ci(r.message)}`),{output:e}),r.hint)pt.info(k.dim(` ${Ci(r.hint)}`),{output:e})}function Ci(t){return Array.from(t.replace(bx,""),(e)=>{let n=e.charCodeAt(0);return n<=Ax&&n!==vx&&n!==xx||n>=Cx&&n<=Rx?`\\u${n.toString(Ix).padStart(Ox,"0")}`:e}).join("")}var Dx=500,Lx="The command stopped before it finished because nothing was left for it to wait for";function Im({json:t}){let e={ending:void 0,failed:!1,settled:!1},n=(o,s)=>(e.ending??=Mx(o,s),e.ending),r=(o)=>{if(e.failed||e.ending)return;e.failed=!0;let s=Cn(o,{json:t&&!jg()});Fg(),n(s,e.settled?void 0:Dx)};return process.on("uncaughtException",r),process.on("unhandledRejection",r),process.on("beforeExit",()=>{if(!e.settled)r(Error(Lx))}),{exit:(o)=>n(o),settle(){e.settled=!0}}}async function Mx(t,e){process.exitCode=t,await Ug(e),process.exit(t)}var sn=new Uint32Array(65536),jx=(t,e)=>{let n=t.length,r=e.length,o=1<<n-1,s=-1,i=0,a=n,c=n;while(c--)sn[t.charCodeAt(c)]|=1<<c;for(c=0;c<r;c++){let l=sn[e.charCodeAt(c)],u=l|i;if(l|=(l&s)+s^s,i|=~(l|s),s&=l,i&o)a++;if(s&o)a--;i=i<<1|1,s=s<<1|~(u|i),i&=u}c=n;while(c--)sn[t.charCodeAt(c)]=0;return a},Fx=(t,e)=>{let n=e.length,r=t.length,o=[],s=[],i=Math.ceil(n/32),a=Math.ceil(r/32);for(let f=0;f<i;f++)s[f]=-1,o[f]=0;let c=0;for(;c<a-1;c++){let f=0,y=-1,S=c*32,R=Math.min(32,r)+S;for(let v=S;v<R;v++)sn[t.charCodeAt(v)]|=1<<v;for(let v=0;v<n;v++){let H=sn[e.charCodeAt(v)],J=s[v/32|0]>>>v&1,N=o[v/32|0]>>>v&1,U=H|f,_=((H|N)&y)+y^y|H|N,A=f|~(_|y),B=y&_;if(A>>>31^J)s[v/32|0]^=1<<v;if(B>>>31^N)o[v/32|0]^=1<<v;A=A<<1|J,B=B<<1|N,y=B|~(U|A),f=A&U}for(let v=S;v<R;v++)sn[t.charCodeAt(v)]=0}let l=0,u=-1,d=c*32,p=Math.min(32,r-d)+d;for(let f=d;f<p;f++)sn[t.charCodeAt(f)]|=1<<f;let m=r;for(let f=0;f<n;f++){let y=sn[e.charCodeAt(f)],S=s[f/32|0]>>>f&1,R=o[f/32|0]>>>f&1,v=y|l,H=((y|R)&u)+u^u|y|R,J=l|~(H|u),N=u&H;if(m+=J>>>r-1&1,m-=N>>>r-1&1,J>>>31^S)s[f/32|0]^=1<<f;if(N>>>31^R)o[f/32|0]^=1<<f;J=J<<1|S,N=N<<1|R,u=N|~(v|J),l=J&v}for(let f=d;f<p;f++)sn[t.charCodeAt(f)]=0;return m},Ll=(t,e)=>{if(t.length<e.length){let n=e;e=t,t=n}if(e.length===0)return t.length;if(t.length<=32)return jx(t,e);return Fx(t,e)},Om=(t,e)=>{let n=1/0,r=0;for(let o=0;o<e.length;o++){let s=Ll(t,e[o]);if(s<n)n=s,r=o}return e[r]};function Ri(t,e,n){let r=e.length>0?Om(t,[...e]):void 0,o=`Run "${n} --help" for usage.`;return new T(`Unknown command: ${t}`,r?`Did you mean "${r}"? ${o}`:o)}function Wo(t,e){if(Array.isArray(e))return[...e];if(!_m(t)||!_m(e))return e;return Object.fromEntries([...Object.entries(t),...Object.entries(e).map(([n,r])=>[n,Wo(Object.hasOwn(t,n)?t[n]:void 0,r)])])}function _m(t){if(t===null||typeof t!=="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Pm(t,e){return{name:t.name,bin:t.bin,version:t.version,description:t.description,exitCodes:{...di},options:Nm(ae),commands:e.map((n)=>Ii(n,`${t.bin} ${n.name}`))}}function Ii(t,e){return{name:t.name,path:e,description:t.description,json:t.json,prompts:t.prompts,passthrough:t.passthrough,positionals:Object.entries(t.positionals).map(([n,r])=>({name:n,required:r.required??!1,variadic:r.variadic??!1,description:r.description??""})),options:Nm(t.args),examples:[...t.examples],commands:t.subcommands.map((n)=>Ii(n,`${e} ${n.name}`))}}function Nm(t){return Object.entries(t).map(([e,n])=>({name:e,flag:`--${xe(e)}`,...n.alias?{alias:`-${n.alias}`}:{},type:n.type,...n.default===void 0?{}:{default:n.default},...n.displayDefault===void 0?{}:{displayDefault:n.displayDefault},description:n.description??""}))}import{stripVTControlCharacters as Dm}from"util";var Gx=2,Hx="0.0.0",Ux=(t)=>t,K={arg:k.magenta,cmd:k.cyan,default:k.bold,desc:Ux,flag:k.green,header:(t)=>k.bold(k.yellow(t)),hint:k.dim,name:(t)=>k.bold(k.cyan(t)),placeholder:k.magenta};function Lm(t){return`${K.name(t.name)} ${K.hint(t.version??Hx)}`}function Mm(t,e){let n=`${K.name(t.name)}${t.version?` ${K.hint(`v${t.version}`)}`:""}`;return Fm([[n,...t.description?[K.desc(t.description)]:[]],He("Usage:",[` ${K.cmd(t.bin)} ${K.placeholder("[command]")} ${K.placeholder("[options]")}`]),He("Commands:",Gm(e)),He("Options:",Um(ae)),He("Exit codes:",Hm()),[`${K.hint("Run")} ${K.cmd(`${t.bin} <command> --help`)} ${K.hint("for command details.")}`]])}function jm(t,e){let n=t.json?{...t.args,json:ae.json}:t.args,r=[...t.subcommands.length>0?[` ${K.cmd(e)} ${K.placeholder("<command>")} ${K.placeholder("[options]")}`]:[],...t.run?[` ${Kx(t,e).join(" ")}`]:[],...t.prompts&&Object.keys(t.positionals).length>0?[` ${K.hint("Omit positional arguments to run interactively.")}`]:[],...t.passthrough?[` ${K.hint("Options end at the first argument; it and everything after it are passed on unchanged.")}`]:[]];return Fm([[K.name(e),K.desc(t.description)],He("Usage:",r),He("Commands:",Gm(t.subcommands)),He("Arguments:",Wx(t.positionals)),He("Options:",Um(n)),He("Examples:",t.examples.map((o)=>` ${K.cmd(o)}`)),He("Exit codes:",Hm())])}function Kx(t,e){let n=Bx(t.positionals);return t.passthrough?[K.cmd(e),K.placeholder("[options]"),K.placeholder("[--]"),...n]:[K.cmd(e),...n,K.placeholder("[options]")]}function He(t,e){return e.length>0?[K.header(t),...e]:[]}function Fm(t){return t.filter((e)=>e.length>0).map((e)=>e.join(`
83
+ `}}}}).prompt();function If(t=process.stdin){return t.readableEnded||t.destroyed}async function Of({edits:t,input:e=process.stdin,signal:n},r){let o=new AbortController,s=()=>o.abort(),i=(c,l)=>{if(l.sequence==="\x04"&&(!t||e.isPaused()))s()},a=r(n?AbortSignal.any([o.signal,n]):o.signal);e.on("keypress",i),e.once("end",s),e.once("close",s);try{return await a}finally{e.off("keypress",i),e.off("end",s),e.off("close",s)}}import{stripVTControlCharacters as vC}from"util";var Eu=Su?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],bC=80,EC=8,$C=3,TC="...",$u="\r\x1B[K",xC=80,AC=/\s*\n\s*/g,hs=new Set;function Pf(){for(let t of[...hs])t.error()}function Nf({output:t=process.stdout}={}){let e=t.isTTY===!0&&!wf(),n=ds(t),r="",o=0,s=!1,i,a=(g)=>{t.write(e||n?g:vC(g))},c=()=>{let g=w.magenta(Eu[o%Eu.length]??""),f=".".repeat(Math.floor(o/EC)%($C+1)),y=`${g} ${r.replace(AC," ")}${f}`;a(`${$u}${Bun.sliceAnsi(y,0,(t.columns||xC)-1)}`),o+=1},l=()=>e?c():a(`${w.magenta(Eu[0]??"")} ${r}${TC}
84
+ `),u=()=>(clearInterval(i),hs.delete(p)),d=(g,f)=>{if(u())a(`${e?$u:""}${g} ${f}
85
+ `)},p={cancel(g=r){s=hs.has(p)||s,d(w.red(vu),g)},clear(){if(u()&&e)a($u)},error(g=r){d(w.red(bu),g)},get isCancelled(){return s},message(g=r){let f=_f(g);if(f===r)return;if(r=f,hs.has(p)&&!e)l()},start(g=""){if(p.clear(),s=!1,r=_f(g),o=0,hs.add(p),a(`${w.gray(U)}
86
+ `),l(),!e)return;i=setInterval(c,bC),i.unref()},stop(g=r){d(w.green(fs),g)}};return p}function _f(t){return t.replace(/\.+$/,"")}var RC="Pass the value as an argument or option instead";function IC(t){if(qi(t))throw new vt;return t}function OC(t){if(ur())return;throw new v(`Cannot prompt for ${t} without a terminal`,RC)}async function Qi(t,e,{edits:n=!1,hint:r}){if(OC(e.message),If(e.input))throw new vt;return PC(r),IC(await Of({...e,edits:n},(o)=>t({...e,signal:o})))}function _C(t){return t.map((e)=>e.key?`${w.bold(e.key)} ${w.dim(e.text)}`:w.dim(e.text)).join(w.dim(" \xB7 "))}function PC(t){Ut.info(_C(t))}var ta={confirm:[{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],multiselect:[{key:"\u2191\u2193",text:"navigate"},{key:"Space",text:"toggle"},{key:"a",text:"all"},{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],select:[{key:"\u2191\u2193",text:"navigate"},{key:"Enter",text:"select"},{key:"Esc",text:"cancel"}],text:[{key:"Enter",text:"submit"},{key:"Esc",text:"cancel"}]};async function Ee(t){return Qi(bf,t,{hint:ta.confirm})}async function Tu(t){return Qi(Rf,t,{edits:!0,hint:ta.text})}async function gr(t){return Qi(Cf,{showInstructions:!1,...t},{hint:ta.select})}async function ea(t){return Qi(Ef,{showInstructions:!1,...t},{hint:ta.multiselect})}function mr(t){return Um()&&t.output===void 0?{...t,output:process.stderr}:t}function eo(t){return(e,n={})=>t(e,mr(n))}var bt={error:eo(Ut.error),info:eo(Ut.info),message:(t,e={})=>Ut.message(t,mr(e)),step:eo(Ut.step),success:eo(Ut.success),warn:eo(Ut.warn),warning:eo(Ut.warning)};function fr(t,e={}){Tf(t,mr(e))}function ce(t,e={}){xf(t,mr(e))}function ys(t,e={}){$f(t,mr(e))}function Nt(t,e,n={}){Af(t,e,mr(n))}function na(t={}){return Nf(mr(t))}import{inspect as NC}from"util";var DC=4;function ra(t,e=[]){if(e.length>=DC)return[];let n=t instanceof AggregateError?t.errors:[],r=[...e,t];return[...n,...t.cause!==void 0?[t.cause]:[]].filter((s)=>!r.includes(s)).flatMap((s)=>[{hint:sa(s),message:oa(s)},...s instanceof Error?ra(s,r):[]])}function oa(t){return ia(t instanceof Error?t.message||t.name:t)}function sa(t){return t instanceof m&&t.hint!==void 0?ia(t.hint):void 0}function ia(t){return typeof t==="string"?t:NC(t,{breakLength:Number.POSITIVE_INFINITY})}var LC="Error",MC=27,jC=new RegExp(`${String.fromCharCode(MC)}\\[[\\d;]*m`,"g"),FC=9,GC=10,HC=31,UC=127,KC=159,BC=16,VC=4;function Kn(t,{json:e}){if(Pf(),qC(t),e)wn(Hn({error:WC(t)}));return Df(t)}function WC(t){let e=Df(t),n=xu(oa(t));if(!(t instanceof Error))return{_tag:LC,message:n,exitCode:e,causes:[]};let r=sa(t);return{_tag:JC(t),message:n,hint:r===void 0?void 0:xu(r),exitCode:e,causes:ra(t).map((o)=>xu(o.message))}}function Df(t){if(t instanceof vt)return zt;if(t instanceof m)return Ii(t.exitCode)?t.exitCode:ss;return ss}function JC(t){let e=Reflect.get(t,"_tag");return typeof e==="string"?e:ia(t.name)}function qC(t){if(t instanceof vt)return;let e=Ki(),n=aa(oa(t));if(t instanceof m){let r=sa(t);if(bt.warn(w.yellow(n),{output:e}),r)bt.info(w.dim(aa(r)),{output:e})}else bt.error(w.red(n),{output:e});if(!(t instanceof Error))return;for(let r of ra(t))if(bt.info(w.dim(`caused by: ${aa(r.message)}`),{output:e}),r.hint)bt.info(w.dim(` ${aa(r.hint)}`),{output:e})}function aa(t){return Array.from(t.replace(jC,""),(e)=>{let n=e.charCodeAt(0);return n<=HC&&n!==FC&&n!==GC||n>=UC&&n<=KC?`\\u${n.toString(BC).padStart(VC,"0")}`:e}).join("")}var YC=500,XC="The command stopped before it finished because nothing was left for it to wait for";function Lf({json:t}){let e={ending:void 0,failed:!1,settled:!1},n=(o,s)=>(e.ending??=zC(o,s),e.ending),r=(o)=>{if(e.failed||e.ending)return;e.failed=!0;let s=Kn(o,{json:t&&!Km()});Bm(),n(s,e.settled?void 0:YC)};return process.on("uncaughtException",r),process.on("unhandledRejection",r),process.on("beforeExit",()=>{if(!e.settled)r(Error(XC))}),{exit:(o)=>n(o),settle(){e.settled=!0}}}async function zC(t,e){process.exitCode=t,await Jm(e),process.exit(t)}var vn=new Uint32Array(65536),ZC=(t,e)=>{let n=t.length,r=e.length,o=1<<n-1,s=-1,i=0,a=n,c=n;while(c--)vn[t.charCodeAt(c)]|=1<<c;for(c=0;c<r;c++){let l=vn[e.charCodeAt(c)],u=l|i;if(l|=(l&s)+s^s,i|=~(l|s),s&=l,i&o)a++;if(s&o)a--;i=i<<1|1,s=s<<1|~(u|i),i&=u}c=n;while(c--)vn[t.charCodeAt(c)]=0;return a},QC=(t,e)=>{let n=e.length,r=t.length,o=[],s=[],i=Math.ceil(n/32),a=Math.ceil(r/32);for(let f=0;f<i;f++)s[f]=-1,o[f]=0;let c=0;for(;c<a-1;c++){let f=0,y=-1,S=c*32,I=Math.min(32,r)+S;for(let C=S;C<I;C++)vn[t.charCodeAt(C)]|=1<<C;for(let C=0;C<n;C++){let q=vn[e.charCodeAt(C)],G=s[C/32|0]>>>C&1,N=o[C/32|0]>>>C&1,H=q|f,A=((q|N)&y)+y^y|q|N,R=f|~(A|y),B=y&A;if(R>>>31^G)s[C/32|0]^=1<<C;if(B>>>31^N)o[C/32|0]^=1<<C;R=R<<1|G,B=B<<1|N,y=B|~(H|R),f=R&H}for(let C=S;C<I;C++)vn[t.charCodeAt(C)]=0}let l=0,u=-1,d=c*32,p=Math.min(32,r-d)+d;for(let f=d;f<p;f++)vn[t.charCodeAt(f)]|=1<<f;let g=r;for(let f=0;f<n;f++){let y=vn[e.charCodeAt(f)],S=s[f/32|0]>>>f&1,I=o[f/32|0]>>>f&1,C=y|l,q=((y|I)&u)+u^u|y|I,G=l|~(q|u),N=u&q;if(g+=G>>>r-1&1,g-=N>>>r-1&1,G>>>31^S)s[f/32|0]^=1<<f;if(N>>>31^I)o[f/32|0]^=1<<f;G=G<<1|S,N=N<<1|I,u=N|~(C|G),l=G&C}for(let f=d;f<p;f++)vn[t.charCodeAt(f)]=0;return g},Au=(t,e)=>{if(t.length<e.length){let n=e;e=t,t=n}if(e.length===0)return t.length;if(t.length<=32)return ZC(t,e);return QC(t,e)},Mf=(t,e)=>{let n=1/0,r=0;for(let o=0;o<e.length;o++){let s=Au(t,e[o]);if(s<n)n=s,r=o}return e[r]};function ca(t,e,n){let r=e.length>0?Mf(t,[...e]):void 0,o=`Run "${n} --help" for usage.`;return new v(`Unknown command: ${t}`,r?`Did you mean "${r}"? ${o}`:o)}function ks(t,e){if(Array.isArray(e))return[...e];if(!jf(t)||!jf(e))return e;return Object.fromEntries([...Object.entries(t),...Object.entries(e).map(([n,r])=>[n,ks(Object.hasOwn(t,n)?t[n]:void 0,r)])])}function jf(t){if(t===null||typeof t!=="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Ff(t,e){return{name:t.name,bin:t.bin,version:t.version,description:t.description,exitCodes:{...Bi},options:Gf(Se),commands:e.map((n)=>la(n,`${t.bin} ${n.name}`))}}function la(t,e){return{name:t.name,path:e,description:t.description,json:t.json,prompts:t.prompts,passthrough:t.passthrough,positionals:Object.entries(t.positionals).map(([n,r])=>({name:n,required:r.required??!1,variadic:r.variadic??!1,description:r.description??""})),options:Gf(t.args),examples:[...t.examples],commands:t.subcommands.map((n)=>la(n,`${e} ${n.name}`))}}function Gf(t){return Object.entries(t).map(([e,n])=>({name:e,flag:`--${Me(e)}`,...n.alias?{alias:`-${n.alias}`}:{},type:n.type,...n.default===void 0?{}:{default:n.default},...n.displayDefault===void 0?{}:{displayDefault:n.displayDefault},description:n.description??""}))}import{stripVTControlCharacters as Hf}from"util";var tR=2,eR="0.0.0",nR=(t)=>t,V={arg:w.magenta,cmd:w.cyan,default:w.bold,desc:nR,flag:w.green,header:(t)=>w.bold(w.yellow(t)),hint:w.dim,name:(t)=>w.bold(w.cyan(t)),placeholder:w.magenta};function Uf(t){return`${V.name(t.name)} ${V.hint(t.version??eR)}`}function Kf(t,e){let n=`${V.name(t.name)}${t.version?` ${V.hint(`v${t.version}`)}`:""}`;return Vf([[n,...t.description?[V.desc(t.description)]:[]],Qe("Usage:",[` ${V.cmd(t.bin)} ${V.placeholder("[command]")} ${V.placeholder("[options]")}`]),Qe("Commands:",Wf(e)),Qe("Options:",qf(Se)),Qe("Exit codes:",Jf()),[`${V.hint("Run")} ${V.cmd(`${t.bin} <command> --help`)} ${V.hint("for command details.")}`]])}function Bf(t,e){let n=t.json?{...t.args,json:Se.json}:t.args,r=[...t.subcommands.length>0?[` ${V.cmd(e)} ${V.placeholder("<command>")} ${V.placeholder("[options]")}`]:[],...t.run?[` ${rR(t,e).join(" ")}`]:[],...t.prompts&&Object.keys(t.positionals).length>0?[` ${V.hint("Omit positional arguments to run interactively.")}`]:[],...t.passthrough?[` ${V.hint("Options end at the first argument; it and everything after it are passed on unchanged.")}`]:[]];return Vf([[V.name(e),V.desc(t.description)],Qe("Usage:",r),Qe("Commands:",Wf(t.subcommands)),Qe("Arguments:",sR(t.positionals)),Qe("Options:",qf(n)),Qe("Examples:",t.examples.map((o)=>` ${V.cmd(o)}`)),Qe("Exit codes:",Jf())])}function rR(t,e){let n=oR(t.positionals);return t.passthrough?[V.cmd(e),V.placeholder("[options]"),V.placeholder("[--]"),...n]:[V.cmd(e),...n,V.placeholder("[options]")]}function Qe(t,e){return e.length>0?[V.header(t),...e]:[]}function Vf(t){return t.filter((e)=>e.length>0).map((e)=>e.join(`
87
87
  `)).join(`
88
88
 
89
- `)}function Gm(t){return Oi(t.map((e)=>[` ${K.cmd(e.name)}`,K.desc(e.description)]))}function Hm(){return Oi(Object.entries(di).map(([t,e])=>[` ${t}`,e]))}function Ml(t,e){return e.variadic?`${t}...`:t}function Bx(t){return Object.entries(t).map(([e,n])=>n.required?K.arg(`<${Ml(e,n)}>`):K.arg(`[${Ml(e,n)}]`))}function Wx(t){return Oi(Object.entries(t).map(([e,n])=>[` ${K.arg(Ml(e,n))}`,`${K.desc(n.description??"")}${n.required?"":K.hint(" (optional)")}`]))}function Um(t){return Oi(Object.entries(t).map(([e,n])=>{let r=n.alias?`${K.flag(`-${n.alias}`)}, `:" ",o=n.type==="boolean"?"":` ${K.placeholder(`<${n.type==="number"?"number":"value"}>`)}`,s=Vx(n),i=s===void 0?"":` (default: ${K.default(s)})`;return[` ${r}${K.flag(`--${xe(e)}`)}${o}`,`${K.desc(n.description??"")}${i}`]}))}function Vx(t){if(typeof t.displayDefault==="string")return t.displayDefault;if(t.default===void 0)return;if(t.type==="boolean"&&t.default===!1)return;if(t.type==="string")return`"${t.default}"`;return String(t.default)}function Oi(t){let e=Math.max(0,...t.map(([n])=>Dm(n).length));return t.map(([n,r])=>`${n}${" ".repeat(e-Dm(n).length+Gx)}${r}`)}function _i(t){let e=!1;return{emitted:()=>e,json:t,result(n,r){if(e)throw Error("ctx.output.result was called more than once; a command emits one result");let o=Jx(t,n,r);if(e=!0,o!==void 0)rn(o)}}}function Jx(t,e,n){if(t)return xn(e);return n?`${n(e)}
90
- `:void 0}function Pi(t,e,n){return{args:e.args,cli:t.info,config:t.config,interactive:e.interactive,json:e.json,output:n,positionals:e.positionals}}async function Ni(t,e,n,r){let o=await Hg(n.json,async()=>{let s=await t.run?.(n);return typeof s==="number"?qx(e,s):Ut});if(n.json&&!r.emitted())throw Error(`${e} finished in JSON mode without calling ctx.output.result`);return o}function qx(t,e){if(zs(e))return e;throw Error(`${t} returned ${e}, which is not an exit code from ${Ut} to ${Tg}`)}var jl="__exit__",Km="__run__",Yx="Back",Xx="Return to previous menu";async function Bm(t,e){if(e)throw new T("Interactive mode cannot be combined with --json","Pass a command and its arguments instead");if(!Fo())throw new T("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(t.interactive.clearOnStart)console.clear();let n=t.info.version?` v${t.info.version}`:"";Zn(k.bgCyan(k.black(` ${t.info.name}${n} `)));let r={commands:t.commands,message:t.interactive.promptMessage,path:t.info.bin,root:!0};return await Wm(t,new Map,r),Xt(t.interactive.goodbyeMessage),Ut}async function Wm(t,e,n){while(!0){let r=await zx(t,e,n);if(r===void 0)return;if(e.set(n.path,r),r===Km&&n.owner){await Vm(t,n.owner,n.path);continue}let o=n.commands.find((s)=>s.name===r);if(o)await Zx(t,e,o,`${n.path} ${r}`)}}async function zx(t,e,n){let r=n.root?{hint:t.interactive.exitHint,label:t.interactive.exitLabel,value:jl}:{hint:Xx,label:Yx,value:jl};try{let o=await Xn({initialValue:e.get(n.path),message:n.message,options:[...n.owner?[{hint:n.owner.description,label:n.owner.name,value:Km}]:[],...n.commands.map((s)=>({hint:s.description,label:s.name,value:s.name})),r]});return o===jl?void 0:o}catch(o){if(o instanceof dt)return;throw o}}async function Zx(t,e,n,r){if(n.subcommands.length===0)return Vm(t,n,r);return Wm(t,e,{commands:n.subcommands,message:`${n.name}:`,path:r,root:!1,...n.run?{owner:n}:{}})}async function Vm(t,e,n){try{await Qx(t,e,n)}catch(r){if(r instanceof dt)return;if(!(r instanceof g))throw r;Cn(r,{json:!1})}}async function Qx(t,e,n){let{args:r}=Mo([],e.args),o=oi([],e.positionals),s=e.prompts?null:si(o,e.positionals);if(s)throw new T(s,`Run "${n} --help" for usage.`);let i=_i(!1),a={args:ni(r,e.args),interactive:e.prompts,json:!1,positionals:o};await Ni(e,n,Pi(t,a,i),i)}var tA="--",eA=/^(?:--json(?:=true)?|-[^-=]*j[^-=]*(?:=true)?)$/,nA=/^(?:--no-(?:help|json)|(?:--(?:help|json)|-[hj]+)(?:=(?:true|false))?)$/;async function Fl(t,e){try{return await rA(t,e)}catch(n){return{code:Cn(n,{json:Hl(e)}),menu:!1}}}function Gl(t,e){let{command:n,restArgs:r}=ei(e,ae),o=n===void 0||n===qn?void 0:Ym(t,n,r);if(!o||o instanceof T||!o.command.passthrough)return{operands:[],options:[...e]};let s=Ag(o.tokens,{...o.command.args,...Or}),i=s<0?[]:o.tokens.slice(s);return{operands:i,options:e.slice(0,e.length-i.length)}}async function rA(t,{options:e,operands:n}){let{command:r,flags:o,restArgs:s}=yl(e,ae,Or),i=o.json===!0,a={code:Ut,menu:!1};if(r===void 0){if(o.interactive&&!o.help&&!o.version)return{code:await Bm(t,i),menu:!0};return rn(o.version&&!o.help?sA(t,i):Jm(t,i)),a}let c=o.interactive?"--interactive":o.version?"--version":void 0;if(c)throw new T(`${c} cannot be combined with a command`,`Run "${t.info.bin} ${c}" on its own.`);if(r===qn)return rn(iA(t,s,i)),a;let l=aA(t,r,s);if(o.help)return rn(Ul(l.command,l.path,i)),a;return{code:await cA(t,l,n,i),menu:!1}}function Hl({options:t}){let{before:e,restArgs:n}=ei(t,ae);return[e,n].some((r)=>oA(r).some((o)=>eA.test(o)))}function oA(t){let e=t.indexOf(tA);return e<0?t:t.slice(0,e)}function sA({info:t},e){return e?xn({name:t.name,bin:t.bin,version:t.version}):`${Lm(t)}
91
- `}function Jm(t,e){return e?xn(Pm(t.info,t.commands)):`${Mm(t.info,t.commands)}
92
- `}function Ul(t,e,n){return n?xn(Ii(t,e)):`${jm(t,e)}
93
- `}function iA(t,e,n){let{args:r,rawPositionals:o}=Mo(e,Or);if(ti(r,Or,`Run "${t.info.bin} ${qn} [command]" for usage.`,e),o.length===0)return Jm(t,n);let{command:s,path:i}=qm(t.commands,o,t.info.bin);return Ul(s,i,n)}function qm(t,e,n){let[r="",...o]=e,s=t.find((a)=>a.name===r);if(!s)throw Ri(r,Kl(t),n);let i=`${n} ${r}`;return o.length===0?{command:s,path:i}:qm(s.subcommands,o,i)}function Kl(t){return t.map((e)=>e.name)}function aA(t,e,n){let r=Ym(t,e,n);if(r instanceof T)throw r;return r}function Ym(t,e,n){let r=t.commands.find((o)=>o.name===e);if(!r)return Ri(e,Kl(t.commands),t.info.bin);return Xm({command:r,path:`${t.info.bin} ${e}`,tokens:n})}function Xm(t){let{command:e,path:n,tokens:r}=t;if(e.subcommands.length===0)return t;let o=r.findIndex((a)=>!nA.test(a)),s=r[o];if(s===void 0||s.startsWith("-"))return t;let i=e.subcommands.find((a)=>a.name===s);if(i)return Xm({command:i,path:`${n} ${s}`,tokens:r.toSpliced(o,1)});if(e.run&&Object.keys(e.positionals).length>0)return t;return Ri(s,Kl(e.subcommands),n)}async function cA(t,{command:e,path:n,tokens:r},o,s){let i=`Run "${n} --help" for usage.`,a={...e.args,...Or},c=Mo(r,a),{args:l}=c,u=[...c.rawPositionals,...o];if(e.strict)ti(l,a,i,r);if(s&&!e.json)throw new T(`${n} does not support --json`,i);let d=e.strict?Rg(u,e.positionals):void 0;if(d!==void 0)throw new T(`Unexpected argument: ${d}`,i);if(!e.run)return rn(Ul(e,n,s)),Ut;let p=oi(u,e.positionals),m=si(p,e.positionals);if(m)throw new T(m,i);let f=e.prompts&&u.length===0&&Fo()&&!s,y={args:ni(l,e.args),interactive:f,json:s,positionals:p},S=_i(s);try{return await Ni(e,n,Pi(t,y,S),S)}catch(R){return Cn(R,{json:s&&!S.emitted()})}}var lA={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",promptMessage:"What would you like to do?"};function Bl(t){let e=`CLI "${t.name}"`;if(ai(e,t.commands),t.commands.some((r)=>r.name===qn))throw Error(`${e} cannot define a command named "${qn}": the framework provides it`);let n={commands:t.commands,config:t.config,info:{bin:t.bin??t.name,description:t.description,name:t.name,version:t.version},interactive:{...lA,...t.interactive}};return{async main(r=process.argv.slice(2)){Gg();let o=Gl(n,r),s=Im({json:Hl(o)}),i=await Fl(n,o);if(s.settle(),i.code===Ut&&!i.menu)return;await s.exit(i.code)},async run(r=process.argv.slice(2)){return(await Fl(n,Gl(n,r))).code}}}import Ue from"fs";import Xl from"path";var Qn=(t)=>(t.map=(e)=>Qn((n)=>e(t(n))),t.or=(e)=>Qn((n)=>{try{return t(n)}catch(r){return e(n)}}),t),Di=()=>"bad banditype"();var zm=()=>Qn((t)=>t),Zm=(t)=>Qn((e)=>t.includes(e)?e:Di()),Wl=(t)=>Qn((e)=>typeof e===typeof t?e:Di()),gt=()=>Wl(""),Vo=()=>Wl(0),Li=()=>Wl(!0);var Nr=()=>Qn((t)=>t===null?t:Di()),Jo=(t)=>Qn((e)=>e instanceof t?e:Di()),Qm=(t)=>Jo(Object).map((e)=>{let n={};for(let r in e){let o=t(e[r]);o!==void 0&&(n[r]=o)}return n}),zt=(t)=>Jo(Object).map((e)=>{let n={};for(let r in t){let o=t[r](e[r]);o!==void 0&&(n[r]=o)}return n});var Mi=(t)=>Jo(Array).map((e)=>e.map(t));import Dr from"fs";var uA=".lock",dA=".break",tf=10,pA=1e4,gA=5000;function ef(t,e){let n=`${t}${uA}`,r=crypto.randomUUID();mA(n,r);try{return e()}finally{nf(n,r)}}function mA(t,e){let n=Date.now()+pA;while(!rf(t,e)){if(Date.now()>n)throw Error(`timed out waiting for ${t}, which another process holds`);if(Vl(t))fA(t,e);else Bun.sleepSync(tf)}}function nf(t,e){if(hA(t)===e)Dr.rmSync(t,{force:!0})}function fA(t,e){let n=`${t}${dA}`;if(!rf(n,e)){if(Vl(n))Dr.rmSync(n,{force:!0});else Bun.sleepSync(tf);return}try{if(Vl(t))Dr.rmSync(t,{force:!0})}finally{nf(n,e)}}function rf(t,e){try{return Dr.writeFileSync(t,e,{flag:"wx"}),!0}catch(n){if(of(n)==="EEXIST")return!1;throw n}}function Vl(t){let e=Dr.statSync(t,{throwIfNoEntry:!1})?.mtimeMs;return e!==void 0&&Date.now()-e>gA}function hA(t){try{return Dr.readFileSync(t,"utf8")}catch(e){if(of(e)==="ENOENT")return;throw e}}function of(t){return t instanceof Error?Reflect.get(t,"code"):void 0}import Jl from"fs";import tr from"path";var yA="..",kA=40;function af(t){let{root:e}=tr.parse(tr.resolve(t)),n=sf(tr.resolve(t)),r=e,o=0;for(let s=n.shift();s!==void 0;s=n.shift()){if(s===yA){r=tr.dirname(Jl.realpathSync(r));continue}let i=tr.join(r,s);if(!Jl.lstatSync(i,{throwIfNoEntry:!1})?.isSymbolicLink()){r=i;continue}if(o+=1,o>kA)throw Error(`too many symbolic links in ${t}`);let a=Jl.readlinkSync(i);if(tr.isAbsolute(a))r=e;n.unshift(...sf(a))}return r}function sf(t){return t.split(tr.sep).filter((e)=>e!==""&&e!==".")}function Yl(t,e){JSON.parse(t);let n=JSON.parse(JSON.stringify(e)),r=wA(t),o=t.match(/^[\t ]+(?=\S)/m)?.[0]??" ",s=t.includes(`\r
89
+ `)}function Wf(t){return ua(t.map((e)=>[` ${V.cmd(e.name)}`,V.desc(e.description)]))}function Jf(){return ua(Object.entries(Bi).map(([t,e])=>[` ${t}`,e]))}function Cu(t,e){return e.variadic?`${t}...`:t}function oR(t){return Object.entries(t).map(([e,n])=>n.required?V.arg(`<${Cu(e,n)}>`):V.arg(`[${Cu(e,n)}]`))}function sR(t){return ua(Object.entries(t).map(([e,n])=>[` ${V.arg(Cu(e,n))}`,`${V.desc(n.description??"")}${n.required?"":V.hint(" (optional)")}`]))}function qf(t){return ua(Object.entries(t).map(([e,n])=>{let r=n.alias?`${V.flag(`-${n.alias}`)}, `:" ",o=n.type==="boolean"?"":` ${V.placeholder(`<${n.type==="number"?"number":"value"}>`)}`,s=iR(n),i=s===void 0?"":` (default: ${V.default(s)})`;return[` ${r}${V.flag(`--${Me(e)}`)}${o}`,`${V.desc(n.description??"")}${i}`]}))}function iR(t){if(typeof t.displayDefault==="string")return t.displayDefault;if(t.default===void 0)return;if(t.type==="boolean"&&t.default===!1)return;if(t.type==="string")return`"${t.default}"`;return String(t.default)}function ua(t){let e=Math.max(0,...t.map(([n])=>Hf(n).length));return t.map(([n,r])=>`${n}${" ".repeat(e-Hf(n).length+tR)}${r}`)}function da(t){let e=!1;return{emitted:()=>e,json:t,result(n,r){if(e)throw Error("ctx.output.result was called more than once; a command emits one result");let o=aR(t,n,r);if(e=!0,o!==void 0)wn(o)}}}function aR(t,e,n){if(t)return Hn(e);return n?`${n(e)}
90
+ `:void 0}function pa(t,e,n){return{args:e.args,cli:t.info,config:t.config,interactive:e.interactive,json:e.json,output:n,positionals:e.positionals}}async function ga(t,e,n,r){let o=await Wm(n.json,async()=>{let s=await t.run?.(n);return typeof s==="number"?cR(e,s):zt});if(n.json&&!r.emitted())throw Error(`${e} finished in JSON mode without calling ctx.output.result`);return o}function cR(t,e){if(Ii(e))return e;throw Error(`${t} returned ${e}, which is not an exit code from ${zt} to ${xm}`)}var Ru="__exit__",Yf="__run__",lR="Back",uR="Return to previous menu";async function Xf(t,e){if(e)throw new v("Interactive mode cannot be combined with --json","Pass a command and its arguments instead");if(!ps())throw new v("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(t.interactive.clearOnStart)console.clear();let n=t.info.version?` v${t.info.version}`:"";fr(w.bgCyan(w.black(` ${t.info.name}${n} `)));let r={commands:t.commands,message:t.interactive.promptMessage,path:t.info.bin,root:!0};return await zf(t,new Map,r),ce(t.interactive.goodbyeMessage),zt}async function zf(t,e,n){while(!0){let r=await dR(t,e,n);if(r===void 0)return;if(e.set(n.path,r),r===Yf&&n.owner){await Zf(t,n.owner,n.path);continue}let o=n.commands.find((s)=>s.name===r);if(o)await pR(t,e,o,`${n.path} ${r}`)}}async function dR(t,e,n){let r=n.root?{hint:t.interactive.exitHint,label:t.interactive.exitLabel,value:Ru}:{hint:uR,label:lR,value:Ru};try{let o=await gr({initialValue:e.get(n.path),message:n.message,options:[...n.owner?[{hint:n.owner.description,label:n.owner.name,value:Yf}]:[],...n.commands.map((s)=>({hint:s.description,label:s.name,value:s.name})),r]});return o===Ru?void 0:o}catch(o){if(o instanceof vt)return;throw o}}async function pR(t,e,n,r){if(n.subcommands.length===0)return Zf(t,n,r);return zf(t,e,{commands:n.subcommands,message:`${n.name}:`,path:r,root:!1,...n.run?{owner:n}:{}})}async function Zf(t,e,n){try{await gR(t,e,n)}catch(r){if(r instanceof vt)return;if(!(r instanceof m))throw r;Kn(r,{json:!1})}}async function gR(t,e,n){let{args:r}=us([],e.args),o=Mi([],e.positionals),s=e.prompts?null:ji(o,e.positionals);if(s)throw new v(s,`Run "${n} --help" for usage.`);let i=da(!1),a={args:Di(r,e.args),interactive:e.prompts,json:!1,positionals:o};await ga(e,n,pa(t,a,i),i)}var mR="--",fR=/^(?:--json(?:=true)?|-[^-=]*j[^-=]*(?:=true)?)$/,hR=/^(?:--no-(?:help|json)|(?:--(?:help|json)|-[hj]+)(?:=(?:true|false))?)$/;async function Iu(t,e){try{return await yR(t,e)}catch(n){return{code:Kn(n,{json:_u(e)}),menu:!1}}}function Ou(t,e){let{command:n,restArgs:r}=Ni(e,Se),o=n===void 0||n===dr?void 0:eh(t,n,r);if(!o||o instanceof v||!o.command.passthrough)return{operands:[],options:[...e]};let s=_m(o.tokens,{...o.command.args,...Qr}),i=s<0?[]:o.tokens.slice(s);return{operands:i,options:e.slice(0,e.length-i.length)}}async function yR(t,{options:e,operands:n}){let{command:r,flags:o,restArgs:s}=cu(e,Se,Qr),i=o.json===!0,a={code:zt,menu:!1};if(r===void 0){if(o.interactive&&!o.help&&!o.version)return{code:await Xf(t,i),menu:!0};return wn(o.version&&!o.help?wR(t,i):Qf(t,i)),a}let c=o.interactive?"--interactive":o.version?"--version":void 0;if(c)throw new v(`${c} cannot be combined with a command`,`Run "${t.info.bin} ${c}" on its own.`);if(r===dr)return wn(SR(t,s,i)),a;let l=vR(t,r,s);if(o.help)return wn(Pu(l.command,l.path,i)),a;return{code:await bR(t,l,n,i),menu:!1}}function _u({options:t}){let{before:e,restArgs:n}=Ni(t,Se);return[e,n].some((r)=>kR(r).some((o)=>fR.test(o)))}function kR(t){let e=t.indexOf(mR);return e<0?t:t.slice(0,e)}function wR({info:t},e){return e?Hn({name:t.name,bin:t.bin,version:t.version}):`${Uf(t)}
91
+ `}function Qf(t,e){return e?Hn(Ff(t.info,t.commands)):`${Kf(t.info,t.commands)}
92
+ `}function Pu(t,e,n){return n?Hn(la(t,e)):`${Bf(t,e)}
93
+ `}function SR(t,e,n){let{args:r,rawPositionals:o}=us(e,Qr);if(Pi(r,Qr,`Run "${t.info.bin} ${dr} [command]" for usage.`,e),o.length===0)return Qf(t,n);let{command:s,path:i}=th(t.commands,o,t.info.bin);return Pu(s,i,n)}function th(t,e,n){let[r="",...o]=e,s=t.find((a)=>a.name===r);if(!s)throw ca(r,Nu(t),n);let i=`${n} ${r}`;return o.length===0?{command:s,path:i}:th(s.subcommands,o,i)}function Nu(t){return t.map((e)=>e.name)}function vR(t,e,n){let r=eh(t,e,n);if(r instanceof v)throw r;return r}function eh(t,e,n){let r=t.commands.find((o)=>o.name===e);if(!r)return ca(e,Nu(t.commands),t.info.bin);return nh({command:r,path:`${t.info.bin} ${e}`,tokens:n})}function nh(t){let{command:e,path:n,tokens:r}=t;if(e.subcommands.length===0)return t;let o=r.findIndex((a)=>!hR.test(a)),s=r[o];if(s===void 0||s.startsWith("-"))return t;let i=e.subcommands.find((a)=>a.name===s);if(i)return nh({command:i,path:`${n} ${s}`,tokens:r.toSpliced(o,1)});if(e.run&&Object.keys(e.positionals).length>0)return t;return ca(s,Nu(e.subcommands),n)}async function bR(t,{command:e,path:n,tokens:r},o,s){let i=`Run "${n} --help" for usage.`,a={...e.args,...Qr},c=us(r,a),{args:l}=c,u=[...c.rawPositionals,...o];if(e.strict)Pi(l,a,i,r);if(s&&!e.json)throw new v(`${n} does not support --json`,i);let d=e.strict?Nm(u,e.positionals):void 0;if(d!==void 0)throw new v(`Unexpected argument: ${d}`,i);if(!e.run)return wn(Pu(e,n,s)),zt;let p=Mi(u,e.positionals),g=ji(p,e.positionals);if(g)throw new v(g,i);let f=e.prompts&&u.length===0&&ps()&&!s,y={args:Di(l,e.args),interactive:f,json:s,positionals:p},S=da(s);try{return await ga(e,n,pa(t,y,S),S)}catch(I){return Kn(I,{json:s&&!S.emitted()})}}var ER={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",promptMessage:"What would you like to do?"};function Du(t){let e=`CLI "${t.name}"`;if(Gi(e,t.commands),t.commands.some((r)=>r.name===dr))throw Error(`${e} cannot define a command named "${dr}": the framework provides it`);let n={commands:t.commands,config:t.config,info:{bin:t.bin??t.name,description:t.description,name:t.name,version:t.version},interactive:{...ER,...t.interactive}};return{async main(r=process.argv.slice(2)){Vm();let o=Ou(n,r),s=Lf({json:_u(o)}),i=await Iu(n,o);if(s.settle(),i.code===zt&&!i.menu)return;await s.exit(i.code)},async run(r=process.argv.slice(2)){return(await Iu(n,Ou(n,r))).code}}}import tn from"fs";import Hu from"path";var hr=(t)=>(t.map=(e)=>hr((n)=>e(t(n))),t.or=(e)=>hr((n)=>{try{return t(n)}catch(r){return e(n)}}),t),ma=()=>"bad banditype"();var rh=()=>hr((t)=>t),oh=(t)=>hr((e)=>t.includes(e)?e:ma()),fa=(t)=>hr((e)=>typeof e===typeof t?e:ma()),X=()=>fa(""),yr=()=>fa(0),ha=()=>fa(!0);var Lu=()=>fa(),Bn=()=>hr((t)=>t===null?t:ma()),ws=(t)=>hr((e)=>e instanceof t?e:ma()),sh=(t)=>ws(Object).map((e)=>{let n={};for(let r in e){let o=t(e[r]);o!==void 0&&(n[r]=o)}return n}),Et=(t)=>ws(Object).map((e)=>{let n={};for(let r in t){let o=t[r](e[r]);o!==void 0&&(n[r]=o)}return n});var no=(t)=>ws(Array).map((e)=>e.map(t));import ro from"fs";var $R=".lock",TR=".break",ih=10,xR=1e4,AR=5000;function ah(t,e){let n=`${t}${$R}`,r=crypto.randomUUID();CR(n,r);try{return e()}finally{ch(n,r)}}function CR(t,e){let n=Date.now()+xR;while(!lh(t,e)){if(Date.now()>n)throw Error(`timed out waiting for ${t}, which another process holds`);if(Mu(t))RR(t,e);else Bun.sleepSync(ih)}}function ch(t,e){if(IR(t)===e)ro.rmSync(t,{force:!0})}function RR(t,e){let n=`${t}${TR}`;if(!lh(n,e)){if(Mu(n))ro.rmSync(n,{force:!0});else Bun.sleepSync(ih);return}try{if(Mu(t))ro.rmSync(t,{force:!0})}finally{ch(n,e)}}function lh(t,e){try{return ro.writeFileSync(t,e,{flag:"wx"}),!0}catch(n){if(uh(n)==="EEXIST")return!1;throw n}}function Mu(t){let e=ro.statSync(t,{throwIfNoEntry:!1})?.mtimeMs;return e!==void 0&&Date.now()-e>AR}function IR(t){try{return ro.readFileSync(t,"utf8")}catch(e){if(uh(e)==="ENOENT")return;throw e}}function uh(t){return t instanceof Error?Reflect.get(t,"code"):void 0}import ju from"fs";import kr from"path";var OR="..",_R=40;function ph(t){let{root:e}=kr.parse(kr.resolve(t)),n=dh(kr.resolve(t)),r=e,o=0;for(let s=n.shift();s!==void 0;s=n.shift()){if(s===OR){r=kr.dirname(ju.realpathSync(r));continue}let i=kr.join(r,s);if(!ju.lstatSync(i,{throwIfNoEntry:!1})?.isSymbolicLink()){r=i;continue}if(o+=1,o>_R)throw Error(`too many symbolic links in ${t}`);let a=ju.readlinkSync(i);if(kr.isAbsolute(a))r=e;n.unshift(...dh(a))}return r}function dh(t){return t.split(kr.sep).filter((e)=>e!==""&&e!==".")}function Gu(t,e){JSON.parse(t);let n=JSON.parse(JSON.stringify(e)),r=PR(t),o=t.match(/^[\t ]+(?=\S)/m)?.[0]??" ",s=t.includes(`\r
94
94
  `)?`\r
95
95
  `:`
96
96
  `,i=/\s/.test(t[r.start+1]??"")||r.entries.some((l)=>/:\s+$/.test(t.slice(l.start,l.node.start)))?" ":"";function a(l,u){let d=t.slice(l.start,l.end);if(JSON.stringify(l.value)===JSON.stringify(u))return d;let p=Array.isArray(u);if(u===null||typeof u!=="object"||l.value===null||typeof l.value!=="object"||Array.isArray(l.value)!==p)return c(u,l.start,d.includes(`
97
- `));let m=p?u.map((A,B)=>String(B)):[...new Set([...l.entries.map((A)=>A.key).filter((A)=>Object.hasOwn(u,A)),...Object.keys(u)])];if(m.length===0)return p?"[]":"{}";let f=l.entries[0],y=l.entries.at(-1);if(!f||!y)return c(u,l.start,d.includes(`
98
- `));let S=(A)=>p?u[Number(A)]:u[A];if(m.length===l.entries.length&&m.every((A,B)=>A===l.entries[B]?.key)){let A=l.start,B="";for(let Dt of l.entries)B+=t.slice(A,Dt.node.start)+a(Dt.node,S(Dt.key)),A=Dt.node.end;return B+t.slice(A,l.end)}let R=t.slice(l.start+1,f.start),v=t.slice(y.node.end,l.end-1),H=l.entries[1],J=H?t.slice(f.node.end,H.start):`,${R.includes(`
99
- `)?R:i}`,N=p?"":t.slice(f.start,f.node.start).match(/:\s*$/)?.[0]??": ",U=new Map(l.entries.map((A)=>[A.key,A])),_=m.map((A)=>{let B=U.get(A);if(B)return t.slice(B.start,B.node.start)+a(B.node,S(A));return(p?"":JSON.stringify(A)+N)+c(S(A),f.start,R.includes(`
100
- `))});return`${p?"[":"{"}${R}${_.join(J)}${v}${p?"]":"}"}`}function c(l,u,d){if(!d)return ql(l,i);let p=t.lastIndexOf(`
101
- `,u-1)+1,m=t.slice(p,u).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(l,null,o).replaceAll(`
102
- `,s+m)}return t.slice(0,r.start)+a(r,n)+t.slice(r.end)}function ql(t,e){if(Array.isArray(t))return`[${t.map((o)=>ql(o,e)).join(`,${e}`)}]`;if(t===null||typeof t!=="object")return JSON.stringify(t);let n=Object.entries(t);if(n.length===0)return"{}";let r=n.map(([o,s])=>`${JSON.stringify(o)}:${e}${ql(s,e)}`);return`{${e}${r.join(`,${e}`)}${e}}`}function wA(t){let e=t.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),n=e.next().value;function r(){if(!n)throw Error("Unexpected end of JSON");let s=n;return n=e.next().value,s}function o(){let s=r(),i=[],a=s[0]==="{";if(!a&&s[0]!=="[")return{end:s.index+s[0].length,entries:i,start:s.index,value:JSON.parse(s[0])};let c=a?"}":"]";while(n&&n[0]!==c){let u=n.index,d=a?JSON.parse(r()[0]):String(i.length);if(a)r();if(i.push({key:d,node:o(),start:u}),n?.[0]===",")r()}let l=r().index+1;return{end:l,entries:i,start:s.index,value:JSON.parse(t.slice(s.index,l))}}return o()}var SA=2,zl="ConfigError",TA=Jo(Object);class Zl{loaded;configPath;defaultConfig;options;constructor(t,e,n={}){this.configPath=Xl.resolve(t),this.defaultConfig=e,this.options=n}get path(){return this.configPath}get failure(){return this.state().failure}get(t){return this.current()[t]}set(t,e){let n=this.writable();this.update((r)=>({...r,[t]:e})),n.config={...n.config,[t]:e}}delete(t){let e=this.writable();this.update((n)=>(delete n[t],n)),delete e.config[t]}exists(){return Ue.existsSync(this.configPath)}getAll(){return structuredClone(this.current())}save(t){let e=this.writable();if(t)e.config={...t};this.update(()=>e.config)}state(){return this.loaded??=this.load(),this.loaded}current(){let{config:t,failure:e}=this.state();if(e)throw e;return t}writable(){let t=this.state();if(t.failure)throw t.failure;if(t.error)throw this.unreadable(t.error);return t}unreadable(t){return new g(`Cannot overwrite unreadable config at ${this.configPath}`,"Repair the file and try again",void 0,{cause:t,tag:zl})}readStored(){try{let t=this.readConfigFile();if(t===void 0)return structuredClone(this.defaultConfig);return Wo(structuredClone(this.defaultConfig),cf(t))}catch(t){throw this.unreadable(t)}}update(t){try{let e=this.savePath();ef(e,()=>this.write(e,t(this.readStored())))}catch(e){throw e instanceof g?e:this.saveFailure(e)}}savePath(){let t=this.exists()?Ue.realpathSync(this.configPath):af(this.configPath);return Ue.mkdirSync(Xl.dirname(t),{recursive:!0}),t}write(t,e){let n=`${t}.${crypto.randomUUID()}.tmp`;try{let r=this.exists()?Ue.statSync(this.configPath).mode:void 0,o=this.exists()?Yl(Ue.readFileSync(this.configPath,"utf-8"),e):`${JSON.stringify(e,null,SA)}
103
- `;if(Ue.writeFileSync(n,o,{flag:"wx",mode:r}),r!==void 0)Ue.chmodSync(n,r);Ue.renameSync(n,t)}finally{Ue.rmSync(n,{force:!0})}}saveFailure(t){return new g(`Cannot save config at ${this.configPath}: ${lf(t)}`,`Check that ${Xl.dirname(this.configPath)} is writable and that no other process is saving the file`,void 0,{cause:t,tag:zl})}load(){let{parse:t,strict:e}=this.options;try{let n=this.readConfigFile();if(n===void 0)return{config:structuredClone(this.defaultConfig)};let r=Wo(structuredClone(this.defaultConfig),cf(n));return{config:t?t(r):r}}catch(n){if(e)return{config:structuredClone(this.defaultConfig),failure:this.loadFailure(n)};return pt.warn(k.yellow(`Config file corrupted at ${this.configPath}. Using defaults.`),{output:ui()}),{config:structuredClone(this.defaultConfig),error:n}}}loadFailure(t){return new g(`Cannot read config at ${this.configPath}: ${lf(t)}`,"Repair the file and try again",void 0,{cause:t,tag:zl})}readConfigFile(){try{return Ue.readFileSync(this.configPath,"utf-8")}catch(t){if(t.code==="ENOENT")return;throw t}}}function cf(t){let e=JSON.parse(t);if(Array.isArray(e))throw Error("Config must be an object");return TA(e)}function lf(t){return t instanceof Error?t.message:String(t)}var ji="0.4.0";var E=ii();var $A=["GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_PREFIX","GIT_WORK_TREE"],Ae=Object.fromEntries($A.map((t)=>[t,void 0]));var gf={SIGHUP:129,SIGINT:130,SIGTERM:143},uf=Object.keys(gf),df={SIGHUP:()=>Ql("SIGHUP"),SIGINT:()=>Ql("SIGINT"),SIGTERM:()=>Ql("SIGTERM")},Lr=[],tu={interrupted:!1};function de(t){if(Lr.length===0)for(let e of uf)process.on(e,df[e]);return Lr.push(t),()=>{let e=Lr.indexOf(t);if(e===-1)return;if(Lr.splice(e,1),Lr.length===0)for(let n of uf)process.off(n,df[n])}}function mf(){return tu.interrupted}function Ql(t){if(tu.interrupted)return;tu.interrupted=!0;let e=gf[t],n=Lr.toReversed().flatMap((r)=>bA(r)??[]);if(n.length===0)process.exit(e);Promise.all(n).finally(()=>process.exit(e))}function bA(t){try{let e=t();return e instanceof Promise?e.catch(pf):null}catch(e){return pf(e),null}}function pf(t){let e=t instanceof Error?t.message:String(t);process.stderr.write(`ari could not clean up after an interrupt: ${e}
104
- `)}var vA=["ESRCH","EPERM"];function Ce(t,e){try{process.kill(-t,e)}catch(n){if(!vA.includes(n.code))throw n}}var ff=new Map;function Z(t,e){return e.some((n)=>AA(n).match(t))}function eu(t){if(t.trim().length===0)return"is empty";if(t!==t.trim())return"has leading or trailing white space";if(t.includes("\x00"))return"contains a NUL character";if(t.startsWith("!"))return"must not be negated with a leading !";if(t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t))return"must be relative to the repository root";if(t.startsWith("./"))return"must not start with ./";if(t.split("/").includes(".."))return"must not contain a .. segment";return xA(t)}function er(t){let e=eu(t);if(e!==null)return e;if(t.endsWith("/"))return"ends with /, so it matches no file; use a pattern such as dir/**";return t.split("/").includes("")?"has an empty path segment, so it matches no file":null}function xA(t){let e=0,n=!1;for(let r=0;r<t.length;r++){let o=t[r];if(o==="\\"){if(r===t.length-1)return"ends with a lone backslash";r++;continue}if(n){n=o!=="]";continue}if(o==="[")n=!0;if(o==="{")e++;if(o==="}"){if(e===0)return"has an unmatched }";e--}}if(n)return"has an unclosed [";return e>0?"has an unclosed {":null}function AA(t){let e=ff.get(t);if(e)return e;let n=new Bun.Glob(t);return ff.set(t,n),n}class b extends Error{_tag="ValidationError"}var CA=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,RA=/^[A-Za-z_$][A-Za-z0-9_$]*$/,IA="must be lower-case letters and digits separated by single hyphens",OA=new Set(Object.getOwnPropertyNames(Object.prototype)),_A=gt(),PA=Li(),Fi=Vo(),NA=Mi(zm()),DA=gt().or(Nr());function Tt(t,e,n){try{return n()}catch(r){if(r instanceof b)throw new g(`Invalid ${t}: ${r.message}`,e);throw r}}function w(t,e){if(typeof e==="number")return`${t}[${e}]`;if(!RA.test(e))return`${t}[${JSON.stringify(e)}]`;return t.length===0?e:`${t}.${e}`}function C(t,e,n){let r=kf(t,e),o=Object.keys(r).find((s)=>!n.includes(s));if(o!==void 0)throw new b(`${e} has unknown key ${JSON.stringify(o)}; expected ${n.join(", ")}`);return r}function an(t,e,n){return Object.entries(kf(t,e)).map(([r,o])=>{if(OA.has(r))throw new b(`${w(e,r)} uses a reserved name`);return[r,n(o,w(e,r),r)]})}function F(t,e,n){return t===void 0?e:n(t)}function ct(t,e,n){return t===void 0||t===null?e:n(t)}function Et(t,e,n){if(t===void 0||t===null)throw new b(`${e} is required`);return n(t,e)}function x(t,e){return cn(_A,t,e,"must be a string")}function ot(t,e){let n=x(t,e);if(n.trim().length===0)throw new b(`${e} must not be empty`);return n}function Ct(t,e){return cn(DA,t,e,"must be a string or null")}function Re(t,e){let n=x(t,e);if(!CA.test(n))throw new b(`${e} ${IA}, got ${JSON.stringify(n)}`);return n}function Mt(t,e){return cn(PA,t,e,"must be true or false")}function Zt(t,e){let n=cn(Fi,t,e,"must be a positive integer");if(!Number.isInteger(n)||n<=0)throw new b(`${e} must be a positive integer`);return n}function $t(t,e){let n=cn(Fi,t,e,"must be a non-negative integer");if(!Number.isInteger(n)||n<0)throw new b(`${e} must be a non-negative integer`);return n}function Rn(t,e){let n=cn(Fi,t,e,"must be a positive number");if(!Number.isFinite(n)||n<=0)throw new b(`${e} must be a positive number`);return n}function nu(t,e){let n=cn(Fi,t,e,"must be a number greater than 0 and at most 1");if(!(n>0&&n<=1))throw new b(`${e} must be a number greater than 0 and at most 1`);return n}function V(t,e,n){return cn(Zm(t),e,n,`must be one of ${t.join(", ")}`)}function D(t,e,n){return cn(NA,t,e,"must be a list").map((o,s)=>n(o,w(e,s)))}function jt(t,e){return D(t,e,x)}function Gi(t,e){return D(t,e,(n,r)=>yf(n,r,eu))}function hf(t,e){return D(t,e,(n,r)=>yf(n,r,er))}function yf(t,e,n){let r=x(t,e),o=n(r);if(o!==null)throw new b(`${e} ${o}`);return r}function kf(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw new b(`${e} must be an object`);return t}function cn(t,e,n,r){try{return t(e)}catch{throw new b(`${n} ${r}`)}}var LA=["task","review"],ru=["task"],Kt="{prompt}",Yo="{model}",MA=["command","reviewCommand","model","modelFlag","env","inheritEnv","timeoutSeconds","roles"],jA=["default","stages","review"],FA=["agent","model"],GA=/^[A-Za-z_][A-Za-z0-9_]*$/,HA=":",UA="-",Hi={default:null,review:null,stages:{}};function nr(t){return t.roles??ru}function Sf(t){let e=an(t,"agents",KA);for(let[n]of e)Re(n,"agent name");return Object.fromEntries(e)}function KA(t,e){let n=C(t,e,MA),r={command:wf(n.command,w(e,"command"))};if(n.reviewCommand!==void 0)r.reviewCommand=wf(n.reviewCommand,w(e,"reviewCommand"));if(n.model!==void 0)r.model=ot(n.model,w(e,"model"));if(n.modelFlag!==void 0)r.modelFlag=VA(n.modelFlag,w(e,"modelFlag"));if(n.env!==void 0)r.env=JA(n.env,w(e,"env"));if(n.inheritEnv!==void 0)r.inheritEnv=Mt(n.inheritEnv,w(e,"inheritEnv"));if(r.inheritEnv===!0&&r.env!==void 0){let[o,s]=[w(e,"inheritEnv"),w(e,"env")];throw new b(`${o} and ${s} are alternatives; set only one of them`)}if(n.timeoutSeconds!==void 0)r.timeoutSeconds=Rn(n.timeoutSeconds,w(e,"timeoutSeconds"));if(n.roles!==void 0)r.roles=qA(n.roles,w(e,"roles"));return r}function Tf(t){let e=C(t,"routing",jA);return{default:F(e.default,Hi.default,(n)=>qo(n,"routing.default")),review:F(e.review,Hi.review,(n)=>qo(n,"routing.review")),stages:Object.fromEntries(F(e.stages,[],(n)=>an(n,"routing.stages",BA)))}}function qo(t,e){if(t===null)return null;if(typeof t==="string")return WA(t,e);let n=C(t,e,FA),r=Re(n.agent,w(e,"agent")),o=F(n.model,null,(s)=>ot(s,w(e,"model")));return{agent:r,model:o}}function BA(t,e){let n=qo(t,e);if(n!==null)return n;throw new b(`${e} must name an agent; leave the stage out to use routing.default`)}function WA(t,e){let n=t.indexOf(HA);if(n===-1)return{agent:Re(t,e),model:null};let r=Re(t.slice(0,n),`${e} (agent)`),o=ot(t.slice(n+1),`${e} (model)`);return{agent:r,model:o}}function Ef(t){let{agents:e,review:n,routing:r}=t,o=[["routing.default",r.default,"task"],...Object.entries(r.stages).map(([s,i])=>[w("routing.stages",s),i,"task"]),["routing.review",r.review,"review"],["review.agent",n.agent===void 0?null:{agent:n.agent,model:null},"review"]];for(let[s,i,a]of o){if(i===null)continue;let c=e[i.agent];if(c===void 0)throw new b(`${s} names agent "${i.agent}", which agents does not define`);if(!nr(c).includes(a))throw new b(`${s} names agent "${i.agent}", whose roles do not include "${a}"; add it to agents.${i.agent}.roles`)}}function wf(t,e){let n=D(t,e,ot);if(n.length===0)throw new b(`${e} must not be empty`);return n}function VA(t,e){let n=x(t,e);if(n.startsWith(UA)&&n.trim()===n&&n.length>1)return n;throw new b(`${e} must be an option such as "--model"`)}function JA(t,e){let n=D(t,e,(r,o)=>{let s=x(r,o);if(GA.test(s))return s;throw new b(`${o} must be an environment variable name, not a value`)});return $f(n,e)}function qA(t,e){let n=$f(D(t,e,(r,o)=>V(LA,r,o)),e);if(n.length===0)throw new b(`${e} must name at least one role`);return n}function $f(t,e){let n=t.find((r,o)=>t.indexOf(r)!==o);if(n!==void 0)throw new b(`${e} repeats ${JSON.stringify(n)}`);return t}var Mr=["task","review","both"],ou="--model",Ie=[{binary:"claude",command:["claude","-p",Kt,"--permission-mode","acceptEdits"],label:"Claude Code",modelFlag:ou,name:"claude",reviewCommand:["claude","-p",Kt,"--tools","Read,Grep,Glob","--permission-mode","dontAsk"]},{binary:"codex",command:["codex","exec","--sandbox","workspace-write",Kt],label:"Codex CLI",modelFlag:ou,name:"codex",reviewCommand:["codex","exec","--sandbox","read-only",Kt]},{binary:"gemini",command:["gemini","--approval-mode","auto_edit","-p",Kt],label:"Gemini CLI",modelFlag:ou,name:"gemini",reviewCommand:["gemini","--approval-mode","plan","-p",Kt]}];function bf(t){let e=Ie.find((n)=>n.name===t);if(e!==void 0)return e;throw new T(`ari has no agent preset "${t}"`,`Choose one of: ${Ie.map((n)=>n.name).join(", ")}, or add the agent to .ari/config.json yourself`)}function vf(t){let e=t??"task",n=Mr.find((r)=>r===e);if(n!==void 0)return n;throw new T(`Unknown role "${e}"`,`Choose one of: ${Mr.join(", ")}`)}function jr(t,e,n){let r=n===void 0?{}:{model:n};switch(e){case"task":return{command:t.command,...r,modelFlag:t.modelFlag,roles:["task"]};case"review":return{command:t.reviewCommand,...r,modelFlag:t.modelFlag,roles:["review"]};case"both":return{command:t.command,reviewCommand:t.reviewCommand,...r,modelFlag:t.modelFlag,roles:["task","review"]}}}var YA="--version",XA=5000,zA=200;async function xf(){return Promise.all(Ie.map(ZA))}async function ZA(t){return{...await Xo([t.binary]),label:t.label,preset:t.name}}async function Xo(t){for(let e of t){let n=Bun.which(e);if(n!==null)return{binary:e,path:n,version:await QA(n)}}return{binary:t[0]??"",path:null,version:null}}async function QA(t){let e;try{e=Bun.spawn([t,YA],{detached:!0,env:{...process.env,...Ae},stderr:"ignore",stdin:"ignore",stdout:"pipe"})}catch{return null}let n=()=>Ce(e.pid,"SIGKILL"),r=de(n),o=setTimeout(n,XA),[s,i]=await Promise.all([new Response(e.stdout).text(),e.exited]);clearTimeout(o),n(),r();let a=s.split(`
105
- `).map((c)=>c.trim()).find((c)=>c.length>0);return i===0&&a!==void 0?a.slice(0,zA):null}import{isDeepStrictEqual as BO}from"util";function zo(t){if(typeof t!=="object"||t===null||Object.isFrozen(t))return t;for(let e of Object.values(t))zo(e);return Object.freeze(t)}var tC=["cached","run"],Af="TYPESAFE_API_URL",eC=["TYPESAFE_API_KEY","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_TOKEN","CLOUDFLARE_AUTH_TOKEN"],nC=["argus"],rC="cached",oC=25,sC=6000,iC=1000,aC=20000,cC=["config","command","mode","limit","maxBytes","timeoutSeconds"];function Rf(t){let e=C(t,"review.argus",cC),n=F(e.timeoutSeconds,null,(r)=>Rn(r,"review.argus.timeoutSeconds"));return{command:F(e.command,[...nC],lC),config:Et(e.config,"review.argus.config",ot),limit:F(e.limit,oC,(r)=>Cf(r,"limit",iC)),maxBytes:F(e.maxBytes,sC,(r)=>Cf(r,"maxBytes",aC)),mode:F(e.mode,rC,(r)=>V(tC,r,"review.argus.mode")),...n===null?{}:{timeoutSeconds:n}}}function Ui(t){return t==="run"?[Af,...eC]:[Af]}function Ki(t,e){let n=t.mode==="run",r=n?["--limit",String(t.limit),...e.only===null?[]:["--only",e.only]]:[];return[...t.command,n?"run":"check","--config",e.configPath,"--base",e.base,...r,"--json"]}function lC(t){let e=D(t,"review.argus.command",ot);if(e.length===0)throw new b("review.argus.command must list at least the program to start");return e}function Cf(t,e,n){let r=`review.argus.${e}`,o=Zt(t,r);if(o>n)throw new b(`${r} must be at most ${n}`);return o}var uC="basic",dC=300,pC=6000,gC=20,mC=1200,fC=60000,hC=25,yC=0.95,kC=0.75,wC=10,SC=!1,TC=["**/*.test.*","**/*.spec.*","**/*_test.*","**/*-test.{js,cjs,mjs,ts,cts,mts}","**/test-*.{js,cjs,mjs,ts,cts,mts}","**/test.{js,cjs,mjs,ts,cts,mts}","**/test_*.py","**/test/**","**/tests/**","**/__tests__/**"],EC="Fix the reported value in .ari/config.json",$C=["$schema","pack","requireTask","checkTimeoutSeconds","testGlobs","regression","review","context","knowledge","agents","routing"],bC=["maxEntryBytes","maxBytes","decayAfterTasks","duplicateSimilarity","mergeSimilarity","rehearsalTasks","sleepOnStop"],Rt=zo({agents:{},checkTimeoutSeconds:dC,context:{budget:pC,journalTail:gC},knowledge:{decayAfterTasks:hC,duplicateSimilarity:yC,maxBytes:fC,maxEntryBytes:mC,mergeSimilarity:kC,rehearsalTasks:wC,sleepOnStop:SC},pack:uC,regression:{setup:[]},requireTask:!1,review:{command:null},routing:Hi,testGlobs:TC});function rr(t){return structuredClone(Tt("config",EC,()=>If(t)))}function Bi(t){try{return If(t),null}catch(e){if(e instanceof b)return e.message;throw e}}function If(t){let e=C(t,"config",$C);if(e.$schema!==void 0)x(e.$schema,"$schema");let n={agents:F(e.agents,Rt.agents,Sf),checkTimeoutSeconds:F(e.checkTimeoutSeconds,Rt.checkTimeoutSeconds,(r)=>Rn(r,"checkTimeoutSeconds")),context:F(e.context,Rt.context,vC),knowledge:F(e.knowledge,Rt.knowledge,xC),pack:F(e.pack,Rt.pack,(r)=>Re(r,"pack")),regression:F(e.regression,Rt.regression,AC),requireTask:F(e.requireTask,Rt.requireTask,(r)=>Mt(r,"requireTask")),review:F(e.review,Rt.review,CC),routing:F(e.routing,Rt.routing,Tf),testGlobs:F(e.testGlobs,Rt.testGlobs,(r)=>hf(r,"testGlobs"))};return Ef(n),n}function vC(t){let e=C(t,"context",["budget","journalTail"]),n=Rt.context;return{budget:F(e.budget,n.budget,(r)=>Zt(r,"context.budget")),journalTail:F(e.journalTail,n.journalTail,(r)=>$t(r,"context.journalTail"))}}function xC(t){let e=C(t,"knowledge",bC),n={decayAfterTasks:Fr(e,"decayAfterTasks",Zt),duplicateSimilarity:Fr(e,"duplicateSimilarity",nu),maxBytes:Fr(e,"maxBytes",Zt),maxEntryBytes:Fr(e,"maxEntryBytes",Zt),mergeSimilarity:Fr(e,"mergeSimilarity",nu),rehearsalTasks:Fr(e,"rehearsalTasks",$t),sleepOnStop:F(e.sleepOnStop,Rt.knowledge.sleepOnStop,(r)=>Mt(r,"knowledge.sleepOnStop"))};if(n.mergeSimilarity>n.duplicateSimilarity)throw new b("knowledge.mergeSimilarity must not exceed knowledge.duplicateSimilarity");if(n.maxEntryBytes>n.maxBytes)throw new b("knowledge.maxEntryBytes must not exceed knowledge.maxBytes");return n}function Fr(t,e,n){return F(t[e],Rt.knowledge[e],(r)=>n(r,`knowledge.${e}`))}function AC(t){let e=C(t,"regression",["setup"]);return{setup:F(e.setup,Rt.regression.setup,(n)=>D(n,"regression.setup",ot))}}function CC(t){let e=C(t,"review",["command","agent","model","argus"]),n=F(e.command,Rt.review.command,(i)=>Ct(i,"review.command"));if(n!==null&&n.trim().length===0)throw new b("review.command must be a command or null");let r=F(e.agent,null,(i)=>i===null?null:Re(i,"review.agent")),o=F(e.model,null,(i)=>i===null?null:ot(i,"review.model"));if(n!==null&&r!==null)throw new b("review.command and review.agent are alternatives; set only one of them");if(o!==null&&r===null)throw new b("review.model needs review.agent");let s=e.argus===void 0?null:Rf(e.argus);return{command:n,...r===null?{}:{agent:r},...o===null?{}:{model:o},...s===null?{}:{argus:s}}}import{randomUUID as NO}from"crypto";import{chmodSync as DO,existsSync as Hu,mkdirSync as LO,readFileSync as ty,renameSync as MO,rmSync as jO,statSync as FO,writeFileSync as GO}from"fs";import{basename as HO,dirname as Qh,join as Uu}from"path";import{isDeepStrictEqual as _f}from"util";var RC=/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g,IC=/"(?:[^"\\\n]|\\.)*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,OC=/[^\r\n]/g,_C=/(?:^|\n)([\t ]*)[^\n]*$/,PC=/^[\t ]*\r?\n/,NC=/^[\t ]+(?=\S)/m,DC=" ",Zo=",";function su(t){return t.replace(IC,(e)=>e.startsWith('"')?e:e.replace(OC," "))}function Wi(t,e){let n=NC.exec(t)?.[0]??DC,r=t.includes(`\r
106
- `)?`\r
107
- `:`
108
- `,o=(i,a)=>{let c=t.slice(i.start,i.end);if(_f(i.value,a))return c;let l=r+(_C.exec(t.slice(0,i.start))?.[1]??""),u=(_,A)=>JSON.stringify(_,null,n).replaceAll(`
109
- `,A);if(!Of(i.value)||!Of(a)||Array.isArray(i.value)!==Array.isArray(a))return u(a,l);let d=LC(i,a),p=[],m="",f=i.start+1,y=(_)=>{let A=t.slice(f,_);return m+(m.length===0||PC.test(A)?"":r)+A};for(let _ of i.entries){let A=y(_.start),B=d.get(_);if(m="",B!==void 0){let Dt=o(_.node,a[B]);p.push(A+t.slice(_.start,_.node.start)+Dt+t.slice(_.node.end,_.end))}else if(A.trim().length>0)m=A.trimEnd();f=t[_.end]===Zo?_.end+1:_.end}let S=new Set(d.values()),R=l+n,v=Object.keys(a).filter((_)=>!S.has(_)).map((_)=>{let A=Array.isArray(a)?"":`${JSON.stringify(_)}: `;return R+A+u(a[_],R)}),H=y(i.end-1),J=H.trimEnd(),N=v.length===0?H.slice(J.length):l,U=p.length>0&&v.length>0?Zo:"";return c[0]+p.join(Zo)+U+J+v.join(Zo)+N+c.at(-1)},s=MC(su(t));return t.slice(0,s.start)+o(s,JSON.parse(JSON.stringify(e)))+t.slice(s.end)}function LC({entries:t},e){let n=Array.isArray(e)&&e.length<t.length,r=new Map;for(let o of t){let s=n?String(r.size):o.key;if((!n||_f(o.node.value,e[s]))&&Object.hasOwn(e,s))r.set(o,s)}return r}function Of(t){return typeof t==="object"&&t!==null}function MC(t){let e=[...t.matchAll(RC)],n=0,r=()=>{let s=e[n];if(s===void 0)throw Error("Unexpected end of JSON");return n+=1,s},o=()=>{let s=r(),i=s[0];if(i!=="{"&&i!=="[")return{end:s.index+i.length,entries:[],start:s.index,value:JSON.parse(i)};let a=i==="{"?"}":"]",c=[];while(e[n]!==void 0&&e[n]?.[0]!==a){let u=e[n]?.index??0,d=i==="{"?JSON.parse(r()[0]):String(c.length);if(i==="{")r();let p=o(),m=e[n]?.[0]===Zo?r().index:p.end;c.push({end:m,key:d,node:p,start:u})}let l=r().index+1;return{end:l,entries:c,start:s.index,value:JSON.parse(t.slice(s.index,l))}};return o()}import{existsSync as Vh,readlinkSync as SO,realpathSync as TO,statSync as EO}from"fs";import{basename as $O,dirname as os,isAbsolute as bO,join as ka,relative as vO,resolve as Jh,sep as xO}from"path";import{copyFileSync as JC,existsSync as qC,mkdtempSync as YC,readFileSync as XC,readlinkSync as zC,rmSync as ZC,utimesSync as QC}from"fs";import{tmpdir as tR}from"os";import{join as Ji,resolve as eR}from"path";function I(t,e){if(t<e)return-1;if(t>e)return 1;return 0}function tt(t){return new Bun.CryptoHasher("sha256").update(t).digest("hex")}import{lstatSync as jC,statSync as FC}from"fs";import{dirname as GC,join as HC}from"path";var UC=["ENOENT","ENOTDIR","ELOOP"];function In(t){return Pf(()=>jC(t))}function iu(t){return Pf(()=>FC(t))}function Gr(t,e,n=new Map){let r=GC(e);if(r===".")return!1;let o=n.get(r);if(o!==void 0)return o;let s=In(HC(t,r))?.isSymbolicLink()===!0||Gr(t,r,n);return n.set(r,s),s}function Pf(t){try{return t()}catch(e){if(UC.includes(e.code))return null;throw e}}import{realpathSync as KC}from"fs";var Qo="ari-base-",au="ari-index-",BC=12;function Vi(t){return`${au}${WC(t)}-`}function WC(t){return tt(VC(t)).slice(0,BC)}function VC(t){try{return KC(t)}catch{return t}}var qi="\x00",Bt=0,nR=128,rR=128,Ff=1,Gf=1,oR=1,cu=["diff","--name-only","--no-renames","--ignore-submodules=untracked","-z"],sR=["git","--no-optional-locks","--no-replace-objects",...["core.fsmonitor=false","core.untrackedCache=false","core.trustctime=true","core.checkStat=default"].flatMap((t)=>["-c",t])],Nf=1,iR=/^(?:[a-z]|S) /,Df=/^s/i,aR=2,cR="symlink:",lR=["--no-assume-unchanged","--no-skip-worktree"],Lf="worktree ",uR="bare",dR="prunable",Mf=/^(?:error|fatal): /;async function P(t,e,n={}){let r=[...sR,...e],o=mR(r,t,n),[s,i,a]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if((n.allowedExitCodes??[Bt]).includes(a))return{exitCode:a,stderr:i,stdout:s};let l=i.trim()||s.trim()||"no output";throw Error(`git ${e.join(" ")} failed in ${t} with exit code ${a}: ${l}`)}async function On(t){let e=await P(t,["rev-parse","--show-toplevel"],{allowedExitCodes:[Bt,nR]});if(e.exitCode!==Bt)throw new g(`${t} is not inside a git working tree`,"Run ari from inside a git repository");return e.stdout.trim()}async function Ke(t,e){let n=await P(t,["rev-parse","--git-path",e]);return eR(t,n.stdout.trim())}async function Yi(t){let e=await P(t,["rev-parse","--verify","--quiet","HEAD^{commit}"],{allowedExitCodes:[Bt,Ff]});if(e.exitCode!==Bt)throw new g("The repository has no commits yet","Make a first commit, then run the command again");return e.stdout.trim()}async function Hf(t){let e=await P(t,["config","user.name"],{allowedExitCodes:[Bt,Gf]}),n=e.stdout.trim();return e.exitCode===Bt&&n.length>0?n:null}async function pe(t,e){let n=await Wf(t,async(s)=>(await Bf(t,await zi(t),s),P(t,[...cu,e,"--"],{env:s}))),r=await P(t,[...cu,"--cached",e,"--"]),o=await P(t,["ls-files","--others","--exclude-standard","-z"]);return uu([n,r,o].flatMap((s)=>Oe(s.stdout)))}async function Xi(t,e,n){let r=await P(t,[...cu,e,n,"--"]);return uu(Oe(r.stdout))}async function Hr(t,e){let n=await P(t,["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],{allowedExitCodes:[Bt,Ff]});if(n.exitCode!==Bt)throw new g(`"${e}" does not name a commit`,"Pass a branch, tag or commit that this repository has");return n.stdout.trim()}async function Uf(t,e,n){let r=await P(t,["merge-base",e,n],{allowedExitCodes:[Bt,oR]});if(r.exitCode!==Bt)throw new g(`${e} and ${n} share no history`,"Pass a ref that the current branch was integrated with");return r.stdout.trim()}async function Kf(t){let e=await P(t,["worktree","list","--porcelain","-z"]),n=[],r=null;for(let o of[...e.stdout.split(qi),""])if(o.startsWith(Lf))r=o.slice(Lf.length);else if(o===uR||o.startsWith(dR))r=null;else if(o===""&&r!==null)n.push(r),r=null;return n}async function ge(t,e){return Wf(t,async(n)=>{await Bf(t,await zi(t),n);let r=await P(t,["add","--all","--sparse","--","."],{allowedExitCodes:[Bt,rR],env:n});if(r.exitCode!==Bt)throw new g(`git cannot hash the working tree: ${lu(r.stderr)}`,"Commit, remove or ignore those paths (an embedded repository needs a commit), then run the command again");if(e.length>0){let s=e.map((i)=>`:(glob)${i}`);await P(t,["rm","--cached","-r","-q","--sparse","--ignore-unmatch","--",...s],{env:n})}return(await P(t,["write-tree"],{env:n})).stdout.trim()})}async function ln(t,e){if(e.length===0)return{};let n=await P(t,["ls-files","--cached","--others","--exclude-standard","-z"]),r=new Map,o=uu(Oe(n.stdout)).filter((s)=>Z(s,e)&&!Gr(t,s,r));return Object.fromEntries(o.flatMap((s)=>{let i=gR(Ji(t,s));return i===null?[]:[[s,i]]}))}function lu(t){let e=t.split(`
110
- `).map((r)=>r.trim()).filter((r)=>r.length>0),n=e.filter((r)=>Mf.test(r)).map((r)=>r.replace(Mf,""));return(n.length>0?n:e).join("; ")||"no output"}async function zi(t){let e=await P(t,["ls-files","-v","-z"]),n=Oe(e.stdout).filter((o)=>iR.test(o)),r=n.some((o)=>Df.test(o))&&await pR(t);return n.filter((o)=>!(r&&Df.test(o))||In(Ji(t,jf(o)))!==null).map(jf)}async function pR(t){return(await P(t,["config","--type=bool","core.sparseCheckout"],{allowedExitCodes:[Bt,Gf]})).stdout.trim()==="true"}function jf(t){return t.slice(aR)}async function Bf(t,e,n){if(e.length===0)return;let r=`${e.join(qi)}${qi}`;for(let o of lR)await P(t,["update-index",o,"-z","--stdin"],{env:n,stdin:r})}async function Wf(t,e){let n=YC(Ji(tR(),Vi(t))),r=Ji(n,"index"),o=()=>ZC(n,{force:!0,recursive:!0}),s=de(o);try{let i=await Ke(t,"index");if(qC(i))JC(i,r),QC(r,Nf,Nf);return await e({GIT_INDEX_FILE:r})}finally{o(),s()}}function gR(t){let e=In(t);if(e?.isSymbolicLink())return`${cR}${tt(zC(t))}`;return e?.isFile()?tt(XC(t)):null}function mR(t,e,n){try{return Bun.spawn(t,{cwd:e,env:n.env?{...process.env,...n.env}:process.env,stderr:"pipe",stdin:n.stdin===void 0?"ignore":new TextEncoder().encode(n.stdin),stdout:"pipe"})}catch(r){throw Error(`Could not run ${t.join(" ")} in ${e}`,{cause:r})}}function Oe(t){return t.split(qi).filter((e)=>e.length>0)}function uu(t){return[...new Set(t)].sort(I)}import{randomUUID as tO}from"crypto";import{appendFileSync as eO,existsSync as mn,linkSync as nO,mkdirSync as $h,readdirSync as rO,readFileSync as ns,renameSync as bh,rmSync as da,writeFileSync as vh}from"fs";import{basename as oO,dirname as xh,join as yt}from"path";var ts='writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys',fR=/"(?:[^"\\]|\\.)*"|'(?:[^']|'')*'/sy,hR=/(?:[^,[\]{}:#\n]|:(?![ \t\n,[\]{}]|$)|(?<![ \t\n])#)+/sy,yR=/(?:[ \t\n]|(?<=[ \t\n])#[^\n]*)+/sy,kR=/[&!*][^\s,[\]{}]*|\?(?=[ \t\n])/sy,wR=/[ \t\n,[\]{}]/;function pu(t){return`defines "${t}" twice`}function gu(t,e){return Zi(fR,t,e)}function mu(t){return String(Bun.YAML.parse(t))}function Vf(t,e){let n=[],r=e,o=!1;while(r<t.length){let s=TR(t,r,o);if(r+=s.text.length,s.kind==="space")continue;let i=SR(s,n);if(i!==null)return{end:r,problem:i};if(n.length===0)return{end:r,problem:null};o=s.kind==="quoted"||s.kind==="close"}return{end:r,problem:null}}function SR(t,e){let n=e.at(-1),r=n?.keys!=null&&n.inKey;switch(t.kind){case"open":{if(r)return'writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys';let o=t.text==="{"?new Set:null;return e.push({inKey:o!==null,key:null,keys:o}),null}case"close":return e.pop(),r?du(n):null;case"comma":{let o=r?du(n):null;if(n!==void 0)Object.assign(n,{inKey:n.keys!==null,key:null});return o}case"colon":if(!r)return null;return n.inKey=!1,du(n);case"special":return r?'writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys':null;case"quoted":case"plain":if(r)n.key=t.kind==="quoted"?mu(t.text):t.text.trim();return null;case"space":return null}}function du(t){let{key:e,keys:n}=t;if(e===null||n===null)return null;if(n.has(e))return pu(e);return n.add(e),null}function TR(t,e,n){let r=t[e]??"";if(r==="{"||r==="[")return{kind:"open",text:r};if(r==="}"||r==="]")return{kind:"close",text:r};if(r===",")return{kind:"comma",text:r};if(r===":"&&(n||wR.test(t[e+1]??" ")))return{kind:"colon",text:r};let o=Zi(yR,t,e);if(o!==null)return{kind:"space",text:o};let s=gu(t,e);if(s!==null)return{kind:"quoted",text:s};let i=Zi(kR,t,e);if(i!==null)return{kind:"special",text:i};return{kind:"plain",text:Zi(hR,t,e)??r}}function Zi(t,e,n){return t.lastIndex=n,t.exec(e)?.[0]??null}var ER=/^(?:---|\.\.\.)(?=[ \t]|$)/,$R=/^( *)((?:-(?: +|$))*)(.*)$/s,Jf=/^(?:[&!][^ \t]*(?:[ \t]+|$))+/,bR=/^#/,vR=/^[{[]/,xR=/^\?(?:[ \t]|$)/,AR=/^\*.*:(?:[ \t]|$)/s,qf=/^[ \t]*:(?:[ \t]+|$)/,CR=/^([^\s|>%@`"'&*!#,[\]{}](?:(?![ \t]#).)*?)[ \t]*:(?:[ \t]+(.*))?$/s,Yf=-1;function Xf(t){let e=[],n=null,r=0,o=0;for(let s of t.split(`
111
- `)){let i=o;if(o+=s.length+1,i<r)continue;let a=s.match(ER)?.[0];if(a!==void 0)e.length=0,n=null;let c=a===void 0?s:s.replace(a," ".repeat(a.length)),[,l="",u="",d=""]=c.match($R)??[];if(n!==null&&l.length>n)continue;if(u===""&&zf(d))continue;let p=l.length+u.length;_R(e,u===""?p:l.length);let m=RR(d);if(m===ts)return m;if(m!==null){let{keys:R}=PR(e,p);if(R.has(m.name))return pu(m.name);R.add(m.name)}let f=OR(m===null?d:m.value),y=u===""?e.at(-1)?.column??Yf:c.lastIndexOf("-",p-1);if(n=f.kind==="text"?m===null?y:p:null,f.kind!=="flow")continue;let S=Vf(t,i+c.length-f.text.length);if(S.problem!==null)return S.problem;if(r=S.end,m===null&&qf.test(t.slice(S.end,o).trimEnd()))return ts}return null}function RR(t){if(xR.test(t)||AR.test(t))return ts;let e=t.replace(Jf,""),n=IR(e);return n!==null&&e!==t?ts:n}function IR(t){let e=gu(t,0);if(e===null){let[,r,o=""]=t.match(CR)??[];return r===void 0?null:{name:r,value:o}}let n=t.slice(e.length).match(qf)?.[0];return n===void 0?null:{name:mu(e),value:t.slice(e.length+n.length)}}function OR(t){let e=t.replace(Jf,"");if(zf(e))return{kind:"block",text:e};return{kind:vR.test(e)?"flow":"text",text:e}}function zf(t){return t.trim()===""||bR.test(t)}function _R(t,e){while((t.at(-1)?.column??Yf)>e)t.pop()}function PR(t,e){let n=t.at(-1);if(n?.column===e)return n;let r={column:e,keys:new Set};return t.push(r),r}var Ur="---",NR=/^\uFEFF+/,DR=/\r\n?/g;function Qi(t){return t.replace(NR,"").replace(DR,`
112
- `)}function ta(t){let e=Qi(t).split(`
113
- `);if(e[0]?.trimEnd()!==Ur)throw new b(`the file must start with a "${Ur}" line that opens the front matter`);let n=e.findIndex((r,o)=>o>0&&r.trimEnd()===Ur);if(n===-1)throw new b(`the front matter has no closing "${Ur}" line`);return{body:e.slice(n+1).join(`
114
- `),data:fu(e.slice(1,n).join(`
115
- `),"the front matter")}}function ea(t,e){return`${Ur}
97
+ `));let g=p?u.map((R,B)=>String(B)):[...new Set([...l.entries.map((R)=>R.key).filter((R)=>Object.hasOwn(u,R)),...Object.keys(u)])];if(g.length===0)return p?"[]":"{}";let f=l.entries[0],y=l.entries.at(-1);if(!f||!y)return c(u,l.start,d.includes(`
98
+ `));let S=(R)=>p?u[Number(R)]:u[R];if(g.length===l.entries.length&&g.every((R,B)=>R===l.entries[B]?.key)){let R=l.start,B="";for(let _t of l.entries)B+=t.slice(R,_t.node.start)+a(_t.node,S(_t.key)),R=_t.node.end;return B+t.slice(R,l.end)}let I=t.slice(l.start+1,f.start),C=t.slice(y.node.end,l.end-1),q=l.entries[1],G=q?t.slice(f.node.end,q.start):`,${I.includes(`
99
+ `)?I:i}`,N=p?"":t.slice(f.start,f.node.start).match(/:\s*$/)?.[0]??": ",H=new Map(l.entries.map((R)=>[R.key,R])),A=g.map((R)=>{let B=H.get(R);if(B)return t.slice(B.start,B.node.start)+a(B.node,S(R));return(p?"":JSON.stringify(R)+N)+c(S(R),f.start,I.includes(`
100
+ `))});return`${p?"[":"{"}${I}${A.join(G)}${C}${p?"]":"}"}`}function c(l,u,d){if(!d)return Fu(l,i);let p=t.lastIndexOf(`
101
+ `,u-1)+1,g=t.slice(p,u).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(l,null,o).replaceAll(`
102
+ `,s+g)}return t.slice(0,r.start)+a(r,n)+t.slice(r.end)}function Fu(t,e){if(Array.isArray(t))return`[${t.map((o)=>Fu(o,e)).join(`,${e}`)}]`;if(t===null||typeof t!=="object")return JSON.stringify(t);let n=Object.entries(t);if(n.length===0)return"{}";let r=n.map(([o,s])=>`${JSON.stringify(o)}:${e}${Fu(s,e)}`);return`{${e}${r.join(`,${e}`)}${e}}`}function PR(t){let e=t.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),n=e.next().value;function r(){if(!n)throw Error("Unexpected end of JSON");let s=n;return n=e.next().value,s}function o(){let s=r(),i=[],a=s[0]==="{";if(!a&&s[0]!=="[")return{end:s.index+s[0].length,entries:i,start:s.index,value:JSON.parse(s[0])};let c=a?"}":"]";while(n&&n[0]!==c){let u=n.index,d=a?JSON.parse(r()[0]):String(i.length);if(a)r();if(i.push({key:d,node:o(),start:u}),n?.[0]===",")r()}let l=r().index+1;return{end:l,entries:i,start:s.index,value:JSON.parse(t.slice(s.index,l))}}return o()}var NR=2,Uu="ConfigError",DR=ws(Object);class Ku{loaded;configPath;defaultConfig;options;constructor(t,e,n={}){this.configPath=Hu.resolve(t),this.defaultConfig=e,this.options=n}get path(){return this.configPath}get failure(){return this.state().failure}get(t){return this.current()[t]}set(t,e){let n=this.writable();this.update((r)=>({...r,[t]:e})),n.config={...n.config,[t]:e}}delete(t){let e=this.writable();this.update((n)=>(delete n[t],n)),delete e.config[t]}exists(){return tn.existsSync(this.configPath)}getAll(){return structuredClone(this.current())}save(t){let e=this.writable();if(t)e.config={...t};this.update(()=>e.config)}state(){return this.loaded??=this.load(),this.loaded}current(){let{config:t,failure:e}=this.state();if(e)throw e;return t}writable(){let t=this.state();if(t.failure)throw t.failure;if(t.error)throw this.unreadable(t.error);return t}unreadable(t){return new m(`Cannot overwrite unreadable config at ${this.configPath}`,"Repair the file and try again",void 0,{cause:t,tag:Uu})}readStored(){try{let t=this.readConfigFile();if(t===void 0)return structuredClone(this.defaultConfig);return ks(structuredClone(this.defaultConfig),gh(t))}catch(t){throw this.unreadable(t)}}update(t){try{let e=this.savePath();ah(e,()=>this.write(e,t(this.readStored())))}catch(e){throw e instanceof m?e:this.saveFailure(e)}}savePath(){let t=this.exists()?tn.realpathSync(this.configPath):ph(this.configPath);return tn.mkdirSync(Hu.dirname(t),{recursive:!0}),t}write(t,e){let n=`${t}.${crypto.randomUUID()}.tmp`;try{let r=this.exists()?tn.statSync(this.configPath).mode:void 0,o=this.exists()?Gu(tn.readFileSync(this.configPath,"utf-8"),e):`${JSON.stringify(e,null,NR)}
103
+ `;if(tn.writeFileSync(n,o,{flag:"wx",mode:r}),r!==void 0)tn.chmodSync(n,r);tn.renameSync(n,t)}finally{tn.rmSync(n,{force:!0})}}saveFailure(t){return new m(`Cannot save config at ${this.configPath}: ${mh(t)}`,`Check that ${Hu.dirname(this.configPath)} is writable and that no other process is saving the file`,void 0,{cause:t,tag:Uu})}load(){let{parse:t,strict:e}=this.options;try{let n=this.readConfigFile();if(n===void 0)return{config:structuredClone(this.defaultConfig)};let r=ks(structuredClone(this.defaultConfig),gh(n));return{config:t?t(r):r}}catch(n){if(e)return{config:structuredClone(this.defaultConfig),failure:this.loadFailure(n)};return bt.warn(w.yellow(`Config file corrupted at ${this.configPath}. Using defaults.`),{output:Ki()}),{config:structuredClone(this.defaultConfig),error:n}}}loadFailure(t){return new m(`Cannot read config at ${this.configPath}: ${mh(t)}`,"Repair the file and try again",void 0,{cause:t,tag:Uu})}readConfigFile(){try{return tn.readFileSync(this.configPath,"utf-8")}catch(t){if(t.code==="ENOENT")return;throw t}}}function gh(t){let e=JSON.parse(t);if(Array.isArray(e))throw Error("Config must be an object");return DR(e)}function mh(t){return t instanceof Error?t.message:String(t)}var ya="0.5.1";var E=Fi();var fh=new Map;function et(t,e){return e.some((n)=>jR(n).match(t))}function Bu(t){if(t.trim().length===0)return"is empty";if(t!==t.trim())return"has leading or trailing white space";if(t.includes("\x00"))return"contains a NUL character";if(t.startsWith("!"))return"must not be negated with a leading !";if(t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t))return"must be relative to the repository root";if(t.startsWith("./"))return"must not start with ./";if(t.split("/").includes(".."))return"must not contain a .. segment";return MR(t)}function wr(t){let e=Bu(t);if(e!==null)return e;if(t.endsWith("/"))return"ends with /, so it matches no file; use a pattern such as dir/**";return t.split("/").includes("")?"has an empty path segment, so it matches no file":null}function MR(t){let e=0,n=!1;for(let r=0;r<t.length;r++){let o=t[r];if(o==="\\"){if(r===t.length-1)return"ends with a lone backslash";r++;continue}if(n){n=o!=="]";continue}if(o==="[")n=!0;if(o==="{")e++;if(o==="}"){if(e===0)return"has an unmatched }";e--}}if(n)return"has an unclosed [";return e>0?"has an unclosed {":null}function jR(t){let e=fh.get(t);if(e)return e;let n=new Bun.Glob(t);return fh.set(t,n),n}class b extends Error{_tag="ValidationError"}var FR=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,GR=/^[A-Za-z_$][A-Za-z0-9_$]*$/,HR="must be lower-case letters and digits separated by single hyphens",UR=new Set(Object.getOwnPropertyNames(Object.prototype)),KR=X(),BR=ha(),ka=yr(),VR=no(rh()),WR=X().or(Bn());function At(t,e,n){try{return n()}catch(r){if(r instanceof b)throw new m(`Invalid ${t}: ${r.message}`,e);throw r}}function k(t,e){if(typeof e==="number")return`${t}[${e}]`;if(!GR.test(e))return`${t}[${JSON.stringify(e)}]`;return t.length===0?e:`${t}.${e}`}function T(t,e,n){let r=kh(t,e),o=Object.keys(r).find((s)=>!n.includes(s));if(o!==void 0)throw new b(`${e} has unknown key ${JSON.stringify(o)}; expected ${n.join(", ")}`);return r}function bn(t,e,n){return Object.entries(kh(t,e)).map(([r,o])=>{if(UR.has(r))throw new b(`${k(e,r)} uses a reserved name`);return[r,n(o,k(e,r),r)]})}function D(t,e,n){return t===void 0?e:n(t)}function lt(t,e,n){return t===void 0||t===null?e:n(t)}function ft(t,e,n){if(t===void 0||t===null)throw new b(`${e} is required`);return n(t,e)}function x(t,e){return En(KR,t,e,"must be a string")}function nt(t,e){let n=x(t,e);if(n.trim().length===0)throw new b(`${e} must not be empty`);return n}function Ct(t,e){return En(WR,t,e,"must be a string or null")}function je(t,e){let n=x(t,e);if(!FR.test(n))throw new b(`${e} ${HR}, got ${JSON.stringify(n)}`);return n}function $t(t,e){return En(BR,t,e,"must be true or false")}function Kt(t,e){let n=En(ka,t,e,"must be a positive integer");if(!Number.isInteger(n)||n<=0)throw new b(`${e} must be a positive integer`);return n}function ht(t,e){let n=En(ka,t,e,"must be a non-negative integer");if(!Number.isInteger(n)||n<0)throw new b(`${e} must be a non-negative integer`);return n}function Vn(t,e){let n=En(ka,t,e,"must be a positive number");if(!Number.isFinite(n)||n<=0)throw new b(`${e} must be a positive number`);return n}function Vu(t,e){let n=En(ka,t,e,"must be a number greater than 0 and at most 1");if(!(n>0&&n<=1))throw new b(`${e} must be a number greater than 0 and at most 1`);return n}function K(t,e,n){return En(oh(t),e,n,`must be one of ${t.join(", ")}`)}function L(t,e,n){return En(VR,t,e,"must be a list").map((o,s)=>n(o,k(e,s)))}function Dt(t,e){return L(t,e,x)}function wa(t,e){return L(t,e,(n,r)=>yh(n,r,Bu))}function hh(t,e){return L(t,e,(n,r)=>yh(n,r,wr))}function yh(t,e,n){let r=x(t,e),o=n(r);if(o!==null)throw new b(`${e} ${o}`);return r}function kh(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw new b(`${e} must be an object`);return t}function En(t,e,n,r){try{return t(e)}catch{throw new b(`${n} ${r}`)}}var JR=["task","review"],Wu=["task"],Zt="{prompt}",vs="{model}",qR=["command","reviewCommand","model","modelFlag","env","inheritEnv","timeoutSeconds","roles"],YR=["default","stages","review"],XR=["agent","model"],zR=/^[A-Za-z_][A-Za-z0-9_]*$/,ZR=":",QR="-",Sa={default:null,review:null,stages:{}};function Sr(t){return t.roles??Wu}function Sh(t){let e=bn(t,"agents",tI);for(let[n]of e)je(n,"agent name");return Object.fromEntries(e)}function tI(t,e){let n=T(t,e,qR),r={command:wh(n.command,k(e,"command"))};if(n.reviewCommand!==void 0)r.reviewCommand=wh(n.reviewCommand,k(e,"reviewCommand"));if(n.model!==void 0)r.model=nt(n.model,k(e,"model"));if(n.modelFlag!==void 0)r.modelFlag=rI(n.modelFlag,k(e,"modelFlag"));if(n.env!==void 0)r.env=oI(n.env,k(e,"env"));if(n.inheritEnv!==void 0)r.inheritEnv=$t(n.inheritEnv,k(e,"inheritEnv"));if(r.inheritEnv===!0&&r.env!==void 0){let[o,s]=[k(e,"inheritEnv"),k(e,"env")];throw new b(`${o} and ${s} are alternatives; set only one of them`)}if(n.timeoutSeconds!==void 0)r.timeoutSeconds=Vn(n.timeoutSeconds,k(e,"timeoutSeconds"));if(n.roles!==void 0)r.roles=sI(n.roles,k(e,"roles"));return r}function vh(t){let e=T(t,"routing",YR);return{default:D(e.default,Sa.default,(n)=>Ss(n,"routing.default")),review:D(e.review,Sa.review,(n)=>Ss(n,"routing.review")),stages:Object.fromEntries(D(e.stages,[],(n)=>bn(n,"routing.stages",eI)))}}function Ss(t,e){if(t===null)return null;if(typeof t==="string")return nI(t,e);let n=T(t,e,XR),r=je(n.agent,k(e,"agent")),o=D(n.model,null,(s)=>nt(s,k(e,"model")));return{agent:r,model:o}}function eI(t,e){let n=Ss(t,e);if(n!==null)return n;throw new b(`${e} must name an agent; leave the stage out to use routing.default`)}function nI(t,e){let n=t.indexOf(ZR);if(n===-1)return{agent:je(t,e),model:null};let r=je(t.slice(0,n),`${e} (agent)`),o=nt(t.slice(n+1),`${e} (model)`);return{agent:r,model:o}}function bh(t){let{agents:e,review:n,routing:r}=t,o=[["routing.default",r.default,"task"],...Object.entries(r.stages).map(([s,i])=>[k("routing.stages",s),i,"task"]),["routing.review",r.review,"review"],["review.agent",n.agent===void 0?null:{agent:n.agent,model:null},"review"]];for(let[s,i,a]of o){if(i===null)continue;let c=e[i.agent];if(c===void 0)throw new b(`${s} names agent "${i.agent}", which agents does not define`);if(!Sr(c).includes(a))throw new b(`${s} names agent "${i.agent}", whose roles do not include "${a}"; add it to agents.${i.agent}.roles`)}}function wh(t,e){let n=L(t,e,nt);if(n.length===0)throw new b(`${e} must not be empty`);return n}function rI(t,e){let n=x(t,e);if(n.startsWith(QR)&&n.trim()===n&&n.length>1)return n;throw new b(`${e} must be an option such as "--model"`)}function oI(t,e){let n=L(t,e,(r,o)=>{let s=x(r,o);if(zR.test(s))return s;throw new b(`${o} must be an environment variable name, not a value`)});return Eh(n,e)}function sI(t,e){let n=Eh(L(t,e,(r,o)=>K(JR,r,o)),e);if(n.length===0)throw new b(`${e} must name at least one role`);return n}function Eh(t,e){let n=t.find((r,o)=>t.indexOf(r)!==o);if(n!==void 0)throw new b(`${e} repeats ${JSON.stringify(n)}`);return t}var iI=["GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_PREFIX","GIT_WORK_TREE"],Fe=Object.fromEntries(iI.map((t)=>[t,void 0]));var Ah={SIGHUP:129,SIGINT:130,SIGTERM:143},$h=Object.keys(Ah),Th={SIGHUP:()=>Ju("SIGHUP"),SIGINT:()=>Ju("SIGINT"),SIGTERM:()=>Ju("SIGTERM")},oo=[],qu={interrupted:!1};function Qt(t){if(oo.length===0)for(let e of $h)process.on(e,Th[e]);return oo.push(t),()=>{let e=oo.indexOf(t);if(e===-1)return;if(oo.splice(e,1),oo.length===0)for(let n of $h)process.off(n,Th[n])}}function Ch(){return qu.interrupted}function Ju(t){if(qu.interrupted)return;qu.interrupted=!0;let e=Ah[t],n=oo.toReversed().flatMap((r)=>aI(r)??[]);if(n.length===0)process.exit(e);Promise.all(n).finally(()=>process.exit(e))}function aI(t){try{let e=t();return e instanceof Promise?e.catch(xh):null}catch(e){return xh(e),null}}function xh(t){let e=t instanceof Error?t.message:String(t);process.stderr.write(`ari could not clean up after an interrupt: ${e}
104
+ `)}var cI=["ESRCH","EPERM"];function Ge(t,e){try{process.kill(-t,e)}catch(n){if(!cI.includes(n.code))throw n}}import{randomUUID as lI}from"crypto";import{existsSync as uI,mkdirSync as dI,readFileSync as pI,realpathSync as gI,renameSync as mI,rmSync as Rh,writeFileSync as fI}from"fs";import{homedir as hI}from"os";import{join as Ih}from"path";function Z(t){return new Bun.CryptoHasher("sha256").update(t).digest("hex")}var yI=".ari",kI="trust",wI=".json",SI=384,vI=Et({root:X(),sha256:X(),trustedAt:X()});function Oh(){let t=process.env.HOME;return Ih(t===void 0||t===""?hI():t,yI,kI)}function bs(t){try{return gI(t)}catch{return t}}function _h(t){let e=bs(t);try{let n=vI(JSON.parse(pI(Yu(e),"utf8")));return n.root===e?n:null}catch{return null}}function Ph(t,e,n=new Date){let r=bs(t),o={root:r,sha256:e,trustedAt:n.toISOString()},s=Yu(r),i=`${s}.${process.pid}.${lI()}.tmp`;dI(Oh(),{recursive:!0});try{fI(i,`${JSON.stringify(o,null,2)}
105
+ `,{mode:SI}),mI(i,s)}finally{Rh(i,{force:!0})}return o}function Nh(t){let e=Yu(bs(t));if(!uI(e))return!1;return Rh(e,{force:!0}),!0}function Yu(t){return Ih(Oh(),`${Z(t)}${wI}`)}import{existsSync as cN}from"fs";import{join as lN}from"path";function O(t,e){if(t<e)return-1;if(t>e)return 1;return 0}var bI=2;function pt(t){return`${JSON.stringify(t,EI,bI)}
106
+ `}function EI(t,e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;return Object.fromEntries(Object.entries(e).sort(([n],[r])=>O(n,r)))}var $I=["cached","run"],Dh="TYPESAFE_API_URL",TI=["TYPESAFE_API_KEY","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_TOKEN","CLOUDFLARE_AUTH_TOKEN"],xI=["argus"],AI="cached",CI=25,RI=6000,II=1000,OI=20000,_I=["config","command","mode","limit","maxBytes","timeoutSeconds","verdicts"];function Mh(t){let e=T(t,"review.argus",_I),n=D(e.timeoutSeconds,null,(o)=>Vn(o,"review.argus.timeoutSeconds")),r=D(e.verdicts,!1,(o)=>$t(o,"review.argus.verdicts"));return{command:D(e.command,[...xI],NI),config:ft(e.config,"review.argus.config",nt),limit:D(e.limit,CI,(o)=>Lh(o,"limit",II)),maxBytes:D(e.maxBytes,RI,(o)=>Lh(o,"maxBytes",OI)),mode:D(e.mode,AI,(o)=>K($I,o,"review.argus.mode")),...n===null?{}:{timeoutSeconds:n},...r?{verdicts:r}:{}}}function PI(t){return t==="run"?[Dh,...TI]:[Dh]}function va(t){let e=t.mode==="run";if(t.verdicts!==!0)return[e?"run":"check"];return e?["run","snapshot","import"]:["snapshot","import"]}function ba(t){return PI(t==="run"?"run":"cached")}function so(t,e,n){let{base:r,configPath:o,file:s,only:i}=n,a=["--config",o,"--base",r],c=i===null?[]:["--only",i],l=t.command;switch(e){case"check":return[...l,"check",...a,"--json"];case"run":return[...l,"run",...a,"--limit",String(t.limit),...c,"--json"];case"snapshot":return[...l,"report","create",...a,...c,"--json"];case"import":return[...l,"verify","--import",s??"",...a,"--json"]}}function NI(t){let e=L(t,"review.argus.command",nt);if(e.length===0)throw new b("review.argus.command must list at least the program to start");return e}function Lh(t,e,n){let r=`review.argus.${e}`,o=Kt(t,r);if(o>n)throw new b(`${r} must be at most ${n}`);return o}import{randomUUID as BP}from"crypto";import{appendFileSync as VP,existsSync as Cn,linkSync as WP,mkdirSync as Ly,readdirSync as JP,readFileSync as Rs,renameSync as My,rmSync as Ua,writeFileSync as jy}from"fs";import{basename as qP,dirname as Fy,join as Rt}from"path";function Es(t){if(typeof t!=="object"||t===null||Object.isFrozen(t))return t;for(let e of Object.values(t))Es(e);return Object.freeze(t)}var DI="basic",LI=300,MI=6000,jI=20,FI=2000,GI=!0,HI=1200,UI=60000,KI=25,BI=0.95,VI=0.75,WI=10,JI=!1,qI=!0,YI=25,XI=["**/*.test.*","**/*.spec.*","**/*_test.*","**/*-test.{js,cjs,mjs,ts,cts,mts}","**/test-*.{js,cjs,mjs,ts,cts,mts}","**/test.{js,cjs,mjs,ts,cts,mts}","**/test_*.py","**/test/**","**/tests/**","**/__tests__/**"],zI="Fix the reported value in .ari/config.json",ZI=["$schema","pack","requireTask","checkTimeoutSeconds","testGlobs","regression","review","context","knowledge","snapshots","hooks","agents","routing"],QI=["maxEntryBytes","maxBytes","decayAfterTasks","duplicateSimilarity","mergeSimilarity","rehearsalTasks","sleepOnStop"],Tt=Es({agents:{},checkTimeoutSeconds:LI,context:{briefBytes:FI,budget:MI,journalTail:jI},hooks:{brief:GI},knowledge:{decayAfterTasks:KI,duplicateSimilarity:BI,maxBytes:UI,maxEntryBytes:HI,mergeSimilarity:VI,rehearsalTasks:WI,sleepOnStop:JI},pack:DI,regression:{setup:[]},requireTask:!1,review:{command:null},routing:Sa,snapshots:{auto:qI,keep:YI},testGlobs:XI});function vr(t){return structuredClone(At("config",zI,()=>jh(t)))}function Ea(t){try{return jh(t),null}catch(e){if(e instanceof b)return e.message;throw e}}function jh(t){let e=T(t,"config",ZI);if(e.$schema!==void 0)x(e.$schema,"$schema");let n={agents:D(e.agents,Tt.agents,Sh),checkTimeoutSeconds:D(e.checkTimeoutSeconds,Tt.checkTimeoutSeconds,(r)=>Vn(r,"checkTimeoutSeconds")),context:D(e.context,Tt.context,tO),hooks:D(e.hooks,Tt.hooks,eO),knowledge:D(e.knowledge,Tt.knowledge,nO),pack:D(e.pack,Tt.pack,(r)=>je(r,"pack")),regression:D(e.regression,Tt.regression,oO),requireTask:D(e.requireTask,Tt.requireTask,(r)=>$t(r,"requireTask")),review:D(e.review,Tt.review,sO),routing:D(e.routing,Tt.routing,vh),snapshots:D(e.snapshots,Tt.snapshots,rO),testGlobs:D(e.testGlobs,Tt.testGlobs,(r)=>hh(r,"testGlobs"))};return bh(n),n}function tO(t){let e=T(t,"context",["budget","journalTail","briefBytes"]),n=Tt.context;return{briefBytes:D(e.briefBytes,n.briefBytes,(r)=>Kt(r,"context.briefBytes")),budget:D(e.budget,n.budget,(r)=>Kt(r,"context.budget")),journalTail:D(e.journalTail,n.journalTail,(r)=>ht(r,"context.journalTail"))}}function eO(t){let e=T(t,"hooks",["brief"]);return{brief:D(e.brief,Tt.hooks.brief,(n)=>$t(n,"hooks.brief"))}}function nO(t){let e=T(t,"knowledge",QI),n={decayAfterTasks:io(e,"decayAfterTasks",Kt),duplicateSimilarity:io(e,"duplicateSimilarity",Vu),maxBytes:io(e,"maxBytes",Kt),maxEntryBytes:io(e,"maxEntryBytes",Kt),mergeSimilarity:io(e,"mergeSimilarity",Vu),rehearsalTasks:io(e,"rehearsalTasks",ht),sleepOnStop:D(e.sleepOnStop,Tt.knowledge.sleepOnStop,(r)=>$t(r,"knowledge.sleepOnStop"))};if(n.mergeSimilarity>n.duplicateSimilarity)throw new b("knowledge.mergeSimilarity must not exceed knowledge.duplicateSimilarity");if(n.maxEntryBytes>n.maxBytes)throw new b("knowledge.maxEntryBytes must not exceed knowledge.maxBytes");return n}function rO(t){let e=T(t,"snapshots",["auto","keep"]),n=Tt.snapshots;return{auto:D(e.auto,n.auto,(r)=>$t(r,"snapshots.auto")),keep:D(e.keep,n.keep,(r)=>Kt(r,"snapshots.keep"))}}function io(t,e,n){return D(t[e],Tt.knowledge[e],(r)=>n(r,`knowledge.${e}`))}function oO(t){let e=T(t,"regression",["setup"]);return{setup:D(e.setup,Tt.regression.setup,(n)=>L(n,"regression.setup",nt))}}function sO(t){let e=T(t,"review",["command","agent","model","argus"]),n=D(e.command,Tt.review.command,(i)=>Ct(i,"review.command"));if(n!==null&&n.trim().length===0)throw new b("review.command must be a command or null");let r=D(e.agent,null,(i)=>i===null?null:je(i,"review.agent")),o=D(e.model,null,(i)=>i===null?null:nt(i,"review.model"));if(n!==null&&r!==null)throw new b("review.command and review.agent are alternatives; set only one of them");if(o!==null&&r===null)throw new b("review.model needs review.agent");let s=e.argus===void 0?null:Mh(e.argus);return{command:n,...r===null?{}:{agent:r},...o===null?{}:{model:o},...s===null?{}:{argus:s}}}var $s='writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys',iO=/"(?:[^"\\]|\\.)*"|'(?:[^']|'')*'/sy,aO=/(?:[^,[\]{}:#\n]|:(?![ \t\n,[\]{}]|$)|(?<![ \t\n])#)+/sy,cO=/(?:[ \t\n]|(?<=[ \t\n])#[^\n]*)+/sy,lO=/[&!*][^\s,[\]{}]*|\?(?=[ \t\n])/sy,uO=/[ \t\n,[\]{}]/;function zu(t){return`defines "${t}" twice`}function Zu(t,e){return $a(iO,t,e)}function Qu(t){return String(Bun.YAML.parse(t))}function Fh(t,e){let n=[],r=e,o=!1;while(r<t.length){let s=pO(t,r,o);if(r+=s.text.length,s.kind==="space")continue;let i=dO(s,n);if(i!==null)return{end:r,problem:i};if(n.length===0)return{end:r,problem:null};o=s.kind==="quoted"||s.kind==="close"}return{end:r,problem:null}}function dO(t,e){let n=e.at(-1),r=n?.keys!=null&&n.inKey;switch(t.kind){case"open":{if(r)return'writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys';let o=t.text==="{"?new Set:null;return e.push({inKey:o!==null,key:null,keys:o}),null}case"close":return e.pop(),r?Xu(n):null;case"comma":{let o=r?Xu(n):null;if(n!==void 0)Object.assign(n,{inKey:n.keys!==null,key:null});return o}case"colon":if(!r)return null;return n.inKey=!1,Xu(n);case"special":return r?'writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys':null;case"quoted":case"plain":if(r)n.key=t.kind==="quoted"?Qu(t.text):t.text.trim();return null;case"space":return null}}function Xu(t){let{key:e,keys:n}=t;if(e===null||n===null)return null;if(n.has(e))return zu(e);return n.add(e),null}function pO(t,e,n){let r=t[e]??"";if(r==="{"||r==="[")return{kind:"open",text:r};if(r==="}"||r==="]")return{kind:"close",text:r};if(r===",")return{kind:"comma",text:r};if(r===":"&&(n||uO.test(t[e+1]??" ")))return{kind:"colon",text:r};let o=$a(cO,t,e);if(o!==null)return{kind:"space",text:o};let s=Zu(t,e);if(s!==null)return{kind:"quoted",text:s};let i=$a(lO,t,e);if(i!==null)return{kind:"special",text:i};return{kind:"plain",text:$a(aO,t,e)??r}}function $a(t,e,n){return t.lastIndex=n,t.exec(e)?.[0]??null}var gO=/^(?:---|\.\.\.)(?=[ \t]|$)/,mO=/^( *)((?:-(?: +|$))*)(.*)$/s,Gh=/^(?:[&!][^ \t]*(?:[ \t]+|$))+/,fO=/^#/,hO=/^[{[]/,yO=/^\?(?:[ \t]|$)/,kO=/^\*.*:(?:[ \t]|$)/s,Hh=/^[ \t]*:(?:[ \t]+|$)/,wO=/^([^\s|>%@`"'&*!#,[\]{}](?:(?![ \t]#).)*?)[ \t]*:(?:[ \t]+(.*))?$/s,Uh=-1;function Kh(t){let e=[],n=null,r=0,o=0;for(let s of t.split(`
107
+ `)){let i=o;if(o+=s.length+1,i<r)continue;let a=s.match(gO)?.[0];if(a!==void 0)e.length=0,n=null;let c=a===void 0?s:s.replace(a," ".repeat(a.length)),[,l="",u="",d=""]=c.match(mO)??[];if(n!==null&&l.length>n)continue;if(u===""&&Bh(d))continue;let p=l.length+u.length;EO(e,u===""?p:l.length);let g=SO(d);if(g===$s)return g;if(g!==null){let{keys:I}=$O(e,p);if(I.has(g.name))return zu(g.name);I.add(g.name)}let f=bO(g===null?d:g.value),y=u===""?e.at(-1)?.column??Uh:c.lastIndexOf("-",p-1);if(n=f.kind==="text"?g===null?y:p:null,f.kind!=="flow")continue;let S=Fh(t,i+c.length-f.text.length);if(S.problem!==null)return S.problem;if(r=S.end,g===null&&Hh.test(t.slice(S.end,o).trimEnd()))return $s}return null}function SO(t){if(yO.test(t)||kO.test(t))return $s;let e=t.replace(Gh,""),n=vO(e);return n!==null&&e!==t?$s:n}function vO(t){let e=Zu(t,0);if(e===null){let[,r,o=""]=t.match(wO)??[];return r===void 0?null:{name:r,value:o}}let n=t.slice(e.length).match(Hh)?.[0];return n===void 0?null:{name:Qu(e),value:t.slice(e.length+n.length)}}function bO(t){let e=t.replace(Gh,"");if(Bh(e))return{kind:"block",text:e};return{kind:hO.test(e)?"flow":"text",text:e}}function Bh(t){return t.trim()===""||fO.test(t)}function EO(t,e){while((t.at(-1)?.column??Uh)>e)t.pop()}function $O(t,e){let n=t.at(-1);if(n?.column===e)return n;let r={column:e,keys:new Set};return t.push(r),r}var ao="---",TO=/^\uFEFF+/,xO=/\r\n?/g;function co(t){return t.replace(TO,"").replace(xO,`
108
+ `)}function Ta(t){let e=co(t).split(`
109
+ `);if(e[0]?.trimEnd()!==ao)throw new b(`the file must start with a "${ao}" line that opens the front matter`);let n=e.findIndex((r,o)=>o>0&&r.trimEnd()===ao);if(n===-1)throw new b(`the front matter has no closing "${ao}" line`);return{body:e.slice(n+1).join(`
110
+ `),data:td(e.slice(1,n).join(`
111
+ `),"the front matter")}}function xa(t,e){return`${ao}
116
112
  ${t.join(`
117
113
  `)}
118
- ${Ur}
119
- ${e}`}function Be(t){return JSON.stringify(t.toWellFormed())}function Kr(t){return`[${t.map(Be).join(", ")}]`}function fu(t,e){let n=Qi(t),r=LR(n,e),o=Xf(n);if(o===null)return r;throw new b(`${e} ${o}`)}function LR(t,e){try{return Bun.YAML.parse(t)}catch(n){let r=n instanceof Error?n.message:String(n);throw new b(`${e} is not valid YAML (${r})`)}}var yu=3,Qf="spike",MR=/^[A-Za-z][A-Za-z0-9._-]*$/,jR=["pass","fail","regression"],FR={all:"check",criteria:"check bound to a criterion","expect:fail":"check with expect: fail","expect:pass":"check with expect: pass","expect:regression":"check with expect: regression"},GR=["title","pack","scope","lock","depends","criteria","checks","invariants","budget"],HR="AC-1",UR="Describe the change, its constraints and how a reviewer can verify it.";function na(t,e,n){return Tt(`contract "${t}"`,`Fix the front matter of .ari/tasks/${t}.md`,()=>KR(t,e,n))}function un(t){return tt(Qi(t))}function th(t,e){let n=e===Qf?["criteria: []"]:["criteria:",` - id: ${Be(HR)}`,' text: ""'," checks: []"],r=[`title: ${Be(t)}`,`pack: ${Be(e)}`,"scope: []","lock: []","depends: []",...n,"checks: {}","invariants: []","budget:",` attempts: ${yu}`];return ea(r,`${UR}
120
- `)}function Br(t,e){let n=e.find((o)=>o.name===t.pack),r=[...zR(t),...ku(t)];return[...JR(t),...qR(t,n,e,r.length>0),...Zf("scope",t.scope,!0),...Zf("lock",t.lock,!1),...XR(t),...r,...ZR(t),...QR(t)]}function Wr(t,e){switch(e){case"all":return t.checks;case"criteria":{let n=new Set(t.criteria.flatMap((r)=>r.checks));return t.checks.filter((r)=>n.has(r.name))}case"expect:pass":return hu(t,"pass");case"expect:fail":return hu(t,"fail");case"expect:regression":return hu(t,"regression")}}function hu(t,e){return t.checks.filter((n)=>n.expect===e)}function ku(t){let e=new Set(t.checks.map((n)=>n.name));return t.criteria.flatMap((n)=>{if(n.checks.length===0)return[`criterion ${n.id} must name at least one check`];return n.checks.filter((r)=>!e.has(r)).map((r)=>`criterion ${n.id} names unknown check "${r}"`)})}function KR(t,e,n){let{body:r,data:o}=ta(e),s=C(o,"front matter",GR);return{body:r.trim(),budget:ct(s.budget,{attempts:yu},BR),checks:ct(s.checks,[],(i)=>VR(i,n.checkTimeoutSeconds)),criteria:ct(s.criteria,[],(i)=>D(i,"criteria",WR)),depends:ct(s.depends,[],(i)=>jt(i,"depends")),id:t,invariants:ct(s.invariants,[],(i)=>jt(i,"invariants")),lock:ct(s.lock,[],(i)=>jt(i,"lock")),pack:ct(s.pack,n.pack,(i)=>x(i,"pack")),scope:Et(s.scope,"scope",jt),title:Et(s.title,"title",x)}}function BR(t){let e=C(t,"budget",["attempts"]);return{attempts:ct(e.attempts,yu,(n)=>Zt(n,"budget.attempts"))}}function WR(t,e){let n=C(t,e,["id","text","checks"]);return{checks:ct(n.checks,[],(r)=>jt(r,w(e,"checks"))),id:Et(n.id,w(e,"id"),x),text:Et(n.text,w(e,"text"),x)}}function VR(t,e){return an(t,"checks",(n,r,o)=>{if(!MR.test(o))throw new b(`${r} must be named with a letter followed by letters, digits, ".", "_" or "-"`);let s=C(n,r,["run","expect","timeout"]);return{expect:ct(s.expect,"pass",(i)=>V(jR,i,w(r,"expect"))),name:o,run:Et(s.run,w(r,"run"),x),timeoutSeconds:ct(s.timeout,e,(i)=>Rn(i,w(r,"timeout")))}}).map(([,n])=>n)}function JR(t){return t.title.trim().length===0?["title must not be empty"]:[]}function qR(t,e,n,r){if(!e){let s=n.map((i)=>i.name).join(", ");return[`pack "${t.pack}" is not a built-in or project pack (available: ${s})`]}return[...new Set(e.stages.flatMap((s)=>s.gates.flatMap(YR)))].filter((s)=>!r||s!=="all"&&s!=="criteria").filter((s)=>Wr(t,s).length===0).map((s)=>`pack "${e.name}" needs at least one ${FR[s]}`)}function YR(t){if(t.kind==="regression")return["expect:regression"];return t.kind==="checks"?[t.select]:[]}function Zf(t,e,n){let r=n&&e.length===0?[`${t} must list at least one glob`]:[],o=e.flatMap((s)=>{let i=er(s);return i===null?[]:[`${t} glob ${JSON.stringify(s)} ${i}`]});return[...r,...o]}function XR(t){return t.depends.flatMap((e)=>{if(e.trim().length===0)return["depends must not contain an empty task id"];return e===t.id?[`depends must not name the task itself ("${t.id}")`]:[]})}function zR(t){let n=t.pack!==Qf&&t.criteria.length===0?[`criteria must list at least one criterion for pack "${t.pack}"`]:[],r=t.criteria.map((s)=>s.id),o=t.criteria.flatMap((s,i)=>{if(s.id.trim().length===0)return[`criteria[${i}] must have an id`];let a=r.indexOf(s.id)<i?[`criterion id "${s.id}" is used more than once`]:[],c=s.text.trim().length===0?[`criterion ${s.id} must have text`]:[];return[...a,...c]});return[...n,...o]}function ZR(t){return t.checks.filter((e)=>e.run.trim().length===0).map((e)=>`check ${e.name} must have a run command`)}function QR(t){return t.invariants.some((e)=>e.trim().length===0)?["invariants must not contain an empty command"]:[]}var tI=2;function ht(t){return`${JSON.stringify(t,eI,tI)}
121
- `}function eI(t,e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;return Object.fromEntries(Object.entries(e).sort(([n],[r])=>I(n,r)))}var Qt=["fact","decision","constraint","pattern","gotcha"],nI=["active","archived"],rI=/^\d{4}-\d{2}-\d{2}$/,oI=/\s+/g,sI=["kind","scope","sources","status","supersedes","supersededBy","created"];function ra(t,e){return Tt(`knowledge entry "${t}"`,`Restore .ari/knowledge/${t}.md from git`,()=>iI(t,e))}function or(t){let e=[`kind: ${Be(t.kind)}`,`scope: ${Kr(t.scope)}`,`sources: ${Kr(t.sources)}`,`status: ${Be(t.status)}`,`supersedes: ${Kr(t.supersedes)}`,`supersededBy: ${t.supersededBy===null?"null":Be(t.supersededBy)}`,`created: ${Be(t.created)}`];return ea(e,`${t.text.trim()}
122
- `)}function wu(t){return t.normalize("NFC").toLowerCase().replace(oI," ").trim()}function iI(t,e){let{body:n,data:r}=ta(e),o=C(r,"front matter",sI),s=Et(o.created,"created",x);if(!rI.test(s))throw new b(`created must be a YYYY-MM-DD date, got "${s}"`);let i=n.trim();if(i.length===0)throw new b("the entry text is empty");return{created:s,id:t,kind:Et(o.kind,"kind",(a,c)=>V(Qt,a,c)),scope:ct(o.scope,[],(a)=>Gi(a,"scope")),sources:ct(o.sources,[],(a)=>jt(a,"sources")),status:ct(o.status,"active",(a)=>V(nI,a,"status")),supersededBy:ct(o.supersededBy,null,(a)=>Ct(a,"supersededBy")),supersedes:ct(o.supersedes,[],(a)=>jt(a,"supersedes")),text:i}}var oh=200,aI=/\{id\}/g,cI="Fix the pack file; see the packs section of the Ariadne design",lI=["all","criteria","expect:pass","expect:fail","expect:regression"],uI=["pass","fail"],oa={kind:"criteria"},_n={kind:"invariants"},_e={kind:"scope"},dn={kind:"locked"},Su={kind:"tests-unchanged"},dI={kind:"regression"},eh={kind:"approval"},pI={kind:"review"};function Pe(t,e){return{expect:e,kind:"checks",select:t}}function nh(t){return{kind:"artifact",minBytes:oh,path:t}}var rh=zo([{description:"Implement the contract and prove it with its checks",name:"basic",stages:[{gates:[oa,Pe("criteria","pass"),_n,_e,dn],instruction:"Implement the change inside the scope until every criterion's checks pass.",name:"implement"}]},{description:"Approved design, implementation, then review",name:"sdlc",stages:[{gates:[nh(".ari/designs/{id}.md"),eh],instruction:"Write the design to .ari/designs/{id}.md, then ask a human to approve it.",name:"design"},{gates:[oa,Pe("all","pass"),_n,_e,dn],instruction:"Implement the approved design inside the scope until every check passes.",name:"implement"},{gates:[pI,Pe("all","pass"),_n,_e,dn],instruction:"Get the change reviewed: run the review command or ask a human to approve it.",name:"review"}]},{description:"Red, green, refactor with frozen tests",name:"tdd",stages:[{gates:[oa,Pe("criteria","fail"),_e],instruction:"Write failing tests for every criterion. Do not implement the change yet.",name:"red"},{gates:[Pe("all","pass"),Su,_n,_e,dn],instruction:"Make every check pass with the smallest change. Do not edit the tests.",name:"green"},{gates:[Pe("all","pass"),Su,_n,_e,dn],instruction:"Improve the code while every check stays green. Do not edit the tests.",name:"refactor"}]},{description:"Reproduce the bug with a regression check, then fix it",name:"bugfix",stages:[{gates:[Pe("expect:regression","fail"),_e],instruction:"Write a regression check that fails because of the bug. Do not fix it yet.",name:"reproduce"},{gates:[dI,Pe("all","pass"),_n,_e,dn],instruction:"Fix the bug so the regression check passes here and still fails on the base commit.",name:"fix"}]},{description:"Approved specification, then implementation",name:"spec-driven",stages:[{gates:[oa,eh],instruction:"Specify the criteria and their checks in the contract, run ari amend, then ask a human to approve.",name:"specify"},{gates:[Pe("all","pass"),_n,_e,dn],instruction:"Implement the approved specification inside the scope until every check passes.",name:"implement"}]},{description:"Change the structure without changing behaviour",name:"refactor",stages:[{gates:[Su,Pe("all","pass"),_n,_e,dn],instruction:"Restructure the code without changing behaviour. Keep the tests unchanged and every check green.",name:"refactor"}]},{description:"Exploration that ends in written findings",name:"spike",stages:[{gates:[nh(".ari/designs/{id}.md"),_e,dn],instruction:"Explore inside the scope and write the findings to .ari/designs/{id}.md.",name:"explore"}]}]),sh={approval:(t,e)=>Pn(t,e,"approval"),artifact:kI,checks:yI,command:(t,e)=>{let n=C(t,e,["kind","run"]);return{kind:"command",run:ot(n.run,w(e,"run"))}},criteria:(t,e)=>Pn(t,e,"criteria"),invariants:(t,e)=>Pn(t,e,"invariants"),locked:(t,e)=>Pn(t,e,"locked"),regression:(t,e)=>Pn(t,e,"regression"),review:(t,e)=>Pn(t,e,"review"),scope:(t,e)=>Pn(t,e,"scope"),"tests-unchanged":(t,e)=>Pn(t,e,"tests-unchanged")},gI=Object.keys(sh);function sa(t,e="pack"){return Tt(e,cI,()=>mI(fu(t,"the pack file")))}function pn(t){let e=new Map(t.map((s)=>[s.name,s])),n=rh.map((s)=>e.get(s.name)??s),r=new Set(rh.map((s)=>s.name)),o=t.filter((s)=>!r.has(s.name)).sort((s,i)=>I(s.name,i.name));return[...n,...o]}function sr(t,e){let n=pn(e),r=n.find((s)=>s.name===t);if(r)return r;let o=n.map((s)=>s.name).join(", ");throw new g(`Unknown pack "${t}"`,`Use one of ${o}, or add .ari/packs/${t}.yaml`)}function ia(t,e){let{agents:n,regression:r,review:o,testGlobs:s}=e,i=t.stages.map(({gates:c,name:l})=>({gates:c,name:l})),a=o.agent===void 0?{}:{reviewer:n[o.agent]??null};return tt(ht({regression:r,review:o,stages:i,testGlobs:s,...a}))}function Vr(t,e){return t.instruction.replace(aI,e)}function mI(t){let e=C(t,"pack",["name","description","stages"]),n=D(e.stages,"stages",fI);if(n.length===0)throw new b("stages must list at least one stage");let r=new Set;for(let[o,s]of n.entries()){if(r.has(s.name))throw new b(`stages[${o}].name repeats "${s.name}"`);r.add(s.name)}return{description:ct(e.description,"",(o)=>x(o,"description")),name:Re(e.name,"name"),stages:n}}function fI(t,e){let n=C(t,e,["name","instruction","gates"]),r=D(n.gates,w(e,"gates"),hI);if(r.length===0)throw new b(`${w(e,"gates")} must list at least one gate`);let o=new Set(r.map((s)=>s.kind));if(o.has("tests-unchanged")&&!o.has("scope"))throw new b(`${w(e,"gates")} has tests-unchanged without scope; tests-unchanged covers the test files inside the scope and relies on the scope gate for the rest`);return{gates:r,instruction:ot(n.instruction,w(e,"instruction")),name:Re(n.name,w(e,"name"))}}function hI(t,e){let n=C(t,e,["kind","select","expect","path","minBytes","run"]),r=V(gI,n.kind,w(e,"kind"));return sh[r](n,e)}function Pn(t,e,n){return C(t,e,["kind"]),{kind:n}}function yI(t,e){let n=C(t,e,["kind","select","expect"]);return Pe(ct(n.select,"all",(r)=>V(lI,r,w(e,"select"))),ct(n.expect,"pass",(r)=>V(uI,r,w(e,"expect"))))}function kI(t,e){let n=C(t,e,["kind","path","minBytes"]),r=ot(n.path,w(e,"path"));if(r.startsWith("/")||r.split("/").includes(".."))throw new b(`${w(e,"path")} must stay inside the repository`);return{kind:"artifact",minBytes:ct(n.minBytes,oh,(s)=>$t(s,w(e,"minBytes"))),path:r}}var ih="attempt budget exhausted",ah="failedAttempts",wI={active:()=>"Run 'ari done' to finish the current stage",blocked:(t)=>`Run 'ari resolve ${t} --answer <text>'`,done:()=>`Done tasks are final; create a follow-up with 'ari new "<title>"'`,draft:(t)=>`Complete the contract, then run 'ari ready ${t}'`,ready:(t)=>`Run 'ari start ${t}'`};function We(t,e,n={}){return{at:e,by:n.by??null,detail:n.detail??null,stage:n.stage??null,type:t}}function Tu(t,e){return{approvals:[],attempts:0,base:null,contractHash:null,evidence:[],gatesHash:null,history:[We("created",e)],id:t,journalStats:null,knowledgeUsed:[],lastFailure:null,lockHashes:{},notes:[],question:null,stage:0,stageTestHashes:{},status:"draft"}}function lh(t){let e=t.history[0]?.at??"";return ht(t)===ht(Tu(t.id,e))}function Eu(t,e){return gn(t,["draft"],"mark ready"),{...t,history:[...t.history,We("ready",e)],status:"ready"}}function uh(t,e,n,r){return gn(t,["ready"],"start"),{...t,attempts:0,...wh(n),base:e,history:[...t.history,We("started",r,{detail:e})],stage:0,status:"active"}}function dh(t,e,n,r){if(gn(t,["active"],"record a passed stage for"),!Number.isInteger(n)||t.stage>=n)throw Error(`Stage ${t.stage} of task "${t.id}" is outside a pack of ${n} stages`);let o=t.stage+1>=n,s=We(o?"done":"advanced",e.at,{stage:e.stage});return{...t,evidence:[...t.evidence,e],history:[...t.history,s],lastFailure:null,stage:o?t.stage:t.stage+1,stageTestHashes:{...r},status:o?"done":"active"}}function ph(t,e,n){if(gn(t,["active"],"record a failed attempt for"),!Number.isInteger(n)||n<=0)throw Error(`Attempt budget must be a positive integer: ${n}`);let r=t.attempts+1,o=e.gates.filter((c)=>!c.ok).map((c)=>c.gate),s=We("failed",e.at,{detail:`attempt ${r} of ${n}: ${o.join(", ")||"no failing gate recorded"}`,stage:e.stage}),i=r>=n,a=We("blocked",e.at,{detail:ih,stage:e.stage});return{...t,attempts:r,history:i?[...t.history,s,a]:[...t.history,s],lastFailure:e,question:i?ih:t.question,status:i?"blocked":"active"}}function $u(t,e,n){gn(t,["draft","ready","active","blocked"],"amend");let r=es(e.reason,"Amending a task needs a reason","Pass --reason <text>"),o=e.base!==null&&e.base!==t.base;if(o)gn(t,["active","blocked"],"move the base of");let s=o?e.base:t.base,i=`gates ${e.gatesHash}, locks ${ch(e.lockHashes)}, tests ${ch(e.stageTestHashes)}`,a=o?`, base ${t.base} -> ${s}`:"",c=`${r} (contract ${e.contractHash}, ${i}${a})`;return{...t,...wh(e),approvals:t.approvals.filter((l)=>l.stage!==e.stage),base:s,history:[...t.history,We("amended",n,{detail:c})]}}function gh(t,e,n){gn(t,["active"],"block");let r=es(e,"Blocking a task needs a question for a human","Pass --reason <text>");return{...t,history:[...t.history,We("blocked",n,{detail:r})],question:r,status:"blocked"}}function bu(t,e,n){gn(t,["blocked"],"resolve");let r=es(e,"Resolving a task needs an answer","Pass --answer <text>");return{...t,attempts:0,history:[...t.history,We("resolved",n,{detail:r})],notes:[...t.notes,{at:n,promoted:!1,text:r}],question:null,status:"active"}}function mh(t,e,n){gn(t,["active"],"approve");let{artifactHashes:r,stage:o,treeHash:s}=e,i=es(e.by,"An approval needs the approver's name","Set git user.name so the approval records who gave it");return{...t,approvals:[...t.approvals,{artifactHashes:{...r},at:n,by:i,stage:o,treeHash:s}],history:[...t.history,We("approved",n,{by:i,stage:o})]}}function fh(t,e,n){let r=es(e,"A note needs text","Pass the note text as an argument");return{...t,notes:[...t.notes,{at:n,promoted:!1,text:r}]}}function aa(t,e){let n=new Map(Object.entries(t.journalStats??{}).filter(([o])=>o!==ah));for(let o of e)n.set(o.type,(n.get(o.type)??0)+1);let r=t.history.filter((o)=>o.type==="failed").length;return{...t,journalStats:{...Object.fromEntries(n),[ah]:r}}}function hh(t,e){let n=[...new Set([...t.knowledgeUsed,...e])].sort(I);return{...t,knowledgeUsed:n}}function yh(t,e){let n=`Run 'ari sleep' to list the unpromoted notes of "${t.id}"`;for(let o of e){let s=t.notes[o];if(s===void 0)throw new g(`Task "${t.id}" has no note ${o}`,n);if(s.promoted)throw new g(`Note ${o} of task "${t.id}" is already promoted`,n)}let r=new Set(e);return{...t,notes:t.notes.map((o,s)=>r.has(s)?{...o,promoted:!0}:o)}}function kh(t,e){let n=new Set(e);return{...t,notes:t.notes.map((r,o)=>n.has(o)?{...r,promoted:!1}:r)}}function wh({contractHash:t,gatesHash:e,lockHashes:n,stageTestHashes:r}){return{contractHash:t,gatesHash:e,lockHashes:{...n},stageTestHashes:{...r}}}function ch(t){return tt(ht(t))}function gn(t,e,n){if(e.includes(t.status))return;throw new g(`Cannot ${n} task "${t.id}": it is ${t.status}, not ${e.join(" or ")}`,wI[t.status](t.id))}function es(t,e,n){let r=t.trim();if(r.length===0)throw new g(e,n);return r}import{mkdirSync as SI,readFileSync as TI,rmSync as ca,statSync as EI,writeFileSync as $I}from"fs";import{dirname as bI}from"path";var vI="EEXIST",xI="ENOENT",AI="ESRCH",CI=".break",RI=20,II=1e4,OI=1000,_I=10,PI=0;function xu(t,e,n){return Au(t,`task "${e}"`,n)}function Au(t,e,n){NI(t,e);try{return n()}finally{ca(t,{force:!0})}}function NI(t,e){SI(bI(t),{recursive:!0});let n=Date.now()+II;while(!Sh(t)){if(vu(t))DI(t);if(Date.now()>=n)throw new g(`Another ari process is still changing ${e}`,`Run the command again once it finishes; if no ari process is running, delete ${t}`);Bun.sleepSync(RI)}}function DI(t){let e=`${t}${CI}`;if(!Sh(e)){if(vu(e))ca(e,{force:!0});return}try{if(vu(t))ca(t,{force:!0})}finally{ca(e,{force:!0})}}function Sh(t){try{return $I(t,`${process.pid}`,{flag:"wx"}),!0}catch(e){if(Cu(e)===vI)return!1;throw e}}function vu(t){let e=LI(t);if(e===null)return!1;if(Number.isNaN(e.pid))return Date.now()-e.modifiedMs>OI;return!MI(e.pid)}function LI(t){try{return{modifiedMs:EI(t).mtimeMs,pid:Number.parseInt(TI(t,"utf8"),_I)}}catch(e){if(Cu(e)===xI)return null;throw e}}function MI(t){try{return process.kill(t,PI),!0}catch(e){return Cu(e)!==AI}}function Cu(t){return t.code}var jI=["draft","ready","active","blocked","done"],FI=["pass","fail"],GI=["criteria","checks","invariants","scope","locked","tests-unchanged","regression","artifact","approval","review","command"],HI=["created","ready","started","advanced","done","failed","amended","blocked","resolved","approved"],UI=["edit","shell","tool","check","done","context","note","stop","compact","session"],KI=["approvals","attempts","base","contractHash","evidence","gatesHash","history","id","journalStats","knowledgeUsed","lastFailure","lockHashes","notes","question","stage","stageTestHashes","status"],BI=["command","durationMs","exitCode","expect","name","ok","outputSha256","outputTail","timedOut"];function Th(t,e){return Tt(`task record "${t}"`,`Restore .ari/tasks/${t}.json from git; only ari writes it`,()=>{let n=WI(e);if(n.id!==t)throw new b(`id is "${n.id}" but the file belongs to task "${t}"`);return n})}function ua(t){let e=C(t,"event",["at","detail","task","type"]);return{at:x(e.at,"at"),detail:Object.fromEntries(an(e.detail,"detail",QI)),task:x(e.task,"task"),type:V(UI,e.type,"type")}}function WI(t){let e=C(t,"record",KI);return{approvals:D(e.approvals,"approvals",VI),attempts:$t(e.attempts,"attempts"),base:Ct(e.base,"base"),contractHash:Ct(e.contractHash,"contractHash"),evidence:D(e.evidence,"evidence",YI),gatesHash:F(e.gatesHash,null,(n)=>Ct(n,"gatesHash")),history:D(e.history,"history",qI),id:x(e.id,"id"),journalStats:e.journalStats===null?null:ZI(e.journalStats,"journalStats"),knowledgeUsed:jt(e.knowledgeUsed,"knowledgeUsed"),lastFailure:e.lastFailure===null?null:XI(e.lastFailure,"lastFailure"),lockHashes:la(e.lockHashes,"lockHashes"),notes:D(e.notes,"notes",JI),question:Ct(e.question,"question"),stage:$t(e.stage,"stage"),stageTestHashes:la(e.stageTestHashes,"stageTestHashes"),status:V(jI,e.status,"status")}}function VI(t,e){let n=C(t,e,["artifactHashes","at","by","stage","treeHash"]);return{artifactHashes:F(n.artifactHashes,{},(r)=>la(r,w(e,"artifactHashes"))),at:x(n.at,w(e,"at")),by:x(n.by,w(e,"by")),stage:x(n.stage,w(e,"stage")),treeHash:F(n.treeHash,null,(r)=>Ct(r,w(e,"treeHash")))}}function JI(t,e){let n=C(t,e,["at","promoted","text"]);return{at:x(n.at,w(e,"at")),promoted:Mt(n.promoted,w(e,"promoted")),text:x(n.text,w(e,"text"))}}function qI(t,e){let n=C(t,e,["at","by","detail","stage","type"]);return{at:x(n.at,w(e,"at")),by:Ct(n.by,w(e,"by")),detail:Ct(n.detail,w(e,"detail")),stage:Ct(n.stage,w(e,"stage")),type:V(HI,n.type,w(e,"type"))}}function YI(t,e){let n=C(t,e,["at","gates","stage","testHashes","treeHash"]);return{at:x(n.at,w(e,"at")),gates:D(n.gates,w(e,"gates"),Eh),stage:x(n.stage,w(e,"stage")),testHashes:la(n.testHashes,w(e,"testHashes")),treeHash:x(n.treeHash,w(e,"treeHash"))}}function XI(t,e){let n=C(t,e,["at","gates","stage","treeHash"]);return{at:x(n.at,w(e,"at")),gates:D(n.gates,w(e,"gates"),Eh),stage:x(n.stage,w(e,"stage")),treeHash:x(n.treeHash,w(e,"treeHash"))}}function Eh(t,e){let n=C(t,e,["checks","details","gate","ok","summary"]);return{checks:D(n.checks,w(e,"checks"),zI),details:jt(n.details,w(e,"details")),gate:V(GI,n.gate,w(e,"gate")),ok:Mt(n.ok,w(e,"ok")),summary:x(n.summary,w(e,"summary"))}}function zI(t,e){let n=C(t,e,BI),r=w(e,"exitCode");return{command:x(n.command,w(e,"command")),durationMs:$t(n.durationMs,w(e,"durationMs")),exitCode:n.exitCode===null?null:$t(n.exitCode,r),expect:V(FI,n.expect,w(e,"expect")),name:x(n.name,w(e,"name")),ok:Mt(n.ok,w(e,"ok")),outputSha256:x(n.outputSha256,w(e,"outputSha256")),outputTail:x(n.outputTail,w(e,"outputTail")),timedOut:Mt(n.timedOut,w(e,"timedOut"))}}function la(t,e){return Object.fromEntries(an(t,e,x))}function ZI(t,e){return Object.fromEntries(an(t,e,$t))}function QI(t,e){if(typeof t==="string"||typeof t==="boolean")return t;if(typeof t==="number"&&Number.isFinite(t))return t;return jt(t,e)}var W=".ari",ir=".ari/tasks/*.json",Ah=".ari/tasks/*.md",Q=".ari/config.json",Jr="ids",sO=`${W}/`,pa="tasks",Ch="knowledge",Rh="packs",iO="ari",Iu="active.json",aO="journal",Ih=".md",Oh=".json",_h=".md",Ru=".yaml",cO=".jsonl",Ou=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Ph=`
123
- `,lO=".ari-",uO=".tmp",dO="ENOENT",Nh="EEXIST",pO=new Set(["EPERM","ENOTSUP","ENOSYS","EXDEV"]),gO="locks",mO=".lock";function qr(t){return t===W||t.startsWith(sO)}function Wt(t){return t.filter((e)=>!qr(e))}function Yr(t){if(mn(yt(t,W)))return;throw new g("Ariadne is not initialised in this repository","Run 'ari init'")}function Dh(){return ht(Rt)}function L(t){Yr(t);let e=yt(t,Q);if(!mn(e))return rr({});return rr(Lu(e,Q,"Fix the JSON syntax of .ari/config.json"))}function _u(t){return Ou.test(t)}function Xr(t){if(_u(t))return t;throw new g(`"${t}" is not a task id`,"Task ids are lower-case words joined by hyphens; run 'ari list'")}function bt(t){return`${W}/${pa}/${Xr(t)}${Ih}`}function fn(t){return`${W}/${pa}/${Xr(t)}${Oh}`}function Pu(t){return`${W}/${Rh}/${t}${Ru}`}function te(t){return Yr(t),fa(yt(t,W,pa),Ih)}function hn(t){return Yr(t),fa(yt(t,W,pa),Oh)}function lt(t,e,n){Yr(t);let r=yt(t,bt(e));if(!mn(r))throw new g(`Task "${e}" does not exist`,"Run 'ari list' to see the tasks of this repository");let o=ns(r,"utf8");return{contractText:o,task:{contract:na(e,o,n),record:yn(t,e)}}}function It(t,e){let n={invalid:[],tasks:[]};for(let r of te(t))try{n.tasks.push(lt(t,r,e).task)}catch(o){if(!(o instanceof g))throw o;n.invalid.push({hint:o.hint??"",id:r,problem:o.message})}return n}function Lh(t,e,n,r){let{id:o}=n,s=bt(o),i=()=>new g(`Task "${o}" already exists at ${s}`,"Run 'ari list'");xu(Uh(e,o),o,()=>{if(mn(yt(t,s))||!Hh(t,o))throw i();jh(t,n),ha(yt(t,s),r,i)})}function Mh(t){let e=te(t);return[...e,...hn(t).filter((n)=>!e.includes(n)&&!Hh(t,n))]}function jh(t,e){rs(yt(t,fn(e.id)),ht(e))}function Ft(t,e,n,r){return xu(Uh(e,n),n,()=>{let o=r(yn(t,n));return jh(t,o),o})}function me(t){Yr(t);let e=yt(t,W,Rh);return fa(e,Ru).map((n)=>{let r=Pu(n),o=sa(ns(yt(t,r),"utf8"),r);if(o.name===n)return o;throw new g(`${r} declares the pack "${o.name}"`,`Rename the file to ${o.name}${Ru} or fix its name`)})}function Ve(t){return Yr(t),fa(yt(t,W,Ch),_h)}function Ne(t){return Ve(t).map((e)=>ra(e,ns(Kh(t,e),"utf8")))}function ga(t,e){if(!Ou.test(e.id))throw Error(`Knowledge entry id "${e.id}" is not a slug`);let n=Kh(t,e.id);ha(n,or(e),()=>Error(`Knowledge entry ${n} already exists`))}async function M(t){return Ke(t,iO)}function ut(t){let e=yt(t,Iu);if(!mn(e))return null;let n=`Delete ${e}, then run 'ari next', which offers to adopt the task again`,r=Lu(e,e,n);return Tt("active task pointer",n,()=>{let o=C(r,"pointer",["since","task"]);return{since:x(o.since,"since"),task:x(o.task,"task")}})}function Nu(t,e){rs(yt(t,Iu),ht(e))}function Fh(t){da(yt(t,Iu),{force:!0})}function ar(t,e){let n=Du(t,e.task);$h(xh(n),{recursive:!0});let r=JSON.stringify(JSON.parse(ht(e)));eO(n,`${r}${Ph}`)}function ma(t,e){da(Du(t,e),{force:!0})}function Gh(t,e){let n=Du(t,e);if(!mn(n))return[];return ns(n,"utf8").split(Ph).flatMap((r)=>{if(r.trim().length===0)return[];let o=fO(r);return o===null||o.task!==e?[]:[o]})}function fO(t){try{return ua(JSON.parse(t))}catch(e){if(e instanceof SyntaxError||e instanceof b)return null;throw e}}function Du(t,e){return yt(t,aO,`${Xr(e)}${cO}`)}function yn(t,e){let n=fn(e),r=yt(t,n);if(!mn(r))throw new g(`Task "${e}" has a contract but no record at ${n}`,`Restore ${n} from git; only ari writes it`);return Th(e,Lu(r,n,`Restore ${n} from git; only ari writes it`))}function Hh(t,e){if(!mn(yt(t,fn(e))))return!0;try{return lh(yn(t,e))}catch(n){if(n instanceof g)return!1;throw n}}function Uh(t,e){return yt(t,gO,`${Xr(e)}${mO}`)}function Kh(t,e){return yt(t,W,Ch,`${e}${_h}`)}function Lu(t,e,n){let r=ns(t,"utf8");try{return JSON.parse(r)}catch(o){let s=o instanceof Error?o.message:String(o);throw new g(`${e} is not valid JSON (${s})`,n)}}function fa(t,e){return hO(t).filter((r)=>r.endsWith(e)).map((r)=>oO(r,e)).filter((r)=>Ou.test(r)).sort(I)}function hO(t){try{return rO(t)}catch(e){if(e.code===dO)return[];throw e}}function rs(t,e){let n=Bh(t);try{vh(n,e),bh(n,t)}catch(r){throw da(n,{force:!0}),r}}function ha(t,e,n){let r=Bh(t);try{vh(r,e),yO(r,t)}catch(o){if(o.code===Nh)throw n();throw o}finally{da(r,{force:!0})}}function yO(t,e){try{nO(t,e)}catch(n){if(!pO.has(n.code??""))throw n;if(mn(e))throw Object.assign(Error(`${e} already exists`),{code:Nh});bh(t,e)}}function Bh(t){let e=xh(t);return $h(e,{recursive:!0}),yt(e,`${lO}${tO()}${uO}`)}async function ya(t){let e=L(t),n=await M(t),r={config:e,drift:null,root:t,state:n,task:null},o=ut(n)?.task??null;if(o===null)return r;if(!te(t).includes(o)){if(hn(t).includes(o)&&Wh(yn(t,o)))throw kO(o);return r}let{contractText:s,task:i}=lt(t,o,e);if(!Wh(i.record))return r;return{...r,drift:wO(i,s),task:i}}function Wh({status:t}){return t==="active"||t==="blocked"}function kO(t){return new g(`the contract of the active task "${t}" is missing`,`Restore ${bt(t)}`)}function wO({contract:t,record:e},n){if(e.contractHash===null||un(n)===e.contractHash)return null;return`the contract of task "${t.id}" changed after its approval; run 'ari amend ${t.id} --reason <text>' or restore ${bt(t.id)}`}var qh=".git",AO="..",wa=0,CO=1,Yh=128,RO=40,IO=["rev-parse","--show-toplevel","--absolute-git-dir","--git-common-dir"];function Xh(){let t=new Map,e=new Map,n=new Map,r=[],o=(c)=>Mu(t,c,()=>OO(c)),s=(c)=>Mu(e,c.root,async()=>{let l=await PO(c);return r.push(l),l}),i=async(c)=>{let l=[],u=null;for(let d of zh(c).filter((p)=>Vh(ka(p,qh)))){let p=await o(d);if(p===null)continue;if(u!==null&&await _O(u,p))break;if(u=p,Vh(ka(d,W)))l.push(await s(p))}return l},a=(c)=>{let l=Zh(Nt(c));return Mu(n,l,()=>i(l))};return{at:async(c)=>(await a(c))[0]??null,governing:a,opened:()=>r}}function Nt(t,e=RO){let n=Fu(()=>TO(t));if(n!==null)return n;let r=os(t);if(r===t)return t;let o=ka(Nt(r,e),$O(t)),s=e>0?ju(o):null;return s===null?o:Nt(Jh(os(o),s),e-1)}function ju(t){return Fu(()=>SO(t))}function Sa(t){return Fu(()=>EO(t).isDirectory())??!1}function Je(t,e){let n=vO(t,e),r=n.split(xO);return r[0]===AO||bO(n)?null:r.join("/")}function Fu(t){try{return t()}catch{return null}}function Mu(t,e,n){let r=t.get(e);if(r!==void 0)return r;let o=n();return t.set(e,o),o}function zh(t){let e=os(t);return e===t?[t]:[t,...zh(e)]}function Zh(t){return Sa(t)||os(t)===t?t:Zh(os(t))}async function OO(t){let e=await P(t,IO,{allowedExitCodes:[wa,Yh]});if(e.exitCode!==wa)return{fault:`git cannot read the repository at ${t}`,gitDirectories:[ka(t,qh)],root:t};let[n="",r="",o=""]=e.stdout.split(`
124
- `);if(Nt(n)!==t)return null;let s=[r,Jh(t,o)].map((i)=>Nt(i));return{fault:null,gitDirectories:[...new Set(s)],root:t}}async function _O(t,e){if(t.fault===null&&t.gitDirectories.at(-1)===e.gitDirectories.at(-1))return!0;if(e.fault!==null)return!1;return(await P(e.root,["check-ignore","-q","--",t.root],{allowedExitCodes:[wa,CO,Yh]})).exitCode===wa}async function PO({fault:t,gitDirectories:e,root:n}){if(t!==null)return{fault:t,gitDirectories:e,root:n,workspace:null};try{return{fault:null,gitDirectories:e,root:n,workspace:await ya(n)}}catch(r){if(!(r instanceof g))throw r;return{fault:Gu(r),gitDirectories:e,root:n,workspace:null}}}function Gu({hint:t,message:e}){return t===void 0?e:`${e} (${t})`}var UO=2;function Ta(t,e){let n=q(t,e);return n===null?null:Vt(e,n)}function q(t,e){let n=Uu(t,e);return Hu(n)?ty(n,"utf8"):null}function Vt(t,e){let n;try{n=JSON.parse(su(e))}catch(r){let o=r instanceof Error?r.message:String(r);throw new g(`${t} is not valid JSON (${o})`,`Fix ${t}, then run the command again`)}if(Y(n))return n;throw new g(`${t} does not hold a JSON object`,`Fix ${t}, then run the command again`)}function Ea(t,e,n){if(!Hu(t))return n;try{return e(JSON.parse(ty(t,"utf8")))}catch{return n}}function Ku(t,e,n){return fe(t,e,Nn(q(t,e),n))}function Nn(t,e){return t===null?`${JSON.stringify(e,null,UO)}
125
- `:Wi(t,e)}function fe(t,e,n){let r=Uu(t,e),o=q(t,e),s=ss(o,n);if(s!=="unchanged")cr(r,n,KO(r));return s}function ss(t,e){if(t===e)return"unchanged";return t===null?"created":"updated"}function cr(t,e,n){let r=Nt(t);LO(Qh(r),{recursive:!0});let o=Uu(Qh(r),`.${HO(r)}.${process.pid}.${NO()}.tmp`);try{if(GO(o,e),n!==void 0)DO(o,n);MO(o,r)}finally{jO(o,{force:!0})}}function KO(t){return Hu(t)?FO(t).mode:void 0}function Y(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}var Bu="agents",ey=1;function ny(t,e){let n=bf(e.preset),r=e.name??n.name,o=jr(n,e.role,e.model),{agents:s,settings:i}=sy(t),a=s[r];if(a!==void 0&&BO(a,o))return{action:"unchanged",entry:o,name:r,preset:n.name};if(a!==void 0)throw new g(`agents.${r} already exists with other settings`,`Choose another name with --name, or run 'ari agents remove ${r}' first`,ey,{tag:"AgentExists"});let c={...i,[Bu]:{...s,[r]:o}};return iy(c,`ari cannot add agent "${r}"`,"Choose another name with --name"),{action:Ku(t,Q,c),entry:o,name:r,preset:n.name}}function ry(t,e){let{agents:n,settings:r}=sy(t);if(n[e]===void 0)return{action:"unchanged",name:e};let{[e]:o,...s}=n,i={...r,[Bu]:s};return iy(i,`ari cannot remove agent "${e}"`,`Change the routing and review settings that name "${e}" in ${Q} first`),Ku(t,Q,i),{action:"removed",name:e}}function oy(t){let e=L(t);return{agents:Object.entries(e.agents).sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>({command:o.command,env:o.env??[],inheritEnv:o.inheritEnv===!0,model:o.model??null,modelFlag:o.modelFlag??null,name:r,reviewCommand:o.reviewCommand??null,roles:nr(o),timeoutSeconds:o.timeoutSeconds??null})),routing:e.routing}}function $a(t){if(t===null)return"none";return t.model===null?t.agent:`${t.agent} (${t.model})`}function sy(t){L(t);let e=Ta(t,Q)??{},n=e[Bu]??{};return{agents:Y(n)?n:{},settings:e}}function iy(t,e,n){let r=Bi(t);if(r!==null)throw new g(`${e}: ${r}`,n,ey,{tag:"InvalidConfig"})}import{existsSync as w_}from"fs";import{join as S_}from"path";import{randomUUID as WO}from"crypto";import{existsSync as VO,mkdirSync as JO,readFileSync as qO,realpathSync as YO,renameSync as XO,rmSync as ay,writeFileSync as zO}from"fs";import{homedir as ZO}from"os";import{join as cy}from"path";var QO=".ari",t_="trust",e_=".json",n_=384,r_=zt({root:gt(),sha256:gt(),trustedAt:gt()});function ly(){let t=process.env.HOME;return cy(t===void 0||t===""?ZO():t,QO,t_)}function is(t){try{return YO(t)}catch{return t}}function uy(t){let e=is(t);try{let n=r_(JSON.parse(qO(Wu(e),"utf8")));return n.root===e?n:null}catch{return null}}function dy(t,e,n=new Date){let r=is(t),o={root:r,sha256:e,trustedAt:n.toISOString()},s=Wu(r),i=`${s}.${process.pid}.${WO()}.tmp`;JO(ly(),{recursive:!0});try{zO(i,`${JSON.stringify(o,null,2)}
126
- `,{mode:n_}),XO(i,s)}finally{ay(i,{force:!0})}return o}function py(t){let e=Wu(is(t));if(!VO(e))return!1;return ay(e,{force:!0}),!0}function Wu(t){return cy(ly(),`${tt(t)}${e_}`)}import{existsSync as o_}from"fs";import{join as s_}from"path";var i_=1,a_=/^[\w@%+=:,./{}-]+$/,Vu="the base set of variables only",c_="the whole environment, with every token in it",l_="{base}",u_="{changed-files}",d_="argus sends the source of the changed files to the model endpoint";function gy(t,e){let n=p_(t),r={agents:e.agents,packCommands:n,regressionSetup:e.regression.setup,reviewCommand:e.review.command,...e.review.argus===void 0?{}:{reviewArgus:e.review.argus},version:i_};return{commands:g_(e,n),sha256:tt(ht(r))}}function p_(t){if(!o_(s_(t,W)))return[];return me(t).sort((e,n)=>I(e.name,n.name)).flatMap((e)=>e.stages.flatMap((n)=>n.gates.flatMap((r)=>r.kind==="command"?[{pack:e.name,run:r.run,stage:n.name}]:[])))}function g_(t,e){let n=Object.entries(t.agents).flatMap(([a,c])=>m_(a,c)),r=t.review.command===null?[]:[zr("review.command",t.review.command)],o=f_(t.review.argus),s=t.regression.setup.map((a,c)=>zr(`regression.setup[${c}]`,a)),i=e.map(({pack:a,run:c,stage:l})=>zr(`.ari/packs/${a}: stage ${l}, command gate`,c));return[...n,...r,...o,...s,...i]}function m_(t,e){let n=h_(e),r=e.reviewCommand===void 0?[]:[zr(`agents.${t}.reviewCommand`,Ju(e.reviewCommand),n)];return[zr(`agents.${t}.command`,Ju(e.command),n),...r]}function f_(t){if(t===void 0)return[];let e={base:l_,configPath:t.config,only:u_},n=`${Vu} and ${Ui(t.mode).join(", ")}, when set`,r=t.mode==="run"?`${n}; ${d_}`:n;return[zr("review.argus.command",Ju(Ki(t,e)),r)]}function h_(t){if(t.inheritEnv===!0)return c_;return t.env===void 0||t.env.length===0?Vu:`${Vu} and ${t.env.join(", ")}`}function zr(t,e,n=null){return{command:e,environment:n,source:t}}function Ju(t){return t.map((e)=>a_.test(e)?e:JSON.stringify(e)).join(" ")}var lr="ARI_TRUST_CONFIG",y_="1";function Zr(){return process.env[lr]===y_}function De(t,e){let n=gy(t,e),r=uy(t),o=k_(n.commands.length,n.sha256,r?.sha256??null);return{commands:n.commands,root:is(t),sha256:n.sha256,state:o,trustedAt:r?.trustedAt??null,trustedSha256:r?.sha256??null}}function kn(t){return t.state==="untrusted"||t.state==="changed"}function Qr(t,e){let n=De(t,e);if(n.state==="not-required")return n;let r=dy(t,n.sha256);return{...n,state:"trusted",trustedAt:r.trustedAt,trustedSha256:r.sha256}}function my(t){return py(t)}function k_(t,e,n){if(t===0)return"not-required";if(n===null)return"untrusted";return n===e?"trusted":"changed"}async function ur(t,e){let n=T_(t),r=await e();if(n)E_(t);return r}function T_(t){if(!w_(S_(t,W)))return!0;try{return!kn(De(t,L(t)))}catch(e){if(e instanceof g)return!1;throw e}}function E_(t){try{let e=L(t);if(kn(De(t,e)))Qr(t,e)}catch(e){if(!(e instanceof g))throw e}}var $_=" ";async function O(){return On(process.cwd())}function wn(t){if(t===void 0)return[];return t.split(",").map((e)=>e.trim()).filter((e)=>e.length>0)}function Dn(t,e,n){if(t!==void 0&&t.trim().length>0)return t;throw new T(`${e} is required`,`Run ${n}`)}function qe(t,e){if(t===void 0||t.trim().length>0)return t;throw new T(`${e} must not be empty`,`Leave ${e} out, or give it a value`)}function ba(t){return t.flatMap((e)=>b_(e)).join(`
127
- `)}function b_(t){let e=`${t.ok?"pass":"FAIL"} ${t.gate}: ${t.summary}`;if(t.ok)return[e];let n=t.details.map((o)=>` - ${o}`),r=t.checks.filter((o)=>!o.ok&&o.outputTail.length>0).flatMap((o)=>[` ${o.name} (${o.command}) output:`,...o.outputTail.trimEnd().split(`
128
- `).map((s)=>`${$_}${s}`)]);return[e,...n,...r]}var v_=Ie.map((t)=>t.name).join(", "),x_=E({description:"List the configured agents, their roles and the routing; environment values are never shown",examples:["ari agents list --json"],json:!0,name:"list",run:async(t)=>{t.output.result(oy(await O()),I_)}}),A_=E({args:j({model:{description:"Model the agent uses unless the routing or --model says otherwise",type:"string"},name:{description:"Name in config.agents (default: the preset's name)",type:"string"},role:{description:`What the agent does: ${Mr.join(", ")} (default: task)`,type:"string"}}),description:"Add an agent from a preset with least-privilege, non-interactive flags to .ari/config.json",examples:["ari agents add claude","ari agents add codex --name codex-review --role review --model gpt-5.5","ari agents add gemini --role both"],json:!0,name:"add",positionals:at({preset:{description:`Preset: ${v_}`,required:!0}}),run:async(t)=>{let e=await O(),n=await ur(e,()=>ny(e,{model:qe(t.args.model,"--model"),name:qe(t.args.name,"--name"),preset:t.positionals.preset,role:vf(t.args.role)}));t.output.result(n,hy)}}),C_=E({description:"Remove an agent from .ari/config.json unless the routing or the review gate still names it",examples:["ari agents remove codex-review"],json:!0,name:"remove",positionals:at({name:{description:"Agent name in config.agents",required:!0}}),run:async(t)=>{let e=await O();t.output.result(await ur(e,()=>ry(e,t.positionals.name)),hy)}}),R_=E({description:"Find the preset agents' binaries on PATH and their versions, running only '<binary> --version'",examples:["ari agents detect --json"],json:!0,name:"detect",run:async(t)=>{t.output.result({agents:await xf()},({agents:e})=>e.map(O_).join(`
129
- `))}}),fy=E({description:"Configure the agents that 'ari run' and 'ari review' start",name:"agents",subcommands:[x_,A_,C_,R_]});function I_(t){let e=t.agents.map((a)=>{let c=a.model===null?"":`, model ${a.model}`,l=a.inheritEnv?", inherits the whole environment":"";return`${a.name} ${a.roles.join("+")}${c}${l}: ${a.command.join(" ")}`}),{default:n,review:r,stages:o}=t.routing,s=Object.entries(o).map(([a,c])=>` stage ${a}: ${$a(c)}`),i=[`routing default: ${$a(n)}`,...s,`routing review: ${$a(r)}`];return[...e.length===0?["No agents are configured; run 'ari agents add <preset>'"]:e,...i].join(`
130
- `)}function hy(t){return`Agent "${t.name}" ${t.action} in .ari/config.json`}function O_(t){if(t.path===null)return`${t.preset} not found on PATH`;return`${t.preset} ${t.path} ${t.version??"version unknown"}`}import{existsSync as Rj}from"fs";import{join as Ij}from"path";import{resolve as N_}from"path";var __=/^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)/,P_=/\r?\n/;function as(t,e){return typeof t==="object"&&t!==null?t[e]:void 0}function Gt(t,e){let n=as(t,e);return typeof n==="string"?n:null}function va(t,e){return Gt(t,"cwd")??e}function yy(t){return t.split(P_).flatMap((e)=>__.exec(e.trim())?.[1]?.trim()??[])}function cs(t,e,n){return{command:n.command??null,cwd:e,event:t,paths:n.paths??[],tool:n.tool??null}}var qu=["before-edit","before-shell","after-tool","stop","pre-compact","session-start"],Sn=new Set(["before-edit","before-shell"]);function ky(t){return qu.includes(t)}var D_=30,L_=120,M_=new Set(["stop","pre-compact"]),j_=1000,F_="apply_patch",wy="run_shell_command";function st(t,e,n=null){let r=M_.has(t)?L_:D_;return{agentEvent:e,event:t,matcher:n,timeoutSeconds:r}}var Sy=[st("stop","Stop"),st("pre-compact","PreCompact","manual|auto"),st("session-start","SessionStart","startup|resume|clear|compact|fork")];function Xu(t){return{decision:"block",reason:t}}function Yu(t){return(e)=>({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t,permissionDecisionReason:e}})}function Ty(t,e,n){let r=as(e,"tool_input"),o=Gt(r,"file_path")??Gt(r,"notebook_path"),s=Gt(r,"command"),i=Gt(e,"tool_name"),a=i===wy?Gt(r,"dir_path"):null;return cs(t,N_(va(e,n),a??""),{command:s,paths:o===null?[]:[o],tool:i})}function G_(t,e,n){let r=Gt(e,"tool_name"),o=Gt(as(e,"tool_input"),"command"),s=r===F_?{paths:yy(o??"")}:{command:o};return cs(t,va(e,n),{...s,tool:r})}function H_(t,e,n){let r=Gt(e,"cwd")??Gt(as(e,"workspace_roots"),"0")??n,o=Gt(e,"file_path");return cs(t,r,{command:Gt(e,"command"),paths:t==="after-tool"&&o!==null?[o]:[]})}function U_(t,e,n){return cs(t,va(e,n),{command:Gt(K_(e),"command"),tool:Gt(e,"toolName")})}function K_({toolArgs:t}){if(typeof t!=="string")return t;try{return JSON.parse(t)}catch{return null}}function zu({answers:t},e,n){let r=B_(t,e,n);return typeof r==="string"?r:JSON.stringify(r)}function B_(t,e,n){switch(n.kind){case"allow":return t.allow?.(e)??"";case"context":return t.context(n.text);case"ask":return(t.ask??t.deny)(n.reason);case"block":return t.block(n.reason);case"deny":return t.deny(n.reason)}}var W_={answers:{ask:Yu("ask"),block:Xu,context:(t)=>t,deny:Yu("deny")},file:".claude/settings.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,...Sn.has(e)?{onFailure:"block"}:{},timeout:n,type:"command"}),label:"Claude Code",layout:"grouped",name:"claude",parse:Ty,registrations:[st("before-edit","PreToolUse","Edit|Write|NotebookEdit"),st("before-shell","PreToolUse","Bash|PowerShell|Monitor"),st("after-tool","PostToolUse","Edit|Write|NotebookEdit|Bash|PowerShell|Monitor"),...Sy],support:"verified"},V_={answers:{allow:(t)=>t==="stop"?{}:"",block:Xu,context:(t)=>t,deny:Yu("deny")},file:".codex/hooks.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,statusMessage:`ari ${e}`,timeout:n,type:"command"}),label:"Codex CLI",layout:"grouped",name:"codex",parse:G_,registrations:[st("before-edit","PreToolUse","^apply_patch$"),st("before-shell","PreToolUse","^Bash$"),st("after-tool","PostToolUse","^(Bash|apply_patch)$"),...Sy],support:"verified"},J_={answers:{block:(t)=>({decision:"deny",reason:t}),context:(t)=>({hookSpecificOutput:{additionalContext:t}}),deny:(t)=>({decision:"deny",reason:t})},file:".gemini/settings.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,name:`ari-${e}`,timeout:n*j_,type:"command"}),label:"Gemini CLI",layout:"grouped",name:"gemini",parse:Ty,registrations:[st("before-edit","BeforeTool","write_file|replace"),st("before-shell","BeforeTool",wy),st("after-tool","AfterTool","write_file|replace|run_shell_command"),st("stop","AfterAgent","*"),st("pre-compact","PreCompress","*"),st("session-start","SessionStart","*")],support:"verified"},q_={answers:{allow:(t)=>Sn.has(t)?{permission:"allow"}:{},block:(t)=>({followup_message:t}),context:(t)=>({additional_context:t}),deny:(t)=>({agent_message:t,permission:"deny",user_message:t})},file:".cursor/hooks.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,...Sn.has(e)?{failClosed:!0}:{},timeout:n}),label:"Cursor",layout:"flat",name:"cursor",parse:H_,registrations:[st("before-shell","beforeShellExecution"),st("after-tool","afterFileEdit"),st("stop","stop"),st("pre-compact","preCompact"),st("session-start","sessionStart")],support:"partial"},Y_={answers:{allow:(t)=>Sn.has(t)?{permissionDecision:"allow"}:"",block:Xu,context:(t)=>({additionalContext:t}),deny:(t)=>({permissionDecision:"deny",permissionDecisionReason:t})},file:".github/hooks/ari.json",handler:(t,{matcher:e,timeoutSeconds:n})=>({bash:t,...e===null?{}:{matcher:e},powershell:t,timeoutSec:n,type:"command"}),label:"GitHub Copilot CLI",layout:"flat",name:"copilot",parse:U_,registrations:[st("before-shell","preToolUse","bash|powershell"),st("stop","agentStop"),st("pre-compact","preCompact"),st("session-start","sessionStart")],support:"partial"},he=[W_,V_,J_,q_,Y_];import{existsSync as ls,readFileSync as vy,rmSync as X_,statSync as z_}from"fs";import{join as us,relative as Qu}from"path";var xy="# ari:managed",Z_=493,Q_=64,tP=1,Ey=0,to=[{command:"ari scope --staged",name:"pre-commit"},{command:"ari verify",name:"pre-push"}],eP=["","."].flatMap((t)=>["yml","yaml","json","toml"].map((e)=>`${t}lefthook.${e}`)),$y=".husky",by=/\.ya?ml$/,Ay=to.map((t)=>t.name);async function eo(t){let e=await Ke(t,"hooks");return to.every(({name:n})=>{let r=us(e,n);return td(r)&&Ry(r)})}async function Aa(t){let e=await ds(t);for(let n of e)if(n.action!=="unchanged")cr(n.target,n.script,Z_);return{agent:"git",files:e.map(({action:n,hook:r,path:o})=>({action:n,hook:r,path:o}))}}async function ds(t){let e=await ed(t);if(e!==null)throw new g(`This repository manages git hooks with ${e.name}; ari will not write hooks beside it`,e.hint);let n=await Ke(t,"hooks"),r=to.map((s)=>({hook:s,path:us(n,s.name),script:nP(s)})),o=r.filter(({path:s})=>ls(s)&&!td(s));if(o.length>0){let s=o.map(({hook:i})=>i.name).join(", ");throw new g(`Unmanaged git hooks already exist: ${s}`,`Add the lines yourself: ${xa("").join("; ")}`)}return r.map(({hook:s,path:i,script:a})=>{let c=ls(i);return{action:c&&vy(i,"utf8")===a&&Ry(i)?"unchanged":c?"updated":"created",hook:s.name,path:Qu(t,i),script:a,target:i}})}async function Cy(t){return Qu(t,await Ke(t,"hooks"))}async function ps(t){let e=await Ke(t,"hooks");return to.map(({name:n})=>{let r=us(e,n);return{action:td(r)?"removed":"unchanged",hook:n,path:Qu(t,r),target:r}})}async function Ca(t){let e=await ps(t);for(let n of e)if(n.action==="removed")X_(n.target);return{agent:"git",files:e.map(({action:n,hook:r,path:o})=>({action:n,hook:r,path:o}))}}function td(t){return ls(t)&&vy(t,"utf8").includes(xy)}function Ry(t){return(z_(t).mode&Q_)!==0}function nP(t){return["#!/bin/sh",xy,"if ! command -v ari >/dev/null 2>&1; then",` echo "ari is not on PATH; install @r5n/ariadne or remove .git/hooks/${t.name}" >&2`," exit 1","fi",`exec ${t.command}`,""].join(`
131
- `)}async function ed(t){let e=await P(t,["config","--get","core.hooksPath"],{allowedExitCodes:[Ey,tP]}),n=e.stdout.trim();if(e.exitCode===Ey&&n.length>0)return Zu(`core.hooksPath (${n})`,xa(`${n}/`),"Add the lines yourself: ");let r=eP.find((o)=>ls(us(t,o)));if(r!==void 0){let o=by.test(r)?rP():xa("lefthook ");return Zu(`lefthook (${r})`,o,by.test(r)?`Add to ${r}:
132
- `:"Add the lines yourself: ")}if(ls(us(t,$y)))return Zu("husky",xa(`${$y}/`),"Add the lines yourself: ");return null}function xa(t){return to.map((e)=>`${t}${e.name}: ${e.command}`)}function Zu(t,e,n){let r=n.endsWith(`
114
+ ${ao}
115
+ ${e}`}function en(t){return JSON.stringify(t.toWellFormed())}function lo(t){return`[${t.map(en).join(", ")}]`}function td(t,e){let n=co(t),r=AO(n,e),o=Kh(n);if(o===null)return r;throw new b(`${e} ${o}`)}function AO(t,e){try{return Bun.YAML.parse(t)}catch(n){let r=n instanceof Error?n.message:String(n);throw new b(`${e} is not valid YAML (${r})`)}}var nd=3,Wh="spike",CO=/^[A-Za-z][A-Za-z0-9._-]*$/,RO=["pass","fail","regression"],IO={all:"check",criteria:"check bound to a criterion","expect:fail":"check with expect: fail","expect:pass":"check with expect: pass","expect:regression":"check with expect: regression"},OO=["title","pack","scope","lock","depends","criteria","checks","invariants","budget"],_O="AC-1",PO="Describe the change, its constraints and how a reviewer can verify it.";function Aa(t,e,n){return At(`contract "${t}"`,`Fix the front matter of .ari/tasks/${t}.md`,()=>NO(t,e,n))}function Bt(t){return Z(co(t))}function Jh(t,e){let n=e===Wh?["criteria: []"]:["criteria:",` - id: ${en(_O)}`,' text: ""'," checks: []"],r=[`title: ${en(t)}`,`pack: ${en(e)}`,"scope: []","lock: []","depends: []",...n,"checks: {}","invariants: []","budget:",` attempts: ${nd}`];return xa(r,`${PO}
116
+ `)}function uo(t,e){let n=e.find((o)=>o.name===t.pack),r=[...UO(t),...rd(t)];return[...jO(t),...FO(t,n,e,r.length>0),...Vh("scope",t.scope,!0),...Vh("lock",t.lock,!1),...HO(t),...r,...KO(t),...BO(t)]}function po(t,e){switch(e){case"all":return t.checks;case"criteria":{let n=new Set(t.criteria.flatMap((r)=>r.checks));return t.checks.filter((r)=>n.has(r.name))}case"expect:pass":return ed(t,"pass");case"expect:fail":return ed(t,"fail");case"expect:regression":return ed(t,"regression")}}function ed(t,e){return t.checks.filter((n)=>n.expect===e)}function rd(t){let e=new Set(t.checks.map((n)=>n.name));return t.criteria.flatMap((n)=>{if(n.checks.length===0)return[`criterion ${n.id} must name at least one check`];return n.checks.filter((r)=>!e.has(r)).map((r)=>`criterion ${n.id} names unknown check "${r}"`)})}function NO(t,e,n){let{body:r,data:o}=Ta(e),s=T(o,"front matter",OO);return{body:r.trim(),budget:lt(s.budget,{attempts:nd},DO),checks:lt(s.checks,[],(i)=>MO(i,n.checkTimeoutSeconds)),criteria:lt(s.criteria,[],(i)=>L(i,"criteria",LO)),depends:lt(s.depends,[],(i)=>Dt(i,"depends")),id:t,invariants:lt(s.invariants,[],(i)=>Dt(i,"invariants")),lock:lt(s.lock,[],(i)=>Dt(i,"lock")),pack:lt(s.pack,n.pack,(i)=>x(i,"pack")),scope:ft(s.scope,"scope",Dt),title:ft(s.title,"title",x)}}function DO(t){let e=T(t,"budget",["attempts"]);return{attempts:lt(e.attempts,nd,(n)=>Kt(n,"budget.attempts"))}}function LO(t,e){let n=T(t,e,["id","text","checks"]);return{checks:lt(n.checks,[],(r)=>Dt(r,k(e,"checks"))),id:ft(n.id,k(e,"id"),x),text:ft(n.text,k(e,"text"),x)}}function MO(t,e){return bn(t,"checks",(n,r,o)=>{if(!CO.test(o))throw new b(`${r} must be named with a letter followed by letters, digits, ".", "_" or "-"`);let s=T(n,r,["run","expect","timeout"]);return{expect:lt(s.expect,"pass",(i)=>K(RO,i,k(r,"expect"))),name:o,run:ft(s.run,k(r,"run"),x),timeoutSeconds:lt(s.timeout,e,(i)=>Vn(i,k(r,"timeout")))}}).map(([,n])=>n)}function jO(t){return t.title.trim().length===0?["title must not be empty"]:[]}function FO(t,e,n,r){if(!e){let s=n.map((i)=>i.name).join(", ");return[`pack "${t.pack}" is not a built-in or project pack (available: ${s})`]}return[...new Set(e.stages.flatMap((s)=>s.gates.flatMap(GO)))].filter((s)=>!r||s!=="all"&&s!=="criteria").filter((s)=>po(t,s).length===0).map((s)=>`pack "${e.name}" needs at least one ${IO[s]}`)}function GO(t){if(t.kind==="regression")return["expect:regression"];return t.kind==="checks"?[t.select]:[]}function Vh(t,e,n){let r=n&&e.length===0?[`${t} must list at least one glob`]:[],o=e.flatMap((s)=>{let i=wr(s);return i===null?[]:[`${t} glob ${JSON.stringify(s)} ${i}`]});return[...r,...o]}function HO(t){return t.depends.flatMap((e)=>{if(e.trim().length===0)return["depends must not contain an empty task id"];return e===t.id?[`depends must not name the task itself ("${t.id}")`]:[]})}function UO(t){let n=t.pack!==Wh&&t.criteria.length===0?[`criteria must list at least one criterion for pack "${t.pack}"`]:[],r=t.criteria.map((s)=>s.id),o=t.criteria.flatMap((s,i)=>{if(s.id.trim().length===0)return[`criteria[${i}] must have an id`];let a=r.indexOf(s.id)<i?[`criterion id "${s.id}" is used more than once`]:[],c=s.text.trim().length===0?[`criterion ${s.id} must have text`]:[];return[...a,...c]});return[...n,...o]}function KO(t){return t.checks.filter((e)=>e.run.trim().length===0).map((e)=>`check ${e.name} must have a run command`)}function BO(t){return t.invariants.some((e)=>e.trim().length===0)?["invariants must not contain an empty command"]:[]}var le=["fact","decision","constraint","pattern","gotcha"],VO=["active","archived"],WO=/^\d{4}-\d{2}-\d{2}$/,JO=/\s+/g,qO=["kind","scope","sources","status","supersedes","supersededBy","created"];function Ca(t,e){return At(`knowledge entry "${t}"`,`Restore .ari/knowledge/${t}.md from git`,()=>YO(t,e))}function br(t){let e=[`kind: ${en(t.kind)}`,`scope: ${lo(t.scope)}`,`sources: ${lo(t.sources)}`,`status: ${en(t.status)}`,`supersedes: ${lo(t.supersedes)}`,`supersededBy: ${t.supersededBy===null?"null":en(t.supersededBy)}`,`created: ${en(t.created)}`];return xa(e,`${t.text.trim()}
117
+ `)}function od(t){return t.normalize("NFC").toLowerCase().replace(JO," ").trim()}function YO(t,e){let{body:n,data:r}=Ta(e),o=T(r,"front matter",qO),s=ft(o.created,"created",x);if(!WO.test(s))throw new b(`created must be a YYYY-MM-DD date, got "${s}"`);let i=n.trim();if(i.length===0)throw new b("the entry text is empty");return{created:s,id:t,kind:ft(o.kind,"kind",(a,c)=>K(le,a,c)),scope:lt(o.scope,[],(a)=>wa(a,"scope")),sources:lt(o.sources,[],(a)=>Dt(a,"sources")),status:lt(o.status,"active",(a)=>K(VO,a,"status")),supersededBy:lt(o.supersededBy,null,(a)=>Ct(a,"supersededBy")),supersedes:lt(o.supersedes,[],(a)=>Dt(a,"supersedes")),text:i}}var qh="<!--",Yh="-->",go="`",Xh=2,XO=/^ {0,3}(`{3,}|~{3,})(.*)$/,zO=/^ {0,3}(`{3,}|~{3,})[ \t]*$/,ZO=/^ {0,3}(#{1,6})(?:[ \t]+(.*))?$/,QO=/(?:^|[ \t]+)#+[ \t]*$/,t_=/\s+/g;function nn(t){return t.replace(t_," ").trim().toLowerCase()}function Zh(t){let{unclosedComment:e,visible:n}=o_(co(t).split(`
118
+ `)),r=[],o=null;for(let s of n){let i=s.fenced?null:r_(s.text);if(i!==null&&i.level<=Xh){if(o=i.level===Xh?e_(i.text,s.line):null,o!==null)r.push(o);continue}o?.lines.push(s)}return{sections:r.map(n_),unclosedComment:e}}function e_(t,e){return{lines:[],section:{body:"",heading:t,key:nn(t),line:e,prose:[]}}}function n_({lines:t,section:e}){return{...e,body:t.map((n)=>n.text).join(`
119
+ `),prose:t.filter((n)=>!n.fenced).map((n)=>n.text)}}function r_(t){let e=ZO.exec(t);if(e===null)return null;return{level:(e[1]??"").length,text:(e[2]??"").replace(QO,"").trim()}}function o_(t){let e=[],n=null,r=null;for(let[o,s]of t.entries()){let i=o+1;if(n!==null){e.push({fenced:!0,line:i,text:s}),n=i_(s,n)?null:n;continue}let a=r===null?s_(s):null;if(a!==null){n=a,e.push({fenced:!0,line:i,text:s});continue}let c=a_(s,r!==null);r=c.inside?c.fresh?i:r:null,e.push({fenced:!1,line:i,text:c.text})}return{unclosedComment:r,visible:e}}function s_(t){let e=XO.exec(t),n=e?.[1];if(n===void 0)return null;let r=n.slice(0,1);if(r===go&&(e?.[2]??"").includes(go))return null;return{length:n.length,marker:r}}function i_(t,e){let n=zO.exec(t)?.[1];return n?.startsWith(e.marker)===!0&&n.length>=e.length}function a_(t,e){let n=e,r=!1,o="",s=0;while(s<t.length){if(n){let a=t.indexOf(Yh,s);if(a===-1)return{fresh:r,inside:!0,text:o};n=!1,r=!1,s=a+Yh.length;continue}if(t.startsWith(qh,s)){n=!0,r=!0,s+=qh.length;continue}let i=t[s]===go?c_(t,s):s+1;o+=t.slice(s,i),s=i}return{fresh:r,inside:n,text:o}}function c_(t,e){let n=zh(t,e),r=t.indexOf(go,e+n);while(r!==-1){let o=zh(t,r);if(o===n)return r+o;r=t.indexOf(go,r+o)}return e+n}function zh(t,e){let n=e;while(t[n]===go)n++;return n-e}var sd="TODO(ari): write this section",$n="Acceptance criteria",Ra=["Problem","Context","Options","Decision",$n,"Scope","Risks and open questions"],l_={Context:["What already exists that this design has to respect.","List the knowledge entries you consulted by id, one per line: - <id>: why it matters (find them with ari knowledge search <query>)."],Decision:["The option you chose, and why it beats the others."],Options:["Two or more ways to solve the problem, each with what it costs."],Problem:["What is wrong or missing, for whom, and what happens today."],"Risks and open questions":["What could go wrong and what you could not settle; write None if nothing."],Scope:["The files and areas the change touches and what it leaves alone; keep it inside the contract's scope."],[$n]:["One line per criterion of the contract, written as - AC-1: what must be true.","The ids must be exactly the ids of the contract's criteria."]},u_=["Fill this section."],d_=/\s+/g,p_=/<!--|-->/g,g_=/^[-*+][ \t]+([^\s:]+):(?=\s|$)/;function Qh(t,e=[]){let n=new Set(Ra.map(nn)),r=e.filter((i)=>!n.has(nn(i))),o=[...Ra,...r].map(m_);return`# ${t.replace(p_,"").replace(d_," ").trim()}
120
+
121
+ ${o.join(`
122
+
123
+ `)}
124
+ `}function ty(t){let{requirements:e}=t,{sections:n,unclosedComment:r}=Zh(t.text),o=r===null?[]:[`Close the HTML comment that starts at line ${r} of ${t.path} with -->`],s=e.sections.flatMap((a)=>f_(a,n,t.path)),i=e.traceable?h_(n,t):{ids:0,problems:[]};return{filled:e.sections.length-s.length,problems:[...o,...s,...i.problems],traced:i.ids}}function m_(t){let e=(l_[t]??u_).join(`
125
+ `);return`## ${t}
126
+ <!--
127
+ ${e}
128
+ -->
129
+ ${sd}`}function f_(t,e,n){let r=e.filter((s)=>s.key===nn(t));if(r.length===0)return[`Add the section '${t}' to ${n}`];if(r.length>1)return[`The section '${t}' appears ${r.length} times in ${n}; keep one and merge the rest`];let o=r[0]?.body??"";if(o.includes(sd))return[`Fill the section '${t}' in ${n}: replace the placeholder '${sd}'`];return o.trim().length===0?[`Fill the section '${t}' in ${n}`]:[]}function h_(t,e){let n=nn($n),r=t.filter((g)=>g.key===n).flatMap((g)=>g.prose.flatMap(y_)),{contractPath:o,criteria:s,path:i}=e,a=new Set(s),c=new Set(r),l=s.filter((g)=>!c.has(g)),u=[...c].filter((g)=>!a.has(g)),d=[...c].filter((g)=>r.filter((f)=>f===g).length>1),p=[...l.map((g)=>`Add '- ${g}: <what must be true>' under '${$n}' in ${i}; the contract has ${g}`),...u.map((g)=>`Remove ${g} from '${$n}' in ${i}, or add it to the criteria of ${o}; the contract lacks ${g}`),...d.map((g)=>`Keep one line for ${g} under '${$n}' in ${i}; it appears more than once`)];return{ids:s.length-l.length,problems:p}}function y_(t){let e=g_.exec(t)?.[1];return e===void 0?[]:[e]}var ry=200,k_=".ari/designs/{id}.md",w_=/\{id\}/g,S_=/[\r\n]/,v_="Fix the pack file; see the packs section of the Ariadne design",b_=["all","criteria","expect:pass","expect:fail","expect:regression"],E_=["pass","fail"],$_=["kind","path","minBytes","sections","traceable"],T_="The design in .ari/designs/{id}.md is the work item: fill in every section (list the knowledge entries you consulted by id under Context), make 'Acceptance criteria' list exactly the ids of the contract's criteria, then ask a human to approve it. Do not change code in this stage.",Ts={kind:"criteria"},rn={kind:"invariants"},te={kind:"scope"},He={kind:"locked"},id={kind:"tests-unchanged"},x_={kind:"regression"},ad={kind:"approval"},ey={kind:"review"};function ue(t,e){return{expect:e,kind:"checks",select:t}}function cd(t,e={}){return{kind:"artifact",minBytes:ry,path:t,...e}}var ny=Es([{description:"Implement the contract and prove it with its checks",name:"basic",stages:[{gates:[Ts,ue("criteria","pass"),rn,te,He],instruction:"Implement the change inside the scope until every criterion's checks pass.",name:"implement"}]},{description:"Approved design, implementation, then review",name:"sdlc",stages:[{gates:[cd(".ari/designs/{id}.md"),ad],instruction:"Write the design to .ari/designs/{id}.md, then ask a human to approve it.",name:"design"},{gates:[Ts,ue("all","pass"),rn,te,He],instruction:"Implement the approved design inside the scope until every check passes.",name:"implement"},{gates:[ey,ue("all","pass"),rn,te,He],instruction:"Get the change reviewed: run the review command or ask a human to approve it.",name:"review"}]},{description:"Red, green, refactor with frozen tests",name:"tdd",stages:[{gates:[Ts,ue("criteria","fail"),te],instruction:"Write failing tests for every criterion. Do not implement the change yet.",name:"red"},{gates:[ue("all","pass"),id,rn,te,He],instruction:"Make every check pass with the smallest change. Do not edit the tests.",name:"green"},{gates:[ue("all","pass"),id,rn,te,He],instruction:"Improve the code while every check stays green. Do not edit the tests.",name:"refactor"}]},{description:"Reproduce the bug with a regression check, then fix it",name:"bugfix",stages:[{gates:[ue("expect:regression","fail"),te],instruction:"Write a regression check that fails because of the bug. Do not fix it yet.",name:"reproduce"},{gates:[x_,ue("all","pass"),rn,te,He],instruction:"Fix the bug so the regression check passes here and still fails on the base commit.",name:"fix"}]},{description:"Approved specification, then implementation",name:"spec-driven",stages:[{gates:[Ts,ad],instruction:"Specify the criteria and their checks in the contract, run ari amend, then ask a human to approve.",name:"specify"},{gates:[ue("all","pass"),rn,te,He],instruction:"Implement the approved specification inside the scope until every check passes.",name:"implement"}]},{description:"Change the structure without changing behaviour",name:"refactor",stages:[{gates:[id,ue("all","pass"),rn,te,He],instruction:"Restructure the code without changing behaviour. Keep the tests unchanged and every check green.",name:"refactor"}]},{description:"Exploration that ends in written findings",name:"spike",stages:[{gates:[cd(".ari/designs/{id}.md"),te,He],instruction:"Explore inside the scope and write the findings to .ari/designs/{id}.md.",name:"explore"}]},{description:"Structured design traced to the criteria, approval, implementation, then review",name:"feature",stages:[{gates:[cd(k_,{sections:[...Ra],traceable:!0}),ad,te],instruction:T_,name:"design"},{gates:[Ts,ue("all","pass"),rn,te,He],instruction:"Implement the approved design inside the scope until every check passes.",name:"implement"},{gates:[ey,ue("all","pass"),rn,te,He],instruction:"Get the change reviewed: run the review command or ask a human to approve it.",name:"review"}]}]),oy={approval:(t,e)=>Wn(t,e,"approval"),artifact:__,checks:O_,command:(t,e)=>{let n=T(t,e,["kind","run"]);return{kind:"command",run:nt(n.run,k(e,"run"))}},criteria:(t,e)=>Wn(t,e,"criteria"),invariants:(t,e)=>Wn(t,e,"invariants"),locked:(t,e)=>Wn(t,e,"locked"),regression:(t,e)=>Wn(t,e,"regression"),review:(t,e)=>Wn(t,e,"review"),scope:(t,e)=>Wn(t,e,"scope"),"tests-unchanged":(t,e)=>Wn(t,e,"tests-unchanged")},A_=Object.keys(oy);function Ia(t,e="pack"){return At(e,v_,()=>C_(td(t,"the pack file")))}function Tn(t){let e=new Map(t.map((s)=>[s.name,s])),n=ny.map((s)=>e.get(s.name)??s),r=new Set(ny.map((s)=>s.name)),o=t.filter((s)=>!r.has(s.name)).sort((s,i)=>O(s.name,i.name));return[...n,...o]}function Ue(t,e){let n=Tn(e),r=n.find((s)=>s.name===t);if(r)return r;let o=n.map((s)=>s.name).join(", ");throw new m(`Unknown pack "${t}"`,`Use one of ${o}, or add .ari/packs/${t}.yaml`)}function Oa(t,e){let{agents:n,regression:r,review:o,testGlobs:s}=e,i=t.stages.map(({gates:c,name:l})=>({gates:c,name:l})),a=o.agent===void 0?{}:{reviewer:n[o.agent]??null};return Z(pt({regression:r,review:o,stages:i,testGlobs:s,...a}))}function mo(t,e){return t.instruction.replace(w_,e)}function C_(t){let e=T(t,"pack",["name","description","stages"]),n=L(e.stages,"stages",R_);if(n.length===0)throw new b("stages must list at least one stage");let r=new Set;for(let[o,s]of n.entries()){if(r.has(s.name))throw new b(`stages[${o}].name repeats "${s.name}"`);r.add(s.name)}return{description:lt(e.description,"",(o)=>x(o,"description")),name:je(e.name,"name"),stages:n}}function R_(t,e){let n=T(t,e,["name","instruction","gates"]),r=L(n.gates,k(e,"gates"),I_);if(r.length===0)throw new b(`${k(e,"gates")} must list at least one gate`);let o=new Set(r.map((s)=>s.kind));if(o.has("tests-unchanged")&&!o.has("scope"))throw new b(`${k(e,"gates")} has tests-unchanged without scope; tests-unchanged covers the test files inside the scope and relies on the scope gate for the rest`);return{gates:r,instruction:nt(n.instruction,k(e,"instruction")),name:je(n.name,k(e,"name"))}}function I_(t,e){let n=T(t,e,["kind","select","expect","path","minBytes","sections","traceable","run"]),r=K(A_,n.kind,k(e,"kind"));return oy[r](n,e)}function Wn(t,e,n){return T(t,e,["kind"]),{kind:n}}function O_(t,e){let n=T(t,e,["kind","select","expect"]);return ue(lt(n.select,"all",(r)=>K(b_,r,k(e,"select"))),lt(n.expect,"pass",(r)=>K(E_,r,k(e,"expect"))))}function __(t,e){let n=T(t,e,$_),r=nt(n.path,k(e,"path"));if(r.startsWith("/")||r.split("/").includes(".."))throw new b(`${k(e,"path")} must stay inside the repository`);let s=lt(n.sections,void 0,(a)=>P_(a,k(e,"sections"))),i=lt(n.traceable,!1,(a)=>$t(a,k(e,"traceable")));if(i&&!(s??[]).some((a)=>nn(a)===nn($n)))throw new b(`${k(e,"traceable")} needs "${$n}" in ${k(e,"sections")}`);return{kind:"artifact",minBytes:lt(n.minBytes,ry,(a)=>ht(a,k(e,"minBytes"))),path:r,...s===void 0?{}:{sections:s},...i?{traceable:i}:{}}}function P_(t,e){let n=L(t,e,(o,s)=>{let i=nt(o,s).trim();if(S_.test(i)||i.startsWith("#"))throw new b(`${s} must be the text of a heading on one line, without leading hashes`);return i});if(n.length===0)throw new b(`${e} must list at least one section`);let r=new Set;for(let[o,s]of n.entries()){let i=nn(s);if(r.has(i))throw new b(`${k(e,o)} repeats "${s}"`);r.add(i)}return n}var sy="attempt budget exhausted",iy="failedAttempts",N_={active:()=>"Run 'ari done' to finish the current stage",blocked:(t)=>`Run 'ari resolve ${t} --answer <text>'`,done:()=>`Done tasks are final; create a follow-up with 'ari new "<title>"'`,draft:(t)=>`Complete the contract, then run 'ari ready ${t}'`,ready:(t)=>`Run 'ari start ${t}'`};function on(t,e,n={}){return{at:e,by:n.by??null,detail:n.detail??null,stage:n.stage??null,type:t}}function ld(t,e){return{approvals:[],attempts:0,base:null,contractHash:null,evidence:[],gatesHash:null,history:[on("created",e)],id:t,journalStats:null,knowledgeUsed:[],lastFailure:null,lockHashes:{},notes:[],question:null,stage:0,stageTestHashes:{},status:"draft"}}function cy(t){let e=t.history[0]?.at??"";return pt(t)===pt(ld(t.id,e))}function ud(t,e){return xn(t,["draft"],"mark ready"),{...t,history:[...t.history,on("ready",e)],status:"ready"}}function ly(t,e,n,r){return xn(t,["ready"],"start"),{...t,attempts:0,...ky(n),base:e,history:[...t.history,on("started",r,{detail:e})],stage:0,status:"active"}}function uy(t,e,n,r){if(xn(t,["active"],"record a passed stage for"),!Number.isInteger(n)||t.stage>=n)throw Error(`Stage ${t.stage} of task "${t.id}" is outside a pack of ${n} stages`);let o=t.stage+1>=n,s=on(o?"done":"advanced",e.at,{stage:e.stage});return{...t,evidence:[...t.evidence,e],history:[...t.history,s],lastFailure:null,stage:o?t.stage:t.stage+1,stageTestHashes:{...r},status:o?"done":"active"}}function dy(t,e,n){if(xn(t,["active"],"record a failed attempt for"),!Number.isInteger(n)||n<=0)throw Error(`Attempt budget must be a positive integer: ${n}`);let r=t.attempts+1,o=e.gates.filter((c)=>!c.ok).map((c)=>c.gate),s=on("failed",e.at,{detail:`attempt ${r} of ${n}: ${o.join(", ")||"no failing gate recorded"}`,stage:e.stage}),i=r>=n,a=on("blocked",e.at,{detail:sy,stage:e.stage});return{...t,attempts:r,history:i?[...t.history,s,a]:[...t.history,s],lastFailure:e,question:i?sy:t.question,status:i?"blocked":"active"}}function dd(t,e,n){xn(t,["draft","ready","active","blocked"],"amend");let r=xs(e.reason,"Amending a task needs a reason","Pass --reason <text>"),o=e.base!==null&&e.base!==t.base;if(o)xn(t,["active","blocked"],"move the base of");let s=o?e.base:t.base,i=`gates ${e.gatesHash}, locks ${ay(e.lockHashes)}, tests ${ay(e.stageTestHashes)}`,a=o?`, base ${t.base} -> ${s}`:"",c=`${r} (contract ${e.contractHash}, ${i}${a})`;return{...t,...ky(e),approvals:t.approvals.filter((l)=>l.stage!==e.stage),base:s,history:[...t.history,on("amended",n,{detail:c})]}}function py(t,e,n){xn(t,["active"],"block");let r=xs(e,"Blocking a task needs a question for a human","Pass --reason <text>");return{...t,history:[...t.history,on("blocked",n,{detail:r})],question:r,status:"blocked"}}function pd(t,e,n){xn(t,["blocked"],"resolve");let r=xs(e,"Resolving a task needs an answer","Pass --answer <text>");return{...t,attempts:0,history:[...t.history,on("resolved",n,{detail:r})],notes:[...t.notes,{at:n,promoted:!1,text:r}],question:null,status:"active"}}function gy(t,e,n){xn(t,["active"],"approve");let{artifactHashes:r,stage:o,treeHash:s}=e,i=xs(e.by,"An approval needs the approver's name","Set git user.name so the approval records who gave it");return{...t,approvals:[...t.approvals,{artifactHashes:{...r},at:n,by:i,stage:o,treeHash:s}],history:[...t.history,on("approved",n,{by:i,stage:o})]}}function my(t,e,n){let r=xs(e,"A note needs text","Pass the note text as an argument");return{...t,notes:[...t.notes,{at:n,promoted:!1,text:r}]}}function _a(t,e){let n=new Map(Object.entries(t.journalStats??{}).filter(([o])=>o!==iy));for(let o of e)n.set(o.type,(n.get(o.type)??0)+1);let r=t.history.filter((o)=>o.type==="failed").length;return{...t,journalStats:{...Object.fromEntries(n),[iy]:r}}}function fy(t,e){let n=[...new Set([...t.knowledgeUsed,...e])].sort(O);return{...t,knowledgeUsed:n}}function hy(t,e){let n=`Run 'ari sleep' to list the unpromoted notes of "${t.id}"`;for(let o of e){let s=t.notes[o];if(s===void 0)throw new m(`Task "${t.id}" has no note ${o}`,n);if(s.promoted)throw new m(`Note ${o} of task "${t.id}" is already promoted`,n)}let r=new Set(e);return{...t,notes:t.notes.map((o,s)=>r.has(s)?{...o,promoted:!0}:o)}}function yy(t,e){let n=new Set(e);return{...t,notes:t.notes.map((r,o)=>n.has(o)?{...r,promoted:!1}:r)}}function ky({contractHash:t,gatesHash:e,lockHashes:n,stageTestHashes:r}){return{contractHash:t,gatesHash:e,lockHashes:{...n},stageTestHashes:{...r}}}function ay(t){return Z(pt(t))}function xn(t,e,n){if(e.includes(t.status))return;throw new m(`Cannot ${n} task "${t.id}": it is ${t.status}, not ${e.join(" or ")}`,N_[t.status](t.id))}function xs(t,e,n){let r=t.trim();if(r.length===0)throw new m(e,n);return r}import{mkdirSync as D_,readFileSync as L_,rmSync as Pa,statSync as M_,writeFileSync as j_}from"fs";import{dirname as F_}from"path";var G_="EEXIST",H_="ENOENT",U_="ESRCH",K_=".break",B_=20,V_=1e4,W_=1000,J_=10,q_=0;function md(t,e,n){return As(t,`task "${e}"`,n)}function As(t,e,n){Y_(t,e);try{return n()}finally{Pa(t,{force:!0})}}function Y_(t,e){D_(F_(t),{recursive:!0});let n=Date.now()+V_;while(!wy(t)){if(gd(t))X_(t);if(Date.now()>=n)throw new m(`Another ari process is still changing ${e}`,`Run the command again once it finishes; if no ari process is running, delete ${t}`);Bun.sleepSync(B_)}}function X_(t){let e=`${t}${K_}`;if(!wy(e)){if(gd(e))Pa(e,{force:!0});return}try{if(gd(t))Pa(t,{force:!0})}finally{Pa(e,{force:!0})}}function wy(t){try{return j_(t,`${process.pid}`,{flag:"wx"}),!0}catch(e){if(fd(e)===G_)return!1;throw e}}function gd(t){let e=z_(t);if(e===null)return!1;if(Number.isNaN(e.pid))return Date.now()-e.modifiedMs>W_;return!Z_(e.pid)}function z_(t){try{return{modifiedMs:M_(t).mtimeMs,pid:Number.parseInt(L_(t,"utf8"),J_)}}catch(e){if(fd(e)===H_)return null;throw e}}function Z_(t){try{return process.kill(t,q_),!0}catch(e){return fd(e)!==U_}}function fd(t){return t.code}var hd=["draft","ready","active","blocked","done"],Q_=["pass","fail"],tP=["criteria","checks","invariants","scope","locked","tests-unchanged","regression","artifact","approval","review","command"],eP=["created","ready","started","advanced","done","failed","amended","blocked","resolved","approved"],nP=["edit","shell","tool","check","done","context","note","stop","compact","session"],rP=["approvals","attempts","base","contractHash","evidence","gatesHash","history","id","journalStats","knowledgeUsed","lastFailure","lockHashes","notes","question","stage","stageTestHashes","status"],oP=["command","durationMs","exitCode","expect","name","ok","outputSha256","outputTail","timedOut"];function Sy(t,e){return At(`task record "${t}"`,`Restore .ari/tasks/${t}.json from git; only ari writes it`,()=>{let n=sP(e);if(n.id!==t)throw new b(`id is "${n.id}" but the file belongs to task "${t}"`);return n})}function Da(t){let e=T(t,"event",["at","detail","task","type"]);return{at:x(e.at,"at"),detail:Object.fromEntries(bn(e.detail,"detail",pP)),task:x(e.task,"task"),type:K(nP,e.type,"type")}}function sP(t){let e=T(t,"record",rP);return{approvals:L(e.approvals,"approvals",iP),attempts:ht(e.attempts,"attempts"),base:Ct(e.base,"base"),contractHash:Ct(e.contractHash,"contractHash"),evidence:L(e.evidence,"evidence",cP),gatesHash:D(e.gatesHash,null,(n)=>Ct(n,"gatesHash")),history:L(e.history,"history",aP),id:x(e.id,"id"),journalStats:e.journalStats===null?null:dP(e.journalStats,"journalStats"),knowledgeUsed:Dt(e.knowledgeUsed,"knowledgeUsed"),lastFailure:e.lastFailure===null?null:lP(e.lastFailure,"lastFailure"),lockHashes:Na(e.lockHashes,"lockHashes"),notes:L(e.notes,"notes",yd),question:Ct(e.question,"question"),stage:ht(e.stage,"stage"),stageTestHashes:Na(e.stageTestHashes,"stageTestHashes"),status:K(hd,e.status,"status")}}function iP(t,e){let n=T(t,e,["artifactHashes","at","by","stage","treeHash"]);return{artifactHashes:D(n.artifactHashes,{},(r)=>Na(r,k(e,"artifactHashes"))),at:x(n.at,k(e,"at")),by:x(n.by,k(e,"by")),stage:x(n.stage,k(e,"stage")),treeHash:D(n.treeHash,null,(r)=>Ct(r,k(e,"treeHash")))}}function yd(t,e){let n=T(t,e,["at","promoted","text"]);return{at:x(n.at,k(e,"at")),promoted:$t(n.promoted,k(e,"promoted")),text:x(n.text,k(e,"text"))}}function aP(t,e){let n=T(t,e,["at","by","detail","stage","type"]);return{at:x(n.at,k(e,"at")),by:Ct(n.by,k(e,"by")),detail:Ct(n.detail,k(e,"detail")),stage:Ct(n.stage,k(e,"stage")),type:K(eP,n.type,k(e,"type"))}}function cP(t,e){let n=T(t,e,["at","gates","stage","testHashes","treeHash"]);return{at:x(n.at,k(e,"at")),gates:L(n.gates,k(e,"gates"),vy),stage:x(n.stage,k(e,"stage")),testHashes:Na(n.testHashes,k(e,"testHashes")),treeHash:x(n.treeHash,k(e,"treeHash"))}}function lP(t,e){let n=T(t,e,["at","gates","stage","treeHash"]);return{at:x(n.at,k(e,"at")),gates:L(n.gates,k(e,"gates"),vy),stage:x(n.stage,k(e,"stage")),treeHash:x(n.treeHash,k(e,"treeHash"))}}function vy(t,e){let n=T(t,e,["checks","details","gate","ok","summary"]);return{checks:L(n.checks,k(e,"checks"),uP),details:Dt(n.details,k(e,"details")),gate:K(tP,n.gate,k(e,"gate")),ok:$t(n.ok,k(e,"ok")),summary:x(n.summary,k(e,"summary"))}}function uP(t,e){let n=T(t,e,oP),r=k(e,"exitCode");return{command:x(n.command,k(e,"command")),durationMs:ht(n.durationMs,k(e,"durationMs")),exitCode:n.exitCode===null?null:ht(n.exitCode,r),expect:K(Q_,n.expect,k(e,"expect")),name:x(n.name,k(e,"name")),ok:$t(n.ok,k(e,"ok")),outputSha256:x(n.outputSha256,k(e,"outputSha256")),outputTail:x(n.outputTail,k(e,"outputTail")),timedOut:$t(n.timedOut,k(e,"timedOut"))}}function Na(t,e){return Object.fromEntries(bn(t,e,x))}function dP(t,e){return Object.fromEntries(bn(t,e,ht))}function pP(t,e){if(typeof t==="string"||typeof t==="boolean")return t;if(typeof t==="number"&&Number.isFinite(t))return t;return Dt(t,e)}import{copyFileSync as bP,existsSync as EP,mkdtempSync as $P,readFileSync as TP,readlinkSync as xP,rmSync as AP,utimesSync as CP}from"fs";import{tmpdir as RP}from"os";import{join as Ma,resolve as IP}from"path";import{lstatSync as gP,statSync as mP}from"fs";import{dirname as fP,join as hP}from"path";var yP=["ENOENT","ENOTDIR","ELOOP"];function $e(t){return by(()=>gP(t))}function kd(t){return by(()=>mP(t))}function Te(t,e,n=new Map){let r=fP(e);if(r===".")return!1;let o=n.get(r);if(o!==void 0)return o;let s=$e(hP(t,r))?.isSymbolicLink()===!0||Te(t,r,n);return n.set(r,s),s}function by(t){try{return t()}catch(e){if(yP.includes(e.code))return null;throw e}}import{realpathSync as kP}from"fs";var Cs="ari-base-",wd="ari-index-",Ey="ari-verdicts-",wP=12;function La(t){return`${wd}${SP(t)}-`}function SP(t){return Z(vP(t)).slice(0,wP)}function vP(t){try{return kP(t)}catch{return t}}var ja="\x00",ee=0,OP=128,_P=128,Ry=1,Iy=1,PP=1,Sd=["diff","--name-only","--no-renames","--ignore-submodules=untracked","-z"],NP=["git","--no-optional-locks","--no-replace-objects",...["core.fsmonitor=false","core.untrackedCache=false","core.trustctime=true","core.checkStat=default"].flatMap((t)=>["-c",t])],$y=1,DP=/^(?:[a-z]|S) /,Ty=/^s/i,LP=2,MP="symlink:",jP=["--no-assume-unchanged","--no-skip-worktree"],xy="worktree ",FP="bare",GP="prunable",Ay=/^(?:error|fatal): /;async function F(t,e,n={}){let r=[...NP,...e],o=KP(r,t,n),[s,i,a]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if((n.allowedExitCodes??[ee]).includes(a))return{exitCode:a,stderr:i,stdout:s};let l=i.trim()||s.trim()||"no output";throw Error(`git ${e.join(" ")} failed in ${t} with exit code ${a}: ${l}`)}async function Jn(t){let e=await F(t,["rev-parse","--show-toplevel"],{allowedExitCodes:[ee,OP]});if(e.exitCode!==ee)throw new m(`${t} is not inside a git working tree`,"Run ari from inside a git repository");return e.stdout.trim()}async function sn(t,e){let n=await F(t,["rev-parse","--git-path",e]);return IP(t,n.stdout.trim())}async function Fa(t){let e=await F(t,["rev-parse","--verify","--quiet","HEAD^{commit}"],{allowedExitCodes:[ee,Ry]});if(e.exitCode!==ee)throw new m("The repository has no commits yet","Make a first commit, then run the command again");return e.stdout.trim()}async function Oy(t){let e=await F(t,["config","user.name"],{allowedExitCodes:[ee,Iy]}),n=e.stdout.trim();return e.exitCode===ee&&n.length>0?n:null}async function xe(t,e){let n=await Dy(t,async(s)=>(await Ny(t,await Ha(t),s),F(t,[...Sd,e,"--"],{env:s}))),r=await F(t,[...Sd,"--cached",e,"--"]),o=await F(t,["ls-files","--others","--exclude-standard","-z"]);return bd([n,r,o].flatMap((s)=>Ke(s.stdout)))}async function Ga(t,e,n){let r=await F(t,[...Sd,e,n,"--"]);return bd(Ke(r.stdout))}async function fo(t,e){let n=await F(t,["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],{allowedExitCodes:[ee,Ry]});if(n.exitCode!==ee)throw new m(`"${e}" does not name a commit`,"Pass a branch, tag or commit that this repository has");return n.stdout.trim()}async function _y(t,e,n){let r=await F(t,["merge-base",e,n],{allowedExitCodes:[ee,PP]});if(r.exitCode!==ee)throw new m(`${e} and ${n} share no history`,"Pass a ref that the current branch was integrated with");return r.stdout.trim()}async function Py(t){let e=await F(t,["worktree","list","--porcelain","-z"]),n=[],r=null;for(let o of[...e.stdout.split(ja),""])if(o.startsWith(xy))r=o.slice(xy.length);else if(o===FP||o.startsWith(GP))r=null;else if(o===""&&r!==null)n.push(r),r=null;return n}async function Ae(t,e){return Dy(t,async(n)=>{await Ny(t,await Ha(t),n);let r=await F(t,["add","--all","--sparse","--","."],{allowedExitCodes:[ee,_P],env:n});if(r.exitCode!==ee)throw new m(`git cannot hash the working tree: ${vd(r.stderr)}`,"Commit, remove or ignore those paths (an embedded repository needs a commit), then run the command again");if(e.length>0){let s=e.map((i)=>`:(glob)${i}`);await F(t,["rm","--cached","-r","-q","--sparse","--ignore-unmatch","--",...s],{env:n})}return(await F(t,["write-tree"],{env:n})).stdout.trim()})}async function An(t,e){if(e.length===0)return{};let n=await F(t,["ls-files","--cached","--others","--exclude-standard","-z"]),r=new Map,o=bd(Ke(n.stdout)).filter((s)=>et(s,e)&&!Te(t,s,r));return Object.fromEntries(o.flatMap((s)=>{let i=UP(Ma(t,s));return i===null?[]:[[s,i]]}))}function vd(t){let e=t.split(`
130
+ `).map((r)=>r.trim()).filter((r)=>r.length>0),n=e.filter((r)=>Ay.test(r)).map((r)=>r.replace(Ay,""));return(n.length>0?n:e).join("; ")||"no output"}async function Ha(t){let e=await F(t,["ls-files","-v","-z"]),n=Ke(e.stdout).filter((o)=>DP.test(o)),r=n.some((o)=>Ty.test(o))&&await HP(t);return n.filter((o)=>!(r&&Ty.test(o))||$e(Ma(t,Cy(o)))!==null).map(Cy)}async function HP(t){return(await F(t,["config","--type=bool","core.sparseCheckout"],{allowedExitCodes:[ee,Iy]})).stdout.trim()==="true"}function Cy(t){return t.slice(LP)}async function Ny(t,e,n){if(e.length===0)return;let r=`${e.join(ja)}${ja}`;for(let o of jP)await F(t,["update-index",o,"-z","--stdin"],{env:n,stdin:r})}async function Dy(t,e){let n=$P(Ma(RP(),La(t))),r=Ma(n,"index"),o=()=>AP(n,{force:!0,recursive:!0}),s=Qt(o);try{let i=await sn(t,"index");if(EP(i))bP(i,r),CP(r,$y,$y);return await e({GIT_INDEX_FILE:r})}finally{o(),s()}}function UP(t){let e=$e(t);if(e?.isSymbolicLink())return`${MP}${Z(xP(t))}`;return e?.isFile()?Z(TP(t)):null}function KP(t,e,n){try{return Bun.spawn(t,{cwd:e,env:n.env?{...process.env,...n.env}:process.env,stderr:"pipe",stdin:n.stdin===void 0?"ignore":new TextEncoder().encode(n.stdin),stdout:"pipe"})}catch(r){throw Error(`Could not run ${t.join(" ")} in ${e}`,{cause:r})}}function Ke(t){return t.split(ja).filter((e)=>e.length>0)}function bd(t){return[...new Set(t)].sort(O)}var J=".ari",Er=".ari/tasks/*.json",Gy=".ari/tasks/*.md",rt=".ari/config.json",ho="ids",YP=`${J}/`,Ka="tasks",Hy="knowledge",Uy="packs",XP="ari",$d="active.json",zP="journal",Ky=".md",By=".json",Vy=".md",Ed=".yaml",ZP=".jsonl",Td=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Wy=`
131
+ `,QP=".ari-",tN=".tmp",eN="ENOENT",Jy="EEXIST",nN=new Set(["EPERM","ENOTSUP","ENOSYS","EXDEV"]),rN="locks",oN=".lock";function yo(t){return t===J||t.startsWith(YP)}function ne(t){return t.filter((e)=>!yo(e))}function ko(t){if(Cn(Rt(t,J)))return;throw new m("Ariadne is not initialised in this repository","Run 'ari init'")}function qy(){return pt(Tt)}function M(t){ko(t);let e=Rt(t,rt);if(!Cn(e))return vr({});return vr(Id(e,rt,"Fix the JSON syntax of .ari/config.json"))}function xd(t){return Td.test(t)}function qn(t){if(xd(t))return t;throw new m(`"${t}" is not a task id`,"Task ids are lower-case words joined by hyphens; run 'ari list'")}function It(t){return`${J}/${Ka}/${qn(t)}${Ky}`}function Rn(t){return`${J}/${Ka}/${qn(t)}${By}`}function Ad(t){return`${J}/${Uy}/${t}${Ed}`}function de(t){return ko(t),Wa(Rt(t,J,Ka),Ky)}function In(t){return ko(t),Wa(Rt(t,J,Ka),By)}function it(t,e,n){ko(t);let r=Rt(t,It(e));if(!Cn(r))throw new m(`Task "${e}" does not exist`,"Run 'ari list' to see the tasks of this repository");let o=Rs(r,"utf8");return{contractText:o,task:{contract:Aa(e,o,n),record:On(t,e)}}}function Pt(t,e){let n={invalid:[],tasks:[]};for(let r of de(t))try{n.tasks.push(it(t,r,e).task)}catch(o){if(!(o instanceof m))throw o;n.invalid.push({hint:o.hint??"",id:r,problem:o.message})}return n}function Yy(t,e,n,r){let{id:o}=n,s=It(o),i=()=>new m(`Task "${o}" already exists at ${s}`,"Run 'ari list'");md(ek(e,o),o,()=>{if(Cn(Rt(t,s))||!tk(t,o))throw i();zy(t,n),Yn(Rt(t,s),r,i)})}function Xy(t){let e=de(t);return[...e,...In(t).filter((n)=>!e.includes(n)&&!tk(t,n))]}function zy(t,e){Tr(Rt(t,Rn(e.id)),pt(e))}function Vt(t,e,n,r){return md(ek(e,n),n,()=>{let o=r(On(t,n));return zy(t,o),o})}function Gt(t){ko(t);let e=Rt(t,J,Uy);return Wa(e,Ed).map((n)=>{let r=Ad(n),o=Ia(Rs(Rt(t,r),"utf8"),r);if(o.name===n)return o;throw new m(`${r} declares the pack "${o.name}"`,`Rename the file to ${o.name}${Ed} or fix its name`)})}function an(t){return ko(t),Wa(Rt(t,J,Hy),Vy)}function pe(t){return an(t).map((e)=>Ca(e,Rs(nk(t,e),"utf8")))}function Ba(t,e){if(!Td.test(e.id))throw Error(`Knowledge entry id "${e.id}" is not a slug`);let n=nk(t,e.id);Yn(n,br(e),()=>Error(`Knowledge entry ${n} already exists`))}async function P(t){return sn(t,XP)}function gt(t){let e=Rt(t,$d);if(!Cn(e))return null;let n=`Delete ${e}, then run 'ari next', which offers to adopt the task again`,r=Id(e,e,n);return At("active task pointer",n,()=>{let o=T(r,"pointer",["since","task"]);return{since:x(o.since,"since"),task:x(o.task,"task")}})}function Cd(t,e){Tr(Rt(t,$d),pt(e))}function Zy(t){Ua(Rt(t,$d),{force:!0})}function $r(t,e){let n=Rd(t,e.task);Ly(Fy(n),{recursive:!0});let r=JSON.stringify(JSON.parse(pt(e)));VP(n,`${r}${Wy}`)}function Va(t,e){Ua(Rd(t,e),{force:!0})}function Qy(t,e){let n=Rd(t,e);if(!Cn(n))return[];return Rs(n,"utf8").split(Wy).flatMap((r)=>{if(r.trim().length===0)return[];let o=sN(r);return o===null||o.task!==e?[]:[o]})}function sN(t){try{return Da(JSON.parse(t))}catch(e){if(e instanceof SyntaxError||e instanceof b)return null;throw e}}function Rd(t,e){return Rt(t,zP,`${qn(e)}${ZP}`)}function On(t,e){let n=Rn(e),r=Rt(t,n);if(!Cn(r))throw new m(`Task "${e}" has a contract but no record at ${n}`,`Restore ${n} from git; only ari writes it`);return Sy(e,Id(r,n,`Restore ${n} from git; only ari writes it`))}function tk(t,e){if(!Cn(Rt(t,Rn(e))))return!0;try{return cy(On(t,e))}catch(n){if(n instanceof m)return!1;throw n}}function ek(t,e){return Rt(t,rN,`${qn(e)}${oN}`)}function nk(t,e){return Rt(t,J,Hy,`${e}${Vy}`)}function Id(t,e,n){let r=Rs(t,"utf8");try{return JSON.parse(r)}catch(o){let s=o instanceof Error?o.message:String(o);throw new m(`${e} is not valid JSON (${s})`,n)}}function Wa(t,e){return iN(t).filter((r)=>r.endsWith(e)).map((r)=>qP(r,e)).filter((r)=>Td.test(r)).sort(O)}function iN(t){try{return JP(t)}catch(e){if(e.code===eN)return[];throw e}}function Tr(t,e){let n=rk(t);try{jy(n,e),My(n,t)}catch(r){throw Ua(n,{force:!0}),r}}function Yn(t,e,n){let r=rk(t);try{jy(r,e),aN(r,t)}catch(o){if(o.code===Jy)throw n();throw o}finally{Ua(r,{force:!0})}}function aN(t,e){try{WP(t,e)}catch(n){if(!nN.has(n.code??""))throw n;if(Cn(e))throw Object.assign(Error(`${e} already exists`),{code:Jy});My(t,e)}}function rk(t){let e=Fy(t);return Ly(e,{recursive:!0}),Rt(e,`${QP}${BP()}${tN}`)}var uN=1,dN=/^[\w@%+=:,./{}-]+$/,Od="the base set of variables only",pN="the whole environment, with every token in it",gN="{base}",mN="{changed-files}",fN="{verdicts-file}",hN="argus sends the source of the changed files to the model endpoint";function ok(t,e){let n=yN(t),r={agents:e.agents,packCommands:n,regressionSetup:e.regression.setup,reviewCommand:e.review.command,...e.review.argus===void 0?{}:{reviewArgus:e.review.argus},version:uN};return{commands:kN(e,n),sha256:Z(pt(r))}}function yN(t){if(!cN(lN(t,J)))return[];return Gt(t).sort((e,n)=>O(e.name,n.name)).flatMap((e)=>e.stages.flatMap((n)=>n.gates.flatMap((r)=>r.kind==="command"?[{pack:e.name,run:r.run,stage:n.name}]:[])))}function kN(t,e){let n=Object.entries(t.agents).flatMap(([a,c])=>wN(a,c)),r=t.review.command===null?[]:[wo("review.command",t.review.command)],o=SN(t.review.argus),s=t.regression.setup.map((a,c)=>wo(`regression.setup[${c}]`,a)),i=e.map(({pack:a,run:c,stage:l})=>wo(`.ari/packs/${a}: stage ${l}, command gate`,c));return[...n,...r,...o,...s,...i]}function wN(t,e){let n=vN(e),r=e.reviewCommand===void 0?[]:[wo(`agents.${t}.reviewCommand`,_d(e.reviewCommand),n)];return[wo(`agents.${t}.command`,_d(e.command),n),...r]}function SN(t){if(t===void 0)return[];let e={base:gN,configPath:t.config,file:fN,only:mN};return va(t).map((n)=>{let r=`${Od} and ${ba(n).join(", ")}, when set`,o=n==="run"?`${r}; ${hN}`:r;return wo("review.argus.command",_d(so(t,n,e)),o)})}function vN(t){if(t.inheritEnv===!0)return pN;return t.env===void 0||t.env.length===0?Od:`${Od} and ${t.env.join(", ")}`}function wo(t,e,n=null){return{command:e,environment:n,source:t}}function _d(t){return t.map((e)=>dN.test(e)?e:JSON.stringify(e)).join(" ")}var xr="ARI_TRUST_CONFIG",bN="1";function So(){return process.env[xr]===bN}function Be(t,e){let n=ok(t,e),r=_h(t),o=EN(n.commands.length,n.sha256,r?.sha256??null);return{commands:n.commands,root:bs(t),sha256:n.sha256,state:o,trustedAt:r?.trustedAt??null,trustedSha256:r?.sha256??null}}function _n(t){return t.state==="untrusted"||t.state==="changed"}function vo(t,e){let n=Be(t,e);if(n.state==="not-required")return n;let r=Ph(t,n.sha256);return{...n,state:"trusted",trustedAt:r.trustedAt,trustedSha256:r.sha256}}function sk(t){return Nh(t)}function EN(t,e,n){if(t===0)return"not-required";if(n===null)return"untrusted";return n===e?"trusted":"changed"}var $N=1,TN="Commands that ari would run for this repository";async function Xn({config:t,root:e},n){if(So())return;let r=Be(e,t);if(!_n(r))return;if(ur()&&await Nd(r.root,r.commands)){vo(e,t);return}let o=r.state==="changed"?"the commands in .ari changed since you trusted them":"nobody has trusted the commands in .ari on this machine";throw new m(`Cannot ${n}: ${o}`,`Review them with 'ari trust', trust them with 'ari trust --yes', or set ${xr}=1 where the repository is already trusted, such as in CI`,$N,{tag:"ConfigNotTrusted"})}function Pd(t){return t.flatMap(({command:e,environment:n,source:r})=>[`${r}: ${e}`,...n===null?[]:[` environment: ${n}`]])}async function Nd(t,e){Nt(Pd(e).join(`
132
+ `),TN);try{return await Ee({initialValue:!1,message:`Trust these commands in ${t}?`})}catch(n){if(n instanceof vt)return!1;throw n}}var xN=2,Ar=1,AN=5000,CN=1000,RN=2147483647,IN=1048576,ON=["HOME","PATH","USER","LOGNAME","SHELL","TERM","TMPDIR","TZ","LANG","LC_ALL","LC_CTYPE","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_CACHE_HOME","XDG_STATE_HOME"];function Cr(t,e){let n=e.agent??e.route?.agent;if(n===void 0)throw new m(`No ${e.role} agent is chosen`,e.role==="task"?"Pass --agent <name>, or set routing.default in .ari/config.json":"Pass --agent <name>, or set routing.review or review.agent in .ari/config.json",Ar,{tag:"NoAgentChosen"});let r=t.agents[n];if(r===void 0)throw new m(`No agent "${n}" is configured`,`Run 'ari agents add <preset> --name ${n}', or add "agents": { "${n}": { "command": ["<binary>", "<non-interactive flag>", "{prompt}"] } } to .ari/config.json`,Ar,{tag:"AgentNotConfigured"});if(!Sr(r).includes(e.role))throw new m(`Agent "${n}" is not configured as a ${e.role} agent`,`Add "${e.role}" to agents.${n}.roles in .ari/config.json`,Ar,{tag:"AgentRoleMismatch"});let o=e.agent===void 0?e.route?.model:void 0,s=e.model??o??r.model??null,i={config:r,model:s,name:n,role:e.role};return Ja(i,""),i}function Ja(t,e){let{config:n,model:r,name:o,role:s}=t,i=s==="review"&&n.reviewCommand!==void 0?"reviewCommand":"command",a=n[i]??n.command,c=`agents.${o}.${i}`;if(!a.some((p)=>p.includes(Zt)))throw new m(`The command of agent "${o}" has no ${Zt} argument`,`Put ${Zt} where the agent takes its prompt in ${c}`,Ar,{tag:"AgentCommandInvalid"});let l=a.some((p)=>p.includes(vs));if(l&&r===null)throw new m(`Agent "${o}" needs a model for ${vs} in ${c}`,`Set agents.${o}.model, give a model in routing, or pass --model`,Ar,{tag:"AgentCommandInvalid"});if(!l&&r!==null&&n.modelFlag===void 0)throw new m(`Agent "${o}" has no way to take the model "${r}"`,`Put ${vs} in ${c}, or set agents.${o}.modelFlag`,Ar,{tag:"AgentCommandInvalid"});let u=a.map((p)=>p.replaceAll(Zt,()=>e).replaceAll(vs,()=>r??"")),d=!l&&r!==null&&n.modelFlag!==void 0?[n.modelFlag,r]:[];return[...u,...d]}function qa(t){if(t.inheritEnv===!0)return{...process.env,...Fe};return Is(t.env??[])}function Is(t){let e=[...ON,...t].filter((n)=>!(n in Fe));return Object.fromEntries(e.flatMap((n)=>process.env[n]===void 0?[]:[[n,process.env[n]]]))}async function Ya(t,e,n){let r=Ja(t,e),{name:o}=t;return Dd(r,{...n,action:`start the agent "${o}"`,maxCaptureBytes:IN,reapGroup:t.role==="review",startFailure:(s,i)=>new m(`Agent "${o}" could not start: ${s}`,`Fix agents.${o}.command in .ari/config.json`,Ar,{cause:i,tag:"AgentStartFailed"}),timeoutSeconds:n.timeoutSeconds??t.config.timeoutSeconds})}async function Dd(t,e){await Xn(e.trust,e.action);let n=_N(t,e),r=Qt(()=>ik(n)),o={timedOut:!1},s=e.timeoutSeconds,i=s===void 0?void 0:setTimeout(()=>{o.timedOut=!0,ik(n)},Math.min(s*CN,RN)),a=e.stdout==="capture"?PN(n,e.maxCaptureBytes):Promise.resolve({overflowed:!1,text:""}),c=await n.exited;if(clearTimeout(i),Ch())await new Promise(()=>{return});if(e.reapGroup)Ge(n.pid,"SIGKILL");r();let{overflowed:l,text:u}=await a;return{exitCode:c,overflowed:l,stdout:u,timedOut:o.timedOut}}function _N(t,e){let n=e.stdout==="inherit"?"inherit":e.stdout==="capture"?"pipe":xN;try{return Bun.spawn(t,{cwd:e.cwd,detached:!0,env:e.environment,stderr:"inherit",stdin:"ignore",stdout:n})}catch(r){throw e.startFailure(t[0]??"",r)}}async function PN(t,e){let n=t.stdout;if(!(n instanceof ReadableStream))return{overflowed:!1,text:""};let r=[],o=0,s=!1;for await(let i of n){if(o+i.length>e){s=!0,Ge(t.pid,"SIGKILL");break}r.push(i),o+=i.length}return{overflowed:s,text:new TextDecoder().decode(Buffer.concat(r))}}async function ik(t){Ge(t.pid,"SIGTERM"),await Promise.race([t.exited,Bun.sleep(AN)]),Ge(t.pid,"SIGKILL")}var bo=["task","review","both"],Ld="--model",Ve=[{binary:"claude",command:["claude","-p",Zt,"--permission-mode","acceptEdits"],label:"Claude Code",modelFlag:Ld,name:"claude",reviewCommand:["claude","-p",Zt,"--tools","Read,Grep,Glob","--permission-mode","dontAsk"]},{binary:"codex",command:["codex","exec","--sandbox","workspace-write",Zt],label:"Codex CLI",modelFlag:Ld,name:"codex",reviewCommand:["codex","exec","--sandbox","read-only",Zt]},{binary:"gemini",command:["gemini","--approval-mode","auto_edit","-p",Zt],label:"Gemini CLI",modelFlag:Ld,name:"gemini",reviewCommand:["gemini","--approval-mode","plan","-p",Zt]}];function ak(t){let e=Ve.find((n)=>n.name===t);if(e!==void 0)return e;throw new v(`ari has no agent preset "${t}"`,`Choose one of: ${Ve.map((n)=>n.name).join(", ")}, or add the agent to .ari/config.json yourself`)}function ck(t){let e=t??"task",n=bo.find((r)=>r===e);if(n!==void 0)return n;throw new v(`Unknown role "${e}"`,`Choose one of: ${bo.join(", ")}`)}function Eo(t,e,n){let r=n===void 0?{}:{model:n};switch(e){case"task":return{command:t.command,...r,modelFlag:t.modelFlag,roles:["task"]};case"review":return{command:t.reviewCommand,...r,modelFlag:t.modelFlag,roles:["review"]};case"both":return{command:t.command,reviewCommand:t.reviewCommand,...r,modelFlag:t.modelFlag,roles:["task","review"]}}}var NN="--version",DN=5000,LN=200;async function lk(){return Promise.all(Ve.map(MN))}async function MN(t){return{...await Os([t.binary]),label:t.label,preset:t.name}}async function Os(t){for(let e of t){let n=Bun.which(e);if(n!==null)return{binary:e,path:n,version:await jN(n)}}return{binary:t[0]??"",path:null,version:null}}async function jN(t){let e;try{e=Bun.spawn([t,NN],{detached:!0,env:{...Is([]),...Fe},stderr:"ignore",stdin:"ignore",stdout:"pipe"})}catch{return null}let n=()=>Ge(e.pid,"SIGKILL"),r=Qt(n),o=setTimeout(n,DN),[s,i]=await Promise.all([new Response(e.stdout).text(),e.exited]);clearTimeout(o),n(),r();let a=s.split(`
133
+ `).map((c)=>c.trim()).find((c)=>c.length>0);return i===0&&a!==void 0?a.slice(0,LN):null}import{isDeepStrictEqual as S0}from"util";import{randomUUID as u0}from"crypto";import{chmodSync as d0,existsSync as Ud,mkdirSync as p0,readFileSync as vk,renameSync as g0,rmSync as m0,statSync as f0,writeFileSync as h0}from"fs";import{basename as y0,dirname as Sk,join as Kd}from"path";import{isDeepStrictEqual as dk}from"util";var FN=/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g,GN=/"(?:[^"\\\n]|\\.)*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,HN=/[^\r\n]/g,UN=/(?:^|\n)([\t ]*)[^\n]*$/,KN=/^[\t ]*\r?\n/,BN=/^[\t ]+(?=\S)/m,VN=" ",_s=",";function Md(t){return t.replace(GN,(e)=>e.startsWith('"')?e:e.replace(HN," "))}function Xa(t,e){let n=BN.exec(t)?.[0]??VN,r=t.includes(`\r
134
+ `)?`\r
135
+ `:`
136
+ `,o=(i,a)=>{let c=t.slice(i.start,i.end);if(dk(i.value,a))return c;let l=r+(UN.exec(t.slice(0,i.start))?.[1]??""),u=(A,R)=>JSON.stringify(A,null,n).replaceAll(`
137
+ `,R);if(!uk(i.value)||!uk(a)||Array.isArray(i.value)!==Array.isArray(a))return u(a,l);let d=WN(i,a),p=[],g="",f=i.start+1,y=(A)=>{let R=t.slice(f,A);return g+(g.length===0||KN.test(R)?"":r)+R};for(let A of i.entries){let R=y(A.start),B=d.get(A);if(g="",B!==void 0){let _t=o(A.node,a[B]);p.push(R+t.slice(A.start,A.node.start)+_t+t.slice(A.node.end,A.end))}else if(R.trim().length>0)g=R.trimEnd();f=t[A.end]===_s?A.end+1:A.end}let S=new Set(d.values()),I=l+n,C=Object.keys(a).filter((A)=>!S.has(A)).map((A)=>{let R=Array.isArray(a)?"":`${JSON.stringify(A)}: `;return I+R+u(a[A],I)}),q=y(i.end-1),G=q.trimEnd(),N=C.length===0?q.slice(G.length):l,H=p.length>0&&C.length>0?_s:"";return c[0]+p.join(_s)+H+G+C.join(_s)+N+c.at(-1)},s=JN(Md(t));return t.slice(0,s.start)+o(s,JSON.parse(JSON.stringify(e)))+t.slice(s.end)}function WN({entries:t},e){let n=Array.isArray(e)&&e.length<t.length,r=new Map;for(let o of t){let s=n?String(r.size):o.key;if((!n||dk(o.node.value,e[s]))&&Object.hasOwn(e,s))r.set(o,s)}return r}function uk(t){return typeof t==="object"&&t!==null}function JN(t){let e=[...t.matchAll(FN)],n=0,r=()=>{let s=e[n];if(s===void 0)throw Error("Unexpected end of JSON");return n+=1,s},o=()=>{let s=r(),i=s[0];if(i!=="{"&&i!=="[")return{end:s.index+i.length,entries:[],start:s.index,value:JSON.parse(i)};let a=i==="{"?"}":"]",c=[];while(e[n]!==void 0&&e[n]?.[0]!==a){let u=e[n]?.index??0,d=i==="{"?JSON.parse(r()[0]):String(c.length);if(i==="{")r();let p=o(),g=e[n]?.[0]===_s?r().index:p.end;c.push({end:g,key:d,node:p,start:u})}let l=r().index+1;return{end:l,entries:c,start:s.index,value:JSON.parse(t.slice(s.index,l))}};return o()}import{existsSync as gk,readlinkSync as XN,realpathSync as zN,statSync as ZN}from"fs";import{basename as QN,dirname as Ps,isAbsolute as t0,join as Za,relative as e0,resolve as mk,sep as n0}from"path";async function za(t){let e=M(t),n=await P(t),r={config:e,drift:null,root:t,state:n,task:null},o=gt(n)?.task??null;if(o===null)return r;if(!de(t).includes(o)){if(In(t).includes(o)&&pk(On(t,o)))throw qN(o);return r}let{contractText:s,task:i}=it(t,o,e);if(!pk(i.record))return r;return{...r,drift:YN(i,s),task:i}}function pk({status:t}){return t==="active"||t==="blocked"}function qN(t){return new m(`the contract of the active task "${t}" is missing`,`Restore ${It(t)}`)}function YN({contract:t,record:e},n){if(e.contractHash===null||Bt(n)===e.contractHash)return null;return`the contract of task "${t.id}" changed after its approval; run 'ari amend ${t.id} --reason <text>' or restore ${It(t.id)}`}var fk=".git",r0="..",Qa=0,o0=1,hk=128,s0=40,i0=["rev-parse","--show-toplevel","--absolute-git-dir","--git-common-dir"];function yk(){let t=new Map,e=new Map,n=new Map,r=[],o=(c)=>jd(t,c,()=>a0(c)),s=(c)=>jd(e,c.root,async()=>{let l=await l0(c);return r.push(l),l}),i=async(c)=>{let l=[],u=null;for(let d of kk(c).filter((p)=>gk(Za(p,fk)))){let p=await o(d);if(p===null)continue;if(u!==null&&await c0(u,p))break;if(u=p,gk(Za(d,J)))l.push(await s(p))}return l},a=(c)=>{let l=wk(Ht(c));return jd(n,l,()=>i(l))};return{at:async(c)=>(await a(c))[0]??null,governing:a,opened:()=>r}}function Ht(t,e=s0){let n=Gd(()=>zN(t));if(n!==null)return n;let r=Ps(t);if(r===t)return t;let o=Za(Ht(r,e),QN(t)),s=e>0?Fd(o):null;return s===null?o:Ht(mk(Ps(o),s),e-1)}function Fd(t){return Gd(()=>XN(t))}function tc(t){return Gd(()=>ZN(t).isDirectory())??!1}function cn(t,e){let n=e0(t,e),r=n.split(n0);return r[0]===r0||t0(n)?null:r.join("/")}function Gd(t){try{return t()}catch{return null}}function jd(t,e,n){let r=t.get(e);if(r!==void 0)return r;let o=n();return t.set(e,o),o}function kk(t){let e=Ps(t);return e===t?[t]:[t,...kk(e)]}function wk(t){return tc(t)||Ps(t)===t?t:wk(Ps(t))}async function a0(t){let e=await F(t,i0,{allowedExitCodes:[Qa,hk]});if(e.exitCode!==Qa)return{fault:`git cannot read the repository at ${t}`,gitDirectories:[Za(t,fk)],root:t};let[n="",r="",o=""]=e.stdout.split(`
138
+ `);if(Ht(n)!==t)return null;let s=[r,mk(t,o)].map((i)=>Ht(i));return{fault:null,gitDirectories:[...new Set(s)],root:t}}async function c0(t,e){if(t.fault===null&&t.gitDirectories.at(-1)===e.gitDirectories.at(-1))return!0;if(e.fault!==null)return!1;return(await F(e.root,["check-ignore","-q","--",t.root],{allowedExitCodes:[Qa,o0,hk]})).exitCode===Qa}async function l0({fault:t,gitDirectories:e,root:n}){if(t!==null)return{fault:t,gitDirectories:e,root:n,workspace:null};try{return{fault:null,gitDirectories:e,root:n,workspace:await za(n)}}catch(r){if(!(r instanceof m))throw r;return{fault:Hd(r),gitDirectories:e,root:n,workspace:null}}}function Hd({hint:t,message:e}){return t===void 0?e:`${e} (${t})`}var k0=2;function ec(t,e){let n=W(t,e);return n===null?null:re(e,n)}function W(t,e){let n=Kd(t,e);return Ud(n)?vk(n,"utf8"):null}function re(t,e){let n;try{n=JSON.parse(Md(e))}catch(r){let o=r instanceof Error?r.message:String(r);throw new m(`${t} is not valid JSON (${o})`,`Fix ${t}, then run the command again`)}if(z(n))return n;throw new m(`${t} does not hold a JSON object`,`Fix ${t}, then run the command again`)}function nc(t,e,n){if(!Ud(t))return n;try{return e(JSON.parse(vk(t,"utf8")))}catch{return n}}function Bd(t,e,n){return Ce(t,e,zn(W(t,e),n))}function zn(t,e){return t===null?`${JSON.stringify(e,null,k0)}
139
+ `:Xa(t,e)}function Ce(t,e,n){let r=Kd(t,e),o=W(t,e),s=Ns(o,n);if(s!=="unchanged")Rr(r,n,w0(r));return s}function Ns(t,e){if(t===e)return"unchanged";return t===null?"created":"updated"}function Rr(t,e,n){let r=Ht(t);p0(Sk(r),{recursive:!0});let o=Kd(Sk(r),`.${y0(r)}.${process.pid}.${u0()}.tmp`);try{if(h0(o,e),n!==void 0)d0(o,n);g0(o,r)}finally{m0(o,{force:!0})}}function w0(t){return Ud(t)?f0(t).mode:void 0}function z(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}var Vd="agents",bk=1;function Ek(t,e){let n=ak(e.preset),r=e.name??n.name,o=Eo(n,e.role,e.model),{agents:s,settings:i}=xk(t),a=s[r];if(a!==void 0&&S0(a,o))return{action:"unchanged",entry:o,name:r,preset:n.name};if(a!==void 0)throw new m(`agents.${r} already exists with other settings`,`Choose another name with --name, or run 'ari agents remove ${r}' first`,bk,{tag:"AgentExists"});let c={...i,[Vd]:{...s,[r]:o}};return Ak(c,`ari cannot add agent "${r}"`,"Choose another name with --name"),{action:Bd(t,rt,c),entry:o,name:r,preset:n.name}}function $k(t,e){let{agents:n,settings:r}=xk(t);if(n[e]===void 0)return{action:"unchanged",name:e};let{[e]:o,...s}=n,i={...r,[Vd]:s};return Ak(i,`ari cannot remove agent "${e}"`,`Change the routing and review settings that name "${e}" in ${rt} first`),Bd(t,rt,i),{action:"removed",name:e}}function Tk(t){let e=M(t);return{agents:Object.entries(e.agents).sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>({command:o.command,env:o.env??[],inheritEnv:o.inheritEnv===!0,model:o.model??null,modelFlag:o.modelFlag??null,name:r,reviewCommand:o.reviewCommand??null,roles:Sr(o),timeoutSeconds:o.timeoutSeconds??null})),routing:e.routing}}function rc(t){if(t===null)return"none";return t.model===null?t.agent:`${t.agent} (${t.model})`}function xk(t){M(t);let e=ec(t,rt)??{},n=e[Vd]??{};return{agents:z(n)?n:{},settings:e}}function Ak(t,e,n){let r=Ea(t);if(r!==null)throw new m(`${e}: ${r}`,n,bk,{tag:"InvalidConfig"})}import{existsSync as v0}from"fs";import{join as b0}from"path";async function Ir(t,e){let n=E0(t),r=await e();if(n)$0(t);return r}function E0(t){if(!v0(b0(t,J)))return!0;try{return!_n(Be(t,M(t)))}catch(e){if(e instanceof m)return!1;throw e}}function $0(t){try{let e=M(t);if(_n(Be(t,e)))vo(t,e)}catch(e){if(!(e instanceof m))throw e}}var T0=" ";async function _(){return Jn(process.cwd())}function We(t){if(t===void 0)return[];return t.split(",").map((e)=>e.trim()).filter((e)=>e.length>0)}function ln(t,e,n){if(t!==void 0&&t.trim().length>0)return t;throw new v(`${e} is required`,`Run ${n}`)}function Re(t,e){if(t===void 0||t.trim().length>0)return t;throw new v(`${e} must not be empty`,`Leave ${e} out, or give it a value`)}function oc(t){return t.flatMap((e)=>x0(e)).join(`
140
+ `)}function x0(t){let e=`${t.ok?"pass":"FAIL"} ${t.gate}: ${t.summary}`;if(t.ok)return[e];let n=t.details.map((o)=>` - ${o}`),r=t.checks.filter((o)=>!o.ok&&o.outputTail.length>0).flatMap((o)=>[` ${o.name} (${o.command}) output:`,...o.outputTail.trimEnd().split(`
141
+ `).map((s)=>`${T0}${s}`)]);return[e,...n,...r]}var A0=Ve.map((t)=>t.name).join(", "),C0=E({description:"List the configured agents, their roles and the routing; environment values are never shown",examples:["ari agents list --json"],json:!0,name:"list",run:async(t)=>{t.output.result(Tk(await _()),_0)}}),R0=E({args:j({model:{description:"Model the agent uses unless the routing or --model says otherwise",type:"string"},name:{description:"Name in config.agents (default: the preset's name)",type:"string"},role:{description:`What the agent does: ${bo.join(", ")} (default: task)`,type:"string"}}),description:"Add an agent from a preset with least-privilege, non-interactive flags to .ari/config.json",examples:["ari agents add claude","ari agents add codex --name codex-review --role review --model gpt-5.5","ari agents add gemini --role both"],json:!0,name:"add",positionals:st({preset:{description:`Preset: ${A0}`,required:!0}}),run:async(t)=>{let e=await _(),n=await Ir(e,()=>Ek(e,{model:Re(t.args.model,"--model"),name:Re(t.args.name,"--name"),preset:t.positionals.preset,role:ck(t.args.role)}));t.output.result(n,Rk)}}),I0=E({description:"Remove an agent from .ari/config.json unless the routing or the review gate still names it",examples:["ari agents remove codex-review"],json:!0,name:"remove",positionals:st({name:{description:"Agent name in config.agents",required:!0}}),run:async(t)=>{let e=await _();t.output.result(await Ir(e,()=>$k(e,t.positionals.name)),Rk)}}),O0=E({description:"Find the preset agents' binaries on PATH and their versions, running only '<binary> --version'",examples:["ari agents detect --json"],json:!0,name:"detect",run:async(t)=>{t.output.result({agents:await lk()},({agents:e})=>e.map(P0).join(`
142
+ `))}}),Ck=E({description:"Configure the agents that 'ari run' and 'ari review' start",name:"agents",subcommands:[C0,R0,I0,O0]});function _0(t){let e=t.agents.map((a)=>{let c=a.model===null?"":`, model ${a.model}`,l=a.inheritEnv?", inherits the whole environment":"";return`${a.name} ${a.roles.join("+")}${c}${l}: ${a.command.join(" ")}`}),{default:n,review:r,stages:o}=t.routing,s=Object.entries(o).map(([a,c])=>` stage ${a}: ${rc(c)}`),i=[`routing default: ${rc(n)}`,...s,`routing review: ${rc(r)}`];return[...e.length===0?["No agents are configured; run 'ari agents add <preset>'"]:e,...i].join(`
143
+ `)}function Rk(t){return`Agent "${t.name}" ${t.action} in .ari/config.json`}function P0(t){if(t.path===null)return`${t.preset} not found on PATH`;return`${t.preset} ${t.path} ${t.version??"version unknown"}`}import{existsSync as CH}from"fs";import{join as RH}from"path";import{resolve as L0}from"path";var N0=/^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)/,D0=/\r?\n/;function Ds(t,e){return typeof t==="object"&&t!==null?t[e]:void 0}function Wt(t,e){let n=Ds(t,e);return typeof n==="string"?n:null}function sc(t,e){return Wt(t,"cwd")??e}function Ik(t){return t.split(D0).flatMap((e)=>N0.exec(e.trim())?.[1]?.trim()??[])}function Ls(t,e,n){return{command:n.command??null,cwd:e,event:t,paths:n.paths??[],tool:n.tool??null}}var Wd=["before-edit","before-shell","after-tool","stop","pre-compact","session-start"],Pn=new Set(["before-edit","before-shell"]);function Ok(t){return Wd.includes(t)}var M0=30,j0=120,F0=new Set(["stop","pre-compact"]),G0=1000,H0="apply_patch",_k="run_shell_command";function mt(t,e,n=null){let r=F0.has(t)?j0:M0;return{agentEvent:e,event:t,matcher:n,timeoutSeconds:r}}var Pk=[mt("stop","Stop"),mt("pre-compact","PreCompact","manual|auto"),mt("session-start","SessionStart","startup|resume|clear|compact|fork")];function qd(t){return{decision:"block",reason:t}}function Jd(t){return(e)=>({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t,permissionDecisionReason:e}})}function Nk(t,e,n){let r=Ds(e,"tool_input"),o=Wt(r,"file_path")??Wt(r,"notebook_path"),s=Wt(r,"command"),i=Wt(e,"tool_name"),a=i===_k?Wt(r,"dir_path"):null;return Ls(t,L0(sc(e,n),a??""),{command:s,paths:o===null?[]:[o],tool:i})}function U0(t,e,n){let r=Wt(e,"tool_name"),o=Wt(Ds(e,"tool_input"),"command"),s=r===H0?{paths:Ik(o??"")}:{command:o};return Ls(t,sc(e,n),{...s,tool:r})}function K0(t,e,n){let r=Wt(e,"cwd")??Wt(Ds(e,"workspace_roots"),"0")??n,o=Wt(e,"file_path");return Ls(t,r,{command:Wt(e,"command"),paths:t==="after-tool"&&o!==null?[o]:[]})}function B0(t,e,n){return Ls(t,sc(e,n),{command:Wt(V0(e),"command"),tool:Wt(e,"toolName")})}function V0({toolArgs:t}){if(typeof t!=="string")return t;try{return JSON.parse(t)}catch{return null}}function Yd({answers:t},e,n){let r=W0(t,e,n);return typeof r==="string"?r:JSON.stringify(r)}function W0(t,e,n){switch(n.kind){case"allow":return t.allow?.(e)??"";case"context":return t.context(n.text);case"ask":return(t.ask??t.deny)(n.reason);case"block":return t.block(n.reason);case"deny":return t.deny(n.reason)}}var J0={answers:{ask:Jd("ask"),block:qd,context:(t)=>t,deny:Jd("deny")},file:".claude/settings.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,...Pn.has(e)?{onFailure:"block"}:{},timeout:n,type:"command"}),label:"Claude Code",layout:"grouped",name:"claude",parse:Nk,registrations:[mt("before-edit","PreToolUse","Edit|Write|NotebookEdit"),mt("before-shell","PreToolUse","Bash|PowerShell|Monitor"),mt("after-tool","PostToolUse","Edit|Write|NotebookEdit|Bash|PowerShell|Monitor"),...Pk],support:"verified"},q0={answers:{allow:(t)=>t==="stop"?{}:"",block:qd,context:(t)=>t,deny:Jd("deny")},file:".codex/hooks.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,statusMessage:`ari ${e}`,timeout:n,type:"command"}),label:"Codex CLI",layout:"grouped",name:"codex",parse:U0,registrations:[mt("before-edit","PreToolUse","^apply_patch$"),mt("before-shell","PreToolUse","^Bash$"),mt("after-tool","PostToolUse","^(Bash|apply_patch)$"),...Pk],support:"verified"},Y0={answers:{block:(t)=>({decision:"deny",reason:t}),context:(t)=>({hookSpecificOutput:{additionalContext:t}}),deny:(t)=>({decision:"deny",reason:t})},file:".gemini/settings.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,name:`ari-${e}`,timeout:n*G0,type:"command"}),label:"Gemini CLI",layout:"grouped",name:"gemini",parse:Nk,registrations:[mt("before-edit","BeforeTool","write_file|replace"),mt("before-shell","BeforeTool",_k),mt("after-tool","AfterTool","write_file|replace|run_shell_command"),mt("stop","AfterAgent","*"),mt("pre-compact","PreCompress","*"),mt("session-start","SessionStart","*")],support:"verified"},X0={answers:{allow:(t)=>Pn.has(t)?{permission:"allow"}:{},block:(t)=>({followup_message:t}),context:(t)=>({additional_context:t}),deny:(t)=>({agent_message:t,permission:"deny",user_message:t})},file:".cursor/hooks.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,...Pn.has(e)?{failClosed:!0}:{},timeout:n}),label:"Cursor",layout:"flat",name:"cursor",parse:K0,registrations:[mt("before-shell","beforeShellExecution"),mt("after-tool","afterFileEdit"),mt("stop","stop"),mt("pre-compact","preCompact"),mt("session-start","sessionStart")],support:"partial"},z0={answers:{allow:(t)=>Pn.has(t)?{permissionDecision:"allow"}:"",block:qd,context:(t)=>({additionalContext:t}),deny:(t)=>({permissionDecision:"deny",permissionDecisionReason:t})},file:".github/hooks/ari.json",handler:(t,{matcher:e,timeoutSeconds:n})=>({bash:t,...e===null?{}:{matcher:e},powershell:t,timeoutSec:n,type:"command"}),label:"GitHub Copilot CLI",layout:"flat",name:"copilot",parse:B0,registrations:[mt("before-shell","preToolUse","bash|powershell"),mt("stop","agentStop"),mt("pre-compact","preCompact"),mt("session-start","sessionStart")],support:"partial"},Ie=[J0,q0,Y0,X0,z0];import{existsSync as Ms,readFileSync as jk,rmSync as Z0,statSync as Q0}from"fs";import{join as js,relative as zd}from"path";var Fk="# ari:managed",tD=493,eD=64,nD=1,Dk=0,$o=[{command:"ari scope --staged",name:"pre-commit"},{command:"ari verify",name:"pre-push"}],rD=["","."].flatMap((t)=>["yml","yaml","json","toml"].map((e)=>`${t}lefthook.${e}`)),Lk=".husky",Mk=/\.ya?ml$/,Gk=$o.map((t)=>t.name);async function To(t){let e=await sn(t,"hooks");return $o.every(({name:n})=>{let r=js(e,n);return Zd(r)&&Uk(r)})}async function ac(t){let e=await Fs(t);for(let n of e)if(n.action!=="unchanged")Rr(n.target,n.script,tD);return{agent:"git",files:e.map(({action:n,hook:r,path:o})=>({action:n,hook:r,path:o}))}}async function Fs(t){let e=await Qd(t);if(e!==null)throw new m(`This repository manages git hooks with ${e.name}; ari will not write hooks beside it`,e.hint);let n=await sn(t,"hooks"),r=$o.map((s)=>({hook:s,path:js(n,s.name),script:oD(s)})),o=r.filter(({path:s})=>Ms(s)&&!Zd(s));if(o.length>0){let s=o.map(({hook:i})=>i.name).join(", ");throw new m(`Unmanaged git hooks already exist: ${s}`,`Add the lines yourself: ${ic("").join("; ")}`)}return r.map(({hook:s,path:i,script:a})=>{let c=Ms(i);return{action:c&&jk(i,"utf8")===a&&Uk(i)?"unchanged":c?"updated":"created",hook:s.name,path:zd(t,i),script:a,target:i}})}async function Hk(t){return zd(t,await sn(t,"hooks"))}async function Gs(t){let e=await sn(t,"hooks");return $o.map(({name:n})=>{let r=js(e,n);return{action:Zd(r)?"removed":"unchanged",hook:n,path:zd(t,r),target:r}})}async function cc(t){let e=await Gs(t);for(let n of e)if(n.action==="removed")Z0(n.target);return{agent:"git",files:e.map(({action:n,hook:r,path:o})=>({action:n,hook:r,path:o}))}}function Zd(t){return Ms(t)&&jk(t,"utf8").includes(Fk)}function Uk(t){return(Q0(t).mode&eD)!==0}function oD(t){return["#!/bin/sh",Fk,"if ! command -v ari >/dev/null 2>&1; then",` echo "ari is not on PATH; install @r5n/ariadne or remove .git/hooks/${t.name}" >&2`," exit 1","fi",`exec ${t.command}`,""].join(`
144
+ `)}async function Qd(t){let e=await F(t,["config","--get","core.hooksPath"],{allowedExitCodes:[Dk,nD]}),n=e.stdout.trim();if(e.exitCode===Dk&&n.length>0)return Xd(`core.hooksPath (${n})`,ic(`${n}/`),"Add the lines yourself: ");let r=rD.find((o)=>Ms(js(t,o)));if(r!==void 0){let o=Mk.test(r)?sD():ic("lefthook ");return Xd(`lefthook (${r})`,o,Mk.test(r)?`Add to ${r}:
145
+ `:"Add the lines yourself: ")}if(Ms(js(t,Lk)))return Xd("husky",ic(`${Lk}/`),"Add the lines yourself: ");return null}function ic(t){return $o.map((e)=>`${t}${e.name}: ${e.command}`)}function Xd(t,e,n){let r=n.endsWith(`
133
146
  `)?`
134
- `:"; ";return{hint:`${n}${e.join(r)}`,lines:e,name:t}}function rP(){return to.flatMap((t)=>[`${t.name}:`," commands:",` ari-${t.name}:`,` run: ${t.command}`])}import{realpathSync as oP,rmSync as sP}from"fs";import{join as Ra}from"path";var Ia={read:q,remove:(t,e)=>{sP(oP(Ra(t,e)))},write:(t,e,n)=>{fe(t,e,n)}};function nd(){let t=new Map;return{read:(e,n)=>{let r=Ra(e,n);return t.has(r)?t.get(r)??null:q(e,n)},remove:(e,n)=>{t.set(Ra(e,n),null)},write:(e,n,r)=>{t.set(Ra(e,n),r)}}}var gs={kind:"none"},ms={kind:"delete"};function no(t,e){return{exact:e,kind:"write",text:t}}function Oa(t,e,n,r){switch(n.kind){case"none":return{action:"unchanged",restored:null};case"delete":return r.remove(t,e),{action:"removed",restored:null};case"write":{let o=ss(r.read(t,e),n.text);if(o!=="unchanged")r.write(t,e,n.text);return{action:o,restored:n.exact?"original":"entries"}}}}import{existsSync as iP,readFileSync as aP}from"fs";import{join as rd}from"path";var od="hooks.json",cP=384,Iy=Qm(zt({installed:gt(),original:gt().or(Nr())}));function Oy(t,e=od){let n=rd(t,e);if(!iP(n))return{state:"absent"};try{return{path:n,receipts:Iy(JSON.parse(aP(n,"utf8"))),state:"readable"}}catch{return{path:n,state:"unreadable"}}}function ro(t,e,n=od){return _y(t,n)[e]??null}function oo(t,e,n,r=od){let{[e]:o,...s}=_y(t,r);if(n===null&&o===void 0)return;let i=n===null?s:{...s,[e]:n};cr(rd(t,r),`${JSON.stringify(i)}
135
- `,cP)}function _y(t,e){return Ea(rd(t,e),Iy,{})}var lP="ari hook",uP=1;function sd(t,e){return`${lP} ${t} ${e}`}function Dy(t,e,n){let{file:r,name:o}=e,s=q(t,r),i=s===null?{}:Vt(r,s),a=ro(n,r),c=ad(i,e)?void 0:s,l=a?.installed===s?a?.original:c,u=fe(t,r,fs(e,s)),d=q(t,r)??"";return oo(n,r,l===void 0?null:{installed:d,original:l}),{action:u,agent:o,events:hs(e),file:r}}function fs(t,e){let n=e===null?{}:Vt(t.file,e);return Nn(e,Ly(n,t,t.registrations))}function _a(t,e,n){let{action:r}=id(t,e,{forget:!0,state:n,view:Ia});return{action:r,agent:e.name,file:e.file}}function dP(t,e,n){if(e===null)return gs;let r=Vt(t.file,e);if(!ad(r,t))return gs;if(n?.installed!==e)return no(Nn(e,Ly(r,t,[])),!1);return n.original===null?ms:no(n.original,!0)}function id(t,e,n){let{file:r}=e,{forget:o,state:s,view:i}=n,a=ro(s,r),c=Oa(t,r,dP(e,i.read(t,r),a),i);if(o)oo(s,r,null);return c}function Ye(t,e){let n=Ta(t,e.file);return n!==null&&ad(n,e)}function hs(t){return[...new Set(t.registrations.map((e)=>e.event))]}function ad({hooks:t},e){if(!Y(t))return!1;return Object.values(t).flat().some((n)=>My(n,e).length>0)}function Ly({hooks:t={},...e},n,r){if(!Y(t))throw Py(n,'"hooks" value that is not an object');let s=[...new Set([...Object.keys(t),...r.map(({agentEvent:a})=>a)])].flatMap((a)=>{let c=t[a]??[];if(!Array.isArray(c))throw Py(n,`hooks.${a} that is not a list`);let l=pP(c,n,r.filter(({agentEvent:u})=>u===a));return l.length===0&&c.length>0?[]:[[a,l]]}),i=n.layout==="flat"?{version:e.version??uP}:{};return{...e,...i,...s.length===0?{}:{hooks:Object.fromEntries(s)}}}function Py({file:t},e){return new g(`${t} has a ${e}`,`Fix ${t}`)}function pP(t,e,n){let r=new Set(n);return[...t.flatMap((s)=>{let i=My(s,e),a=[...r].filter(({event:c})=>i.includes(sd(e.name,c)));for(let c of a)r.delete(c);return[...gP(s,e),...a.map((c)=>Ny(e,c))]}),...[...r].map((s)=>Ny(e,s))]}function Ny(t,e){let n=t.handler(sd(t.name,e.event),e);if(t.layout==="flat")return n;return e.matcher===null?{hooks:[n]}:{hooks:[n],matcher:e.matcher}}function gP(t,e){let n=jy(t,e),r=n.filter((o)=>Fy(o,e).length===0);if(r.length===n.length)return[t];return r.length>0&&Y(t)?[{...t,hooks:r}]:[]}function My(t,e){return jy(t,e).flatMap((n)=>Fy(n,e))}function jy(t,{layout:e}){if(e==="flat")return[t];return Y(t)&&Array.isArray(t.hooks)?t.hooks:[]}function Fy(t,{name:e}){let n=Y(t)?Object.values(t):[],r=sd(e,"");return n.filter((o)=>typeof o==="string"&&o.startsWith(r))}import{join as MM,resolve as zw}from"path";var Gy=1.2,Hy=0.75,Uy=0.5,mP=/[\p{Variation_Selector}\p{Me}]/gu,fP=/[\p{L}\p{N}][\p{L}\p{M}\p{N}]*/gu;function Ky(t){return t.normalize("NFC").toLowerCase().replace(mP,"").match(fP)??[]}function Pa(t,e){let n=[...new Set(Ky(t))].sort(I),r=e.map(hP),o=r.reduce((a,c)=>a+c.length,0),s=r.length===0?0:o/r.length,i=new Map(n.map((a)=>[a,yP(a,r)]));return r.map((a)=>({id:a.id,score:kP(a,n,i,s)})).sort((a,c)=>c.score-a.score||I(a.id,c.id))}function hP(t){let e=Ky(t.text),n=new Map;for(let r of e)n.set(r,(n.get(r)??0)+1);return{frequencies:n,id:t.id,length:e.length}}function yP(t,e){let n=e.filter((r)=>r.frequencies.has(t)).length;return Math.log(1+(e.length-n+Uy)/(n+Uy))}function kP(t,e,n,r){let o=r===0?1:t.length/r,s=Gy*(1-Hy+Hy*o);return e.reduce((i,a)=>{let c=t.frequencies.get(a)??0,l=n.get(a)??0;return i+l*c*(Gy+1)/(c+s)},0)}function vt(t){return Buffer.byteLength(t,"utf8")}function cd(t){return Math.ceil(vt(t)/4)}import{readFileSync as u0}from"fs";import{join as Lk}from"path";var wP=1000,SP=2147483647,TP=60,Jy=8192,qy=Jy*2,EP=1000,$P=`exec 2>&1
136
- `,bP=192,vP=128,By=`
137
- `,xP=[126,127],Wy=128,AP=31;async function Yy(t,e){let n=performance.now(),r=Bun.spawn(["sh","-c",`${$P}${t}`],{cwd:e.cwd,detached:!0,env:{...process.env,...Ae},stderr:"pipe",stdin:"ignore",stdout:"pipe"}),o=de(()=>ld(r.pid));try{return await CP(r,t,e,n)}finally{o()}}async function CP(t,e,n,r){let o={hasher:new Bun.CryptoHasher("sha256"),window:new Uint8Array},s=[t.stdout.getReader(),t.stderr.getReader()],i=Promise.all(s.map((u)=>RP(u,o))),a={timedOut:!1},c=setTimeout(()=>{a.timedOut=!0,ld(t.pid)},Math.min(n.timeoutSeconds*wP,SP));await t.exited,clearTimeout(c);let l=await IP(i,EP);if(ld(t.pid),!l)await Promise.all(s.map((u)=>u.cancel()));return{command:e,durationMs:Math.round(performance.now()-r),exitCode:t.exitCode,outputSha256:o.hasher.digest("hex"),outputTail:Qy(o.window),timedOut:a.timedOut}}function Xy(t){return t.exitCode===0&&!t.timedOut}function zy(t){return t.exitCode!==0&&!t.timedOut&&!ud(t)&&!dd(t)}function ud(t){let{exitCode:e}=t;return e===null||e>Wy&&e<=Wy+AP}function dd(t){return t.exitCode!==null&&!t.timedOut&&xP.includes(t.exitCode)}async function RP(t,e){for(;;){let{done:n,value:r}=await t.read();if(n)return;e.hasher.update(r),e.window=pd(OP(e.window,r),qy)}}async function IP(t,e){let n,r=new Promise((s)=>{n=setTimeout(()=>s(!1),e)}),o=await Promise.race([t.then(()=>!0),r]);return clearTimeout(n),o}function ld(t){Ce(t,"SIGKILL")}function Zy(t){return Qy(pd(new TextEncoder().encode(t),qy))}function Qy(t){let n=new TextDecoder().decode(Vy(t)).split(By);if(n.at(-1)==="")n.pop();let r=new TextEncoder().encode(n.slice(-TP).join(By));return new TextDecoder().decode(Vy(pd(r,Jy)))}function Vy(t){let e=0;while(e<t.length&&((t[e]??0)&bP)===vP)e++;return t.subarray(e)}function pd(t,e){return t.length<=e?t:t.subarray(t.length-e)}function OP(t,e){let n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}var _P=1,PP="Commands that ari would run for this repository";async function Ln({config:t,root:e},n){if(Zr())return;let r=De(e,t);if(!kn(r))return;if(Jn()&&await md(r.root,r.commands)){Qr(e,t);return}let o=r.state==="changed"?"the commands in .ari changed since you trusted them":"nobody has trusted the commands in .ari on this machine";throw new g(`Cannot ${n}: ${o}`,`Review them with 'ari trust', trust them with 'ari trust --yes', or set ${lr}=1 where the repository is already trusted, such as in CI`,_P,{tag:"ConfigNotTrusted"})}function gd(t){return t.flatMap(({command:e,environment:n,source:r})=>[`${r}: ${e}`,...n===null?[]:[` environment: ${n}`]])}async function md(t,e){St(gd(e).join(`
138
- `),PP);try{return await ue({initialValue:!1,message:`Trust these commands in ${t}?`})}catch(n){if(n instanceof dt)return!1;throw n}}function mt(t,e,n,r=[],o=[]){return{checks:[...o],details:[...r],gate:t,ok:e,summary:n}}async function Le(t,e,n){let r=[];for(let o of t){let s=await Yy(o.run,{cwd:n,timeoutSeconds:o.timeoutSeconds});r.push(NP(o.name,e,s))}return r}async function ys(t,e,n,r,o){return await Ln(t,e),Le(n,r,o)}function NP(t,e,n){let r=e==="pass"?Xy(n):zy(n);return{...n,expect:e,name:t,ok:r}}function fd(t){return`${t.name} should ${t.expect} but ${DP(t)}`}function dr(t){return t.filter((e)=>!e.ok).map(fd)}function kt(t,e,n){return t===1?e:n}function DP(t){if(t.timedOut)return`timed out after ${t.durationMs} ms`;if(dd(t))return`could not run (exit code ${t.exitCode})`;if(!ud(t))return`exited with ${t.exitCode}`;return t.exitCode===null?"was killed by a signal":`was killed by a signal (exit code ${t.exitCode})`}import{copyFileSync as WP,mkdirSync as VP,readlinkSync as JP,rmSync as yd,symlinkSync as qP}from"fs";import{dirname as YP,join as Da}from"path";import{existsSync as LP,mkdtempSync as MP,readFileSync as jP,realpathSync as FP,rmSync as tk}from"fs";import{tmpdir as GP}from"os";import{join as hd}from"path";var ks=0,ek=128,HP="gitdir",UP=".git",KP=["-c","core.hooksPath=/dev/null"];async function Na(t,e,n){let r=FP(MP(hd(GP(),Qo))),o={admin:null,directory:r},s=de(()=>nk(t,o));try{return await BP(t,e,o),await n(r)}finally{nk(t,o),s()}}async function BP(t,e,n){let{directory:r}=n,o=await P(t,[...KP,"worktree","add","--detach",r,e],{allowedExitCodes:[ks,ek],env:{GIT_INDEX_FILE:void 0}});if(o.exitCode!==ks)throw Error(`git worktree add ${r} ${e} failed in ${t}: ${lu(o.stderr)}`);let s=await P(r,["rev-parse","--absolute-git-dir"],{allowedExitCodes:[ks,ek],env:Ae}),i=s.stdout.trim();if(s.exitCode===ks&&rk(i,r))n.admin=i}function nk(t,e){let{admin:n,directory:r}=e,o=Bun.spawnSync(["git","worktree","remove","--force",r],{cwd:t,env:{...process.env,GIT_INDEX_FILE:void 0},stderr:"ignore",stdin:"ignore",stdout:"ignore"});if(tk(r,{force:!0,recursive:!0}),o.exitCode===ks||n===null)return;if(rk(n,r))tk(n,{force:!0,recursive:!0})}function rk(t,e){let n=hd(t,HP);return LP(n)&&jP(n,"utf8").trim()===hd(e,UP)}var XP="@base",zP=12;async function ok(t){let e=t.contract.checks.filter((p)=>p.expect==="regression");if(e.length===0)return mt("regression",!1,"the contract has no check with expect: regression");let n=t.base.slice(0,zP),r=Wt(t.changedFiles).filter((p)=>Z(p,t.config.testGlobs)),o=await Na(t.root,t.base,(p)=>ZP(t,e,r,p)),s=await Le(e,"pass",t.root),i=[...o.setup,...o.checks,...s],c=o.setup.some((p)=>!p.ok)?[`regression checks did not run on ${n} because its setup failed`]:[],l=[...dr(i),...c],u=l.length===0,d=u?`every regression check fails on ${n} and passes on the working tree`:`${l.length} regression ${kt(l.length,"problem","problems")} against ${n}`;return mt("regression",u,d,l,i)}async function ZP(t,e,n,r){for(let a of n)tN(t.root,r,a);let o=QP(t.config),s=o.length===0?[]:await ys({config:t.config,root:t.root},"run regression.setup",o,"pass",r);if(s.some((a)=>!a.ok))return{checks:[],setup:s};let i=e.map((a)=>({...a,name:`${a.name}${XP}`}));return{checks:await Le(i,"fail",r),setup:s}}function QP(t){return t.regression.setup.map((e,n)=>({name:`setup[${n}]`,run:e,timeoutSeconds:t.checkTimeoutSeconds}))}function tN(t,e,n){let r=Da(t,n),o=Da(e,n),s=Gr(t,n)?null:In(r);if(s===null){eN(e,n);return}if(!s.isFile()&&!s.isSymbolicLink())return;if(sk(e,n),yd(o,{force:!0,recursive:!0}),s.isFile())WP(r,o);else qP(JP(r),o)}function eN(t,e){let n=Da(t,e);if(Gr(t,e)||In(n)?.isDirectory()!==!1)return;yd(n,{force:!0})}function sk(t,e){let n=YP(e);if(n===".")return;sk(t,n);let r=Da(t,n),o=In(r);if(o?.isDirectory())return;if(o!==null)yd(r,{force:!0});VP(r)}import{readFileSync as r0}from"fs";import{join as o0}from"path";var nN=2,pr=1,rN=5000,oN=1000,sN=2147483647,iN=1048576,aN=["HOME","PATH","USER","LOGNAME","SHELL","TERM","TMPDIR","TZ","LANG","LC_ALL","LC_CTYPE","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_CACHE_HOME","XDG_STATE_HOME"];function gr(t,e){let n=e.agent??e.route?.agent;if(n===void 0)throw new g(`No ${e.role} agent is chosen`,e.role==="task"?"Pass --agent <name>, or set routing.default in .ari/config.json":"Pass --agent <name>, or set routing.review or review.agent in .ari/config.json",pr,{tag:"NoAgentChosen"});let r=t.agents[n];if(r===void 0)throw new g(`No agent "${n}" is configured`,`Run 'ari agents add <preset> --name ${n}', or add "agents": { "${n}": { "command": ["<binary>", "<non-interactive flag>", "{prompt}"] } } to .ari/config.json`,pr,{tag:"AgentNotConfigured"});if(!nr(r).includes(e.role))throw new g(`Agent "${n}" is not configured as a ${e.role} agent`,`Add "${e.role}" to agents.${n}.roles in .ari/config.json`,pr,{tag:"AgentRoleMismatch"});let o=e.agent===void 0?e.route?.model:void 0,s=e.model??o??r.model??null,i={config:r,model:s,name:n,role:e.role};return La(i,""),i}function La(t,e){let{config:n,model:r,name:o,role:s}=t,i=s==="review"&&n.reviewCommand!==void 0?"reviewCommand":"command",a=n[i]??n.command,c=`agents.${o}.${i}`;if(!a.some((p)=>p.includes(Kt)))throw new g(`The command of agent "${o}" has no ${Kt} argument`,`Put ${Kt} where the agent takes its prompt in ${c}`,pr,{tag:"AgentCommandInvalid"});let l=a.some((p)=>p.includes(Yo));if(l&&r===null)throw new g(`Agent "${o}" needs a model for ${Yo} in ${c}`,`Set agents.${o}.model, give a model in routing, or pass --model`,pr,{tag:"AgentCommandInvalid"});if(!l&&r!==null&&n.modelFlag===void 0)throw new g(`Agent "${o}" has no way to take the model "${r}"`,`Put ${Yo} in ${c}, or set agents.${o}.modelFlag`,pr,{tag:"AgentCommandInvalid"});let u=a.map((p)=>p.replaceAll(Kt,()=>e).replaceAll(Yo,()=>r??"")),d=!l&&r!==null&&n.modelFlag!==void 0?[n.modelFlag,r]:[];return[...u,...d]}function Ma(t){if(t.inheritEnv===!0)return{...process.env,...Ae};return kd(t.env??[])}function kd(t){let e=[...aN,...t].filter((n)=>!(n in Ae));return Object.fromEntries(e.flatMap((n)=>process.env[n]===void 0?[]:[[n,process.env[n]]]))}async function ja(t,e,n){let r=La(t,e),{name:o}=t;return wd(r,{...n,action:`start the agent "${o}"`,maxCaptureBytes:iN,reapGroup:t.role==="review",startFailure:(s,i)=>new g(`Agent "${o}" could not start: ${s}`,`Fix agents.${o}.command in .ari/config.json`,pr,{cause:i,tag:"AgentStartFailed"}),timeoutSeconds:n.timeoutSeconds??t.config.timeoutSeconds})}async function wd(t,e){await Ln(e.trust,e.action);let n=cN(t,e),r=de(()=>ik(n)),o={timedOut:!1},s=e.timeoutSeconds,i=s===void 0?void 0:setTimeout(()=>{o.timedOut=!0,ik(n)},Math.min(s*oN,sN)),a=e.stdout==="capture"?lN(n,e.maxCaptureBytes):Promise.resolve({overflowed:!1,text:""}),c=await n.exited;if(clearTimeout(i),mf())await new Promise(()=>{return});if(e.reapGroup)Ce(n.pid,"SIGKILL");r();let{overflowed:l,text:u}=await a;return{exitCode:c,overflowed:l,stdout:u,timedOut:o.timedOut}}function cN(t,e){let n=e.stdout==="inherit"?"inherit":e.stdout==="capture"?"pipe":nN;try{return Bun.spawn(t,{cwd:e.cwd,detached:!0,env:e.environment,stderr:"inherit",stdin:"ignore",stdout:n})}catch(r){throw e.startFailure(t[0]??"",r)}}async function lN(t,e){let n=t.stdout;if(!(n instanceof ReadableStream))return{overflowed:!1,text:""};let r=[],o=0,s=!1;for await(let i of n){if(o+i.length>e){s=!0,Ce(t.pid,"SIGKILL");break}r.push(i),o+=i.length}return{overflowed:s,text:new TextDecoder().decode(Buffer.concat(r))}}async function ik(t){Ce(t.pid,"SIGTERM"),await Promise.race([t.exited,Bun.sleep(rN)]),Ce(t.pid,"SIGKILL")}import{realpathSync as yk}from"fs";var uN=1,dN=300,ak="...",pN=/\p{Cc}+/gu,gN=zt({choice:gt(),confidence:Vo()}),mN=zt({evaluation:zt({answer:gN}).or(Nr()),flagged:Li(),line:Vo(),path:gt(),question:gt(),status:gt(),target:gt()}),fN=zt({results:Mi(mN),root:gt()}),hN=zt({error:zt({message:gt()})});function lk(t,e){let n;try{n=JSON.parse(t)}catch{return{kind:"invalid"}}let r=ck(()=>fN(n));if(r!==null)return yN(r,e);let o=ck(()=>hN(n));if(o===null)return{kind:"invalid"};return{kind:"failure",message:Sd(o.error.message,dN)}}function yN(t,e){let n=t.results.filter((s)=>e.has(s.path)),r=n.flatMap((s)=>{let i=s.evaluation?.answer;if(s.status!=="checked"||!s.flagged||i===void 0)return[];if(!Number.isInteger(s.line)||s.line<uN)return[];let{line:a,path:c,question:l,target:u}=s;return[{answer:i.choice,confidence:i.confidence,line:a,path:c,question:l,target:u}]}),o=(s)=>n.filter((i)=>i.status===s).length;return{candidates:r.sort(kN),counts:{blocked:o("blocked"),checked:o("checked"),pending:o("pending")},kind:"report",root:t.root}}function kN(t,e){return e.confidence-t.confidence||I(t.path,e.path)||t.line-e.line||I(t.question,e.question)}function Sd(t,e){let n=t.replace(pN," ").trim();return n.length>e?`${n.slice(0,e-ak.length)}${ak}`:n}function ck(t){try{return t()}catch{return null}}import{existsSync as wN,realpathSync as dk}from"fs";import{dirname as SN,join as TN,relative as EN,resolve as $N,sep as pk}from"path";var bN=["cache","reports","reviews","verifications"],vN="ari-probe",gk=1,uk=0,xN=1;function mk(t,e){let n=$N(t,e);if(!wN(n))return{location:null,problem:`the argus config ${e} does not exist`};try{return{location:{configPath:n,stateDirectory:dk(SN(n))},problem:null}}catch{return{location:null,problem:`the directory of the argus config ${e} cannot be read`}}}async function fk(t,e){let n=dk(t);for(let r of bN){let o=TN(e.stateDirectory,r);if(!AN(n,o))continue;let s=EN(n,o).split(pk).join("/");if(await CN(t,`${s}/${vN}`))continue;throw new g(`Cannot run argus: its state directory ${s} is inside the repository and git does not ignore it, so running argus would change the working tree that the review hashes`,`Keep the argus config outside the repository, for example 'argus init --root . --config <directory outside the repository>/config.json', or add ${s}/ to .gitignore. Pass --no-argus to review without it`,gk,{tag:"ArgusStateInRepository"})}}async function hk(t,e){if(await ge(t,[])===e)return;throw new g("The working tree changed while argus collected evidence, so the review stops","Keep the state of the argus config outside the repository or ignored by git, make sure that the argus command only reads the project, and leave the files alone while the review runs",gk,{tag:"ArgusChangedTree"})}function AN(t,e){return e===t||e.startsWith(`${t}${pk}`)}async function CN(t,e){try{return(await P(t,["check-ignore","--quiet","--",e],{allowedExitCodes:[uk,xN]})).exitCode===uk}catch{return!1}}var kk="ArgusStartFailed",wk=1,Sk=16777216,RN=500,Tk={blocked:0,checked:0,pending:0},IN=/[\\*?[\]{}()!@+,#]/g,ON="argus (run) was allowed to send the source of the changed files to its model endpoint",_N=0,PN=1;async function Ek(t){let{argus:e,changedFiles:n,root:r}=t,o=e.mode==="run"?DN(n):{files:[],warnings:[]};if(e.mode==="run"?o.files.length===0:n.length===0)return Td(e.mode,!0,[],Tk,[]);let i=mk(r,e.config);if(i.location===null)return mr(t,i.problem);await fk(r,i.location);let a=Ki(e,{base:t.base,configPath:i.location.configPath,only:o.files.map(LN).join(`
139
- `)});if(e.mode==="run")t.notify?.(jN(e.limit));let c=e.timeoutSeconds??t.config.checkTimeoutSeconds,l=await NN(t,a,c);if(typeof l==="string")return mr(t,l);if(l.timedOut)return mr(t,`argus did not finish within ${c} seconds`);if(l.overflowed)return mr(t,`argus printed more than ${Sk} bytes`);let u=lk(l.stdout,new Set(n));if(u.kind==="failure")return mr(t,`argus failed: ${u.message}`);if(u.kind==="invalid"||![_N,PN].includes(l.exitCode))return mr(t,`argus exited with ${l.exitCode} and did not print its JSON report`);if(!MN(u.root,r))return mr(t,`its project root ${u.root} is not the root of this repository`);return Td(e.mode,!0,u.candidates,u.counts,o.warnings)}function $k(t,e){let n=e?.included??0;return{blocked:t.counts.blocked,candidates:t.candidates.length,checked:t.counts.checked,included:n,mode:t.mode,modelRequestsAllowed:t.used&&t.mode==="run",omitted:t.candidates.length-n,pending:t.counts.pending,used:t.used,warnings:t.warnings}}async function NN(t,e,n){try{return await wd(e,{action:"start argus to collect review evidence",cwd:t.root,environment:kd(Ui(t.argus.mode)),maxCaptureBytes:Sk,reapGroup:!0,startFailure:(r,o)=>new g(`argus could not start: ${r}`,"Install argus or fix review.argus.command",wk,{cause:o,tag:kk}),stdout:"capture",timeoutSeconds:n,trust:{config:t.config,root:t.root}})}catch(r){if(r instanceof g&&r._tag===kk)return r.message;throw r}}function Fa(t){let{candidates:e,checked:n,included:r,mode:o,omitted:s,pending:i,blocked:a}=t;if(!t.used)return t.warnings;let c=s===0?`${r} added to the prompt`:`${r} added to the prompt, ${s} left out`,l=`${n} checks answered, ${i} without an answer, ${a} blocked`,u=t.modelRequestsAllowed?[ON]:[];return[`argus (${o}): ${e} candidates in the changed files, ${c}; ${l}`,...u,...t.warnings]}function mr(t,e){if(!t.explicit)return Td(t.argus.mode,!1,[],Tk,[`argus gave no evidence: ${e}`]);throw new g(`argus was requested with --argus, but ${e}`,"Fix review.argus in .ari/config.json, run the argus command yourself to see why it fails, or leave out --argus to review without it",wk,{tag:"ArgusUnavailable"})}function Td(t,e,n,r,o){return{candidates:n,counts:r,mode:t,used:e,warnings:o}}function DN(t){let e=t.filter((s)=>!s.includes(`
140
- `)),n=e.slice(0,RN),r=e.length-n.length,o=`argus was asked about the first ${n.length} changed files; ${r} more were left out`;return{files:n,warnings:r>0?[o]:[]}}function LN(t){return t.replace(IN,"\\$&")}function MN(t,e){try{return yk(t)===yk(e)}catch{return t===e}}function jN(t){return`argus (mode run) may send the source of the changed files to its model endpoint, in at most ${t} requests`}var FN=120,GN=2,ws=`
141
- `,HN="## Candidates from a decision model (not verified defects)",UN=["A decision model answered review questions about the files that this change touches, and flagged the answers below.","Each line is a lead, not a finding: the model can be wrong, and a file without a lead is not thereby clean.","Check a lead against the code before you report it, and judge the change by the contract, as above."].join(ws);function vk(t,e){let n=`${HN}${ws}${ws}${UN}${ws}`,r=[];for(let s of t){let i=[...r,KN(s)],a=bk(n,i,t.length-i.length,e);if(Buffer.byteLength(a)>e)break;r=i}if(r.length===0)return null;let o=t.length-r.length;return{included:r.length,omitted:o,text:bk(n,r,o,e)}}function bk(t,e,n,r){let o=n===0?[]:[BN(n,r)];return[t,...e,...o].join(ws)}function KN(t){let e=`${Ga(t.path)}:${t.line}`,n=t.confidence.toFixed(GN);return`- ${e} ${Ga(t.target)}: question "${Ga(t.question)}", answer "${Ga(t.answer)}", confidence ${n}`}function BN(t,e){return`(${t} more candidate${t===1?"":"s"} left out to stay within ${e} bytes)`}function Ga(t){return Sd(t.replaceAll('"',"'"),FN)}var Ed=["critical","major","minor","info"],WN=["critical","major"],VN=["pass","fail"],JN=["verdict","findings"],xk=["severity","file","line","summary"],qN=/^```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```$/;function Ak(t){let e=t.trim();if(e.length===0)return{problem:"the review agent printed nothing",verdict:null};let n=qN.exec(e)?.[1]??e,r;try{r=JSON.parse(n)}catch{return{problem:"the review agent's answer is not one JSON object",verdict:null}}try{return{problem:null,verdict:YN(r)}}catch(o){if(o instanceof b)return{problem:`the review agent's answer: ${o.message}`,verdict:null};throw o}}function Ck(t){return t.findings.filter((e)=>WN.includes(e.severity))}function Ha(t){let e=t.file===null?"":` ${t.file}${t.line===null?"":`:${t.line}`}`;return`${t.severity}${e}: ${t.summary}`}function YN(t){let e=C(t,"verdict object",JN),n=V(VN,e.verdict,"verdict");return{findings:D(e.findings,"findings",XN),verdict:n}}function XN(t,e){let n=C(t,e,xk);for(let r of xk)if(!(r in n))throw new b(`${w(e,r)} is required`);return{file:n.file===null?null:ot(n.file,w(e,"file")),line:n.line===null?null:Zt(n.line,w(e,"line")),severity:V(Ed,n.severity,w(e,"severity")),summary:ot(n.summary,w(e,"summary"))}}var Ik=120000,zN=20000,ZN=3,QN=12,Ss=`
147
+ `:"; ";return{hint:`${n}${e.join(r)}`,lines:e,name:t}}function sD(){return $o.flatMap((t)=>[`${t.name}:`," commands:",` ari-${t.name}:`,` run: ${t.command}`])}import{realpathSync as iD,rmSync as aD}from"fs";import{join as lc}from"path";var uc={read:W,remove:(t,e)=>{aD(iD(lc(t,e)))},write:(t,e,n)=>{Ce(t,e,n)}};function tp(){let t=new Map;return{read:(e,n)=>{let r=lc(e,n);return t.has(r)?t.get(r)??null:W(e,n)},remove:(e,n)=>{t.set(lc(e,n),null)},write:(e,n,r)=>{t.set(lc(e,n),r)}}}var Hs={kind:"none"},Us={kind:"delete"};function xo(t,e){return{exact:e,kind:"write",text:t}}function dc(t,e,n,r){switch(n.kind){case"none":return{action:"unchanged",restored:null};case"delete":return r.remove(t,e),{action:"removed",restored:null};case"write":{let o=Ns(r.read(t,e),n.text);if(o!=="unchanged")r.write(t,e,n.text);return{action:o,restored:n.exact?"original":"entries"}}}}import{existsSync as cD,readFileSync as lD}from"fs";import{join as ep}from"path";var np="hooks.json",uD=384,Kk=sh(Et({installed:X(),original:X().or(Bn())}));function Bk(t,e=np){let n=ep(t,e);if(!cD(n))return{state:"absent"};try{return{path:n,receipts:Kk(JSON.parse(lD(n,"utf8"))),state:"readable"}}catch{return{path:n,state:"unreadable"}}}function Ao(t,e,n=np){return Vk(t,n)[e]??null}function Co(t,e,n,r=np){let{[e]:o,...s}=Vk(t,r);if(n===null&&o===void 0)return;let i=n===null?s:{...s,[e]:n};Rr(ep(t,r),`${JSON.stringify(i)}
148
+ `,uD)}function Vk(t,e){return nc(ep(t,e),Kk,{})}var dD="ari hook",pD=1;function rp(t,e){return`${dD} ${t} ${e}`}function qk(t,e,n){let{file:r,name:o}=e,s=W(t,r),i=s===null?{}:re(r,s),a=Ao(n,r),c=sp(i,e)?void 0:s,l=a?.installed===s?a?.original:c,u=Ce(t,r,Ks(e,s)),d=W(t,r)??"";return Co(n,r,l===void 0?null:{installed:d,original:l}),{action:u,agent:o,events:Bs(e),file:r}}function Ks(t,e){let n=e===null?{}:re(t.file,e);return zn(e,Yk(n,t,t.registrations))}function pc(t,e,n){let{action:r}=op(t,e,{forget:!0,state:n,view:uc});return{action:r,agent:e.name,file:e.file}}function gD(t,e,n){if(e===null)return Hs;let r=re(t.file,e);if(!sp(r,t))return Hs;if(n?.installed!==e)return xo(zn(e,Yk(r,t,[])),!1);return n.original===null?Us:xo(n.original,!0)}function op(t,e,n){let{file:r}=e,{forget:o,state:s,view:i}=n,a=Ao(s,r),c=dc(t,r,gD(e,i.read(t,r),a),i);if(o)Co(s,r,null);return c}function un(t,e){let n=ec(t,e.file);return n!==null&&sp(n,e)}function Bs(t){return[...new Set(t.registrations.map((e)=>e.event))]}function sp({hooks:t},e){if(!z(t))return!1;return Object.values(t).flat().some((n)=>Xk(n,e).length>0)}function Yk({hooks:t={},...e},n,r){if(!z(t))throw Wk(n,'"hooks" value that is not an object');let s=[...new Set([...Object.keys(t),...r.map(({agentEvent:a})=>a)])].flatMap((a)=>{let c=t[a]??[];if(!Array.isArray(c))throw Wk(n,`hooks.${a} that is not a list`);let l=mD(c,n,r.filter(({agentEvent:u})=>u===a));return l.length===0&&c.length>0?[]:[[a,l]]}),i=n.layout==="flat"?{version:e.version??pD}:{};return{...e,...i,...s.length===0?{}:{hooks:Object.fromEntries(s)}}}function Wk({file:t},e){return new m(`${t} has a ${e}`,`Fix ${t}`)}function mD(t,e,n){let r=new Set(n);return[...t.flatMap((s)=>{let i=Xk(s,e),a=[...r].filter(({event:c})=>i.includes(rp(e.name,c)));for(let c of a)r.delete(c);return[...fD(s,e),...a.map((c)=>Jk(e,c))]}),...[...r].map((s)=>Jk(e,s))]}function Jk(t,e){let n=t.handler(rp(t.name,e.event),e);if(t.layout==="flat")return n;return e.matcher===null?{hooks:[n]}:{hooks:[n],matcher:e.matcher}}function fD(t,e){let n=zk(t,e),r=n.filter((o)=>Zk(o,e).length===0);if(r.length===n.length)return[t];return r.length>0&&z(t)?[{...t,hooks:r}]:[]}function Xk(t,e){return zk(t,e).flatMap((n)=>Zk(n,e))}function zk(t,{layout:e}){if(e==="flat")return[t];return z(t)&&Array.isArray(t.hooks)?t.hooks:[]}function Zk(t,{name:e}){let n=z(t)?Object.values(t):[],r=rp(e,"");return n.filter((o)=>typeof o==="string"&&o.startsWith(r))}import{join as G1,resolve as jv}from"path";var Qk=1.2,tw=0.75,ew=0.5,hD=/[\p{Variation_Selector}\p{Me}]/gu,yD=/[\p{L}\p{N}][\p{L}\p{M}\p{N}]*/gu;function nw(t){return t.normalize("NFC").toLowerCase().replace(hD,"").match(yD)??[]}function gc(t,e){let n=[...new Set(nw(t))].sort(O),r=e.map(kD),o=r.reduce((a,c)=>a+c.length,0),s=r.length===0?0:o/r.length,i=new Map(n.map((a)=>[a,wD(a,r)]));return r.map((a)=>({id:a.id,score:SD(a,n,i,s)})).sort((a,c)=>c.score-a.score||O(a.id,c.id))}function kD(t){let e=nw(t.text),n=new Map;for(let r of e)n.set(r,(n.get(r)??0)+1);return{frequencies:n,id:t.id,length:e.length}}function wD(t,e){let n=e.filter((r)=>r.frequencies.has(t)).length;return Math.log(1+(e.length-n+ew)/(n+ew))}function SD(t,e,n,r){let o=r===0?1:t.length/r,s=Qk*(1-tw+tw*o);return e.reduce((i,a)=>{let c=t.frequencies.get(a)??0,l=n.get(a)??0;return i+l*c*(Qk+1)/(c+s)},0)}function yt(t){return Buffer.byteLength(t,"utf8")}function ip(t){return Math.ceil(yt(t)/4)}import{readFileSync as tS}from"fs";import{join as eS}from"path";var vD=1000,bD=2147483647,ED=60,iw=8192,aw=iw*2,$D=1000,TD=`exec 2>&1
149
+ `,xD=192,AD=128,rw=`
150
+ `,CD=[126,127],ow=128,RD=31;async function cw(t,e){let n=performance.now(),r=Bun.spawn(["sh","-c",`${TD}${t}`],{cwd:e.cwd,detached:!0,env:{...process.env,...Fe},stderr:"pipe",stdin:"ignore",stdout:"pipe"}),o=Qt(()=>ap(r.pid));try{return await ID(r,t,e,n)}finally{o()}}async function ID(t,e,n,r){let o={hasher:new Bun.CryptoHasher("sha256"),window:new Uint8Array},s=[t.stdout.getReader(),t.stderr.getReader()],i=Promise.all(s.map((u)=>OD(u,o))),a={timedOut:!1},c=setTimeout(()=>{a.timedOut=!0,ap(t.pid)},Math.min(n.timeoutSeconds*vD,bD));await t.exited,clearTimeout(c);let l=await _D(i,$D);if(ap(t.pid),!l)await Promise.all(s.map((u)=>u.cancel()));return{command:e,durationMs:Math.round(performance.now()-r),exitCode:t.exitCode,outputSha256:o.hasher.digest("hex"),outputTail:pw(o.window),timedOut:a.timedOut}}function lw(t){return t.exitCode===0&&!t.timedOut}function uw(t){return t.exitCode!==0&&!t.timedOut&&!cp(t)&&!lp(t)}function cp(t){let{exitCode:e}=t;return e===null||e>ow&&e<=ow+RD}function lp(t){return t.exitCode!==null&&!t.timedOut&&CD.includes(t.exitCode)}async function OD(t,e){for(;;){let{done:n,value:r}=await t.read();if(n)return;e.hasher.update(r),e.window=up(PD(e.window,r),aw)}}async function _D(t,e){let n,r=new Promise((s)=>{n=setTimeout(()=>s(!1),e)}),o=await Promise.race([t.then(()=>!0),r]);return clearTimeout(n),o}function ap(t){Ge(t,"SIGKILL")}function dw(t){return pw(up(new TextEncoder().encode(t),aw))}function pw(t){let n=new TextDecoder().decode(sw(t)).split(rw);if(n.at(-1)==="")n.pop();let r=new TextEncoder().encode(n.slice(-ED).join(rw));return new TextDecoder().decode(sw(up(r,iw)))}function sw(t){let e=0;while(e<t.length&&((t[e]??0)&xD)===AD)e++;return t.subarray(e)}function up(t,e){return t.length<=e?t:t.subarray(t.length-e)}function PD(t,e){let n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function kt(t,e,n,r=[],o=[]){return{checks:[...o],details:[...r],gate:t,ok:e,summary:n}}async function Je(t,e,n){let r=[];for(let o of t){let s=await cw(o.run,{cwd:n,timeoutSeconds:o.timeoutSeconds});r.push(ND(o.name,e,s))}return r}async function Vs(t,e,n,r,o){return await Xn(t,e),Je(n,r,o)}function ND(t,e,n){let r=e==="pass"?lw(n):uw(n);return{...n,expect:e,name:t,ok:r}}function dp(t){return`${t.name} should ${t.expect} but ${DD(t)}`}function Or(t){return t.filter((e)=>!e.ok).map(dp)}function wt(t,e,n){return t===1?e:n}function DD(t){if(t.timedOut)return`timed out after ${t.durationMs} ms`;if(lp(t))return`could not run (exit code ${t.exitCode})`;if(!cp(t))return`exited with ${t.exitCode}`;return t.exitCode===null?"was killed by a signal":`was killed by a signal (exit code ${t.exitCode})`}import{copyFileSync as VD,mkdirSync as WD,readlinkSync as JD,rmSync as gp,symlinkSync as qD}from"fs";import{dirname as YD,join as fc}from"path";import{existsSync as LD,mkdtempSync as MD,readFileSync as jD,realpathSync as FD,rmSync as gw}from"fs";import{tmpdir as GD}from"os";import{join as pp}from"path";var Ws=0,mw=128,HD="gitdir",UD=".git",KD=["-c","core.hooksPath=/dev/null"];async function mc(t,e,n){let r=FD(MD(pp(GD(),Cs))),o={admin:null,directory:r},s=Qt(()=>fw(t,o));try{return await BD(t,e,o),await n(r)}finally{fw(t,o),s()}}async function BD(t,e,n){let{directory:r}=n,o=await F(t,[...KD,"worktree","add","--detach",r,e],{allowedExitCodes:[Ws,mw],env:{GIT_INDEX_FILE:void 0}});if(o.exitCode!==Ws)throw Error(`git worktree add ${r} ${e} failed in ${t}: ${vd(o.stderr)}`);let s=await F(r,["rev-parse","--absolute-git-dir"],{allowedExitCodes:[Ws,mw],env:Fe}),i=s.stdout.trim();if(s.exitCode===Ws&&hw(i,r))n.admin=i}function fw(t,e){let{admin:n,directory:r}=e,o=Bun.spawnSync(["git","worktree","remove","--force",r],{cwd:t,env:{...process.env,GIT_INDEX_FILE:void 0},stderr:"ignore",stdin:"ignore",stdout:"ignore"});if(gw(r,{force:!0,recursive:!0}),o.exitCode===Ws||n===null)return;if(hw(n,r))gw(n,{force:!0,recursive:!0})}function hw(t,e){let n=pp(t,HD);return LD(n)&&jD(n,"utf8").trim()===pp(e,UD)}var XD="@base",zD=12;async function yw(t){let e=t.contract.checks.filter((p)=>p.expect==="regression");if(e.length===0)return kt("regression",!1,"the contract has no check with expect: regression");let n=t.base.slice(0,zD),r=ne(t.changedFiles).filter((p)=>et(p,t.config.testGlobs)),o=await mc(t.root,t.base,(p)=>ZD(t,e,r,p)),s=await Je(e,"pass",t.root),i=[...o.setup,...o.checks,...s],c=o.setup.some((p)=>!p.ok)?[`regression checks did not run on ${n} because its setup failed`]:[],l=[...Or(i),...c],u=l.length===0,d=u?`every regression check fails on ${n} and passes on the working tree`:`${l.length} regression ${wt(l.length,"problem","problems")} against ${n}`;return kt("regression",u,d,l,i)}async function ZD(t,e,n,r){for(let a of n)tL(t.root,r,a);let o=QD(t.config),s=o.length===0?[]:await Vs({config:t.config,root:t.root},"run regression.setup",o,"pass",r);if(s.some((a)=>!a.ok))return{checks:[],setup:s};let i=e.map((a)=>({...a,name:`${a.name}${XD}`}));return{checks:await Je(i,"fail",r),setup:s}}function QD(t){return t.regression.setup.map((e,n)=>({name:`setup[${n}]`,run:e,timeoutSeconds:t.checkTimeoutSeconds}))}function tL(t,e,n){let r=fc(t,n),o=fc(e,n),s=Te(t,n)?null:$e(r);if(s===null){eL(e,n);return}if(!s.isFile()&&!s.isSymbolicLink())return;if(kw(e,n),gp(o,{force:!0,recursive:!0}),s.isFile())VD(r,o);else qD(JD(r),o)}function eL(t,e){let n=fc(t,e);if(Te(t,e)||$e(n)?.isDirectory()!==!1)return;gp(n,{force:!0})}function kw(t,e){let n=YD(e);if(n===".")return;kw(t,n);let r=fc(t,n),o=$e(r);if(o?.isDirectory())return;if(o!==null)gp(r,{force:!0});WD(r)}import{readFileSync as TM}from"fs";import{join as xM}from"path";var Zn="candidates",nL=["confirmed","false_positive","deferred","uncertain"],rL=["id","verdict","rationale"],mp="argus verdicts: ";function ww(t,e){if(t===void 0)return{answers:[],warnings:[]};if(!Array.isArray(t))return sL(`${Zn} must be a list, so no answer was sent`);let n=[],r=[];for(let[i,a]of t.entries())try{r.push(oL(a,k(Zn,i),e))}catch(c){if(!(c instanceof b))throw c;n.push(`${mp}${c.message}; dropped`)}let o=new Map;for(let i of r)o.set(i.id,(o.get(i.id)??0)+1);for(let[i,a]of o)if(a>1)n.push(`${mp}candidate ${i} was answered more than once; none of its answers was sent`);return{answers:r.filter((i)=>o.get(i.id)===1).map(({rationale:i,reviewId:a,verdict:c})=>({rationale:i,reviewId:a,verdict:c})),warnings:n}}function oL(t,e,n){let r=T(t,e,rL),o=nt(r.id,k(e,"id")),s=n.get(o);if(s===void 0)throw new b(`${e}.id ${JSON.stringify(o)} is not a candidate of this review`);return{id:o,rationale:nt(r.rationale,k(e,"rationale")),reviewId:s,verdict:K(nL,r.verdict,k(e,"verdict"))}}function sL(t){return{answers:[],warnings:[`${mp}${t}`]}}import{realpathSync as Pw}from"fs";import{readFileSync as iL,realpathSync as aL}from"fs";import{join as cL,sep as lL}from"path";var uL="reviews",Sw=8,dL=/^[a-f0-9]{64}$/,pL=Et({reviewer:Et({promptVersion:X()}),snapshotId:X(),verdicts:no(Et({reviewId:X()}))});function vw(t,e,n){let r=cL(n.stateDirectory,uL),o;try{let l=aL(t.verdictFile);if(!l.startsWith(`${r}${lL}`))return`its verdict template ${t.verdictFile} is not in ${r}`;o=pL(JSON.parse(iL(l,"utf8")))}catch{return`its verdict template ${t.verdictFile} cannot be read`}if(o.snapshotId!==t.id)return"its verdict template belongs to another snapshot";let s=o.verdicts.map((l)=>l.reviewId),i=new Set(s.filter((l)=>dL.test(l))),a=e.filter((l)=>i.has(l.reviewId)),c=gL(a.map((l)=>l.reviewId));return{candidates:a.map((l)=>({...l,id:l.reviewId.slice(0,c)})),offer:{configPath:n.configPath,promptVersion:o.reviewer.promptVersion,reviewIds:s,snapshotId:t.id}}}function gL(t){let e=Math.max(Sw,...t.map((n)=>n.length));for(let n=Sw;n<e;n+=1)if(new Set(t.map((r)=>r.slice(0,n))).size===t.length)return n;return e}function bw(t,e){return new Map(t.slice(0,e).flatMap((n)=>n.id===void 0?[]:[[n.id,n.reviewId]]))}var Ew="ArgusStartFailed",fp=16777216,mL=1;async function hc(t,e,n,r){try{return await Dd(n,{action:e==="import"?"start argus to import review verdicts":"start argus to collect review evidence",cwd:t.root,environment:Is(ba(e)),maxCaptureBytes:fp,reapGroup:!0,startFailure:(o,s)=>new m(`argus could not start: ${o}`,"Install argus or fix review.argus.command",mL,{cause:s,tag:Ew}),stdout:"capture",timeoutSeconds:r,trust:{config:t.config,root:t.root}})}catch(o){if(o instanceof m&&o._tag===Ew)return o.message;throw o}}var fL=1,hL=300,$w="...",yL=/\p{Cc}+/gu,kL=Et({choice:X(),confidence:yr()}),wL=Et({evaluation:Et({answer:kL}).or(Bn()),flagged:ha(),line:yr(),path:X(),question:X(),reviewId:X(),status:X(),target:X()}),SL=Et({results:no(wL),root:X(),snapshotId:X().or(Bn()).or(Lu()),verdictFile:X().or(Bn()).or(Lu())}),vL=Et({error:Et({message:X()})});function xw(t,e){let n;try{n=JSON.parse(t)}catch{return{kind:"invalid"}}let r=Tw(()=>SL(n));if(r!==null)return bL(r,e);let o=Tw(()=>vL(n));if(o===null)return{kind:"invalid"};return{kind:"failure",message:Js(o.error.message,hL)}}function bL(t,e){let n=t.results.filter((s)=>e.has(s.path)),r=n.flatMap((s)=>{let i=s.evaluation?.answer;if(s.status!=="checked"||!s.flagged||i===void 0)return[];if(!Number.isInteger(s.line)||s.line<fL)return[];let{line:a,path:c,question:l,reviewId:u,target:d}=s;return[{answer:i.choice,confidence:i.confidence,line:a,path:c,question:l,reviewId:u,target:d}]}),o=(s)=>n.filter((i)=>i.status===s).length;return{candidates:r.sort($L),counts:{blocked:o("blocked"),checked:o("checked"),pending:o("pending")},kind:"report",root:t.root,snapshot:EL(t)}}function EL(t){let{snapshotId:e,verdictFile:n}=t;return typeof e==="string"&&typeof n==="string"?{id:e,verdictFile:n}:null}function $L(t,e){return e.confidence-t.confidence||O(t.path,e.path)||t.line-e.line||O(t.question,e.question)}function Js(t,e){let n=t.replace(yL," ").trim();return n.length>e?`${n.slice(0,e-$w.length)}${$w}`:n}function Tw(t){try{return t()}catch{return null}}import{existsSync as TL,realpathSync as Cw}from"fs";import{dirname as xL,join as AL,relative as CL,resolve as RL,sep as Rw}from"path";var IL=["cache","reports","reviews","verifications"],OL="ari-probe",Iw=1,Aw=0,_L=1;function Ow(t,e){let n=RL(t,e);if(!TL(n))return{location:null,problem:`the argus config ${e} does not exist`};try{return{location:{configPath:n,stateDirectory:Cw(xL(n))},problem:null}}catch{return{location:null,problem:`the directory of the argus config ${e} cannot be read`}}}async function _w(t,e){let n=Cw(t);for(let r of IL){let o=AL(e.stateDirectory,r);if(!PL(n,o))continue;let s=CL(n,o).split(Rw).join("/");if(await NL(t,`${s}/${OL}`))continue;throw new m(`Cannot run argus: its state directory ${s} is inside the repository and git does not ignore it, so running argus would change the working tree that the review hashes`,`Keep the argus config outside the repository, for example 'argus init --root . --config <directory outside the repository>/config.json', or add ${s}/ to .gitignore. Pass --no-argus to review without it`,Iw,{tag:"ArgusStateInRepository"})}}async function yc(t,e,n="collected evidence"){if(await Ae(t,[])===e)return;throw new m(`The working tree changed while argus ${n}, so the review stops`,"Keep the state of the argus config outside the repository or ignored by git, make sure that the argus command only reads the project, and leave the files alone while the review runs",Iw,{tag:"ArgusChangedTree"})}function PL(t,e){return e===t||e.startsWith(`${t}${Rw}`)}async function NL(t,e){try{return(await F(t,["check-ignore","--quiet","--",e],{allowedExitCodes:[Aw,_L]})).exitCode===Aw}catch{return!1}}var DL=1,LL=500,Nw={blocked:0,checked:0,pending:0},ML=/[\\*?[\]{}()!@+,#]/g,jL="argus (run) was allowed to send the source of the changed files to its model endpoint",FL=0,GL=1;async function Dw(t){let{argus:e,changedFiles:n,root:r}=t,o=e.mode==="run"||e.verdicts===!0,s=o?BL(n):{files:[],warnings:[]};if(o?s.files.length===0:n.length===0)return wc(e.mode,!0,[],Nw,[]);let a=Ow(r,e.config);if(a.location===null)return kc(t,a.problem);await _w(r,a.location);let c={base:t.base,configPath:a.location.configPath,only:s.files.map(VL).join(`
151
+ `)};if(e.mode==="run")t.notify?.(JL(e.limit));let l=await HL(t,c);if(typeof l==="string")return kc(t,l);if(e.verdicts!==!0)return wc(e.mode,!0,l.candidates,l.counts,s.warnings);if(l.snapshot===null)return kc(t,"argus report create saved no snapshot");let u=vw(l.snapshot,l.candidates,a.location);if(typeof u==="string")return kc(t,u);return{...wc(e.mode,!0,u.candidates,l.counts,s.warnings),offer:u.offer}}function Lw(t,e,n){let r=e?.included??0;return{blocked:t.counts.blocked,candidates:t.candidates.length,checked:t.counts.checked,included:r,mode:t.mode,modelRequestsAllowed:t.used&&t.mode==="run",omitted:t.candidates.length-r,pending:t.counts.pending,used:t.used,warnings:[...t.warnings,...n?.warnings??[]],...n===void 0?{}:{verdicts:n.verdicts}}}async function HL(t,e){let n="argus was not asked anything";for(let r of va(t.argus).filter((o)=>o!=="import"))if(n=await UL(t,r,e),typeof n==="string")return n;return n}async function UL(t,e,n){let r=t.argus.timeoutSeconds??t.config.checkTimeoutSeconds,o=await hc(t,e,so(t.argus,e,n),r);if(typeof o==="string")return o;if(o.timedOut)return`argus did not finish within ${r} seconds`;if(o.overflowed)return`argus printed more than ${fp} bytes`;let s=xw(o.stdout,new Set(t.changedFiles));if(s.kind==="failure")return`argus failed: ${s.message}`;if(s.kind==="invalid"||![FL,GL].includes(o.exitCode))return`argus exited with ${o.exitCode} and did not print its JSON report`;if(!WL(s.root,t.root))return`its project root ${s.root} is not the root of this repository`;return s}function Sc(t){let{candidates:e,checked:n,included:r,mode:o,omitted:s,pending:i,blocked:a}=t;if(!t.used)return t.warnings;let c=s===0?`${r} added to the prompt`:`${r} added to the prompt, ${s} left out`,l=`${n} checks answered, ${i} without an answer, ${a} blocked`,u=t.modelRequestsAllowed?[jL]:[];return[`argus (${o}): ${e} candidates in the changed files, ${c}; ${l}`,...u,...t.verdicts===void 0?[]:[KL(t.verdicts)],...t.warnings]}function KL({answered:t,offered:e,saved:n,sent:r}){return`argus verdicts: ${e} candidates offered to the reviewer, ${t} answered, ${r} sent to argus, ${n} saved`}function kc(t,e){if(!t.explicit&&t.verdictsExplicit!==!0)return wc(t.argus.mode,!1,[],Nw,[`argus gave no evidence: ${e}`]);let n=t.verdictsExplicit===!0?"--argus-verdicts":"--argus";throw new m(`argus was requested with ${n}, but ${e}`,`Fix review.argus in .ari/config.json, run the argus command yourself to see why it fails, or leave out ${n} to review without it`,DL,{tag:"ArgusUnavailable"})}function wc(t,e,n,r,o){return{candidates:n,counts:r,mode:t,offer:null,used:e,warnings:o}}function BL(t){let e=t.filter((s)=>!s.includes(`
152
+ `)),n=e.slice(0,LL),r=e.length-n.length,o=`argus was asked about the first ${n.length} changed files; ${r} more were left out`;return{files:n,warnings:r>0?[o]:[]}}function VL(t){return t.replace(ML,"\\$&")}function WL(t,e){try{return Pw(t)===Pw(e)}catch{return t===e}}function JL(t){return`argus (mode run) may send the source of the changed files to its model endpoint, in at most ${t} requests`}import{mkdtempSync as qL,rmSync as YL,writeFileSync as XL}from"fs";import{tmpdir as zL}from"os";import{join as Mw}from"path";var ZL="verdicts.json",QL=384,tM=2,eM=300,jw="argus verdicts: ",nM=Et({imported:yr()}).or(Et({error:Et({message:X()})}));async function Fw(t){let{answers:e}=t;if(e.length===0)return{saved:0,sent:0,warnings:[]};let n=qL(Mw(zL(),Ey)),r=()=>YL(n,{force:!0,recursive:!0}),o=Qt(r);try{let s=Mw(n,ZL);return XL(s,`${JSON.stringify(oM(t),null,tM)}
153
+ `,{mode:QL}),await rM(t,s)}finally{r(),o()}}async function rM(t,e){let{answers:n,base:r,context:o,offer:s,seconds:i}=t,a=so(o.argus,"import",{base:r,configPath:s.configPath,file:e,only:null}),c=n.length,l=await hc(o,"import",a,i);if(typeof l==="string")return vc(c,l);if(l.timedOut)return vc(c,`argus did not finish importing within ${i} seconds`);let u=sM(l.stdout);if(u===null)return vc(c,`argus exited with ${l.exitCode} and did not print its JSON result`);if("error"in u)return vc(c,`argus rejected the verdicts: ${Js(u.error.message,eM)}`);let d=u.imported<c?[`${jw}argus saved ${u.imported} of ${c} verdicts`]:[];return{saved:u.imported,sent:c,warnings:d}}function oM({answers:t,model:e,offer:n}){let r=new Map(t.map((o)=>[o.reviewId,o]));return{snapshotId:n.snapshotId,verdicts:n.reviewIds.map((o)=>{let s=r.get(o);return{evidence:[],rationale:s?.rationale??"",reviewId:o,verdict:s?.verdict??""}}),version:2,...e===null?{}:{reviewer:{model:e,promptVersion:n.promptVersion}}}}function sM(t){try{return nM(JSON.parse(t))}catch{return null}}function vc(t,e){return{saved:0,sent:t,warnings:[`${jw}${e}; nothing was saved, and the review is not affected`]}}var iM="argus verdicts: the review did not finish cleanly, so no answer was sent";async function Gw(t){let{before:e,clean:n,found:r,input:o,model:s,offered:i,written:a}=t,{offer:c}=r;if(c===null)return null;let l=ww(a,i),u={answered:l.answers.length,offered:i.size,saved:0,sent:0,snapshotId:c.snapshotId};if(!n)return{verdicts:u,warnings:[...l.warnings,...l.answers.length===0?[]:[iM]]};let d=o.argus.timeoutSeconds??o.config.checkTimeoutSeconds,p=await Fw({answers:l.answers,base:o.base,context:o,model:s,offer:c,seconds:d});if(p.sent>0)await yc(o.root,e,"imported the verdicts");return{verdicts:{...u,saved:p.saved,sent:p.sent},warnings:[...l.warnings,...p.warnings]}}var aM=120,cM=2,_r=`
154
+ `,lM="## Candidates from a decision model (not verified defects)",Hw=["A decision model answered review questions about the files that this change touches, and flagged the answers below.","Each line is a lead, not a finding: the model can be wrong, and a file without a lead is not thereby clean.","Check a lead against the code before you report it, and judge the change by the contract, as above."].join(_r),uM=[`Each lead has an ID in square brackets. You may answer a lead that you checked against the code, in the same JSON object, under an optional "${Zn}" key:`,`"${Zn}":[{"id":"<ID>","verdict":"confirmed","rationale":"<why, citing the code>"}]`,"A verdict is confirmed (a real problem), false_positive (not a problem), deferred (real, but fine to leave in this change) or uncertain (you cannot tell).","Answer only the leads that you checked and leave the others out; a lead that you leave out stays unreviewed. These answers are stored with the decision model's candidates and never change your own verdict or findings."].join(_r);function Kw(t,e){let r=t.some((a)=>a.id!==void 0)?`${Hw}${_r}${uM}`:Hw,o=`${lM}${_r}${_r}${r}${_r}`,s=[];for(let a of t){let c=[...s,dM(a)],l=Uw(o,c,t.length-c.length,e);if(Buffer.byteLength(l)>e)break;s=c}if(s.length===0)return null;let i=t.length-s.length;return{included:s.length,omitted:i,text:Uw(o,s,i,e)}}function Uw(t,e,n,r){let o=n===0?[]:[pM(n,r)];return[t,...e,...o].join(_r)}function dM(t){let e=`${bc(t.path)}:${t.line}`,n=t.confidence.toFixed(cM);return`- ${t.id===void 0?"":`[${t.id}] `}${e} ${bc(t.target)}: question "${bc(t.question)}", answer "${bc(t.answer)}", confidence ${n}`}function pM(t,e){return`(${t} more candidate${t===1?"":"s"} left out to stay within ${e} bytes)`}function bc(t){return Js(t.replaceAll('"',"'"),aM)}var hp=["critical","major","minor","info"],gM=["critical","major"],mM=["pass","fail"],fM=["verdict","findings"],Bw=["severity","file","line","summary"],hM=/^```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```$/;function Vw(t,e=[]){let n=t.trim();if(n.length===0)return{extras:{},problem:"the review agent printed nothing",verdict:null};let r=hM.exec(n)?.[1]??n,o;try{o=JSON.parse(r)}catch{return{extras:{},problem:"the review agent's answer is not one JSON object",verdict:null}}try{let s=T(o,"verdict object",[...fM,...e]);return{extras:Object.fromEntries(e.filter((a)=>(a in s)).map((a)=>[a,s[a]])),problem:null,verdict:yM(s)}}catch(s){if(s instanceof b)return{extras:{},problem:`the review agent's answer: ${s.message}`,verdict:null};throw s}}function Ww(t){return t.findings.filter((e)=>gM.includes(e.severity))}function Ec(t){let e=t.file===null?"":` ${t.file}${t.line===null?"":`:${t.line}`}`;return`${t.severity}${e}: ${t.summary}`}function yM(t){let e=K(mM,t.verdict,"verdict");return{findings:L(t.findings,"findings",kM),verdict:e}}function kM(t,e){let n=T(t,e,Bw);for(let r of Bw)if(!(r in n))throw new b(`${k(e,r)} is required`);return{file:n.file===null?null:nt(n.file,k(e,"file")),line:n.line===null?null:Kt(n.line,k(e,"line")),severity:K(hp,n.severity,k(e,"severity")),summary:nt(n.summary,k(e,"summary"))}}var qw=120000,wM=20000,SM=3,vM=12,qs=`
142
155
 
143
- `,Rk="```",t0='{"verdict":"fail","findings":[{"severity":"major","file":"src/a.ts","line":12,"summary":"\u2026"}]}';function Ok(t){let{contract:e,stage:n}=t,r=[[`You review a change for the Ariadne task "${e.id}" (${e.title}), at stage ${n}.`,"You run in a temporary copy of the repository. Read any file you need, but change nothing: a changed file fails the review.","Judge the change against the task's contract: does it meet every acceptance criterion, stay inside the scope, and avoid bugs, regressions and risky code?"].join(`
144
- `),["Answer with exactly one JSON object and nothing else, for example:",t0,'- "verdict" is "pass" when the change meets the contract and has no critical or major problem, otherwise "fail".',`- "severity" is one of ${Ed.join(", ")}; "file" and "line" may be null; "findings" may be empty.`].join(`
156
+ `,Jw="```",bM='{"verdict":"fail","findings":[{"severity":"major","file":"src/a.ts","line":12,"summary":"\u2026"}]}';function Yw(t){let{contract:e,stage:n}=t,r=[[`You review a change for the Ariadne task "${e.id}" (${e.title}), at stage ${n}.`,"You run in a temporary copy of the repository. Read any file you need, but change nothing: a changed file fails the review.","Judge the change against the task's contract: does it meet every acceptance criterion, stay inside the scope, and avoid bugs, regressions and risky code?"].join(`
157
+ `),["Answer with exactly one JSON object and nothing else, for example:",bM,'- "verdict" is "pass" when the change meets the contract and has no critical or major problem, otherwise "fail".',`- "severity" is one of ${hp.join(", ")}; "file" and "line" may be null; "findings" may be empty.`].join(`
145
158
  `),`## Contract (${t.contractPath})
146
159
 
147
- ${t.contractText.trim()}`,[`## Files changed since ${t.base.slice(0,QN)}`,"",...t.changedFiles.length===0?["(none)"]:t.changedFiles.map((c)=>`- ${c}`)].join(`
148
- `)].join(Ss),o=e0(t,r),s=o===null?r:[r,o.text].join(Ss),i=Ik-Buffer.byteLength(s)-Ss.length*2,a=[s,`## Diff
160
+ ${t.contractText.trim()}`,[`## Files changed since ${t.base.slice(0,vM)}`,"",...t.changedFiles.length===0?["(none)"]:t.changedFiles.map((c)=>`- ${c}`)].join(`
161
+ `)].join(qs),o=EM(t,r),s=o===null?r:[r,o.text].join(qs),i=qw-Buffer.byteLength(s)-qs.length*2,a=[s,`## Diff
149
162
 
150
- ${Rk}diff
151
- ${n0(t.diff,i)}
152
- ${Rk}`].join(Ss);return{argus:o,prompt:a}}function e0(t,e){if(t.argus===void 0)return null;let n=Ik-Buffer.byteLength(e)-Ss.length*ZN;return vk(t.argus.candidates,Math.max(0,Math.min(t.argus.maxBytes,n-zN)))}function n0(t,e){let n=Buffer.from(t.trimEnd());if(n.length<=e)return n.toString();let r=`
153
- [diff truncated after ${e} bytes; read the changed files in the copy]`;return`${n.subarray(0,Math.max(0,e-Buffer.byteLength(r))).toString().replace(/\uFFFD$/,"")}${r}`}var s0={GIT_AUTHOR_DATE:"@0 +0000",GIT_AUTHOR_EMAIL:"ari@localhost",GIT_AUTHOR_NAME:"ari",GIT_COMMITTER_DATE:"@0 +0000",GIT_COMMITTER_EMAIL:"ari@localhost",GIT_COMMITTER_NAME:"ari"},_k=["--no-color","--no-ext-diff","--no-textconv","--no-renames"],Pk=[":(glob,exclude).ari/tasks/*.json",":(glob,exclude).ari/knowledge/**"],i0="review:",a0=1;async function Nk(t){let{config:e,root:n,task:r}=t,{agent:o,model:s}=e.review,i=gr(e,{agent:o,model:s,role:"review",route:null}),a=r0(o0(n,bt(r.contract.id)),"utf8"),{argus:c}=e.review,l=await $d({...t,contractText:a,...c===void 0?{}:{argus:{argus:c,explicit:!1}}},i),u=l.ok?"passed":"failed",d=[...l.problems,...l.findings.map(Ha),...l.argus===void 0?[]:Fa(l.argus)],p=`the review agent ${l.agent} ${u} the change`;return mt("review",l.ok,p,d,[l.evidence])}async function $d(t,e){let{config:n,root:r,task:o}=t,s=l0(o);await Ln({config:n,root:r},`start the agent "${e.name}"`);let i=await ge(r,[]),a=await c0(r,i,s,o.contract.id),c=Oe((await P(r,["diff","--name-only","-z",..._k,s,a,"--",".",...Pk])).stdout),l=t.argus===void 0?null:await Ek({...t.argus,base:s,changedFiles:c,config:n,root:r});if(l!==null)await hk(r,i);let u=(await P(r,["diff",..._k,s,a,"--",".",...Pk])).stdout,{argus:d,prompt:p}=Ok({...l===null||t.argus===void 0?{}:{argus:{candidates:l.candidates,maxBytes:t.argus.argus.maxBytes}},base:s,changedFiles:c,contract:o.contract,contractPath:bt(o.contract.id),contractText:t.contractText,diff:u,stage:t.stage}),m=e.config.timeoutSeconds??n.checkTimeoutSeconds,f=performance.now(),y=await Na(r,a,async(A)=>{let B=await ja(e,p,{cwd:A,environment:Ma(e.config),stdout:"capture",timeoutSeconds:m,trust:{config:n,root:r}});return{copyChanged:await ge(A,[])!==i,ran:B}}),S=Math.round(performance.now()-f),R=await ge(r,[])!==i,{ran:v}=y,H=Ak(v.stdout),J=H.verdict===null?[]:Ck(H.verdict),N=[...v.timedOut?[`the review agent did not finish within ${m} seconds`]:[],...!v.timedOut&&v.exitCode!==0?[`the review agent exited with ${v.exitCode}`]:[],...v.overflowed?["the review agent printed more than 1 MiB"]:[],...y.copyChanged?["the review agent changed files in its copy of the repository"]:[],...R?["the working tree changed while the review ran"]:[],...H.problem===null?[]:[H.problem],...H.verdict?.verdict==="pass"&&J.length>0?[`the verdict is pass, but ${J.length} finding(s) are critical or major`]:[]],U=N.length===0&&H.verdict?.verdict==="pass",_={command:La(e,Kt).join(" "),durationMs:S,exitCode:v.timedOut?null:v.exitCode,expect:"pass",name:`${i0}${e.name}`,ok:U,outputSha256:tt(v.stdout),outputTail:Zy(v.stdout),timedOut:v.timedOut};return{agent:e.name,...l===null?{}:{argus:$k(l,d)},durationMs:S,evidence:_,exitCode:v.exitCode,findings:H.verdict?.findings??[],model:e.model,ok:U,problems:N,timedOut:v.timedOut,verdict:H.verdict?.verdict??null}}async function c0(t,e,n,r){let o=`ari review snapshot of ${r}`;return(await P(t,["commit-tree","--no-gpg-sign",e,"-p",n,"-m",o],{env:s0})).stdout.trim()}function l0(t){if(t.record.base!==null)return t.record.base;throw new g(`Task "${t.contract.id}" has not started, so it has no change to review`,`Run 'ari start ${t.contract.id}' first`,a0,{tag:"TaskNotStarted"})}var d0="{id}",p0=[".ari/tasks/**",".ari/knowledge/**"];async function vd(t){let e=Tn(t.task,t.pack),r={...t,changedFiles:()=>pe(t.root,Fk(t.task)),stage:e},o=[],s=[];for(let[i,a]of e.gates.entries()){let c=await g0(a,r);if(o.push(c),c.ok&&T0(a)&&i<e.gates.length-1)s.push({index:i,result:await E0(a.kind,c,r)})}for(let i of s)o[i.index]=await i.result();return o}function Tn(t,e){let n=e.stages[t.record.stage];if(n)return n;throw new g(`Task "${t.contract.id}" is at stage ${t.record.stage}, but pack "${e.name}" has ${e.stages.length}`,`Restore the stages of pack "${e.name}", or amend the task's pack`)}async function Ts(t,e,n){let r=await ln(t,e.testGlobs);return Object.fromEntries(Object.entries(r).filter(([o])=>!qr(o)&&Z(o,n.scope)))}async function xd(t,e,n){let o=e.gates.flatMap((s)=>s.kind==="artifact"?[Mk(s.path,n)]:[]).flatMap((s)=>{let i=Lk(t,s);return iu(i)?.isFile()?[[s,tt(u0(i))]]:[]});return{artifactHashes:Object.fromEntries(o),treeHash:await ge(t,p0)}}function Es(t,e){return[...new Set([...Object.keys(t),...Object.keys(e)])].sort(I).flatMap((r)=>{let o=t[r],s=e[r];if(o===s)return[];if(o===void 0)return[`added ${r}`];return s===void 0?[`deleted ${r}`]:[`changed ${r}`]})}async function g0(t,e){switch(t.kind){case"criteria":return m0(e.task.contract);case"checks":return f0(t.select,t.expect,e);case"invariants":return h0(e);case"scope":return y0(e);case"locked":return k0(e);case"tests-unchanged":return w0(e);case"regression":return ok({base:Fk(e.task),changedFiles:await e.changedFiles(),config:e.config,contract:e.task.contract,root:e.root});case"artifact":return S0(t.path,t.minBytes,e);case"approval":return Ad("approval",e);case"review":return $0(e);case"command":return b0(t.run,e)}}function m0(t){let e=ku(t),n=e.length===0?`${t.criteria.length} ${kt(t.criteria.length,"criterion","criteria")} bound to existing checks`:`${e.length} criteria ${kt(e.length,"problem","problems")}`;return mt("criteria",e.length===0,n,e)}async function f0(t,e,n){let r=Wr(n.task.contract,t);if(r.length===0)return mt("checks",!1,`no check matches the selection "${t}"`);let o=await Le(r,e,n.root),s=dr(o),i=e==="pass"?"passed":"failed as expected",a=`${o.length-s.length} of ${o.length} ${kt(o.length,"check","checks")} ${i}`;return mt("checks",s.length===0,a,s,o)}async function h0(t){let e=t.task.contract.invariants.map((s,i)=>({name:`invariants[${i}]`,run:s,timeoutSeconds:t.config.checkTimeoutSeconds})),n=await Le(e,"pass",t.root),r=dr(n),o=`${n.length-r.length} of ${n.length} ${kt(n.length,"invariant","invariants")} passed`;return mt("invariants",r.length===0,o,r,n)}async function y0(t){let e=Wt(await t.changedFiles()),n=e.filter((o)=>!Z(o,t.task.contract.scope)),r=n.length===0?`${e.length} changed ${kt(e.length,"file","files")} inside the scope`:`${n.length} of ${e.length} changed ${kt(e.length,"file","files")} outside the scope`;return mt("scope",n.length===0,r,n)}async function k0(t){let e=await ln(t.root,t.task.contract.lock),n=Es(t.task.record.lockHashes,e),r=Object.keys(t.task.record.lockHashes).length,o=n.length===0?`${r} locked ${kt(r,"file","files")} unchanged`:`${n.length} locked ${kt(n.length,"file","files")} changed`;return mt("locked",n.length===0,o,n)}async function w0(t){let e=await Ts(t.root,t.config,t.task.contract),n=Es(t.task.record.stageTestHashes,e),r=Object.keys(t.task.record.stageTestHashes).length,o=n.length===0?`${r} test ${kt(r,"file","files")} unchanged since the stage started`:`${n.length} test ${kt(n.length,"file","files")} changed since the stage started`;return mt("tests-unchanged",n.length===0,o,n)}function S0(t,e,n){let r=Mk(t,n.task.contract.id),o=iu(Lk(n.root,r));if(!o?.isFile())return mt("artifact",!1,`${r} does not exist`);let s=o.size>=e,i=s?`${r} has ${o.size} bytes`:`${r} has ${o.size} bytes; it needs at least ${e}`;return mt("artifact",s,i)}function Mk(t,e){return t.replaceAll(d0,e)}function T0(t){return t.kind==="approval"||t.kind==="review"}async function E0(t,e,n){let{agent:r,command:o}=n.config.review;if(t==="approval"||o===null&&r===void 0)return()=>Ad(t,n);let s=await bd(n);return async()=>{if(jk(s,await bd(n)))return e;return mt(t,!1,"the working tree changed while the gates after the review ran",[],e.checks)}}function bd(t){return xd(t.root,t.stage,t.task.contract.id)}function jk(t,e){return t.treeHash===e.treeHash&&Es(t.artifactHashes,e.artifactHashes).length===0}async function Ad(t,e){let n=e.stage.name,r=`a human runs 'ari approve ${e.task.contract.id}'`,o=e.task.record.approvals.filter((c)=>c.stage===n);if(o.length===0)return mt(t,!1,`stage ${n} has no approval; ${r}`);let s=await bd(e),i=o.filter((c)=>jk(c,s));if(i.length>0)return mt(t,!0,`stage ${n} approved by ${Dk(i)}`);let a=`the working tree changed after ${Dk(o)} approved stage ${n}`;return mt(t,!1,`${a}; ${r} again`)}function Dk(t){return[...new Set(t.map((e)=>e.by))].join(", ")}async function $0(t){let{agent:e,command:n}=t.config.review;if(e!==void 0){let{config:c,root:l,stage:u,task:d}=t;return Nk({config:c,root:l,stage:u.name,task:d})}if(n===null)return Ad("review",t);let r={name:"review",run:n,timeoutSeconds:t.config.checkTimeoutSeconds},o={config:t.config,root:t.root},s=await ys(o,"run review.command",[r],"pass",t.root),i=dr(s),a=i.length===0?"the review command passed":"the review command failed";return mt("review",i.length===0,a,i,s)}async function b0(t,e){let n={name:"command",run:t,timeoutSeconds:e.config.checkTimeoutSeconds},r={config:e.config,root:e.root},o=await ys(r,"run a command gate of a project pack",[n],"pass",e.root),s=dr(o),i=s.length===0?`${t} passed`:`${t} failed`;return mt("command",s.length===0,i,s,o)}function Fk(t){if(t.record.base!==null)return t.record.base;throw Error(`Task "${t.contract.id}" has no base commit; gates run only after 'ari start'`)}import{closeSync as v0,existsSync as x0,fstatSync as A0,openSync as C0,readSync as R0}from"fs";import{join as I0}from"path";var O0="journal",_0=".jsonl",Gk=65536,P0=1000,Ua=10;function Ka(t,e,n){let r=[];if(n===0)return r;for(let o of D0(Uk(t,e))){let s=Kk(o,e);if(s!==null)r.push(s);if(r.length===n)break}return r.reverse()}function*Hk(t,e){let n=[];for(let r of N0(Uk(t,e))){let o=Kk(r,e);if(o===null)continue;if(n.push(o),n.length<P0)continue;yield n,n=[]}if(n.length>0)yield n}function Uk(t,e){return I0(t,O0,`${Xr(e)}${_0}`)}function Kk(t,e){try{let n=ua(JSON.parse(t.toString("utf8")));return n.task===e?n:null}catch(n){if(n instanceof SyntaxError||n instanceof b)return null;throw n}}function*N0(t){let e=[];for(let n of Bk(t,!1)){let r=0;for(let o=n.indexOf(Ua);o!==-1;o=n.indexOf(Ua,r))yield Buffer.concat([...e,n.subarray(r,o)]),e=[],r=o+1;e.push(n.subarray(r))}yield Buffer.concat(e)}function*D0(t){let e=[];for(let n of Bk(t,!0)){let r=n.length;for(let o=n.lastIndexOf(Ua);o!==-1;o=o===0?-1:n.lastIndexOf(Ua,o-1))yield Buffer.concat([n.subarray(o+1,r),...e]),e=[],r=o;e.unshift(n.subarray(0,r))}yield Buffer.concat(e)}function*Bk(t,e){if(!x0(t))return;let n=C0(t,"r");try{let{size:r}=A0(n);for(let o=0;o<r;o+=Gk){let s=Math.min(Gk,r-o),i=Buffer.alloc(s),a=R0(n,i,0,s,e?r-o-s:o);yield i.subarray(0,a)}}finally{v0(n)}}import{randomUUID as H0}from"crypto";import{mkdirSync as U0,readFileSync as K0,renameSync as B0,rmSync as W0,writeFileSync as V0}from"fs";import{basename as J0,dirname as Wk,join as Vk}from"path";var L0=/\p{M}+/gu,M0=/[\u00DF\u00E6\u0111\u00F0\u0127\u0131\u0142\u0153\u00F8\u00FE]/g,j0=/[^a-z0-9]+/,F0={\u{e6}:"ae",\u{f0}:"d",\u{111}:"d",\u{127}:"h",\u{131}:"i",\u{142}:"l",\u{f8}:"o",\u{153}:"oe",\u{df}:"ss",\u{fe}:"th"};function $s(t,e){if(!Number.isInteger(e)||e<=0)throw Error(`slugify needs a positive maxWords, got ${e}`);let r=t.toLowerCase().normalize("NFKD").replace(L0,"").replace(M0,(o)=>F0[o]??"").split(j0).filter((o)=>o.length>0).slice(0,e).join("-");return G0(r)}function G0(t){if(t.length<=64)return t;let e=t.lastIndexOf("-",64);return e>0?t.slice(0,e):t.slice(0,64)}function bs(t,e){if(t.length===0)throw Error("uniqueId needs a non-empty base");let n=new Set(e);if(!n.has(t))return t;let r=2;while(n.has(`${t}-${r}`))r++;return`${t}-${r}`}var q0=["constraint","decision"],Y0=6,X0=10,z0="knowledge",Z0=".md",Q0=4,tD="\x00",eD=",",nD={"[":"]","{":"}"},rD="\\",oD=()=>new Date().toISOString();function Cd(t,e,n){let r=ot(t.text,`${e}.text`).trim(),o=vt(r);if(o>n)throw new b(`${e}.text is ${o} bytes, but a knowledge entry holds at most ${n}`);return{kind:V(Qt,t.kind,`${e}.kind`),scope:Gi(t.scope,`${e}.scope`),text:r}}function Jk(t){return Qt.includes(t)}function vs(t,e){return{created:e.created,id:e.id,kind:t.kind,scope:[...t.scope],sources:[...e.sources],status:"active",supersededBy:null,supersedes:[...e.supersedes],text:t.text}}function Rd(t,e){let n=$s(t.text,Y0),r=bs(n.length>0?n:t.kind,e);return e.add(r),r}function Id(t,e,n,r){for(;;){let o=vs(e,{...n,id:Rd(e,r)});try{return ga(t,o),o}catch(s){if(!Ve(t).includes(o.id))throw s}}}function Xe(t,e){return{...t,status:"archived",supersededBy:e}}function Mn(t){return q0.includes(t.kind)}function so(t){return t.slice(0,X0)}function xs(t,e){let n=ye(t,e.id),r=Vk(Wk(n),`.${J0(n)}.${process.pid}.${H0()}.tmp`);U0(Wk(n),{recursive:!0});try{V0(r,or(e)),B0(r,n)}catch(o){throw W0(r,{force:!0}),o}}function sD(t){let e=new Map;for(let n of t){if(n.record.status!=="done")continue;for(let r of n.record.knowledgeUsed)e.set(r,(e.get(r)??0)+1)}return e}async function io(t){let e=await P(t,["ls-files","--cached","--others","--exclude-standard","-z"]);return Wt([...new Set(e.stdout.split(tD).filter((n)=>n.length>0))])}function Ba(t,e,n){if(t.length===0||e.length===0)return!0;return t.some((o)=>e.some((s)=>o===s||Z(o,[s])||Z(s,[o])))||n.some((o)=>Z(o,t)&&Z(o,e))}function qk(t){let e=[],n=[],r="";for(let o=0;o<t.length;o++){let s=t[o]??"";if(s===rD){r+=t.slice(o,o+2),o++;continue}let i=nD[s];if(i!==void 0)n.push(i);else if(s===n.at(-1))n.pop();if(s===eD&&n.length===0){e.push(r.trim()),r="";continue}r+=s}return e.push(r.trim()),e.filter((o)=>o.length>0)}function iD(t,e,n={}){let r=L(t),o=Tt("note","Shorten the text or fix the --kind and --scope values",()=>Cd(e,"note",r.knowledge.maxEntryBytes)),i={created:so((n.clock??oD)()),sources:[...n.sources??[]],supersedes:[]};return Id(t,o,i,new Set(Ve(t)))}async function Yk(t,e,n={}){L(t);let r=ut(await M(t))?.task,o=r!==void 0&&te(t).includes(r)?[r]:[];return iD(t,e,{...n,sources:o})}function Od(t,e={}){return L(t),{entries:Ne(t).filter((r)=>e.all===!0||r.status==="active")}}function Xk(t,e,n={}){let{entries:r}=Od(t,n),o=new Map(r.map((a)=>[a.id,a]));return{matches:Pa(e,r.map((a)=>({id:a.id,text:a.text}))).flatMap(({id:a,score:c})=>{let l=o.get(a);return l===void 0||c<=0?[]:[{entry:l,score:aD(c)}]}),query:e}}function zk(t,e,n){return{entry:As(t,e),uses:sD(n).get(e)??0}}function Zk(t,e,n={}){let r=As(t,e);if(r.status==="archived")throw new g(`Knowledge entry "${e}" is already archived`,"Run 'ari knowledge list' to see the active entries");if(Mn(r)&&n.force!==!0)throw new g(`Knowledge entry "${e}" is a ${r.kind}; ${r.kind} entries are archived only on purpose`,`Run 'ari knowledge archive ${e} --force' if it no longer holds`);let o=Xe(r,null);return xs(t,o),o}function As(t,e){if(L(t),Ve(t).includes(e))return ra(e,K0(ye(t,e),"utf8"));throw new g(`Knowledge entry "${e}" does not exist`,"Run 'ari knowledge list --all' to see every entry")}function ye(t,e){return Vk(t,W,z0,`${e}${Z0}`)}function aD(t){let e=10**Q0;return Math.round(t*e)/e}var cD=4,ke=`
163
+ ${Jw}diff
164
+ ${$M(t.diff,i)}
165
+ ${Jw}`].join(qs);return{argus:o,prompt:a}}function EM(t,e){if(t.argus===void 0)return null;let n=qw-Buffer.byteLength(e)-qs.length*SM;return Kw(t.argus.candidates,Math.max(0,Math.min(t.argus.maxBytes,n-wM)))}function $M(t,e){let n=Buffer.from(t.trimEnd());if(n.length<=e)return n.toString();let r=`
166
+ [diff truncated after ${e} bytes; read the changed files in the copy]`;return`${n.subarray(0,Math.max(0,e-Buffer.byteLength(r))).toString().replace(/\uFFFD$/,"")}${r}`}var AM={GIT_AUTHOR_DATE:"@0 +0000",GIT_AUTHOR_EMAIL:"ari@localhost",GIT_AUTHOR_NAME:"ari",GIT_COMMITTER_DATE:"@0 +0000",GIT_COMMITTER_EMAIL:"ari@localhost",GIT_COMMITTER_NAME:"ari"},Xw=["--no-color","--no-ext-diff","--no-textconv","--no-renames"],zw=[":(glob,exclude).ari/tasks/*.json",":(glob,exclude).ari/knowledge/**"],CM="review:",RM=1;async function Zw(t){let{config:e,root:n,task:r}=t,{agent:o,model:s}=e.review,i=Cr(e,{agent:o,model:s,role:"review",route:null}),a=TM(xM(n,It(r.contract.id)),"utf8"),{argus:c}=e.review,l=await yp({...t,contractText:a,...c===void 0?{}:{argus:{argus:c,explicit:!1}}},i),u=l.ok?"passed":"failed",d=[...l.problems,...l.findings.map(Ec),...l.argus===void 0?[]:Sc(l.argus)],p=`the review agent ${l.agent} ${u} the change`;return kt("review",l.ok,p,d,[l.evidence])}async function yp(t,e){let{config:n,root:r,task:o}=t,s=OM(o);await Xn({config:n,root:r},`start the agent "${e.name}"`);let i=await Ae(r,[]),a=await IM(r,i,s,o.contract.id),c=Ke((await F(r,["diff","--name-only","-z",...Xw,s,a,"--",".",...zw])).stdout),l=t.argus===void 0?null:await Dw({...t.argus,base:s,changedFiles:c,config:n,root:r});if(l!==null)await yc(r,i);let u=(await F(r,["diff",...Xw,s,a,"--",".",...zw])).stdout,{argus:d,prompt:p}=Yw({...l===null||t.argus===void 0?{}:{argus:{candidates:l.candidates,maxBytes:t.argus.argus.maxBytes}},base:s,changedFiles:c,contract:o.contract,contractPath:It(o.contract.id),contractText:t.contractText,diff:u,stage:t.stage}),g=e.config.timeoutSeconds??n.checkTimeoutSeconds,f=performance.now(),y=await mc(r,a,async(Q)=>{let Xr=await Ya(e,p,{cwd:Q,environment:qa(e.config),stdout:"capture",timeoutSeconds:g,trust:{config:n,root:r}});return{copyChanged:await Ae(Q,[])!==i,ran:Xr}}),S=Math.round(performance.now()-f),I=await Ae(r,[])!==i,{ran:C}=y,q=d===null||l===null?new Map:bw(l.candidates,d.included),G=Vw(C.stdout,q.size===0?[]:[Zn]),N=G.verdict===null?[]:Ww(G.verdict),H=[...C.timedOut?[`the review agent did not finish within ${g} seconds`]:[],...!C.timedOut&&C.exitCode!==0?[`the review agent exited with ${C.exitCode}`]:[],...C.overflowed?["the review agent printed more than 1 MiB"]:[],...y.copyChanged?["the review agent changed files in its copy of the repository"]:[],...I?["the working tree changed while the review ran"]:[]],A=[...H,...G.problem===null?[]:[G.problem],...G.verdict?.verdict==="pass"&&N.length>0?[`the verdict is pass, but ${N.length} finding(s) are critical or major`]:[]],R=A.length===0&&G.verdict?.verdict==="pass",B={command:Ja(e,Zt).join(" "),durationMs:S,exitCode:C.timedOut?null:C.exitCode,expect:"pass",name:`${CM}${e.name}`,ok:R,outputSha256:Z(C.stdout),outputTail:dw(C.stdout),timedOut:C.timedOut},_t=l===null||t.argus===void 0?null:await Gw({before:i,clean:G.verdict!==null&&H.length===0,found:l,input:{argus:t.argus.argus,base:s,config:n,root:r},model:e.model,offered:q,written:G.extras[Zn]});return{agent:e.name,...l===null?{}:{argus:Lw(l,d,_t??void 0)},durationMs:S,evidence:B,exitCode:C.exitCode,findings:G.verdict?.findings??[],model:e.model,ok:R,problems:A,timedOut:C.timedOut,verdict:G.verdict?.verdict??null}}async function IM(t,e,n,r){let o=`ari review snapshot of ${r}`;return(await F(t,["commit-tree","--no-gpg-sign",e,"-p",n,"-m",o],{env:AM})).stdout.trim()}function OM(t){if(t.record.base!==null)return t.record.base;throw new m(`Task "${t.contract.id}" has not started, so it has no change to review`,`Run 'ari start ${t.contract.id}' first`,RM,{tag:"TaskNotStarted"})}var _M="{id}",PM=[".ari/tasks/**",".ari/knowledge/**"];async function wp(t){let e=Nn(t.task,t.pack),r={...t,changedFiles:()=>xe(t.root,rS(t.task)),stage:e},o=[],s=[];for(let[i,a]of e.gates.entries()){let c=await NM(a,r);if(o.push(c),c.ok&&UM(a)&&i<e.gates.length-1)s.push({index:i,result:await KM(a.kind,c,r)})}for(let i of s)o[i.index]=await i.result();return o}function Nn(t,e){let n=e.stages[t.record.stage];if(n)return n;throw new m(`Task "${t.contract.id}" is at stage ${t.record.stage}, but pack "${e.name}" has ${e.stages.length}`,`Restore the stages of pack "${e.name}", or amend the task's pack`)}async function Ys(t,e,n){let r=await An(t,e.testGlobs);return Object.fromEntries(Object.entries(r).filter(([o])=>!yo(o)&&et(o,n.scope)))}async function Sp(t,e,n){let o=e.gates.flatMap((s)=>s.kind==="artifact"?[Ro(s.path,n)]:[]).flatMap((s)=>{let i=eS(t,s);return kd(i)?.isFile()?[[s,Z(tS(i))]]:[]});return{artifactHashes:Object.fromEntries(o),treeHash:await Ae(t,PM)}}function Xs(t,e){return[...new Set([...Object.keys(t),...Object.keys(e)])].sort(O).flatMap((r)=>{let o=t[r],s=e[r];if(o===s)return[];if(o===void 0)return[`added ${r}`];return s===void 0?[`deleted ${r}`]:[`changed ${r}`]})}async function NM(t,e){switch(t.kind){case"criteria":return DM(e.task.contract);case"checks":return LM(t.select,t.expect,e);case"invariants":return MM(e);case"scope":return jM(e);case"locked":return FM(e);case"tests-unchanged":return GM(e);case"regression":return yw({base:rS(e.task),changedFiles:await e.changedFiles(),config:e.config,contract:e.task.contract,root:e.root});case"artifact":return HM(t,e);case"approval":return vp("approval",e);case"review":return BM(e);case"command":return VM(t.run,e)}}function DM(t){let e=rd(t),n=e.length===0?`${t.criteria.length} ${wt(t.criteria.length,"criterion","criteria")} bound to existing checks`:`${e.length} criteria ${wt(e.length,"problem","problems")}`;return kt("criteria",e.length===0,n,e)}async function LM(t,e,n){let r=po(n.task.contract,t);if(r.length===0)return kt("checks",!1,`no check matches the selection "${t}"`);let o=await Je(r,e,n.root),s=Or(o),i=e==="pass"?"passed":"failed as expected",a=`${o.length-s.length} of ${o.length} ${wt(o.length,"check","checks")} ${i}`;return kt("checks",s.length===0,a,s,o)}async function MM(t){let e=t.task.contract.invariants.map((s,i)=>({name:`invariants[${i}]`,run:s,timeoutSeconds:t.config.checkTimeoutSeconds})),n=await Je(e,"pass",t.root),r=Or(n),o=`${n.length-r.length} of ${n.length} ${wt(n.length,"invariant","invariants")} passed`;return kt("invariants",r.length===0,o,r,n)}async function jM(t){let e=ne(await t.changedFiles()),n=e.filter((o)=>!et(o,t.task.contract.scope)),r=n.length===0?`${e.length} changed ${wt(e.length,"file","files")} inside the scope`:`${n.length} of ${e.length} changed ${wt(e.length,"file","files")} outside the scope`;return kt("scope",n.length===0,r,n)}async function FM(t){let e=await An(t.root,t.task.contract.lock),n=Xs(t.task.record.lockHashes,e),r=Object.keys(t.task.record.lockHashes).length,o=n.length===0?`${r} locked ${wt(r,"file","files")} unchanged`:`${n.length} locked ${wt(n.length,"file","files")} changed`;return kt("locked",n.length===0,o,n)}async function GM(t){let e=await Ys(t.root,t.config,t.task.contract),n=Xs(t.task.record.stageTestHashes,e),r=Object.keys(t.task.record.stageTestHashes).length,o=n.length===0?`${r} test ${wt(r,"file","files")} unchanged since the stage started`:`${n.length} test ${wt(n.length,"file","files")} changed since the stage started`;return kt("tests-unchanged",n.length===0,o,n)}function HM(t,e){let{contract:n}=e.task,r=Ro(t.path,n.id),o=eS(e.root,r),s=kd(o),i=t.sections!==void 0||t.traceable===!0;if(!s?.isFile()){let g=t.sections===void 0?[]:[`Write ${r} with the sections: ${t.sections.join(", ")}`];return kt("artifact",!1,`${r} does not exist`,g)}let a=`${r} has ${s.size} bytes`,c=s.size<t.minBytes?`${a}; it needs at least ${t.minBytes}`:null;if(!i)return kt("artifact",c===null,c??a);let l=ty({contractPath:It(n.id),criteria:n.criteria.map((g)=>g.id),path:r,requirements:{sections:t.sections??[],traceable:t.traceable===!0},text:tS(o,"utf8")}),u=c===null?l.problems:[c,...l.problems];if(u.length>0)return kt("artifact",!1,`${r} has ${u.length} ${wt(u.length,"problem","problems")}`,u);let d=`${l.filled} required ${wt(l.filled,"section","sections")} filled`,p=t.traceable===!0?`, ${l.traced} ${wt(l.traced,"criterion","criteria")} traced`:"";return kt("artifact",!0,`${a}, ${d}${p}`)}function Ro(t,e){return t.replaceAll(_M,e)}function UM(t){return t.kind==="approval"||t.kind==="review"}async function KM(t,e,n){let{agent:r,command:o}=n.config.review;if(t==="approval"||o===null&&r===void 0)return()=>vp(t,n);let s=await kp(n);return async()=>{if(nS(s,await kp(n)))return e;return kt(t,!1,"the working tree changed while the gates after the review ran",[],e.checks)}}function kp(t){return Sp(t.root,t.stage,t.task.contract.id)}function nS(t,e){return t.treeHash===e.treeHash&&Xs(t.artifactHashes,e.artifactHashes).length===0}async function vp(t,e){let n=e.stage.name,r=`a human runs 'ari approve ${e.task.contract.id}'`,o=e.task.record.approvals.filter((c)=>c.stage===n);if(o.length===0)return kt(t,!1,`stage ${n} has no approval; ${r}`);let s=await kp(e),i=o.filter((c)=>nS(c,s));if(i.length>0)return kt(t,!0,`stage ${n} approved by ${Qw(i)}`);let a=`the working tree changed after ${Qw(o)} approved stage ${n}`;return kt(t,!1,`${a}; ${r} again`)}function Qw(t){return[...new Set(t.map((e)=>e.by))].join(", ")}async function BM(t){let{agent:e,command:n}=t.config.review;if(e!==void 0){let{config:c,root:l,stage:u,task:d}=t;return Zw({config:c,root:l,stage:u.name,task:d})}if(n===null)return vp("review",t);let r={name:"review",run:n,timeoutSeconds:t.config.checkTimeoutSeconds},o={config:t.config,root:t.root},s=await Vs(o,"run review.command",[r],"pass",t.root),i=Or(s),a=i.length===0?"the review command passed":"the review command failed";return kt("review",i.length===0,a,i,s)}async function VM(t,e){let n={name:"command",run:t,timeoutSeconds:e.config.checkTimeoutSeconds},r={config:e.config,root:e.root},o=await Vs(r,"run a command gate of a project pack",[n],"pass",e.root),s=Or(o),i=s.length===0?`${t} passed`:`${t} failed`;return kt("command",s.length===0,i,s,o)}function rS(t){if(t.record.base!==null)return t.record.base;throw Error(`Task "${t.contract.id}" has no base commit; gates run only after 'ari start'`)}import{closeSync as WM,existsSync as JM,fstatSync as qM,openSync as YM,readSync as XM}from"fs";import{join as zM}from"path";var ZM="journal",QM=".jsonl",oS=65536,tj=1000,$c=10;function Tc(t,e,n){let r=[];if(n===0)return r;for(let o of nj(iS(t,e))){let s=aS(o,e);if(s!==null)r.push(s);if(r.length===n)break}return r.reverse()}function*sS(t,e){let n=[];for(let r of ej(iS(t,e))){let o=aS(r,e);if(o===null)continue;if(n.push(o),n.length<tj)continue;yield n,n=[]}if(n.length>0)yield n}function iS(t,e){return zM(t,ZM,`${qn(e)}${QM}`)}function aS(t,e){try{let n=Da(JSON.parse(t.toString("utf8")));return n.task===e?n:null}catch(n){if(n instanceof SyntaxError||n instanceof b)return null;throw n}}function*ej(t){let e=[];for(let n of cS(t,!1)){let r=0;for(let o=n.indexOf($c);o!==-1;o=n.indexOf($c,r))yield Buffer.concat([...e,n.subarray(r,o)]),e=[],r=o+1;e.push(n.subarray(r))}yield Buffer.concat(e)}function*nj(t){let e=[];for(let n of cS(t,!0)){let r=n.length;for(let o=n.lastIndexOf($c);o!==-1;o=o===0?-1:n.lastIndexOf($c,o-1))yield Buffer.concat([n.subarray(o+1,r),...e]),e=[],r=o;e.unshift(n.subarray(0,r))}yield Buffer.concat(e)}function*cS(t,e){if(!JM(t))return;let n=YM(t,"r");try{let{size:r}=qM(n);for(let o=0;o<r;o+=oS){let s=Math.min(oS,r-o),i=Buffer.alloc(s),a=XM(n,i,0,s,e?r-o-s:o);yield i.subarray(0,a)}}finally{WM(n)}}import{randomUUID as cj}from"crypto";import{mkdirSync as lj,readFileSync as uj,renameSync as dj,rmSync as pj,writeFileSync as gj}from"fs";import{basename as mj,dirname as lS,join as uS}from"path";var rj=/\p{M}+/gu,oj=/[\u00DF\u00E6\u0111\u00F0\u0127\u0131\u0142\u0153\u00F8\u00FE]/g,sj=/[^a-z0-9]+/,ij={\u{e6}:"ae",\u{f0}:"d",\u{111}:"d",\u{127}:"h",\u{131}:"i",\u{142}:"l",\u{f8}:"o",\u{153}:"oe",\u{df}:"ss",\u{fe}:"th"};function zs(t,e){if(!Number.isInteger(e)||e<=0)throw Error(`slugify needs a positive maxWords, got ${e}`);let r=t.toLowerCase().normalize("NFKD").replace(rj,"").replace(oj,(o)=>ij[o]??"").split(sj).filter((o)=>o.length>0).slice(0,e).join("-");return aj(r)}function aj(t){if(t.length<=64)return t;let e=t.lastIndexOf("-",64);return e>0?t.slice(0,e):t.slice(0,64)}function Zs(t,e){if(t.length===0)throw Error("uniqueId needs a non-empty base");let n=new Set(e);if(!n.has(t))return t;let r=2;while(n.has(`${t}-${r}`))r++;return`${t}-${r}`}var fj=["constraint","decision"],hj=6,yj=10,kj="knowledge",wj=".md",Sj=4,vj="\x00",bj=",",Ej={"[":"]","{":"}"},$j="\\",Tj=()=>new Date().toISOString();function bp(t,e,n){let r=nt(t.text,`${e}.text`).trim(),o=yt(r);if(o>n)throw new b(`${e}.text is ${o} bytes, but a knowledge entry holds at most ${n}`);return{kind:K(le,t.kind,`${e}.kind`),scope:wa(t.scope,`${e}.scope`),text:r}}function dS(t){return le.includes(t)}function Qs(t,e){return{created:e.created,id:e.id,kind:t.kind,scope:[...t.scope],sources:[...e.sources],status:"active",supersededBy:null,supersedes:[...e.supersedes],text:t.text}}function Ep(t,e){let n=zs(t.text,hj),r=Zs(n.length>0?n:t.kind,e);return e.add(r),r}function $p(t,e,n,r){for(;;){let o=Qs(e,{...n,id:Ep(e,r)});try{return Ba(t,o),o}catch(s){if(!an(t).includes(o.id))throw s}}}function dn(t,e){return{...t,status:"archived",supersededBy:e}}function pn(t){return fj.includes(t.kind)}function Io(t){return t.slice(0,yj)}function ti(t,e){let n=Oe(t,e.id),r=uS(lS(n),`.${mj(n)}.${process.pid}.${cj()}.tmp`);lj(lS(n),{recursive:!0});try{gj(r,br(e)),dj(r,n)}catch(o){throw pj(r,{force:!0}),o}}function xj(t){let e=new Map;for(let n of t){if(n.record.status!=="done")continue;for(let r of n.record.knowledgeUsed)e.set(r,(e.get(r)??0)+1)}return e}async function Oo(t){let e=await F(t,["ls-files","--cached","--others","--exclude-standard","-z"]);return ne([...new Set(e.stdout.split(vj).filter((n)=>n.length>0))])}function xc(t,e,n){if(t.length===0||e.length===0)return!0;return t.some((o)=>e.some((s)=>o===s||et(o,[s])||et(s,[o])))||n.some((o)=>et(o,t)&&et(o,e))}function pS(t){let e=[],n=[],r="";for(let o=0;o<t.length;o++){let s=t[o]??"";if(s===$j){r+=t.slice(o,o+2),o++;continue}let i=Ej[s];if(i!==void 0)n.push(i);else if(s===n.at(-1))n.pop();if(s===bj&&n.length===0){e.push(r.trim()),r="";continue}r+=s}return e.push(r.trim()),e.filter((o)=>o.length>0)}function Aj(t,e,n={}){let r=M(t),o=At("note","Shorten the text or fix the --kind and --scope values",()=>bp(e,"note",r.knowledge.maxEntryBytes)),i={created:Io((n.clock??Tj)()),sources:[...n.sources??[]],supersedes:[]};return $p(t,o,i,new Set(an(t)))}async function gS(t,e,n={}){M(t);let r=gt(await P(t))?.task,o=r!==void 0&&de(t).includes(r)?[r]:[];return Aj(t,e,{...n,sources:o})}function Tp(t,e={}){return M(t),{entries:pe(t).filter((r)=>e.all===!0||r.status==="active")}}function mS(t,e,n={}){let{entries:r}=Tp(t,n),o=new Map(r.map((a)=>[a.id,a]));return{matches:gc(e,r.map((a)=>({id:a.id,text:a.text}))).flatMap(({id:a,score:c})=>{let l=o.get(a);return l===void 0||c<=0?[]:[{entry:l,score:Cj(c)}]}),query:e}}function fS(t,e,n){return{entry:ei(t,e),uses:xj(n).get(e)??0}}function hS(t,e,n={}){let r=ei(t,e);if(r.status==="archived")throw new m(`Knowledge entry "${e}" is already archived`,"Run 'ari knowledge list' to see the active entries");if(pn(r)&&n.force!==!0)throw new m(`Knowledge entry "${e}" is a ${r.kind}; ${r.kind} entries are archived only on purpose`,`Run 'ari knowledge archive ${e} --force' if it no longer holds`);let o=dn(r,null);return ti(t,o),o}function ei(t,e){if(M(t),an(t).includes(e))return Ca(e,uj(Oe(t,e),"utf8"));throw new m(`Knowledge entry "${e}" does not exist`,"Run 'ari knowledge list --all' to see every entry")}function Oe(t,e){return uS(t,J,kj,`${e}${wj}`)}function Cj(t){let e=10**Sj;return Math.round(t*e)/e}var Rj=4,_e=`
154
167
 
155
- `,ow=`
156
- `,lD=3,uD=/`+/g,dD=/^ {0,3}(?:```|~~~)/,pD=/\n+$/,gD=/\n/g,sw=`
157
- `,Dd="none",Qk={constraint:0,decision:1},Ld={contract:{title:"Contract",unit:"contract"},failure:{title:"Last failed attempt",unit:"failed attempt"},journal:{title:"Journal tail",unit:"journal event"},knowledge:{title:"Knowledge",unit:"knowledge entry"},notes:{title:"Task notes",unit:"task note"},rules:{title:"Constraints and decisions",unit:"constraint or decision entry"},task:{title:"Task",unit:"task header"}},mD=["failure","rules","notes","knowledge","journal"],fD=/y$/,hD=()=>new Date().toISOString();async function ao(t,e={}){let n=L(t),r=await M(t),o=e.id??yD(r),s=e.budget??n.context.budget,{task:i}=lt(t,o,n),a=Ne(t).filter((m)=>m.status==="active"),c=(await io(t)).filter((m)=>Z(m,i.contract.scope)),l=SD(t,i),u=TD(i),d=[...ED(i.record.lastFailure),...$D(i,a,c),...bD(i.record.notes),...vD(i,a,c),...xD(Ka(r,o,n.context.journalTail))],p=kD(o,s,l,u,d);if(i.record.status!=="done"){let m=(e.clock??hD)(),f={[Jr]:p.knowledge,tokens:p.estimatedTokens};ar(r,{at:m,detail:f,task:o,type:"context"})}return p}function yD(t){let e=ut(t);if(e!==null)return e.task;throw new g("No task is active in this worktree","Pass a task id: ari context <id>")}function kD(t,e,n,r,o){let s=e*cD,i=[n,Wa(r.fields,r.body)],a=tw(o,vt(i.join(ke)),Number.POSITIVE_INFINITY),c=vt(ew(i,a.sections,null))<=s,l=vt(`${ke}${rw(e,nw(o))}`),u=c?i:[n,wD(t,n,r,s-l)],d=u.join(ke),p=c?a:tw(o,vt(d)+l,s),m=nw(p.omitted),f=ew(u,p.sections,m.length===0?null:rw(e,m)),y=[_d("task",u[0]??"",1),_d("contract",u[1]??"",1),...p.sections.map((S)=>_d(S.name,iw(S),S.items.length))];return{budget:e,estimatedTokens:cd(f),knowledge:p.sections.flatMap((S)=>S.knowledge),omitted:m,sections:y,sha256:tt(f),task:t,text:f}}function wD(t,e,{body:n,fields:r},o){let s=Wa(r,n);if(vt([e,s].join(ke))<=o)return s;let i=`_The contract body is shortened to fit the budget; read ${bt(t)}._`,a=o-vt([e,Wa(r,i)].join(ke))-ke.length,c=[];for(let d of n.split(`
158
- `)){if(a-=vt(d)+1,a<0)break;c.push(d)}let l=c.flatMap((d,p)=>dD.test(d)?[p]:[]),u=l.length%2===0?c:c.slice(0,l.at(-1));return Wa(r,[u.join(`
159
- `).trim(),i].filter((d)=>d.length>0).join(ke))}function Wa(t,e){return e.length===0?t:`${t}${ke}${e}`}function tw(t,e,n){let r=[],o=[],s=e;for(let i of t){let a=r.at(-1),c=a?.name===i.section,l=c?ow:`${ke}${Md(i.section)}${ke}`,u=vt(l)+vt(i.text);if(s+u>n){o.push(i);continue}s+=u;let d=c&&a?a:{items:[],knowledge:[],name:i.section};if(d!==a)r.push(d);if(d.items.push(i.text),i.knowledgeId!==null)d.knowledge.push(i.knowledgeId)}return{omitted:o,sections:r}}function ew(t,e,n){return[...[...t,...e.map(iw)],...n===null?[]:[n]].join(ke)}function iw(t){return`${Md(t.name)}${ke}${t.items.join(ow)}`}function Md(t){return`## ${Ld[t].title}`}function _d(t,e,n){return{estimatedTokens:cd(e),items:n,name:t,text:e,title:Ld[t].title}}function nw(t){return mD.flatMap((e)=>{let n=t.filter((r)=>r.section===e).length;return n===0?[]:[{count:n,section:e}]})}function rw(t,e){let n=e.map(({count:r,section:o})=>{let{unit:s}=Ld[o];return`${r} ${r===1?s:`${s.replace(fD,"ie")}s`}`});return`_Omitted to fit the budget of ${t} tokens: ${n.join(", ")}._`}function SD(t,e){let{contract:n,record:r}=e,o=sr(n.pack,me(t)),s=Tn(e,o);return[`# ${n.id}: ${n.title}`,"",`- Status: ${r.status}`,`- Pack: ${o.name}`,`- Stage: ${s.name} (${r.stage+1} of ${o.stages.length})`,`- Instruction: ${jn(Vr(s,n.id))}`,...r.question===null?[]:[`- Question: ${jn(r.question)}`]].join(`
160
- `)}function TD(t){let{contract:e}=t,n=e.criteria.map((i)=>{let a=i.checks.length===0?Dd:i.checks.join(", ");return`- ${i.id}: ${jn(i.text)} (checks: ${a})`}),r=e.checks.map((i)=>`- ${i.name} (expect ${i.expect}, timeout ${i.timeoutSeconds}s): ${Va(i.run)}`),o=e.invariants.map((i)=>`- ${Va(i)}`),s=[Md("contract"),"",`Scope: ${Nd(e.scope)}`,`Lock: ${Nd(e.lock)}`,...Pd("Criteria:",n),...Pd("Checks:",r),...Pd("Invariants:",o)];return{body:e.body.trim(),fields:s.join(`
161
- `)}}function Pd(t,e){return e.length===0?[`${t} ${Dd}`]:[t,...e]}function ED(t){if(t===null)return[];let e=t.gates.filter((r)=>!r.ok).flatMap((r)=>[`- ${r.gate}: ${jn(r.summary)}`,...r.details.map((o)=>` - ${jn(o)}`),...r.checks.filter((o)=>!o.ok&&o.outputTail.length>0).map((o)=>` ${o.name} output:${sw}${jn(AD(o.outputTail))}`)]);return[{knowledgeId:null,section:"failure",text:[`Stage ${t.stage} at ${t.at}:`,...e].join(`
162
- `)}]}function $D(t,e,n){return aw(t,e,n).sort((r,o)=>(Qk[r.kind]??0)-(Qk[o.kind]??0)).map((r)=>cw("rules",r))}function aw(t,e,n){return e.filter((r)=>Mn(r)&&Ba(r.scope,t.contract.scope,n))}function bD(t){return t.map((e,n)=>({index:n,note:e})).sort((e,n)=>I(n.note.at,e.note.at)||n.index-e.index).map(({note:e})=>({knowledgeId:null,section:"notes",text:`- ${e.at}: ${jn(e.text)}`}))}function vD(t,e,n){let r=new Set(aw(t,e,n).map((l)=>l.id)),o=e.filter((l)=>!r.has(l.id)),s=new Map(o.map((l)=>[l.id,l])),{contract:i}=t,a=[i.title,i.body,...i.criteria.map((l)=>l.text)].join(`
163
- `);return Pa(a,o.map((l)=>({id:l.id,text:l.text}))).flatMap(({id:l})=>{let u=s.get(l);return u===void 0?[]:[cw("knowledge",u)]})}function cw(t,e){let n=e.scope.length===0?"":` (scope: ${Nd(e.scope)})`;return{knowledgeId:e.id,section:t,text:`- ${e.kind} ${Va(e.id)}${n}: ${jn(e.text)}`}}function xD(t){return t.map((e)=>({knowledgeId:null,section:"journal",text:`- ${e.at} ${e.type} ${JSON.stringify(JSON.parse(ht(e.detail)))}`}))}function Nd(t){return t.length===0?Dd:t.map(Va).join(", ")}function Va(t){let e="`".repeat(lw(t)+1),n=t.startsWith("`")||t.endsWith("`")?" ":"";return`${e}${n}${t}${n}${e}`}function AD(t){let e="`".repeat(Math.max(lD,lw(t)+1));return`${e}
164
- ${t.replace(pD,"")}
165
- ${e}`}function lw(t){return Math.max(0,...[...t.matchAll(uD)].map((e)=>e[0].length))}function jn(t){return t.replace(gD,sw)}function uw(t,e){let n=Math.max(t.length,e.length);return n===0?1:1-Ll(t,e)/n}var CD=3;function jd(t,e,n,r){return{clusters:RD(t,r),decisions:OD(t,n),notes:ID(e)}}function Fd(t,e,n){let r=wu(t),o=wu(e),s=Math.max(r.length,o.length);if(s>0&&Math.min(r.length,o.length)/s<n)return 0;return uw(r,o)}function RD(t,e){let n=new Map(t.map((i)=>[i.id,i.id])),r=new Map,o=(i)=>{let a=n.get(i)??i;return a===i?i:o(a)};t.forEach((i,a)=>{for(let c of t.slice(a+1)){let l=Fd(i.text,c.text,e.knowledge.mergeSimilarity);if(l<e.knowledge.mergeSimilarity)continue;let[u,d]=[o(i.id),o(c.id)].sort(I);n.set(d,u),r.set(u,Math.max(r.get(u)??0,r.get(d)??0,l))}});let s=new Map;for(let i of t){let a=o(i.id);s.set(a,[...s.get(a)??[],i.id])}return[...s.entries()].filter(([,i])=>i.length>1).map(([i,a])=>({ids:a,similarity:_D(r.get(i)??0)})).sort((i,a)=>I(i.ids[0]??"",a.ids[0]??""))}function ID(t){return t.filter((e)=>e.record.status==="done").flatMap((e)=>e.record.notes.flatMap((n,r)=>n.promoted?[]:[{at:n.at,note:r,task:e.contract.id,text:n.text}]))}function OD(t,e){let n=t.filter((r)=>r.kind==="decision");return n.flatMap((r,o)=>n.slice(o+1).filter((s)=>Ba(r.scope,s.scope,e)).map((s)=>({ids:[r.id,s.id]})))}function _D(t){let e=10**CD;return Math.round(t*e)/e}import{existsSync as ZD,readFileSync as xw}from"fs";function Gd(t,e){let n=dw(t),r=dw(e),o=PD(n,r),s=[],i=0,a=0;while(i<n.length&&a<r.length)if(n[i]===r[a])i++,a++;else if(Cs(o,i+1,a)>=Cs(o,i,a+1))s.push(`-${n[i]}`),i++;else s.push(`+${r[a]}`),a++;for(let c of n.slice(i))s.push(`-${c}`);for(let c of r.slice(a))s.push(`+${c}`);return s}function dw(t){if(t.length===0)return[];let e=t.split(`
166
- `);if(e.at(-1)==="")e.pop();return e}function PD(t,e){let n=Array.from({length:t.length+1},()=>Array(e.length+1).fill(0));for(let r=t.length-1;r>=0;r--){let o=n[r]??[];for(let s=e.length-1;s>=0;s--)o[s]=t[r]===e[s]?Cs(n,r+1,s+1)+1:Math.max(Cs(n,r+1,s),Cs(n,r,s+1))}return n}function Cs(t,e,n){return t[e]?.[n]??0}import{existsSync as Ud,mkdirSync as BD,readdirSync as WD,readFileSync as $w}from"fs";import{join as Os}from"path";var Rs=1,pw=["pass","apply","undo"];var ND=/^[0-9a-f]{64}$/,yw=["version","id","at","kind"],gw=[...yw,"forced","reason","proposal","pruned","archived","created","promoted"],mw=[...yw,"undoes","restored","removed","unpromoted"],DD=["duplicate","decay","budget","merge","proposal"],LD=["merge","promotion"],MD=["utf8","base64"];function kw(t,e,n){return Tt(`sleep ledger entry ${e}`,n,()=>jD(t))}function jD(t){let e=C(t,"entry",mw.concat(gw)),n=V(pw,e.kind,"kind"),r=$t(e.version,"version");if(r!==Rs)throw new b(`version ${r} is not supported`);let o={at:x(e.at,"at"),id:x(e.id,"id"),version:Rs};if(n==="undo"){let i=C(t,"entry",mw);return{...o,kind:n,removed:D(i.removed,"removed",fw),restored:D(i.restored,"restored",fw),undoes:x(i.undoes,"undoes"),unpromoted:D(i.unpromoted,"unpromoted",hw)}}let s=C(t,"entry",gw);return{...o,archived:D(s.archived,"archived",FD),created:D(s.created,"created",GD),forced:Mt(s.forced,"forced"),kind:n,promoted:D(s.promoted,"promoted",hw),proposal:s.proposal===null?null:KD(s.proposal),pruned:D(s.pruned,"pruned",UD),reason:Ct(s.reason,"reason")}}function FD(t,e){let n=C(t,e,["id","reason","supersededBy","original","sha256"]);return{id:x(n.id,`${e}.id`),original:Et(n.original,`${e}.original`,HD),reason:V(DD,n.reason,`${e}.reason`),sha256:Is(n.sha256,`${e}.sha256`),supersededBy:Ct(n.supersededBy,`${e}.supersededBy`)}}function GD(t,e){let n=C(t,e,["id","kind","origin","replaces","task","notes","sha256"]);return{id:x(n.id,`${e}.id`),kind:V(Qt,n.kind,`${e}.kind`),notes:D(n.notes,`${e}.notes`,$t),origin:V(LD,n.origin,`${e}.origin`),replaces:jt(n.replaces,`${e}.replaces`),sha256:Is(n.sha256,`${e}.sha256`),task:Ct(n.task,`${e}.task`)}}function HD(t,e){let n=C(t,e,["sha256","encoding","content"]);return{content:x(n.content,`${e}.content`),encoding:V(MD,n.encoding,`${e}.encoding`),sha256:Is(n.sha256,`${e}.sha256`)}}function fw(t,e){let n=C(t,e,["id","sha256"]);return{id:x(n.id,`${e}.id`),sha256:Is(n.sha256,`${e}.sha256`)}}function hw(t,e){let n=C(t,e,["task","notes"]);return{notes:D(n.notes,`${e}.notes`,$t),task:x(n.task,`${e}.task`)}}function UD(t,e){let n=C(t,e,["task","events"]);return{events:$t(n.events,`${e}.events`),task:x(n.task,`${e}.task`)}}function KD(t){let e=C(t,"proposal",["sha256"]);return{sha256:Is(e.sha256,"proposal.sha256")}}function Is(t,e){let n=x(t,e);if(!ND.test(n))throw new b(`${e} must be a SHA-256 hex digest`);return n}var VD="sleep",JD=Os("locks","sleep.ledger.lock"),qD="the sleep ledger",Ja=".json",bw=/^(\d{8}T\d{9}Z)(?:-(\d+))?$/,YD=/[^0-9TZ]/g,ww=10,Hd="Restore the file from a backup, or delete it to drop that entry from the sleep history";function Kd(t){return Os(t,VD)}function fr(t,e){return Au(Os(t,JD),qD,e)}function Bd(t){return bw.test(t)}function co(t){return t.kind!=="undo"}function lo(t,e,n){let r=Kd(t);BD(r,{recursive:!0});let o=e.replace(YD,""),s=1;while(Ud(Tw(t,Sw(o,s))))s++;let i=Sw(o,s),a={...n,at:e,id:i,version:Rs};return ha(Tw(t,i),ht(a),()=>Error(`The sleep ledger entry ${i} already exists`)),a}function _s(t){let e=Kd(t);if(!Ud(e))return[];return WD(e).filter((n)=>n.endsWith(Ja)&&Bd(n.slice(0,-Ja.length))).map((n)=>XD(Os(e,n),n)).sort((n,r)=>zD(n.id,r.id))}function Ps(t){let e=new Map;for(let n of t)if(n.kind==="undo")e.set(n.undoes,n.id);return e}function vw(t){let e=Buffer.from(t),n=e.toString("utf8"),r=Buffer.from(n,"utf8").equals(e);return{content:r?n:e.toString("base64"),encoding:r?"utf8":"base64",sha256:tt(t)}}function Wd(t){return Buffer.from(t.content,t.encoding==="utf8"?"utf8":"base64")}function uo(t){return tt($w(t))}function Vd(t){return Ud(t)?uo(t):null}function Sw(t,e){return e===1?t:`${t}-${e}`}function Tw(t,e){return Os(Kd(t),`${e}${Ja}`)}function XD(t,e){let n;try{n=JSON.parse($w(t,"utf8"))}catch(o){let s=o instanceof Error?o.message:String(o);throw new g(`The sleep ledger entry ${t} is not valid JSON (${s})`,Hd)}let r=kw(n,t,Hd);if(`${r.id}${Ja}`===e)return r;throw new g(`The sleep ledger entry ${t} declares the id "${r.id}"`,Hd)}function zD(t,e){let[n="",r="1"]=Ew(t),[o="",s="1"]=Ew(e);return I(n,o)||Number.parseInt(r,ww)-Number.parseInt(s,ww)}function Ew(t){return bw.exec(t)?.slice(1).filter((e)=>e!==void 0)??[t]}function qa(t,e){return e.map(({after:n,reason:r})=>{let o=ye(t,n.id),s=vw(xw(o));return xs(t,n),{id:n.id,original:s,reason:r,sha256:uo(o),supersededBy:n.supersededBy}})}function Aw(t,e){return e.map(({entry:n,notes:r,origin:o,replaces:s,task:i})=>({id:n.id,kind:n.kind,notes:r,origin:o,replaces:s,sha256:uo(ye(t,n.id)),task:i}))}function Ya(t,e,n){let r=n.map(({entry:s,origin:i})=>({change:"created",diff:Gd("",or(s)),id:s.id,reason:i,supersededBy:null})),o=e.map(({after:s,reason:i})=>({change:i==="merge"?"replaced":"archived",diff:Gd(QD(t,s.id),or(s)),id:s.id,reason:i,supersededBy:s.supersededBy}));return[...r,...o]}function QD(t,e){let n=ye(t,e);return ZD(n)?xw(n,"utf8"):""}function Fn(t){let{activeBytes:e,clusters:n,decisions:r,journaled:o,maxBytes:s,notes:i}=t,a=[...o.length>0?["journals"]:[],...e>s?["budget"]:[],...n+i+r>0?["candidates"]:[]];return{activeBytes:e,candidates:{clusters:n,decisions:r,notes:i},due:a.length>0,journaled:[...o],maxBytes:s,reasons:a}}function hr(t){let e=(n)=>n.record.history.findLast((r)=>r.type==="done")?.at??n.record.history.at(-1)?.at??"";return t.filter((n)=>n.record.status==="done").sort((n,r)=>I(e(r),e(n))||I(n.contract.id,r.contract.id))}function Jd(t,e){return[...new Set(t.record.knowledgeUsed.map((n)=>tL(n,e)))]}function qd(t){let e=eL(t);return(n)=>{let r=new Set,o=[n];for(let s=o.pop();s!==void 0;s=o.pop()){if(r.has(s))continue;r.add(s);let i=t.get(s);if(i===void 0)continue;if(i.status==="active")return i;if(i.supersededBy!==null)o.push(i.supersededBy);o.push(...e.get(s)??[])}return null}}function tL(t,e){let n=new Set([t]),r=t;for(;;){let o=e.get(r)?.supersededBy??null;if(o===null||n.has(o)||!e.has(o))return r;n.add(o),r=o}}function eL(t){let e=new Map;for(let n of t.values())for(let r of n.supersedes)e.set(r,[...e.get(r)??[],n.id]);return e}var nL=["fact","pattern","gotcha"],rL=()=>new Date().toISOString();async function yr(t,e={}){let n=L(t),r=await M(t),o=await io(t),s=(e.clock??rL)();return fr(r,()=>{let{retirements:i,...a}=Iw(t,r,n,o,!0),c=lo(r,s,{archived:qa(t,i),created:[],forced:!1,kind:"pass",promoted:[],proposal:null,pruned:a.pruned,reason:null});return{...a,ledger:c.id}})}async function Cw(t){let e=L(t),n=await M(t),r=await io(t),{retirements:o,...s}=Iw(t,n,e,r,!1);return{...s,changes:Ya(t,o,[]),dryRun:!0}}async function kr(t,e={}){let n=L(t),r=await M(t),{tasks:o}=It(t,n),s=po(new Map(Ne(t).map((a)=>[a.id,a]))),i=e.candidates===!1?{clusters:[],decisions:[],notes:[]}:jd(s,o,await io(t),n);return{activeBytes:Yd(s),clusters:i.clusters.length,decisions:i.decisions.length,journaled:o.filter((a)=>Ow(r,a)).map((a)=>a.contract.id).sort(I),maxBytes:n.knowledge.maxBytes,notes:i.notes.length}}async function Rw(t){return Fn(await kr(t,{candidates:!1})).due?yr(t):null}function Iw(t,e,n,r,o){let{tasks:s}=It(t,n),{pruned:i,tasks:a}=oL(t,e,s,o),c=new Map(Ne(t).map((p)=>[p.id,p])),l=[...aL(c,n),...cL(c,a,n),...lL(c,a,n)],u=l.flatMap(({id:p,reason:m})=>{let f=c.get(p);return f===void 0?[]:[{after:f,reason:m}]}),d=po(c);return{activeBytes:Yd(d),archived:l,candidates:jd(d,a,r,n),maxBytes:n.knowledge.maxBytes,pruned:i,retirements:u}}function oL(t,e,n,r){let o=[],s=n.map((i)=>{let{id:a}=i.contract;if(!Ow(e,i))return i;let c=0,l=(d)=>{let p=sL(d,e,a);return c=p.events,p.record},u=r?Ft(t,e,a,l):l(i.record);if(r)ma(e,a);return o.push({events:c,task:a}),{contract:i.contract,record:u}});return{pruned:o,tasks:s}}function Ow(t,e){return e.record.status==="done"&&Ka(t,e.contract.id,1).length>0}function sL(t,e,n){let r=t,o=0;for(let s of Hk(e,n))r=iL(r,s),o+=s.length;return{events:o,record:r}}function iL(t,e){let n=e.flatMap((r)=>{let o=r.detail[Jr];return r.type==="context"&&Array.isArray(o)?o:[]});return aa(hh(t,n),e)}function po(t){return[...t.values()].filter((e)=>e.status==="active").sort((e,n)=>I(e.id,n.id))}function Yd(t){return t.reduce((e,n)=>e+vt(n.text),0)}function _w(t,e){return I(t.created,e.created)||I(t.id,e.id)}function aL(t,e){let n=[],r=[];for(let o of po(t).filter((s)=>!Mn(s)).sort(_w)){let s=n.find((i)=>i.kind===o.kind&&Fd(i.text,o.text,e.knowledge.duplicateSimilarity)>=e.knowledge.duplicateSimilarity);if(s===void 0){n.push(o);continue}t.set(o.id,Xe(o,s.id)),r.push({id:o.id,reason:"duplicate",supersededBy:s.id})}return r}function cL(t,e,n){let r=hr(e).slice(0,n.knowledge.decayAfterTasks);if(r.length<n.knowledge.decayAfterTasks)return[];let o=new Set(r.flatMap((i)=>Jd(i,t))),s=r.map((i)=>so(i.record.history[0]?.at??"")).sort(I)[0]??"";return po(t).flatMap((i)=>{if(!nL.includes(i.kind)||o.has(i.id))return[];if(I(i.created,s)>=0)return[];return t.set(i.id,Xe(i,null)),[{id:i.id,reason:"decay",supersededBy:null}]})}function lL(t,e,n){let r=new Map;for(let a of hr(e).flatMap((c)=>Jd(c,t)))r.set(a,(r.get(a)??0)+1);let o=po(t).filter((a)=>!Mn(a)).sort((a,c)=>(r.get(a.id)??0)-(r.get(c.id)??0)||_w(a,c)),s=[],i=Yd(po(t));for(let a of o){if(i<=n.knowledge.maxBytes)break;t.set(a.id,Xe(a,null)),i-=vt(a.text),s.push({id:a.id,reason:"budget",supersededBy:null})}return s}import{resolve as qw}from"path";var Pw=new RegExp([/\\\n/,/\\(?<escaped>[\s\S])/,/(?<![^ \t\r\n;&|()])#[^\n]*/,/'(?<single>[^']*)'?/,/"(?<double>(?:[^"\\$]+|\\[\s\S]|\$\(cat <<-?[ \t]*["']?(?<mark>\w+)[^\n]*\n[\s\S]*?\n[ \t]*\k<mark>\n\s*\)|\$)*)"?/,/\(\((?<arithmetic>(?:[^()\n]|\([^()\n]*\))*)\)\)/,/<<(?!<)(?<tabs>-?)[ \t]*(?<delimiter>(?:'[^'\n]*'|"[^"\n]*"|\\.|[^ \t\r\n'"\\`;&|()<>])+)/,/(?:(?<![^ \t\r\n;&|()<>])\d+)?[<>]&[ \t]*(?:\d+-?|-)(?![^ \t\r\n;&|()<>])/,/(?<output>(?:&|(?<![^ \t\r\n;&|()<>])\d+)?>(?!\()[>|&]?)/,/(?<input><<<|(?:(?<![^ \t\r\n;&|()<>])\d+)?<(?!\()>?)/,/(?<separator>&&|\|\||\|&|;;|[<>]?\(|[;&|)\n`])/,/(?<blank>[ \t\r]+)/,/(?<plain>[^ \t\r\n'"\\`;&|()<>#]+|[\s\S])/].map(({source:t})=>t).join("|"),"y"),uL=/[ \t\r\n]/,dL=/\$\(cat <<-?[ \t]*(["'])(\w+)\1\n[\s\S]*?\n[ \t]*\2\n\s*\)/g,pL=/\\[\s\S]/g,gL=/\\([$`"\\\n])/g,mL=/[$`]/,fL=/[$*?[]|\{./;var hL=/['"\\]/g,yL=/^\t+/;var kL=/[(`]/,wL=new Set(["-C","-c","--config-env","--exec-path","--git-dir","--namespace","--work-tree"]);function Xd(t){let e=[],n=[],r=Nw(""),o="words",s=null,i=0,a=(u,d)=>{s=(s??"")+u,r.literal&&=d},c=(u="words")=>{if(s!==null)r[o].push(s);s=null,o=u},l=(u)=>{if(c(),r.literal&&=!kL.test(u),r.words.length+r.inputs.length+r.outputs.length>0)e.push(r);r=Nw(u)};while(i<t.length){Pw.lastIndex=i;let u=Pw.exec(t);if(u===null)break;let{arithmetic:d,blank:p,delimiter:m,double:f,escaped:y,input:S,output:R,plain:v,separator:H,single:J,tabs:N}=u.groups??{};if(i+=u[0].length,y!==void 0)a(y,!0);else if(J!==void 0)a(J,!0);else if(f!==void 0)a(TL(f),SL(f));else if(d!==void 0)a(d,!1);else if(v!==void 0)a(v,!fL.test(v)&&(s!==null||!v.startsWith("~")));else if(p!==void 0&&s!==null)c();else if(R!==void 0)c("outputs");else if(S!==void 0)c("inputs");else if(m!==void 0)c(),n.push({delimiter:m.replace(hL,""),tabs:N!==""});else if(H!==void 0){if(H===`
167
- `)for(let U of n.splice(0)){let{body:_,end:A}=EL(t,i,U);r.inputs.push(_),i=A}l(H)}}return l(""),e}function zd(t){return Xd(t).flatMap((e)=>[e,...[...e.words,...e.inputs].filter((n)=>uL.test(n)).flatMap(zd)])}function Xa(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n]??"";if(!r.startsWith("-"))return{args:t.slice(n+1),directories:e,subcommand:r};if(wL.has(r))n+=1;if(r==="-C")e.push(t[n]??"")}return null}function wr(t){return t.slice(t.lastIndexOf("/")+1)}function Nw(t){return{before:t,inputs:[],literal:!0,outputs:[],words:[]}}function SL(t){return!mL.test(t.replace(dL,"").replace(pL,""))}function TL(t){return t.replace(gL,(e,n)=>n===`
168
- `?"":n)}function EL(t,e,{delimiter:n,tabs:r}){for(let o=e;o<t.length;){let s=t.indexOf(`
169
- `,o),i=s===-1?t.length:s,a=t.slice(o,i);if((r?a.replace(yL,""):a)===n)return{body:t.slice(e,o),end:i};o=i+1}return{body:t.slice(e),end:t.length}}import{basename as $L,isAbsolute as bL,join as vL,resolve as Za}from"path";var xL=/^[A-Za-z_]\w*\+?=/,AL=new Set("! { builtin command do elif else env exec if nohup sudo then time until while".split(" ")),CL=new Map([["mkdir",["created","m mode"]],["rm",["removed",""]],["rmdir",["removed",""]],["tee",["written",""]],["touch",["written","A d r t date reference"]],["truncate",["written","r s reference size"]]]),RL=new Set("ari ariadne cat cd diff echo egrep file gh grep head jq ls popd printf pushd rg tail test wc".split(" ")),IL=new Set("add blame branch commit diff fetch grep log ls-files push show status tag".split(" ")),OL=new Set(["cd","popd","pushd"]),Dw=new Set(["","&&",";",`
170
- `]),_L="S suffix",PL=/^(?:-[a-z0-9E]*i|--in-place)/,NL=/^(?:-[a-zA-Z0-9]*[ef]|--expression|--file)/,DL="e f l expression file line-length",LL=/^-[a-zA-Z0-9]*[eE]/,ML="e E",jL=/^-\w+$/,FL=/^\.\w+$/,GL=/^(?:-[a-zA-Z]*t$|--target-directory)/,HL=/^(?:--staged|-[A-Za-z]*S)/,UL=/^(?:--worktree|-[A-Za-z]*W)/,Lw="of=",Qd="--",Zd=".";function jw(t,e){let n=e,r=e,o=!0,s=t.map((i,a)=>{let c=BL(i,n),[l="",u="-",...d]=Qa(i);if(!OL.has(l))return o=!1,c;return o&&=l==="cd"&&i.literal&&!u.startsWith("-")&&d.length===0,o&&=Dw.has(i.before)&&Dw.has(t[a+1]?.before??""),r=o?Za(r,u):r,n=o?r:null,c});return{directory:r,steps:s}}function Qa({words:t}){let e=t.findIndex((n)=>!xL.test(n)&&!AL.has(n));return e===-1?[]:[wr(t[e]??""),...t.slice(e+1)]}function tc(t,e=""){let n=new Set(e.split(" ")),r=t.indexOf(Qd),o=[],s=r===-1?t:t.slice(0,r);for(let i=0;i<s.length;i+=1){let a=s[i]??"";if(!a.startsWith("-"))o.push(a);else if(n.has(KL(a)))i+=1}return[...o,...r===-1?[]:t.slice(r+1)].filter((i)=>i.length>0)}function KL(t){if(t.startsWith("--"))return t.slice(2);return jL.test(t)?t.slice(-1):""}function BL(t,e){if(!t.literal)return{command:t,resolved:!1,targets:[]};let[n="",...r]=Qa(t),o=n==="git"?Xa(r):null,s=e===null?null:Za(e,...o?.directories??[]),i=o===null?Fw(n,r,e):WL(o.subcommand,o.args,s),a=[...za(e,"file",t.outputs),...za(s,"file",i?.written),...za(s,"directory",i?.created),...za(s,"removed",i?.removed)],c=a.filter((l)=>l!==null);return{command:t,resolved:i!==null&&c.length===a.length,targets:c}}function za(t,e,n=[]){return n.flatMap((r)=>{if(t===null&&!bL(r))return null;let o=Za(t??r,r),s=e!=="removed"&&Sa(o);if(s&&e==="directory")return[];return{kind:s?"directory":e,path:o}})}function Fw(t,e,n){let[r,o]=CL.get(t)??[];if(r!==void 0)return{[r]:tc(e,o)};switch(t){case"dd":return{written:e.filter((s)=>s.startsWith(Lw)).map((s)=>s.slice(Lw.length))};case"cp":case"ln":case"mv":return VL(t,e,n);case"sed":return{written:Mw(e,DL,NL)??[]};case"perl":{let s=Mw(e,ML,LL);return s===null?null:{written:s}}default:return RL.has(t)?{}:null}}function WL(t,e,n){switch(t){case"checkout":return e.includes(Qd)?{removed:e.slice(e.indexOf(Qd)+1)}:null;case"restore":return e.some((o)=>HL.test(o))&&!e.some((o)=>UL.test(o))?{}:{removed:tc(e,"s source pathspec-from-file")};case"rm":case"mv":return Fw(t,e,n);default:return IL.has(t)?{}:null}}function VL(t,e,n){if(e.some((a)=>GL.test(a)))return null;let r=tc(e,_L),[o=Zd,s]=r.length<2?[Zd,r]:[r.at(-1),r.slice(0,-1)],i=o.endsWith("/")||Sa(Za(n??Zd,o));return{removed:t==="mv"?s:[],written:i?s.map((a)=>vL(o,$L(a))):[o]}}function Mw(t,e,n){if(!t.some((s)=>PL.test(s)))return null;let r=tc(t,e),o=r.length>1&&FL.test(r[0]??"")?r.slice(1):r;return t.some((s)=>n.test(s))?o:o.slice(1)}import{basename as Gw,dirname as JL,join as Hw}from"path";var qL=[`${W}/tasks/*.md`,`${W}/designs/**`],YL="x",XL=/\*\*.*/,zL=".git",ZL=[/^(?:ari|hooks|info)(?:\/|$)/,/^(?:HEAD|commondir|config(?:\.worktree)?|gitdir|objects|packed-refs|refs|worktrees)$/,/^(?:objects|refs|worktrees)\/(?!.*\.lock$)/],QL="; pass the paths to change instead of their directory",tM="\x00",ec=0,eM=1,Uw=128;async function Kw(t,e){let n=Nt(e),r=await t.governing(n),o=Vw(t.opened(),n);if(o!==null)return o;return r.flatMap((i)=>{let a=Je(i.root,n);return a===null||a.length===0?[]:Ns(i,a)??[]})[0]??null}async function Bw(t,e){let n=[],r=new Map;for(let{kind:o,path:s}of e){let a=o==="removed"&&ju(s)!==null?Hw(Nt(JL(s)),Gw(s)):Nt(s),c=await t.governing(a),l=Vw(t.opened(),a);if(l!==null)n.push(l);let u=o==="removed"?t.opened().filter(({root:d})=>Je(a,d)!==null):[];for(let d of new Set([...c,...u])){let p=r.get(d)??[];r.set(d,[...p,{file:Je(d.root,a)??"",kind:o}])}}for(let[o,s]of r)n.push(...await nM(o,s));return n}async function nM(t,e){let n=e.filter(({kind:a})=>a==="removed").map(({file:a})=>a),r=n.length===0?[]:await iM(t,n),o=n.flatMap((a)=>r.filter((u)=>a.length===0||u===a||u.startsWith(`${a}/`)).flatMap((u)=>{let d=Ns(t,u);return d===null?[]:`${d}${u===a?"":QL}`}).slice(0,1)),s=e.flatMap(({file:a,kind:c})=>{if(c==="removed"||a.length===0)return[];let l=c==="file"?Ns(t,a):rM(t,a),u=c==="file"?a:`${a}/`;return l===null?[]:[{guarded:Ww(t,a)!==null,name:u,reason:l}]}),i=await aM(t.root,s.filter(({guarded:a})=>!a).map(({name:a})=>a));return[...o,...s.filter(({name:a})=>!i.has(a)).map(({reason:a})=>a)]}function Ww(t,e){if(qr(e)&&!Z(e,qL))return`${e} is written only by ari; use ari commands instead of editing it`;let n=t.workspace?.task??null;if(n===null)return null;return Object.hasOwn(n.record.lockHashes,e)||Z(e,n.contract.lock)?`${e} is locked by task "${n.contract.id}" and must stay unchanged`:null}function Ns(t,e,n=Z){let r=Ww(t,e);if(r!==null||qr(e))return r;let o=t.fault??t.workspace?.drift??null;if(o!==null)return`ari cannot check ${e}: ${o}`;let s=t.workspace?.task??null;if(s===null||n(e,s.contract.scope))return null;let{id:i,scope:a}=s.contract;return`${e} is outside the scope of task "${i}" (${a.join(", ")}); change the scope with a contract edit and 'ari amend ${i} --reason <text>', or ask a human`}function rM(t,e){return Ns(t,`${e}/${YL}`)===null?null:Ns(t,e,oM)}function oM(t,e){let n=t.split("/").length,r=e.map((o)=>o.replace(XL,"**").split("/").slice(0,n).join("/"));return Z(t,r)}function Vw(t,e){return t.some(({gitDirectories:r,root:o})=>Je(Hw(o,zL),e)===""||r.some((s)=>sM(s,e)))?`${Gw(e)} belongs to git and to ari's own state; use git and ari commands instead`:null}function sM(t,e){let n=Je(t,e);return n!==null&&ZL.some((r)=>r.test(n))}async function iM({root:t,workspace:e},n){let r=await P(t,["--literal-pathspecs","ls-files","-z","-co","--exclude-standard","--",...n.map((s)=>s.length===0?".":s)],{allowedExitCodes:[ec,Uw]}),o=r.exitCode===ec?Oe(r.stdout):n;return[...Object.keys(e?.task?.record.lockHashes??{}),W,...o]}async function aM(t,e){if(e.length===0)return new Set;let n=await P(t,["check-ignore","-z","--stdin"],{allowedExitCodes:[ec,eM,Uw],stdin:[...new Set(e)].join(tM)});return new Set(n.exitCode===ec?Oe(n.stdout):[])}var cM="'ari approve' records a human approval; ask a person to run it, and pass text that contains these words in a file, as in 'git commit -F <file>'",lM="'ari trust' records that a person has read the commands in .ari/config.json; ask a person to run it, and to run 'ari trust' without --yes to read them first",uM="'ari uninstall' and 'ari hooks uninstall' remove the hooks that guard this repository; ask a person to run them",dM="'git commit --no-verify' skips ari's pre-commit scope check; commit without --no-verify, -n or core.hooksPath, and fix what the check reports",pM="run it as a plain command with literal paths, or ask a person to run it",gM=/(?:^|\/)(?:ari|ariadne)(?:@[^/]*)?$/,mM="approve",fM="trust",Jw="uninstall",hM="hooks",yM="git",kM="commit",wM="config",SM=/^core\.hookspath$/i,TM=/^(?:--config-env=)?core\.hookspath=|^GIT_CONFIG_KEY_\d+=core\.hookspath$/i,EM=/^(?:--)?unset/,$M=/^(?:--no-veri(?:f|fy)?|-[^-\smFcCtSu]*n\S*)$/,bM=/(?<![\w-])\.ari(?![\w.-])/,tp=/[\s'"`;&|()<>=,]+/,vM=[[/^(?:cp|dd|eval|ln|mkdir|mv|rm|rmdir|tee|touch|truncate|xargs)$/,null],[/^find$/,/^-(?:delete|exec(?:dir)?|ok(?:dir)?)$/],[/^git$/,/^(?:checkout|restore)$/],[/^sed$/,/^(?:-[a-zA-Z]*i|--in-place)/]],xM=/^(?:ba|da|fi|k|z)?sh$/,AM=/^-[a-z]*c$/,CM=/^(?:bun|deno|node|perl|php|python|ruby)[\d.]*$/,RM=/^(?:-[a-zA-Z]*[ceEip]|--eval|--print)$/;async function Yw(t,e,n){let{directory:r,steps:o}=jw(Xd(e),n),s=[...new Set([...await t.governing(n),...await t.governing(r)])],i=IM(zd(e));if(i!==null&&(s.length>0||await OM(t,e,n)))return{kind:"deny",reason:i};let a=await Bw(t,o.flatMap(({targets:d})=>d));if(a.length>0)return{kind:"deny",reason:[...new Set(a)].join("; ")};let c=o.filter(({resolved:d})=>!d).flatMap((d)=>NM(d)??[])[0],l=s.filter(({fault:d,workspace:p})=>d!==null||p?.task!=null),u=c===void 0?null:LM(l,e,[n,r]);if(u===null)return{kind:"allow"};return{kind:"ask",reason:`the command mentions ${u}, which ari protects, and ari does not resolve what its '${c}' writes; ${pM}`}}function IM(t){if(t.some((e)=>nc(e,mM)))return cM;if(t.some((e)=>nc(e,fM)))return lM;if(t.some((e)=>nc(e,Jw)||nc(e,hM,Jw)))return uM;return t.some(_M)?dM:null}async function OM(t,e,n){for(let r of new Set(e.split(tp)))if((await t.governing(qw(n,r))).length>0)return!0;return!1}function nc({words:t},e,n){return t.some((r,o)=>{if(!gM.test(r))return!1;let[s,...i]=t.slice(o+1).filter((a)=>!a.startsWith("-"));return s===e&&(n===void 0||i.includes(n))})}function _M({words:t}){if(t.some((e)=>TM.test(e)))return!0;return t.some((e,n)=>{let r=wr(e)===yM?Xa(t.slice(n+1)):null;if(r?.subcommand===wM)return PM(r.args);return r?.subcommand===kM&&r.args.some((o)=>$M.test(o))})}function PM(t){let e=t.findIndex((n)=>SM.test(n));return e!==-1&&(e<t.length-1||t.some((n)=>EM.test(n)))}function NM({command:t}){let[e]=Qa(t),n=t.words.flatMap((o)=>o.split(tp)).filter((o)=>o.length>0);return n.map(wr).find((o,s)=>DM(o,e,n,s+1))??(!t.literal&&t.outputs.length>0?">":null)}function DM(t,e,n,r){let o=vM.find(([c])=>c.test(t))?.[1];if(o===null)return!0;if(o!==void 0)return n.slice(r).some((c)=>o.test(c));let s=xM.test(t);if(!s&&!CM.test(t))return!1;let i=n.slice(r),a=i.findIndex((c)=>!c.startsWith("-"));if(a===-1&&t===e)return!0;return s?i.some((c)=>AM.test(c)):i.slice(0,a===-1?i.length:a).some((c)=>RM.test(c))}function LM(t,e,n){if(t.length>0&&bM.test(e))return W;let r=new Set(e.split(tp));for(let{root:o,workspace:s}of t){let i=Object.keys(s?.task?.record.lockHashes??{}),a=new Set(i.map(wr));for(let c of[...r].filter((l)=>a.has(wr(l)))){let u=[o,...n].map((d)=>Je(o,Nt(qw(d,c)))).find((d)=>d!==null&&i.includes(d));if(u!==void 0)return u}}return null}var jM="stop.json",FM=500,GM=20000,we={kind:"allow"},HM={decision:{kind:"ask",reason:"ari could not check this in time; write a simpler command, or ask a person to run it"},expired:!0,warning:"ari hook ran out of time"},UM=zt({task:gt(),tree:gt()});async function Zw(t){let e=Xh();if(Sn.has(t.event))return KM(BM(e,t));let n=await e.at(t.cwd);if(n===null)return rc(we);if(n.workspace===null)return Xw(t,n.fault??"");try{return rc(await VM(t,n.workspace))}catch(r){if(!(r instanceof g))throw r;return Xw(t,Gu(r))}}function Xw({event:t},e){return{...rc(we),warning:`ari hook skipped ${t}: ${e}`}}async function KM(t){let e=Promise.withResolvers(),n=setTimeout(e.resolve,GM,HM);try{return await Promise.race([e.promise,t.then(rc)])}finally{clearTimeout(n)}}function rc(t){return{decision:t,expired:!1,warning:null}}async function BM(t,e){let{command:n,cwd:r,event:o,paths:s}=e,i=await t.at(r);if(o==="before-shell"&&n!==null)return Yw(t,n,r);if(o==="before-edit"&&s.length>0)return WM(t,e);if(i===null)return we;return{kind:"ask",reason:`ari found no ${o==="before-edit"?"path":"command"} in the hook payload`}}async function WM(t,e){let n=[];for(let r of e.paths){let o=await Kw(t,zw(e.cwd,r));if(o!==null)n.push(o)}return n.length===0?we:{kind:"deny",reason:n.join("; ")}}async function VM(t,e){switch(t.event){case"before-edit":case"before-shell":return we;case"after-tool":return oc(e,JM(t,e)),we;case"stop":{let n=await qM(e);if(n.kind==="allow"&&e.config.knowledge.sleepOnStop)await YM(e.root);return n}case"pre-compact":return oc(e,{detail:{},type:"compact"}),await yr(e.root),we;case"session-start":return XM(e)}}function JM(t,e){let n=Nt(e.root),r=t.paths.flatMap((o)=>Je(n,Nt(zw(t.cwd,o)))??[]);if(r.length>0)return{detail:{paths:r},type:"edit"};if(t.command!==null)return{detail:{command:t.command.slice(0,FM)},type:"shell"};return{detail:t.tool===null?{}:{tool:t.tool},type:"tool"}}async function qM(t){let{task:e}=t;if(e===null||e.record.status!=="active")return we;let n=e.contract.id,r=await ge(t.root,[ir]);if(e.record.evidence.at(-1)?.treeHash===r)return we;let o=MM(t.state,jM),s=Ea(o,UM,null);if(s?.task===n&&s.tree===r)return we;return cr(o,`${JSON.stringify({task:n,tree:r})}
171
- `),oc(t,{detail:{blocked:!0},type:"stop"}),{kind:"block",reason:`Task "${n}" has changes that no gate has passed yet. Run 'ari check', fix what it reports, then 'ari done'. If you are stuck, run 'ari block ${n} --reason <question>' for a human.`}}async function YM(t){try{await Rw(t)}catch(e){let n=e instanceof Error?e.message:String(e);throw new g(`the sleep pass at stop failed (${n})`,"Run 'ari sleep' to see the failure, or set knowledge.sleepOnStop to false")}}async function XM(t){if(t.task===null)return we;oc(t,{detail:{},type:"session"});let{text:e}=await ao(t.root,{id:t.task.contract.id});return e.trim().length===0?we:{kind:"context",text:e}}function oc(t,e){if(t.task===null)return;ar(t.state,{...e,at:new Date().toISOString(),task:t.task.contract.id})}var go="git",zM={amp:"Amp",opencode:"OpenCode"},ZM=".git/hooks";function ep(){return[...he.map((t)=>t.name),go]}function Se(t){let e=he.find((r)=>r.name===t);if(e!==void 0)return e;if(t===go)throw new T("git hooks run 'ari scope --staged' and 'ari verify' directly","Run 'ari hooks install --agent git'");let n=zM[t];if(n!==void 0)throw new g(`${n} hooks run only as in-process plugins, which ari does not ship`,"Rely on the AGENTS.md block from 'ari init', 'ari hooks install --agent git' and 'ari verify' in CI");throw new T(`Unknown agent "${t}"`,`Choose one of: ${ep().join(", ")}`)}function Qw(t){if(t!==go)Se(t)}async function mo(t,e){if(e===go)return Aa(t);return Dy(t,Se(e),await M(t))}async function tS(t,e){if(e===go)return Ca(t);return _a(t,Se(e),await M(t))}async function eS(t){return[...he.map((n)=>({agent:n.name,events:hs(n),file:n.file,installed:Ye(t,n),label:n.label,support:n.support})),{agent:go,events:[...Ay],file:ZM,installed:await eo(t),label:"git",support:"git"}]}async function nS(t,e,n,r){let o=Se(t),s=QM(o,e);try{let{decision:i,expired:a,warning:c}=await Zw(o.parse(s,tj(n),r));return{expired:a,stdout:zu(o,s,i),warning:c}}catch(i){if(!Sn.has(s))throw i;let a=`ari could not check this ${s} event: ${i instanceof Error?i.message:String(i)}`;return{expired:!1,stdout:zu(o,s,{kind:"deny",reason:a}),warning:a}}}function QM(t,e){if(!ky(e))throw new T(`Unknown hook event "${e}"`,`Choose one of: ${qu.join(", ")}`);if(hs(t).includes(e))return e;throw new T(`${t.label} has no ari adapter for "${e}"`,`Its adapter handles: ${hs(t).join(", ")}`)}function tj(t){if(t.trim().length===0)return{};let e=null;try{e=JSON.parse(t)}catch{}if(Y(e))return e;throw new g("The hook payload on stdin is not a JSON object","Agents call 'ari hook' with a JSON object")}import{homedir as rS}from"os";import{join as ej}from"path";var fo=["project","user"],nj=".ari",rj="receipts",oj="~/";function ho(t){let e=t??"project",n=fo.find((r)=>r===e);if(n!==void 0)return n;throw new T(`Unknown scope "${e}"`,`Choose one of: ${fo.join(", ")}`)}async function Ot(t,e){if(t==="user")return{base:rS(),receipts:ej(rS(),nj,rj),scope:t};let n=await On(e);return{base:n,receipts:await M(n),scope:t}}function ee(t,e){return t==="user"?`${oj}${e}`:e}function Ds(t,e,n){let r=t.find((o)=>o.agent===e);if(r!==void 0)return r;throw new T(`ari has no ${n} integration for "${e}"`,`Choose one of: ${t.map((o)=>o.agent).join(", ")}`)}function np(t,e,n){return[...new Set(e)].map((r)=>Ds(t,r,n))}import{isDeepStrictEqual as dj}from"util";function sc(t){let{base:e,file:n,receipts:r}=t,o=q(e,n),s=t.install(o),i=ro(r.directory,n,r.store),a=t.managed(o)?void 0:o,c=i?.installed===o?i.original:a,l=fe(e,n,s),u=q(e,n)??"";return oo(r.directory,n,c===void 0?null:{installed:u,original:c},r.store),l}function sj(t,e,n){if(e===null||!t.managed(e))return gs;if(n?.installed!==e){let r=t.remove(e);return r===null?ms:no(r,!1)}return n.original===null?ms:no(n.original,!0)}function rp(t,e,n){let{base:r,file:o,receipts:s}=t,i=ro(s.directory,o,s.store),a=Oa(r,o,sj(t,e.read(r,o),i),e);if(n)oo(s.directory,o,null,s.store);return a}function ic(t){return rp(t,Ia,!0).action}function En(t){return t.managed(q(t.base,t.file))}import{isDeepStrictEqual as ij}from"util";var yo="# ari:begin",Ls="# ari:end",Ms=`\r
172
- `,ze=`
173
- `,aj=1,cj=/^\r?\n/,lj=/\r$/;function sS(t){return(t??"").split(ze).some((e)=>sp(e,yo))}function iS(t,e){let n=t??"";op(e.file,n);let r=n.includes(Ms)?Ms:ze,o=[`${yo} managed by 'ari mcp install'; 'ari mcp uninstall' removes it`,...e.lines,Ls].join(r),s=cS(e.file,n);if(s===null&&oS(op(e.file,n),e.table)!==void 0)throw new g(`${e.file} already defines [${e.table.join(".")}] outside ari's managed block`,`Remove that table from ${e.file}, or keep it and do not install ari's`);let i=s===null?uj(n,o,r):n.slice(0,s.start)+o+n.slice(s.end),a;try{a=op(e.file,i)}catch(c){throw new g(`ari cannot add [${e.table.join(".")}] to ${e.file} without breaking it`,`Add the table yourself:
174
- ${e.lines.join(ze)}`,aj,{cause:c})}if(ij(oS(a,e.table),e.value))return i;throw new g(`ari cannot add [${e.table.join(".")}] to ${e.file}: the file defines it in another way`,`Add the table yourself:
175
- ${e.lines.join(ze)}`)}function aS(t,e){let n=cS(t,e);if(n===null)return e;let r=e.slice(0,n.start),o=e.slice(n.end).replace(cj,""),i=(r.endsWith(`${Ms}${Ms}`)?r.slice(0,-Ms.length):r.endsWith(`${ze}${ze}`)?r.slice(0,-ze.length):r)+o;return i.trim().length===0?null:i}function uj(t,e,n){if(t.length===0)return`${e}${n}`;return`${t.endsWith(ze)?t:`${t}${n}`}${n}${e}${n}`}function cS(t,e){let n=[],r=0;for(let i of e.split(ze)){let a=r+i.replace(lj,"").length;if(sp(i,yo))n.push({end:a,kind:yo,start:r});else if(sp(i,Ls))n.push({end:a,kind:Ls,start:r});r+=i.length+ze.length}let[o,s]=n;if(o===void 0)return null;if(n.length!==2||o.kind!==yo||s?.kind!==Ls)throw new g(`${t} has a damaged ari block: expect one '${yo}' line followed by one '${Ls}' line`,`Remove the ari marker lines and the lines between them from ${t}, then run the command again`);return{end:s.end,start:o.start}}function sp(t,e){let n=t.trim();return n===e||n.startsWith(`${e} `)}function op(t,e){try{return Bun.TOML.parse(e)}catch(n){let r=n instanceof Error?n.message:String(n);throw new g(`${t} is not valid TOML (${r})`,`Fix ${t}, then run the command again`)}}function oS(t,e){return e.reduce((n,r)=>typeof n==="object"&&n!==null?n[r]:void 0,t)}var Ze="ari",ip="ari",cc=["mcp","serve"],js="mcpServers",pj="mcp.json",lS=900,gj=1000,mj=2,ac={command:ip,args:cc},Jt=[{agent:"claude",entry:ac,format:"json",label:"Claude Code",project:".mcp.json",user:null,userHint:`Claude Code keeps user-scope servers in its own state file; run 'claude mcp add --scope user ${Ze} -- ${ip} ${cc.join(" ")}'`},{agent:"codex",entry:{...ac,tool_timeout_sec:lS},format:"toml",label:"Codex CLI",project:".codex/config.toml",user:".codex/config.toml",userHint:null},{agent:"gemini",entry:{...ac,timeout:lS*gj},format:"json",label:"Gemini CLI",project:".gemini/settings.json",user:".gemini/settings.json",userHint:null},{agent:"cursor",entry:{type:"stdio",...ac},format:"json",label:"Cursor",project:".cursor/mcp.json",user:".cursor/mcp.json",userHint:null}];function ne(t){return Ds(Jt,t,"MCP")}function Te(t,e){return uc(t,e)}function ko(t,e){let n=uc(t,e);return{...pS(t,e,n.file),action:sc(n)}}function lc(t,e){let n=uc(t,e);return{...pS(t,e,n.file),action:ic(n)}}function dS(t,e){return Jt.map((n)=>({agent:n.agent,files:[t,e].flatMap((r)=>{let o=n[r.scope];if(o===null)return[];let s=En(uc(n,r));return[{file:ee(r.scope,o),installed:s,scope:r.scope}]}),label:n.label}))}function pS(t,e,n){return{agent:t.agent,file:ee(e.scope,n),scope:e.scope,server:Ze}}function uc(t,e){let n=t[e.scope];if(n===null)throw new g(`ari does not write ${t.label}'s ${e.scope}-scope MCP configuration`,t.userHint??"");let r={directory:e.receipts,store:pj},o={base:e.base,file:n,receipts:r};return t.format==="toml"?{...o,...fj(t,n)}:{...o,...hj(t,n)}}function fj(t,e){let n={file:e,lines:[`[mcp_servers.${Ze}]`,...yj(t.entry)],table:["mcp_servers",Ze],value:t.entry};return{install:(r)=>iS(r,n),managed:sS,remove:(r)=>aS(e,r)}}function hj(t,e){let n=(o)=>{let s=o[js]??{};if(Y(s))return s;throw new g(`${e} has a "${js}" value that is not an object`,`Fix ${e}`)},r=(o,s)=>o===null?`${JSON.stringify(s,null,mj)}
176
- `:Wi(o,s);return{install:(o)=>{let s=o===null?{}:Vt(e,o),i=n(s),a=i[Ze];if(a!==void 0&&!uS(a))throw new g(`${e} already has an MCP server named "${Ze}" that ari did not write`,`Rename or remove mcpServers.${Ze} in ${e}, then run the command again`);let c={...Y(a)?a:{},...t.entry};return r(o,{...s,[js]:{...i,[Ze]:c}})},managed:(o)=>o!==null&&uS(n(Vt(e,o))[Ze]),remove:(o)=>{let{[js]:s,...i}=Vt(e,o),{[Ze]:a,...c}=n(Vt(e,o));return r(o,Object.keys(c).length===0?i:{...i,[js]:c})}}}function yj(t){let{args:e,command:n,...r}=t;return Object.entries({command:n,args:e,...r}).map(([o,s])=>`${o} = ${gS(s)}`)}function gS(t){if(Array.isArray(t))return`[${t.map(gS).join(", ")}]`;return typeof t==="number"?String(t):JSON.stringify(t)}function uS(t){if(!Y(t)||t.command!==ip||!Array.isArray(t.args))return!1;return dj(t.args.slice(0,cc.length),cc)}import{existsSync as vj,readdirSync as xj,rmdirSync as Aj}from"fs";import{dirname as hS,join as yS}from"path";var Me="ariadne",mS="SKILL.md",dc="<!-- ari:managed by 'ari skills install'; 'ari skills uninstall' removes it -->";var kj=["---","name: ariadne","description: Work through this repository's Ariadne (ari) tasks, whose contracts, gates and memory the ari CLI keeps. Use it whenever the repository has an .ari/ directory, before changing code there, and when asked to pick up, check, finish or write an ari task.","---"],wj=["# Ariadne","","This repository tracks work as Ariadne tasks. A task's contract (`.ari/tasks/<id>.md`) says what \"done\" means, and `ari` decides when it is done by running the contract's checks itself. Never report a task as finished on your own word: only `ari done` finishes a stage."],Sj=["## The loop","","1. Run `ari next` and follow the one action it prints.","2. Change only files inside the active task's `scope`. Files the contract locks must stay byte-identical.","3. Run `ari check` to evaluate the current stage's gates. It records nothing.","4. Run `ari done`. It records the evidence and advances to the next stage, or prints every failing gate with its output and exits 1. Fix what it reports and run it again.","","Repeat until `ari done` reports `done`. Each failed `ari done` spends an attempt, and a spent budget (3 by default) blocks the task for a person, so run `ari check` first. Add `--json` to any of these commands for one JSON document on stdout. `ari show <id>` prints a task with its stage and instruction, and `ari list` lists the tasks.","","When ari's MCP server is connected, the tools `ari_next`, `ari_check`, `ari_done` and the others do the same and return the same JSON documents."],Tj=["## Writing a contract","",'`ari new "<title>" --scope "src/feature/**"` creates a draft contract. Complete its YAML front matter:',"","```markdown","---","title: Add profile inheritance","pack: basic","scope:"," - src/profiles/**","lock:"," - src/profiles/inheritance.test.ts","criteria:"," - id: AC-1"," text: A child profile's values override its parent's"," checks: [inheritance]","checks:"," inheritance:"," run: bun test src/profiles/inheritance.test.ts"," expect: pass","invariants:"," - bun run lint","---","What the implementer should know.","```","","- `scope` lists globs of the files the task may change. Write `src/**`, never `src/`.","- Bind every criterion to at least one check. A check is a shell command run from the repository root.","- `lock` keeps files, such as the tests that define the work, unchanged from `ari start` onwards.","- `pack` chooses the stages: `basic`, `sdlc`, `tdd`, `bugfix`, `spec-driven`, `refactor` or `spike`.","","Then `ari ready <id>` validates the contract and `ari start <id>` starts the task in this worktree. Starting needs a clean working tree outside `.ari/`."],Ej=["## What the gates mean","","| Gate | Passes when |","| --- | --- |","| `criteria` | every criterion names a check that exists |","| `checks` | each selected check exits as the stage expects; in a `tdd` red stage they must fail |","| `invariants` | every invariant command exits 0 |","| `scope` | every file changed since the task started matches the scope |","| `locked` | the locked files are unchanged |","| `tests-unchanged` | the test files in the scope are unchanged since the stage started |","| `regression` | each regression check fails on the base commit and passes now |","| `artifact` | a file such as `.ari/designs/<id>.md` exists with enough content |","| `approval` | a person approved the stage and nothing has changed since |","| `review` | the review command, or the review agent's verdict, passed the change; `ari review` shows that verdict first and records nothing |","| `command` | the pack's command exits 0 |","","When `ari check` reports `contractChanged` or `gatesChanged`, the contract or the gates differ from the ones frozen at start, and `ari done` refuses. Ask a person to amend the task."],$j=["## Memory","",'- `ari note "<text>"` adds a note to the active task.','- `ari note --global --kind pattern "<text>"` adds project knowledge that outlives the task; the kinds are `fact`, `decision`, `constraint`, `pattern` and `gotcha`.',"- `ari knowledge search <query>` finds project knowledge, and `ari knowledge show <id>` prints one entry.","- `ari context` prints the active task's context pack: the contract, its notes and the relevant knowledge, within a token budget. Run it after your context is reset or compacted."],bj=["## What only people do","","- `ari approve`, `ari amend`, `ari resolve` and `ari trust` are for people. Never run them; ask instead.","- When a command fails with `ConfigNotTrusted`, the configuration's commands are not trusted on this machine yet. Ask a person to run `ari trust`; never set `ARI_TRUST_CONFIG` yourself.",'- When you are stuck, or the contract looks wrong, run `ari block <id> --reason "<question>"` and stop.',"- Never edit `.ari/config.json`, `.ari/tasks/*.json` or `.ari/knowledge/**`: ari writes them. Edit only contracts (`.ari/tasks/*.md`) and designs (`.ari/designs/**`).","- Never skip the git hooks with `git commit --no-verify`.","","`ari --help --json` describes every command and option."];function fS(){let t=[wj,Sj,Tj,Ej,$j,bj].map((e)=>e.join(`
177
- `));return`${[...kj,"<!-- ari:managed by 'ari skills install'; 'ari skills uninstall' removes it -->",""].join(`
178
- `)}
179
- ${t.join(`
168
+ `,bS=`
169
+ `,Ij=3,Oj=/`+/g,_j=/^ {0,3}(?:```|~~~)/,Pj=/\n+$/,Nj=/\n/g,ES=`
170
+ `,Rp="none",yS={constraint:0,decision:1},Ip={contract:{title:"Contract",unit:"contract"},failure:{title:"Last failed attempt",unit:"failed attempt"},journal:{title:"Journal tail",unit:"journal event"},knowledge:{title:"Knowledge",unit:"knowledge entry"},notes:{title:"Task notes",unit:"task note"},rules:{title:"Constraints and decisions",unit:"constraint or decision entry"},task:{title:"Task",unit:"task header"}},Dj=["failure","rules","notes","knowledge","journal"],Lj=/y$/,Mj=()=>new Date().toISOString();async function tr(t,e={}){let n=M(t),r=await P(t),o=e.id??jj(r),s=e.budget??n.context.budget,{task:i}=it(t,o,n),a=pe(t).filter((g)=>g.status==="active"),c=(await Oo(t)).filter((g)=>et(g,i.contract.scope)),l=Hj(t,i),u=Uj(i),d=[...Kj(i.record.lastFailure,e.commandOutput!==!1),...Bj(i,a,c),...Vj(i.record.notes),...Wj(i,a,c),...Jj(Tc(r,o,n.context.journalTail))],p=Fj(o,s,l,u,d);if(i.record.status!=="done"&&e.journal!==!1){let g=(e.clock??Mj)(),f={[ho]:p.knowledge,tokens:p.estimatedTokens};$r(r,{at:g,detail:f,task:o,type:"context"})}return p}function jj(t){let e=gt(t);if(e!==null)return e.task;throw new m("No task is active in this worktree","Pass a task id: ari context <id>")}function Fj(t,e,n,r,o){let s=e*Rj,i=[n,Ac(r.fields,r.body)],a=kS(o,yt(i.join(_e)),Number.POSITIVE_INFINITY),c=yt(wS(i,a.sections,null))<=s,l=yt(`${_e}${vS(e,SS(o))}`),u=c?i:[n,Gj(t,n,r,s-l)],d=u.join(_e),p=c?a:kS(o,yt(d)+l,s),g=SS(p.omitted),f=wS(u,p.sections,g.length===0?null:vS(e,g)),y=[xp("task",u[0]??"",1),xp("contract",u[1]??"",1),...p.sections.map((S)=>xp(S.name,$S(S),S.items.length))];return{budget:e,estimatedTokens:ip(f),knowledge:p.sections.flatMap((S)=>S.knowledge),omitted:g,sections:y,sha256:Z(f),task:t,text:f}}function Gj(t,e,{body:n,fields:r},o){let s=Ac(r,n);if(yt([e,s].join(_e))<=o)return s;let i=`_The contract body is shortened to fit the budget; read ${It(t)}._`,a=o-yt([e,Ac(r,i)].join(_e))-_e.length,c=[];for(let d of n.split(`
171
+ `)){if(a-=yt(d)+1,a<0)break;c.push(d)}let l=c.flatMap((d,p)=>_j.test(d)?[p]:[]),u=l.length%2===0?c:c.slice(0,l.at(-1));return Ac(r,[u.join(`
172
+ `).trim(),i].filter((d)=>d.length>0).join(_e))}function Ac(t,e){return e.length===0?t:`${t}${_e}${e}`}function kS(t,e,n){let r=[],o=[],s=e;for(let i of t){let a=r.at(-1),c=a?.name===i.section,l=c?bS:`${_e}${Op(i.section)}${_e}`,u=yt(l)+yt(i.text);if(s+u>n){o.push(i);continue}s+=u;let d=c&&a?a:{items:[],knowledge:[],name:i.section};if(d!==a)r.push(d);if(d.items.push(i.text),i.knowledgeId!==null)d.knowledge.push(i.knowledgeId)}return{omitted:o,sections:r}}function wS(t,e,n){return[...[...t,...e.map($S)],...n===null?[]:[n]].join(_e)}function $S(t){return`${Op(t.name)}${_e}${t.items.join(bS)}`}function Op(t){return`## ${Ip[t].title}`}function xp(t,e,n){return{estimatedTokens:ip(e),items:n,name:t,text:e,title:Ip[t].title}}function SS(t){return Dj.flatMap((e)=>{let n=t.filter((r)=>r.section===e).length;return n===0?[]:[{count:n,section:e}]})}function vS(t,e){let n=e.map(({count:r,section:o})=>{let{unit:s}=Ip[o];return`${r} ${r===1?s:`${s.replace(Lj,"ie")}s`}`});return`_Omitted to fit the budget of ${t} tokens: ${n.join(", ")}._`}function Hj(t,e){let{contract:n,record:r}=e,o=Ue(n.pack,Gt(t)),s=Nn(e,o);return[`# ${n.id}: ${n.title}`,"",`- Status: ${r.status}`,`- Pack: ${o.name}`,`- Stage: ${s.name} (${r.stage+1} of ${o.stages.length})`,`- Instruction: ${Qn(mo(s,n.id))}`,...r.question===null?[]:[`- Question: ${Qn(r.question)}`]].join(`
173
+ `)}function Uj(t){let{contract:e}=t,n=e.criteria.map((i)=>{let a=i.checks.length===0?Rp:i.checks.join(", ");return`- ${i.id}: ${Qn(i.text)} (checks: ${a})`}),r=e.checks.map((i)=>`- ${i.name} (expect ${i.expect}, timeout ${i.timeoutSeconds}s): ${Cc(i.run)}`),o=e.invariants.map((i)=>`- ${Cc(i)}`),s=[Op("contract"),"",`Scope: ${Cp(e.scope)}`,`Lock: ${Cp(e.lock)}`,...Ap("Criteria:",n),...Ap("Checks:",r),...Ap("Invariants:",o)];return{body:e.body.trim(),fields:s.join(`
174
+ `)}}function Ap(t,e){return e.length===0?[`${t} ${Rp}`]:[t,...e]}function Kj(t,e){if(t===null)return[];let n=t.gates.filter((o)=>!o.ok).flatMap((o)=>[`- ${o.gate}: ${Qn(o.summary)}`,...o.details.map((s)=>` - ${Qn(s)}`),...o.checks.filter((s)=>e&&!s.ok&&s.outputTail.length>0).map((s)=>` ${s.name} output:${ES}${Qn(qj(s.outputTail))}`)]);return[{knowledgeId:null,section:"failure",text:[`Stage ${t.stage} at ${t.at}:`,...n].join(`
175
+ `)}]}function Bj(t,e,n){return TS(t,e,n).sort((r,o)=>(yS[r.kind]??0)-(yS[o.kind]??0)).map((r)=>xS("rules",r))}function TS(t,e,n){return e.filter((r)=>pn(r)&&xc(r.scope,t.contract.scope,n))}function Vj(t){return t.map((e,n)=>({index:n,note:e})).sort((e,n)=>O(n.note.at,e.note.at)||n.index-e.index).map(({note:e})=>({knowledgeId:null,section:"notes",text:`- ${e.at}: ${Qn(e.text)}`}))}function Wj(t,e,n){let r=new Set(TS(t,e,n).map((l)=>l.id)),o=e.filter((l)=>!r.has(l.id)),s=new Map(o.map((l)=>[l.id,l])),{contract:i}=t,a=[i.title,i.body,...i.criteria.map((l)=>l.text)].join(`
176
+ `);return gc(a,o.map((l)=>({id:l.id,text:l.text}))).flatMap(({id:l})=>{let u=s.get(l);return u===void 0?[]:[xS("knowledge",u)]})}function xS(t,e){let n=e.scope.length===0?"":` (scope: ${Cp(e.scope)})`;return{knowledgeId:e.id,section:t,text:`- ${e.kind} ${Cc(e.id)}${n}: ${Qn(e.text)}`}}function Jj(t){return t.map((e)=>({knowledgeId:null,section:"journal",text:`- ${e.at} ${e.type} ${JSON.stringify(JSON.parse(pt(e.detail)))}`}))}function Cp(t){return t.length===0?Rp:t.map(Cc).join(", ")}function Cc(t){let e="`".repeat(AS(t)+1),n=t.startsWith("`")||t.endsWith("`")?" ":"";return`${e}${n}${t}${n}${e}`}function qj(t){let e="`".repeat(Math.max(Ij,AS(t)+1));return`${e}
177
+ ${t.replace(Pj,"")}
178
+ ${e}`}function AS(t){return Math.max(0,...[...t.matchAll(Oj)].map((e)=>e[0].length))}function Qn(t){return t.replace(Nj,ES)}function CS(t,e){let n=Math.max(t.length,e.length);return n===0?1:1-Au(t,e)/n}var Yj=3;function _p(t,e,n,r){return{clusters:Xj(t,r),decisions:Zj(t,n),notes:zj(e)}}function Pp(t,e,n){let r=od(t),o=od(e),s=Math.max(r.length,o.length);if(s>0&&Math.min(r.length,o.length)/s<n)return 0;return CS(r,o)}function Xj(t,e){let n=new Map(t.map((i)=>[i.id,i.id])),r=new Map,o=(i)=>{let a=n.get(i)??i;return a===i?i:o(a)};t.forEach((i,a)=>{for(let c of t.slice(a+1)){let l=Pp(i.text,c.text,e.knowledge.mergeSimilarity);if(l<e.knowledge.mergeSimilarity)continue;let[u,d]=[o(i.id),o(c.id)].sort(O);n.set(d,u),r.set(u,Math.max(r.get(u)??0,r.get(d)??0,l))}});let s=new Map;for(let i of t){let a=o(i.id);s.set(a,[...s.get(a)??[],i.id])}return[...s.entries()].filter(([,i])=>i.length>1).map(([i,a])=>({ids:a,similarity:Qj(r.get(i)??0)})).sort((i,a)=>O(i.ids[0]??"",a.ids[0]??""))}function zj(t){return t.filter((e)=>e.record.status==="done").flatMap((e)=>e.record.notes.flatMap((n,r)=>n.promoted?[]:[{at:n.at,note:r,task:e.contract.id,text:n.text}]))}function Zj(t,e){let n=t.filter((r)=>r.kind==="decision");return n.flatMap((r,o)=>n.slice(o+1).filter((s)=>xc(r.scope,s.scope,e)).map((s)=>({ids:[r.id,s.id]})))}function Qj(t){let e=10**Yj;return Math.round(t*e)/e}import{existsSync as kF,readFileSync as BS}from"fs";function Np(t,e){let n=RS(t),r=RS(e),o=tF(n,r),s=[],i=0,a=0;while(i<n.length&&a<r.length)if(n[i]===r[a])i++,a++;else if(ni(o,i+1,a)>=ni(o,i,a+1))s.push(`-${n[i]}`),i++;else s.push(`+${r[a]}`),a++;for(let c of n.slice(i))s.push(`-${c}`);for(let c of r.slice(a))s.push(`+${c}`);return s}function RS(t){if(t.length===0)return[];let e=t.split(`
179
+ `);if(e.at(-1)==="")e.pop();return e}function tF(t,e){let n=Array.from({length:t.length+1},()=>Array(e.length+1).fill(0));for(let r=t.length-1;r>=0;r--){let o=n[r]??[];for(let s=e.length-1;s>=0;s--)o[s]=t[r]===e[s]?ni(n,r+1,s+1)+1:Math.max(ni(n,r+1,s),ni(n,r,s+1))}return n}function ni(t,e,n){return t[e]?.[n]??0}import{existsSync as US,mkdirSync as gF,readFileSync as KS}from"fs";import{join as si}from"path";import{existsSync as eF,readdirSync as nF}from"fs";var gn=".json",PS=/^(\d{8}T\d{9}Z)(?:-(\d+))?$/,rF=/[^0-9TZ]/g,IS=10,Rc=1;function ri(t){return PS.test(t)}function Ic(t,e){let n=t.replace(rF,""),r=Rc;while(e(OS(n,r)))r++;return OS(n,r)}function _o(t){if(!eF(t))return[];return nF(t).filter((e)=>e.endsWith(gn)&&ri(e.slice(0,-gn.length)))}function Pr(t,e){let[n="",r=`${Rc}`]=_S(t),[o="",s=`${Rc}`]=_S(e);return O(n,o)||Number.parseInt(r,IS)-Number.parseInt(s,IS)}function OS(t,e){return e===Rc?t:`${t}-${e}`}function _S(t){return PS.exec(t)?.slice(1).filter((e)=>e!==void 0)??[t]}var oi=1,NS=["pass","apply","undo"];var oF=/^[0-9a-f]{64}$/,FS=["version","id","at","kind"],DS=[...FS,"forced","reason","proposal","pruned","archived","created","promoted"],LS=[...FS,"undoes","restored","removed","unpromoted"],sF=["duplicate","decay","budget","merge","proposal"],iF=["merge","promotion"],aF=["utf8","base64"];function GS(t,e,n){return At(`sleep ledger entry ${e}`,n,()=>cF(t))}function cF(t){let e=T(t,"entry",LS.concat(DS)),n=K(NS,e.kind,"kind"),r=ht(e.version,"version");if(r!==oi)throw new b(`version ${r} is not supported`);let o={at:x(e.at,"at"),id:x(e.id,"id"),version:oi};if(n==="undo"){let i=T(t,"entry",LS);return{...o,kind:n,removed:L(i.removed,"removed",MS),restored:L(i.restored,"restored",MS),undoes:x(i.undoes,"undoes"),unpromoted:L(i.unpromoted,"unpromoted",jS)}}let s=T(t,"entry",DS);return{...o,archived:L(s.archived,"archived",lF),created:L(s.created,"created",uF),forced:$t(s.forced,"forced"),kind:n,promoted:L(s.promoted,"promoted",jS),proposal:s.proposal===null?null:pF(s.proposal),pruned:L(s.pruned,"pruned",dF),reason:Ct(s.reason,"reason")}}function lF(t,e){let n=T(t,e,["id","reason","supersededBy","original","sha256"]);return{id:x(n.id,`${e}.id`),original:ft(n.original,`${e}.original`,Oc),reason:K(sF,n.reason,`${e}.reason`),sha256:Dn(n.sha256,`${e}.sha256`),supersededBy:Ct(n.supersededBy,`${e}.supersededBy`)}}function uF(t,e){let n=T(t,e,["id","kind","origin","replaces","task","notes","sha256"]);return{id:x(n.id,`${e}.id`),kind:K(le,n.kind,`${e}.kind`),notes:L(n.notes,`${e}.notes`,ht),origin:K(iF,n.origin,`${e}.origin`),replaces:Dt(n.replaces,`${e}.replaces`),sha256:Dn(n.sha256,`${e}.sha256`),task:Ct(n.task,`${e}.task`)}}function Oc(t,e){let n=T(t,e,["sha256","encoding","content"]);return{content:x(n.content,`${e}.content`),encoding:K(aF,n.encoding,`${e}.encoding`),sha256:Dn(n.sha256,`${e}.sha256`)}}function MS(t,e){let n=T(t,e,["id","sha256"]);return{id:x(n.id,`${e}.id`),sha256:Dn(n.sha256,`${e}.sha256`)}}function jS(t,e){let n=T(t,e,["task","notes"]);return{notes:L(n.notes,`${e}.notes`,ht),task:x(n.task,`${e}.task`)}}function dF(t,e){let n=T(t,e,["task","events"]);return{events:ht(n.events,`${e}.events`),task:x(n.task,`${e}.task`)}}function pF(t){let e=T(t,"proposal",["sha256"]);return{sha256:Dn(e.sha256,"proposal.sha256")}}function Dn(t,e){let n=x(t,e);if(!oF.test(n))throw new b(`${e} must be a SHA-256 hex digest`);return n}var mF="sleep",fF=si("locks","sleep.ledger.lock"),hF="the sleep ledger",Dp="Restore the file from a backup, or delete it to drop that entry from the sleep history";function Lp(t){return si(t,mF)}function Nr(t,e){return As(si(t,fF),hF,e)}function Po(t){return t.kind!=="undo"}function No(t,e,n){let r=Lp(t);gF(r,{recursive:!0});let o=Ic(e,(i)=>US(HS(t,i))),s={...n,at:e,id:o,version:oi};return Yn(HS(t,o),pt(s),()=>Error(`The sleep ledger entry ${o} already exists`)),s}function ii(t){let e=Lp(t);return _o(e).map((n)=>yF(si(e,n),n)).sort((n,r)=>Pr(n.id,r.id))}function ai(t){let e=new Map;for(let n of t)if(n.kind==="undo")e.set(n.undoes,n.id);return e}function Do(t){let e=Buffer.from(t),n=e.toString("utf8"),r=Buffer.from(n,"utf8").equals(e);return{content:r?n:e.toString("base64"),encoding:r?"utf8":"base64",sha256:Z(t)}}function Dr(t){return Buffer.from(t.content,t.encoding==="utf8"?"utf8":"base64")}function Lo(t){return Z(KS(t))}function Mp(t){return US(t)?Lo(t):null}function HS(t,e){return si(Lp(t),`${e}${gn}`)}function yF(t,e){let n;try{n=JSON.parse(KS(t,"utf8"))}catch(o){let s=o instanceof Error?o.message:String(o);throw new m(`The sleep ledger entry ${t} is not valid JSON (${s})`,Dp)}let r=GS(n,t,Dp);if(`${r.id}${gn}`===e)return r;throw new m(`The sleep ledger entry ${t} declares the id "${r.id}"`,Dp)}function _c(t,e){return e.map(({after:n,reason:r})=>{let o=Oe(t,n.id),s=Do(BS(o));return ti(t,n),{id:n.id,original:s,reason:r,sha256:Lo(o),supersededBy:n.supersededBy}})}function VS(t,e){return e.map(({entry:n,notes:r,origin:o,replaces:s,task:i})=>({id:n.id,kind:n.kind,notes:r,origin:o,replaces:s,sha256:Lo(Oe(t,n.id)),task:i}))}function Pc(t,e,n){let r=n.map(({entry:s,origin:i})=>({change:"created",diff:Np("",br(s)),id:s.id,reason:i,supersededBy:null})),o=e.map(({after:s,reason:i})=>({change:i==="merge"?"replaced":"archived",diff:Np(wF(t,s.id),br(s)),id:s.id,reason:i,supersededBy:s.supersededBy}));return[...r,...o]}function wF(t,e){let n=Oe(t,e);return kF(n)?BS(n,"utf8"):""}function er(t){let{activeBytes:e,clusters:n,decisions:r,journaled:o,maxBytes:s,notes:i}=t,a=[...o.length>0?["journals"]:[],...e>s?["budget"]:[],...n+i+r>0?["candidates"]:[]];return{activeBytes:e,candidates:{clusters:n,decisions:r,notes:i},due:a.length>0,journaled:[...o],maxBytes:s,reasons:a}}function Lr(t){let e=(n)=>n.record.history.findLast((r)=>r.type==="done")?.at??n.record.history.at(-1)?.at??"";return t.filter((n)=>n.record.status==="done").sort((n,r)=>O(e(r),e(n))||O(n.contract.id,r.contract.id))}function jp(t,e){return[...new Set(t.record.knowledgeUsed.map((n)=>SF(n,e)))]}function Fp(t){let e=vF(t);return(n)=>{let r=new Set,o=[n];for(let s=o.pop();s!==void 0;s=o.pop()){if(r.has(s))continue;r.add(s);let i=t.get(s);if(i===void 0)continue;if(i.status==="active")return i;if(i.supersededBy!==null)o.push(i.supersededBy);o.push(...e.get(s)??[])}return null}}function SF(t,e){let n=new Set([t]),r=t;for(;;){let o=e.get(r)?.supersededBy??null;if(o===null||n.has(o)||!e.has(o))return r;n.add(o),r=o}}function vF(t){let e=new Map;for(let n of t.values())for(let r of n.supersedes)e.set(r,[...e.get(r)??[],n.id]);return e}var bF=["fact","pattern","gotcha"],EF=()=>new Date().toISOString();async function Mr(t,e={}){let n=M(t),r=await P(t),o=await Oo(t),s=(e.clock??EF)();return Nr(r,()=>{let{retirements:i,...a}=qS(t,r,n,o,!0),c=No(r,s,{archived:_c(t,i),created:[],forced:!1,kind:"pass",promoted:[],proposal:null,pruned:a.pruned,reason:null});return{...a,ledger:c.id}})}async function WS(t){let e=M(t),n=await P(t),r=await Oo(t),{retirements:o,...s}=qS(t,n,e,r,!1);return{...s,changes:Pc(t,o,[]),dryRun:!0}}async function jr(t,e={}){let n=M(t),r=await P(t),{tasks:o}=Pt(t,n),s=Mo(new Map(pe(t).map((a)=>[a.id,a]))),i=e.candidates===!1?{clusters:[],decisions:[],notes:[]}:_p(s,o,await Oo(t),n);return{activeBytes:Gp(s),clusters:i.clusters.length,decisions:i.decisions.length,journaled:o.filter((a)=>YS(r,a)).map((a)=>a.contract.id).sort(O),maxBytes:n.knowledge.maxBytes,notes:i.notes.length}}async function JS(t){return er(await jr(t,{candidates:!1})).due?Mr(t):null}function qS(t,e,n,r,o){let{tasks:s}=Pt(t,n),{pruned:i,tasks:a}=$F(t,e,s,o),c=new Map(pe(t).map((p)=>[p.id,p])),l=[...AF(c,n),...CF(c,a,n),...RF(c,a,n)],u=l.flatMap(({id:p,reason:g})=>{let f=c.get(p);return f===void 0?[]:[{after:f,reason:g}]}),d=Mo(c);return{activeBytes:Gp(d),archived:l,candidates:_p(d,a,r,n),maxBytes:n.knowledge.maxBytes,pruned:i,retirements:u}}function $F(t,e,n,r){let o=[],s=n.map((i)=>{let{id:a}=i.contract;if(!YS(e,i))return i;let c=0,l=(d)=>{let p=TF(d,e,a);return c=p.events,p.record},u=r?Vt(t,e,a,l):l(i.record);if(r)Va(e,a);return o.push({events:c,task:a}),{contract:i.contract,record:u}});return{pruned:o,tasks:s}}function YS(t,e){return e.record.status==="done"&&Tc(t,e.contract.id,1).length>0}function TF(t,e,n){let r=t,o=0;for(let s of sS(e,n))r=xF(r,s),o+=s.length;return{events:o,record:r}}function xF(t,e){let n=e.flatMap((r)=>{let o=r.detail[ho];return r.type==="context"&&Array.isArray(o)?o:[]});return _a(fy(t,n),e)}function Mo(t){return[...t.values()].filter((e)=>e.status==="active").sort((e,n)=>O(e.id,n.id))}function Gp(t){return t.reduce((e,n)=>e+yt(n.text),0)}function XS(t,e){return O(t.created,e.created)||O(t.id,e.id)}function AF(t,e){let n=[],r=[];for(let o of Mo(t).filter((s)=>!pn(s)).sort(XS)){let s=n.find((i)=>i.kind===o.kind&&Pp(i.text,o.text,e.knowledge.duplicateSimilarity)>=e.knowledge.duplicateSimilarity);if(s===void 0){n.push(o);continue}t.set(o.id,dn(o,s.id)),r.push({id:o.id,reason:"duplicate",supersededBy:s.id})}return r}function CF(t,e,n){let r=Lr(e).slice(0,n.knowledge.decayAfterTasks);if(r.length<n.knowledge.decayAfterTasks)return[];let o=new Set(r.flatMap((i)=>jp(i,t))),s=r.map((i)=>Io(i.record.history[0]?.at??"")).sort(O)[0]??"";return Mo(t).flatMap((i)=>{if(!bF.includes(i.kind)||o.has(i.id))return[];if(O(i.created,s)>=0)return[];return t.set(i.id,dn(i,null)),[{id:i.id,reason:"decay",supersededBy:null}]})}function RF(t,e,n){let r=new Map;for(let a of Lr(e).flatMap((c)=>jp(c,t)))r.set(a,(r.get(a)??0)+1);let o=Mo(t).filter((a)=>!pn(a)).sort((a,c)=>(r.get(a.id)??0)-(r.get(c.id)??0)||XS(a,c)),s=[],i=Gp(Mo(t));for(let a of o){if(i<=n.knowledge.maxBytes)break;t.set(a.id,dn(a,null)),i-=yt(a.text),s.push({id:a.id,reason:"budget",supersededBy:null})}return s}import{readFileSync as IF}from"fs";import{join as zS}from"path";var ZS=1048576,OF=".ari/designs/";function Nc(t,e){let n=t.stages.flatMap((r)=>r.gates.flatMap((o)=>o.kind==="artifact"?[Ro(o.path,e)]:[]));return[...new Set(n)].sort(O)}function Up(t){return t.startsWith(OF)}function QS(t,e){let n=$e(zS(t,e));if(n===null)return{artifact:null,warning:null};if(n.isSymbolicLink()||Te(t,e))return Hp(e,"it is a symbolic link or lies behind one");if(!n.isFile())return Hp(e,"it is not a regular file");if(n.size>ZS)return Hp(e,`it is larger than ${ZS} bytes`);return{artifact:{file:Do(IF(zS(t,e))),path:e},warning:null}}function Hp(t,e){return{artifact:null,warning:`${t} was not captured: ${e}`}}async function tv(t,e,n){let{contractText:r,task:o}=it(t,e,n),s=Ue(o.contract.pack,Gt(t)),i=Nc(s,e).map((u)=>QS(t,u)),a=await tr(t,{commandOutput:!1,id:e,journal:!1}),{record:c}=o;return{plan:{artifacts:i.flatMap(({artifact:u})=>u===null?[]:[u]),context:{budget:a.budget,estimatedTokens:a.estimatedTokens,knowledge:a.knowledge,sha256:a.sha256,text:a.text},contract:{sha256:Bt(r),text:r},notes:c.notes.map((u)=>({...u})),record:{pack:s.name,stage:c.stage,stageName:s.stages[c.stage]?.name??null,status:c.status}},warnings:i.flatMap(({warning:u})=>u===null?[]:[u])}}function Kp(t){return pt({artifacts:t.artifacts.map(({file:e,path:n})=>[n,e.sha256]),context:t.context.sha256,contract:t.contract.sha256,notes:t.notes,record:t.record})}import{existsSync as lv,mkdirSync as GF,readFileSync as HF,rmSync as UF}from"fs";import{join as Dc}from"path";var ci=1,ev=["manual","pre-compact","approve","stage"],nv=["save","restore"];var iv=["version","id","at","kind","task","pruned"],rv=[...iv,"trigger","reason","contract","record","artifacts","notes","context"],ov=[...iv,"restores","written"],sv="/",_F="..",PF=/[\\\0]/;function av(t,e,n){return At(`snapshot entry ${e}`,n,()=>NF(t))}function NF(t){let e=T(t,"entry",rv.concat(ov)),n=K(nv,e.kind,"kind"),r=ht(e.version,"version");if(r!==ci)throw new b(`version ${r} is not supported`);let o={at:x(e.at,"at"),id:x(e.id,"id"),pruned:Dt(e.pruned,"pruned"),task:x(e.task,"task"),version:ci};if(n==="restore"){let i=T(t,"entry",ov);return{...o,kind:n,restores:x(i.restores,"restores"),written:L(i.written,"written",FF)}}let s=T(t,"entry",rv);return{...o,artifacts:L(s.artifacts,"artifacts",MF),context:ft(s.context,"context",jF),contract:ft(s.contract,"contract",DF),kind:n,notes:L(s.notes,"notes",yd),reason:Ct(s.reason,"reason"),record:ft(s.record,"record",LF),trigger:K(ev,s.trigger,"trigger")}}function DF(t,e){let n=T(t,e,["sha256","text"]);return{sha256:Dn(n.sha256,k(e,"sha256")),text:x(n.text,k(e,"text"))}}function LF(t,e){let n=T(t,e,["pack","stage","stageName","status"]);return{pack:x(n.pack,k(e,"pack")),stage:ht(n.stage,k(e,"stage")),stageName:Ct(n.stageName,k(e,"stageName")),status:K(hd,n.status,k(e,"status"))}}function MF(t,e){let n=T(t,e,["path","file"]);return{file:ft(n.file,k(e,"file"),Oc),path:cv(n.path,k(e,"path"))}}function jF(t,e){let n=T(t,e,["budget","estimatedTokens","knowledge","sha256","text"]);return{budget:ht(n.budget,k(e,"budget")),estimatedTokens:ht(n.estimatedTokens,k(e,"estimatedTokens")),knowledge:Dt(n.knowledge,k(e,"knowledge")),sha256:Dn(n.sha256,k(e,"sha256")),text:x(n.text,k(e,"text"))}}function FF(t,e){let n=T(t,e,["path","before","sha256"]);return{before:n.before===null?null:Oc(n.before,k(e,"before")),path:cv(n.path,k(e,"path")),sha256:Dn(n.sha256,k(e,"sha256"))}}function cv(t,e){let n=x(t,e);if(n.length===0||n.startsWith(sv)||n.split(sv).includes(_F)||PF.test(n))throw new b(`${e} must be a path inside the repository, got ${JSON.stringify(n)}`);return n}var KF="snapshots",BF=Dc("locks","snapshots.lock"),VF="the snapshots",Bp="Restore the file from a backup, or delete it to drop that entry from the snapshot history";function Fr(t){return Dc(t,KF)}function Lc(t,e){return As(Dc(t,BF),VF,e)}function Mc(t,e,n){GF(Fr(t),{recursive:!0});let r=Ic(e,(s)=>lv(nr(t,s))),o={...n,at:e,id:r,version:ci};return Yn(nr(t,r),pt(o),()=>Error(`The snapshot entry ${r} already exists`)),o}function Ln(t){let e=[],n=[];for(let r of _o(Fr(t))){let o=r.slice(0,-gn.length);try{e.push(uv(t,o))}catch(s){n.push({id:o,problem:WF(s)})}}return{entries:e.sort((r,o)=>Pr(r.id,o.id)),unreadable:n.sort((r,o)=>Pr(r.id,o.id))}}function jo(t,e){if(ri(e)&&lv(nr(t,e)))return uv(t,e);let n=Ln(t),r=[...n.entries.map((o)=>o.id),...n.unreadable.map((o)=>o.id)];throw new m(`The snapshot history has no entry "${e}"`,r.length===0?"Run 'ari snapshot' to save the first one":`Known entries: ${r.join(", ")}`)}function jc(t,e){for(let n of e)UF(nr(t,n),{force:!0})}function nr(t,e){return Dc(Fr(t),`${e}${gn}`)}function uv(t,e){let n=nr(t,e),r;try{r=JSON.parse(HF(n,"utf8"))}catch(s){let i=s instanceof Error?s.message:String(s);throw new m(`The snapshot entry ${n} cannot be read (${i})`,Bp)}let o=av(r,n,Bp);if(o.id===e)return o;throw new m(`The snapshot entry ${n} declares the id "${o.id}"`,Bp)}function WF(t){if(t instanceof m)return t.message;return t instanceof Error?t.message:String(t)}var JF=()=>new Date().toISOString(),qF={id:null,warning:null};async function Vp(t,e={}){let n=M(t),r=await P(t),o=e.task??YF(r),{plan:s,warnings:i}=await tv(t,o,n),a=(e.clock??JF)();return Lc(r,()=>{let c=Ln(r).entries.filter((p)=>p.task===o),l=c.findLast(Wp);if(l!==void 0&&Kp(l)===Kp(s))return dv(l.id,o,s,[],i,!1);let u=c.slice(0,Math.max(0,c.length+1-n.snapshots.keep)).map((p)=>p.id),d=Mc(r,a,{...s,kind:"save",pruned:u,reason:e.reason??null,task:o,trigger:e.trigger??"manual"});return jc(r,u),dv(d.id,o,s,u,i,!0)})}async function Fo(t,e,n,r={}){try{if(!M(t).snapshots.auto)return qF;let o=await Vp(t,{clock:r.clock,task:e,trigger:n});return{id:o.saved?o.id:null,warning:o.warnings.length===0?null:o.warnings.join("; ")}}catch(o){let s=o instanceof Error?o.message:String(o);return{id:null,warning:`ari could not save a snapshot of task "${e}" (${s})`}}}function Wp(t){return t.kind==="save"}function YF(t){let e=gt(t);if(e!==null)return e.task;throw new m("No task is active in this worktree","Pass --task <id>, or run 'ari next' to see what to do")}function dv(t,e,n,r,o,s){let{artifacts:i,context:a,record:c}=n;return{artifacts:i.map((l)=>l.path),context:{estimatedTokens:a.estimatedTokens,knowledge:a.knowledge,sha256:a.sha256},id:t,pack:c.pack,pruned:r,saved:s,stage:c.stageName,status:c.status,task:e,warnings:o}}var yv=`
180
180
 
181
- `)}
182
- `}var Cj="skills.json";function Gn(t){return yS(t,Me,mS)}var qt=[{agent:"claude",label:"Claude Code",project:Gn(".claude/skills"),user:Gn(".claude/skills")},{agent:"codex",label:"Codex CLI",project:Gn(".agents/skills"),user:Gn(".agents/skills")},{agent:"gemini",label:"Gemini CLI",project:Gn(".gemini/skills"),user:Gn(".gemini/skills")},{agent:"cursor",label:"Cursor",project:Gn(".cursor/skills"),user:Gn(".cursor/skills")}];function re(t){return Ds(qt,t,"skill")}function Ee(t,e){return gc(t,e)}function wo(t,e){let n=gc(t,e);return{...wS(t,e),action:sc(n)}}function pc(t,e){let n=gc(t,e),r=ic(n);if(r==="removed")SS(e.base,hS(n.file));return{...wS(t,e),action:r}}function kS(t,e){return qt.map((n)=>({agent:n.agent,files:[t,e].map((r)=>({file:ee(r.scope,n[r.scope]),installed:En(gc(n,r)),scope:r.scope})),label:n.label}))}function wS(t,e){let n=ee(e.scope,t[e.scope]);return{agent:t.agent,file:n,scope:e.scope,skill:Me}}function gc(t,e){let n=t[e.scope],r=(o)=>(o??"").includes(dc);return{base:e.base,file:n,install:(o)=>{if(o===null||r(o))return fS();throw new g(`${ee(e.scope,n)} exists and ari did not write it`,`Move or remove that skill, then run 'ari skills install --agent ${t.agent}' again`)},managed:r,receipts:{directory:e.receipts,store:Cj},remove:()=>null}}function SS(t,e){let n=yS(t,e);if(e==="."||!vj(n)||xj(n).length>0)return;Aj(n),SS(t,hS(e))}var _t="AGENTS.md",ap="<!-- ari:begin -->",mc="<!-- ari:end -->",Oj=/^ {0,3}(<!-- ari:(?:begin|end) -->)\s*$/,_j=/^ {0,3}(`{3,}(?=[^`]*$)|~{3,})/,Pj=/^ {0,3}(`{3,}|~{3,})[ \t]*\r?$/,cp=`${W}/config.json`,Nj="git",TS=`\r
183
- `,lp=`
184
- `,Dj=[ap,"## Ariadne","","This repository tracks work as Ariadne (`ari`) tasks. Work in this loop:","","1. Run `ari next` and follow the one action it prints.","2. Change only files inside the active task's `scope`.","3. Run `ari check` to evaluate the current stage's gates.","4. Run `ari done`; it records evidence and advances. Fix what it reports and run it again.","",'Record learnings with `ari note "<text>"` and reload context with `ari context`. If you are stuck, ask a human with `ari block <id> --reason "<question>"`.',"Edit task contracts (`.ari/tasks/*.md`) and designs, never other files under `.ari/`: ari writes them. `ari --help --json` describes every command.",mc];function up(t){let e=Fs(q(t,_t));return{action:fe(t,_t,e),path:_t}}function dp(t,e){return fe(t,cp,pp(q(t,cp),e))}function pp(t,e){let n=t??Dh();if(e===null)return n;let r=Vt(cp,n);if(rr(r).pack===e)return n;return Nn(n,{...r,pack:e})}async function ES(t,e={}){let n=[...e.agents??[],...e.gitHooks===!0?[Nj]:[]],r=[...new Set(n)];for(let f of r)Qw(f);let o=np(Jt,e.mcp??[],"MCP"),s=np(qt,e.skills??[],"skill"),i=Rj(Ij(t,W))?me(t):[],a=e.pack===void 0?null:sr(e.pack,i).name,c=dp(t,a),l=up(t),u=[];for(let f of r)u.push(await mo(t,f));let d={base:t,receipts:await M(t),scope:"project"},p=o.map((f)=>ko(f,d)),m=s.map((f)=>wo(f,d));return{agentsMd:l,config:c,hooks:u,mcp:p,pack:L(t).pack,root:t,skills:m}}function Fs(t){let e=t??"",n=e.includes(TS)?TS:lp,r=Dj.join(n),o=Lj(e),[s,i]=o;if(s===void 0){let a=e.length===0?"":e.endsWith(n)?n:`${n}${n}`;return`${e}${a}${r}${n}`}if(o.length!==2||s.marker!==ap||i?.marker!==mc)throw new g(`${_t} has a damaged ari block: expect one ${ap} followed by one ${mc}`,`Remove the ari markers and the lines between them from ${_t}, then run 'ari init' again`);return`${e.slice(0,s.start)}${r}${e.slice(i.start+mc.length)}`}function Lj(t){let e=[],n=null,r=0;for(let o of t.split(lp)){let s=_j.exec(o)?.[1];if(n===null&&s!==void 0)n={mark:s,markers:e.length};else if(n!==null&&Mj(o,n.mark))e.length=n.markers,n=null;let i=Oj.exec(o)?.[1];if(i!==void 0)e.push({marker:i,start:r+o.indexOf(i)});r+=o.length+lp.length}return e}function Mj(t,e){return Pj.exec(t)?.[1]?.startsWith(e)===!0}function Sr(t){return t.kind==="config"?"ari init":vS("install",t)}function bS(t){return vS("uninstall",t)}function vS(t,{agent:e,kind:n,scope:r}){switch(n){case"hooks":return e===null?null:`ari hooks ${t} --agent ${e}`;case"git":return`ari hooks ${t} --agent git`;case"mcp":return e===null?null:`ari mcp ${t} --agent ${e}${$S(r)}`;case"skill":return e===null?null:`ari skills ${t} --agent ${e}${$S(r)}`;case"config":case"routing":return null}}function $S(t){return t==="user"?" --scope user":""}var AS=5000,jj=new Set(["created","updated","unchanged"]),Fj="2025-11-25",CS=2,Gj="ari_next",Hj=new Set(["hooks","mcp","skill","git"]),Uj="<!-- ari:begin -->",RS=".ari/config.json",Kj=".git/hooks",IS="Install ari globally (bun add -g @r5n/ariadne), then run 'ari install' again",Bj=`---
185
- name: ${Me}
186
- `;async function gp(t,e,n={}){let r=e.filter((a)=>jj.has(a.action)),o=await Promise.all(Wj(r).map((a)=>Vj(t,a)));if(!r.some((a)=>Hj.has(a.kind)))return o;let s=n.ari===void 0?Bun.which("ari"):n.ari,i=s!==null&&r.some((a)=>a.kind==="mcp")?[await fp(s,t,n.timeoutMs??AS)]:[];return[mp(s),...i,...o]}function mp(t){return t===null?So("ari on PATH","ari is not on PATH, so agents cannot start it",IS):hp("ari on PATH",t)}function fp(t,e,n=AS){return Xj(t,e,n)}function Wj(t){let e=new Set;return t.filter((n)=>{let r=n.kind==="git"?"git":n.kind==="routing"?"config:.ari/config.json":`${n.kind}:${n.file}`;if(e.has(r))return!1;return e.add(r),!0})}async function Vj(t,e){let n=fc(e),r=e.kind==="routing"?RS:e.kind==="git"?Kj:e.file??"";try{let o=await qj(t,e);return o===null?hp(n,Yj(e,r)):So(n,`${r}: ${o}`,Jj(e))}catch(o){if(!(o instanceof Error))throw o;let s=o instanceof g&&o.hint!==void 0?o.hint:`Fix ${r}`;return So(n,o.message,s)}}function Jj(t){let e=Sr(t);return e===null?"Run 'ari install' again to repair it":`Run '${e}' to repair it`}function fc(t){switch(t.kind){case"hooks":return`${t.agent} hooks`;case"mcp":return`${t.agent} MCP server`;case"skill":return`${t.agent} skill`;case"git":return"git hooks";case"config":return t.file===_t?"AGENTS.md block":"configuration";case"routing":return"configuration"}}async function qj(t,e){let n=e.agent??"";switch(e.kind){case"hooks":return Ye(t,Se(n))?null:"has no ari hook entries";case"mcp":{let r=Te(ne(n),await xS(t,e.scope));return r.managed(q(r.base,r.file))?null:"does not register the ari server"}case"skill":{let r=Ee(re(n),await xS(t,e.scope)),o=q(r.base,r.file)??"";return o.startsWith(Bj)&&o.includes(dc)?null:"is not ari's skill"}case"git":return await eo(t)?null:"pre-commit and pre-push do not both run ari";case"config":if(e.file===_t)return(q(t,_t)??"").includes(Uj)?null:"has no ari block";return L(t),null;case"routing":return L(t),null}}function Yj(t,e){switch(t.kind){case"hooks":case"mcp":case"skill":return e;case"git":return"pre-commit and pre-push run ari";case"config":case"routing":return t.file===_t?"AGENTS.md has the ari block":`${RS} is valid`}}async function xS(t,e){return Ot(e,t)}async function Xj(t,e,n){let o=Bun.spawn([t,"mcp","serve"],{cwd:e,detached:!0,env:{...process.env,...Ae},stderr:"pipe",stdin:"pipe",stdout:"pipe"}),s=()=>Ce(o.pid,"SIGKILL"),i=de(s),a=setTimeout(s,n);try{o.stdin.write(zj()),await o.stdin.flush();let c=await Zj(o.stdout);return await o.stdin.end(),tF("ari mcp serve",c,n,await new Response(o.stderr).text())}catch(c){return So("ari mcp serve",`'ari mcp serve' failed: ${c instanceof Error?c.message:String(c)}`,IS)}finally{clearTimeout(a),s(),i()}}function zj(){return[{id:1,jsonrpc:"2.0",method:"initialize",params:{capabilities:{},clientInfo:{name:"ari-install",version:"1"},protocolVersion:Fj}},{jsonrpc:"2.0",method:"notifications/initialized"},{id:CS,jsonrpc:"2.0",method:"tools/list"}].map((e)=>`${JSON.stringify(e)}
187
- `).join("")}async function Zj(t){let e=new TextDecoder,n="";for await(let r of t){n+=e.decode(r,{stream:!0});let o=n.split(`
188
- `);n=o.pop()??"";for(let s of o){let i=Qj(s);if(i!==null&&i.id===CS)return i}}return null}function Qj(t){try{let e=JSON.parse(t);return Y(e)?e:null}catch{return null}}function tF(t,e,n,r){if(e===null){let s=r.trim().split(`
189
- `).at(-1)??"",i=s.length>0?`stopped without answering: ${s}`:`did not answer within ${n} ms`;return So(t,i,"Run 'ari mcp serve' in this repository to see why")}let o=eF(e);if(!o.includes(Gj))return So(t,"answered tools/list without ari's tools","Make sure 'ari' on PATH is @r5n/ariadne");return hp(t,`answers, with ${o.length} tools`)}function eF(t){let e=t.result;if(!Y(e)||!Array.isArray(e.tools))return[];return e.tools.flatMap((n)=>Y(n)&&typeof n.name==="string"?[n.name]:[])}function hp(t,e){return{detail:e,hint:null,name:t,ok:!0}}function So(t,e,n){return{detail:e,hint:n,name:t,ok:!1}}import{existsSync as HS}from"fs";import{join as US}from"path";import{dirname as OS}from"path";var et=["claude","codex","gemini","cursor","copilot"],Hn=["hooks","mcp","skill"],Fe={hooks:"hooks",mcp:"MCP server",skill:"skill"},wp="config",Un="agents-md",je="git",yc="claude mcp add --scope user ari -- ari mcp serve",yp=".ari/config.json",nF="AGENTS.md",_S=".claude/settings.json",PS=["cursor","copilot"],NS={cursor:["claude","codex"],gemini:["codex"]},rF=["claude","codex","gemini"],oF=":";function wt(t,e){return`${t}${oF}${e}`}function kc(t){return et.includes(t)}function Pt(t,e){let n=t.agents.find((r)=>r.agent===e);if(n!==void 0)return n;throw Error(`No detected state for agent ${e}`)}function wc(t){let e=new Set(t.targets.filter(Ep).map((n)=>n.agent));return et.filter((n)=>Pt(t,n).path!==null||e.has(n))}function Tr(t,e,n,r){let o=t.initialised&&!r?[jS(t,Un,"project")]:[],s=Hn.flatMap((i)=>et.filter((a)=>e.includes(a)).map((a)=>gF(t,a,i,n)));return[...o,...s,mF(t)]}function sF(t,e,n,r){let s=Tr(t,e,n,r).filter((a)=>a.skip===null&&a.problem===null).map((a)=>a.id),i=new Set(To(t,s).map(({id:a})=>a));return s.filter((a)=>!i.has(a))}function DS(t,e,n,r){return Tr(t,e,n,r).map((o)=>o.id)}function LS(t,e,n,r){let o=Tr(t,e,n,r),s=new Set(o.filter((i)=>i.status!=="current"&&i.elsewhere===null).map((i)=>i.id));return sF(t,e,n,r).filter((i)=>s.has(i))}function MS(t,e){let n=t.configured.map((s)=>({...s,configured:!0})),r=new Set(n.map((s)=>s.name)),o=e.filter((s)=>Pt(t,s).preset&&!r.has(s)).map((s)=>({configured:!1,model:null,name:s,roles:[]}));return[...n,...o]}function Sp(t,e){if(e.pack!==null&&!t.packs.some((d)=>d.name===e.pack))throw new T(`Unknown pack "${e.pack}"`,`Choose one of: ${t.packs.map((d)=>d.name).join(", ")}`);if(e.routing!==null)pF(t,e.routing,e.init);let n=e.init,r=Tr(t,e.agents,e.scope,n),o=new Set(e.targets),s=e.recommended?To(t,e.targets):[],i=new Map(s.map(({id:d,reason:p})=>[d,p])),a=n?[hc(wp,null,"config","project",yp,null),hc(Un,null,"config","project",nF,null)]:[],c=new Set(r.filter((d)=>o.has(d.id)).map((d)=>d.kind)),l=r.flatMap((d)=>{if(!(o.has(d.id)||d.skip!==null&&c.has(d.kind)))return[];let m=e.recommended&&d.problem!==null?fF(d.problem):null,f=d.skip??i.get(d.id)??m;return[hc(d.id,d.agent,d.kind,d.scope,d.file,f)]}),u=e.routing===null?[]:[hc("routing",null,"routing","project",yp,null)];return{init:n,pack:e.pack,routing:e.routing,scope:e.scope,targets:[...a,...l,...u],warnings:Sc(t,{...e,targets:e.targets.filter((d)=>!i.has(d))})}}function Sc(t,e){let n=Tr(t,e.agents,e.scope,e.init),r=new Set(e.targets),o=new Set(n.filter((c)=>c.skip===null).map((c)=>c.id)),s=FS(t),i=new Set([...[...r].filter((c)=>o.has(c)),...s]),a={answers:e,effective:i,installed:s,requested:r,state:t};return[...iF(a),...aF(a),...cF(a),...lF(a),...uF(a),...dF(a,n)]}function iF({answers:t,state:e}){return t.agents.flatMap((n)=>{let r=Pt(e,n);if(r.path!==null)return[];return[Eo("agent-not-found",`${r.label} was not found on PATH (looked for ${r.binaries.join(", ")})`,`ari writes its files anyway; they take effect once ${r.label} is installed`)]})}function aF({answers:t,requested:e}){if(t.scope!=="user"||!e.has(wt("mcp","claude")))return[];return[Eo("claude-user-mcp","Claude Code keeps user-scope MCP servers in its own state file, which ari does not edit",`Run: ${yc}`)]}function cF({requested:t,state:e}){let n=e.hookManager;if(n===null||!t.has(je))return[];return[Eo("git-hooks-managed",GS(n.name),n.hint)]}function lF({effective:t,installed:e,requested:n,state:r}){let o=wt("hooks","claude");if(!t.has(o))return[];return PS.flatMap((s)=>{let i=wt("hooks",s);if(!t.has(i)||!(n.has(i)||n.has(o)))return[];let a=Pt(r,s).label,c=n.has(i)&&!e.has(i)?[i]:[],l=c.length>0?`Leave out ${a}'s hooks; it runs Claude Code's`:`Run 'ari hooks uninstall --agent ${s}', or leave out Claude Code's hooks`,u=`${a} also runs Claude Code's hooks from ${_S}, so every ari hook would run twice there`;return[Eo("hooks-twice",u,l,c)]})}function uF({answers:t,effective:e,installed:n,requested:r,state:o}){return et.flatMap((s)=>{let i=NS[s];if(i===void 0||!t.agents.includes(s))return[];let a=[s,...i].filter((y)=>e.has(wt("skill",y)));if(a.length<2||!a.some((y)=>r.has(wt("skill",y))))return[];let c=Pt(o,s).label,l=wt("skill",s),u=r.has(l)&&!n.has(l)&&a.includes(s)?[l]:[],d=a.map((y)=>kp(o,y)),p=a.filter((y)=>y!==s).map((y)=>kp(o,y)),m=u.length>0?`Leave out ${c}'s own skill; it reads the copy in ${p.join(" and ")}`:a.includes(s)?`Run 'ari skills uninstall --agent ${s}'; ${c} reads the copy in ${p.join(" and ")}`:`The copies are identical; keep both while ${a.map((y)=>Pt(o,y).label).join(" and ")} need them`,f=`${c} reads ${d.join(" and ")}, so it would load the ariadne skill ${hF(a.length)}`;return[Eo("skill-twice",f,m,u)]})}function dF({requested:t},e){return e.flatMap((n)=>{if(n.problem===null||n.skip!==null||!t.has(n.id))return[];return[Eo("target-blocked",n.problem.message,n.problem.hint)]})}function To(t,e){let n=new Set(e),r=FS(t),o=new Set([...n,...r]),s=o.has(wt("hooks","claude")),i=PS.flatMap((c)=>{let l=wt("hooks",c);if(!s||!n.has(l)||r.has(l))return[];let u=`${Pt(t,c).label} runs Claude Code's hooks from ${_S}`;return[{id:l,reason:u}]}),a=et.flatMap((c)=>{let l=wt("skill",c),u=(NS[c]??[]).find((m)=>o.has(wt("skill",m)));if(u===void 0||!n.has(l)||r.has(l))return[];let d=kp(t,u),p=`${Pt(t,c).label} also reads ${d}, where ${Pt(t,u).label}'s copy is`;return[{id:l,reason:p}]});return[...i,...a]}function pF(t,e,n){if(!t.initialised&&!n)throw new T("Routing needs .ari/config.json, which does not exist yet","Pass --init to create it in the same run, or run 'ari init' first");let r=new Set([...t.configured.map((s)=>s.name),...rF]);for(let[s,i]of[["--task-agent",e.task],["--review-agent",e.review]]){if(r.has(i.agent))continue;throw new T(`${s} names "${i.agent}", which is neither a configured agent nor a preset`,`Choose one of: ${[...r].join(", ")}`)}let o=t.routing.reviewCommand;if(o===null)return;throw new g(`review.command (${o}) runs the review gate, so ari cannot also set review.agent`,`Remove review.command from ${yp}, or leave the review agent out`,1,{tag:"ReviewCommandSet"})}function gF(t,e,n,r){let o=Pt(t,e),s=wt(n,e),i=n==="hooks"?"project":r,a={agent:e,elsewhere:null,file:null,id:s,kind:n,problem:null,scope:i,status:null};if(!o.kinds.includes(n))return{...a,skip:`ari has no ${Fe[n]} integration for ${o.label}`};if(i==="user"&&!o.userScope.includes(n))return{...a,skip:`${o.label} keeps user-scope MCP servers itself; run '${yc}'`};let c=Tp(t,s,i),l=i==="user"?"project":"user",u=n==="hooks"?void 0:t.targets.find((p)=>p.id===s&&p.scope===l),d=u!==void 0&&Ep(u)?u.scope:null;return{...a,elsewhere:d,file:c.file,problem:c.problem,skip:null,status:c.status}}function mF(t){let e=t.hookManager,n={agent:null,elsewhere:null,id:je,kind:"git",scope:"project"};if(e!==null)return{...n,file:t.gitHooksDirectory,problem:null,skip:GS(e.name),status:null};return jS(t,je,"project")}function jS(t,e,n){let r=Tp(t,e,n),{agent:o,file:s,kind:i,problem:a,status:c}=r;return{agent:o,elsewhere:null,file:s,id:e,kind:i,problem:a,scope:n,skip:null,status:c}}function Tp(t,e,n){let r=t.targets.find((o)=>o.id===e&&o.scope===n);if(r!==void 0)return r;throw Error(`No detected state for ${e} in the ${n} scope`)}function FS(t){return new Set(t.targets.filter(Ep).map((e)=>e.id))}function Ep(t){return t.status!=="missing"&&t.agent!==null}function kp(t,e){return OS(OS(Tp(t,wt("skill",e),"project").file))}function GS(t){return`${t} manages this repository's git hooks, so ari leaves them alone`}function fF(t){return t.hint.length===0?t.message:`${t.message}. ${t.hint}`}function hc(t,e,n,r,o,s){return{agent:e,file:o,id:t,kind:n,scope:r,skip:s}}function Eo(t,e,n,r=[]){return{code:t,drop:r,fix:n,message:e}}function hF(t){return t===2?"twice":`${t} times`}var yF={claude:["claude"],codex:["codex"],copilot:["copilot"],cursor:["cursor-agent","cursor"],gemini:["gemini"]},kF="<!-- ari:begin -->",wF=new Set(["EACCES","EISDIR","ELOOP","ENOTDIR","EPERM"]);async function Gs(t,e){let n=HS(US(t,Q)),r=e!==void 0?e:n?L(t):null,o=HS(US(t,W))?me(t):[],s={project:await vF(t),user:await Ot("user",t)},[i,a,c]=await Promise.all([Promise.all(et.map(SF)),ed(t),Cy(t)]),l=[...n?[EF(t)]:[],...he.map((u)=>BS(wt("hooks",$p(u.name)),$p(u.name),"hooks","project",u.file,()=>Ye(t,u),()=>fs(u,q(t,u.file))===q(t,u.file))),...Tc("mcp",s),...Tc("skill",s),...a===null?[await $F(t,c)]:[]];return{agents:i,configured:bF(r),gitHooksDirectory:c,hookManager:a,initialised:n,pack:r?.pack??null,packs:pn(o).map(({description:u,name:d})=>({description:u,name:d})),root:t,routing:{review:r?.review.agent===void 0?null:{agent:r.review.agent,model:r.review.model??null},reviewCommand:r?.review.command??null,task:r?.routing.default??null},targets:l}}async function KS(t){let e={user:await Ot("user",t)};return[...Tc("mcp",e),...Tc("skill",e)]}async function SF(t){let e=he.find((c)=>c.name===t),n=Jt.find((c)=>c.agent===t),r=qt.find((c)=>c.agent===t),o=yF[t],s=await Xo(o),i=[...e===void 0?[]:["hooks"],...n===void 0?[]:["mcp"],...r===void 0?[]:["skill"]],a=[...n?.user==null?[]:["mcp"],...r?.user==null?[]:["skill"]];return{agent:t,binaries:o,kinds:i,label:e?.label??t,path:s.path,preset:Ie.some((c)=>c.name===t),support:e?.support??"partial",userScope:a,version:s.version}}function Tc(t,e){return(t==="mcp"?Jt:qt).flatMap((r)=>fo.flatMap((o)=>{let s=e[o];if(r[o]===null||s===void 0)return[];let i=$p(r.agent),a=TF(t,i,s),c=()=>a.install(q(a.base,a.file))===q(a.base,a.file);return[BS(wt(t,i),i,t,o,a.file,()=>En(a),c)]}))}function TF(t,e,n){if(t==="mcp"){let o=Jt.find((s)=>s.agent===e);if(o!==void 0)return Te(o,n)}let r=qt.find((o)=>o.agent===e);if(r!==void 0)return Ee(r,n);throw Error(`ari has no ${t} target for ${e}`)}function BS(t,e,n,r,o,s,i){let a={agent:e,file:ee(r,o),id:t,kind:n,scope:r},c=Ec(s,a.file);if(c.problem!==null)return{...a,problem:c.problem,status:"outdated"};let l=c.value===!0,u=Ec(i,a.file);if(u.problem!==null)return{...a,problem:u.problem,status:l?"outdated":"missing"};return{...a,problem:null,status:bp(l,u.value===!0)}}function EF(t){let e={agent:null,file:_t,id:Un,kind:"config",scope:"project"},n=Ec(()=>q(t,_t),_t);if(n.problem!==null)return{...e,problem:n.problem,status:"outdated"};let r=n.value,o=(r??"").includes(kF),s=Ec(()=>Fs(r)===r,_t);if(s.problem!==null)return{...e,problem:s.problem,status:"outdated"};return{...e,problem:null,status:bp(o,s.value===!0)}}async function $F(t,e){let n={agent:null,file:e,id:je,kind:"git",scope:"project"},r=await xF(()=>eo(t),e);if(r.problem!==null)return{...n,problem:r.problem,status:"outdated"};let o=r.value===!0;try{let s=await ds(t);return{...n,problem:null,status:bp(o,s.every((i)=>i.action==="unchanged"))}}catch(s){return{...n,problem:vp(s,e),status:o?"outdated":"missing"}}}function bF(t){if(t===null)return[];return Object.entries(t.agents).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>({model:n.model??null,name:e,roles:nr(n)}))}async function vF(t){return{base:t,receipts:await M(t),scope:"project"}}function bp(t,e){if(!t)return"missing";return e?"current":"outdated"}function Ec(t,e){try{return{problem:null,value:t()}}catch(n){return{problem:vp(n,e),value:null}}}async function xF(t,e){try{return{problem:null,value:await t()}}catch(n){return{problem:vp(n,e),value:null}}}function vp(t,e){if(t instanceof g)return{hint:t.hint??"",message:t.message};let n=t.code;if(t instanceof Error&&typeof n==="string"&&wF.has(n))return{hint:`Check that ${e} is a readable file, then run the command again`,message:`${e} cannot be read (${n})`};throw t}function $p(t){let e=et.find((n)=>n===t);if(e!==void 0)return e;throw Error(`ari has no install support for ${t}`)}function X(t,e){return{detail:e,hint:null,name:t,status:"ok"}}function it(t,e,n){return{detail:e,hint:n,name:t,status:"warn"}}function ft(t,e,n){return{detail:e,hint:n,name:t,status:"fail"}}function WS(t){return{fail:t.filter((e)=>e.status==="fail").length,ok:t.filter((e)=>e.status==="ok").length,warn:t.filter((e)=>e.status==="warn").length}}function Er(t){return`'${t.replaceAll("'","'\\''")}'`}function $c(t,e){return t.ok?X(t.name,t.detail):ft(t.name,t.detail,t.hint??e)}var AF="agent binaries",CF="ari agents detect";function VS(t){let e=Object.keys(t.agents).sort(I);if(e.length===0)return[X(AF,"none configured; 'ari agents add <preset>' adds one for ari run and ari review")];let n=IF(t);return e.map((r)=>RF(r,t.agents[r],n.has(r)))}function RF(t,e,n){let r=`agent ${t}`,s=[...new Set([e?.command[0],e?.reviewCommand?.[0]].filter((l)=>l!==void 0))].map((l)=>({binary:l,path:Bun.which(l)})),i=s.filter((l)=>l.path===null).map((l)=>l.binary);if(i.length===0)return X(r,s.map((l)=>`${l.binary} at ${l.path}`).join("; "));let a=`${i.join(", ")} not found on PATH${n?", and the routing or review gate uses this agent":""}`,c=`Install ${i.join(" and ")} and put it on PATH, then run '${CF}'`;return n?ft(r,a,c):it(r,a,c)}function IF(t){let{review:e,routing:n}=t,o=[n.default,n.review,...Object.values(n.stages)].flatMap((s)=>s===null?[]:[s.agent]);return new Set([...o,...e.agent===void 0?[]:[e.agent]])}import{existsSync as JS}from"fs";import{join as qS}from"path";var bc="configuration",vc="trust",YS="ari init",OF="ari doctor",_F=12;function XS(t){if(!JS(qS(t,W)))return{check:ft(bc,"ari is not set up in this repository: .ari/ does not exist",YS),config:null,skipReason:"ari is not set up in this repository"};try{let e=L(t);if(!JS(qS(t,Q)))return{check:it(bc,`${Q} is missing, so the defaults apply`,YS),config:e,skipReason:null};return{check:X(bc,`${Q} is valid (pack ${e.pack})`),config:e,skipReason:null}}catch(e){if(!(e instanceof g))throw e;return{check:ft(bc,e.message,`Fix ${Q} by hand, then run '${OF}' again`),config:null,skipReason:"the configuration is not valid"}}}function zS(t,e){let n=De(t,e),r=Zr();switch(n.state){case"not-required":return X(vc,"the configuration starts no commands, so nothing needs trust");case"trusted":return X(vc,`trusted since ${n.trustedAt} (configuration ${n.sha256.slice(0,_F)})`);case"untrusted":case"changed":{let o=n.state==="changed"?`the commands changed since ${n.trustedAt}`:"nobody has trusted them on this machine";if(r)return X(vc,`${o}, but ${lr}=1 lets ari run them`);return it(vc,`${n.commands.length} configured command(s) are not trusted: ${o}, so ari run, ari review and command gates refuse to start them`,"ari trust")}}}var xc="ari on PATH",PF=/\d+(?:\.\d+)+[\w.+-]*/,ZS="bun add -g @r5n/ariadne";async function QS(t){let e=mp(Bun.which("ari"));if(!e.ok)return ft(xc,e.detail,ZS);let n=await Xo(["ari"]),r=n.path??e.detail;if(n.version===null)return it(xc,`${r} did not report a version`,`${r} --version`);let o=PF.exec(n.version)?.[0]??n.version;if(o===t)return X(xc,`${r} (Ariadne ${o})`);return it(xc,`${r} is Ariadne ${o}, but this is Ariadne ${t}`,`${ZS}@${t}`)}var NF="ari doctor",tT="git hooks",DF="agents",LF="ari hooks install --agent git",xp="ari install";function Ap(t){return t.flatMap((e)=>{let n=FF(e);if(e.problem!==null)return[HF(n,e)];if(e.status==="missing")return e.kind==="config"?[UF(n,e)]:[];if(e.status==="current")return[X(n,GF(e))];return[it(n,`${e.file} is not what this ari installs now`,nT(e))]})}function eT(t){let e=et.filter((r)=>t.targets.some((o)=>o.agent===r&&o.status!=="missing"));return[...e.length===0?[it(DF,"no agent is set up here: no hooks, MCP server or skill is installed",xp)]:e.flatMap((r)=>MF(t,r)),...jF(t)]}function MF(t,e){let n=t.agents.find((r)=>r.agent===e);if(n===void 0)return[];return n.kinds.flatMap((r)=>{if(t.targets.some((c)=>c.agent===e&&c.kind===r&&c.status!=="missing"))return[];let s=fc({agent:e,file:null,kind:r}),i=To(t,[wt(r,e)])[0];if(i!==void 0)return[X(s,`not needed: ${i.reason}`)];let a=Sr({agent:e,kind:r,scope:"project"})??xp;return[it(s,`${n.label} has no ${Fe[r]} installed`,a)]})}function jF(t){if(t.hookManager!==null)return[X(tT,`${t.hookManager.name} manages them, so ari leaves them alone`)];let e=t.targets.find((n)=>n.id==="git");if(e===void 0||e.status!=="missing"||e.problem!==null)return[];return[it(tT,"not installed: commits and pushes are not checked against the task's scope",LF)]}function FF(t){let e=fc(t);return t.scope==="user"?`${e} (user)`:e}function GF(t){if(t.kind==="git")return"pre-commit and pre-push run ari";return t.kind==="config"?`${t.file} has the ari block`:t.file}function HF(t,e){let n=e.problem?.message??"";return ft(t,n,`Make ${e.file} a valid, readable file by hand, then run '${NF}' again`)}function UF(t,e){return it(t,`${e.file} has no ari block, so agents are not told the loop`,nT(e))}function nT(t){return Sr(t)??xp}import{existsSync as KF,readdirSync as BF,readFileSync as WF,realpathSync as VF,statSync as JF}from"fs";import{tmpdir as qF}from"os";import{join as sT,resolve as YF,sep as XF}from"path";var zF=3600,ZF=1000,iT=zF*ZF,rT="temporary files",QF=".git",oT="gitdir:",tG="git worktree prune";async function aT(t,e=Date.now()){let n=await eG(t,e);if(n.length===0)return X(rT,"no leftover ari-base-* or ari-index-* directory older than one hour");let r=n.map((i)=>`${i.path} (${i.kind}, ${iG(i.ageMs)} old)`),o=n.map((i)=>i.kind==="base worktree"?`git worktree remove --force ${Er(i.path)}`:`rm -r ${Er(i.path)}`),s=n.some((i)=>i.kind==="base worktree")?[tG]:[];return it(rT,`${n.length} directory(ies) left behind by an interrupted run: ${r.join("; ")}`,[...o,...s].join(" && "))}async function eG(t,e){let n=qF(),r=Vi(t),o=await nG(t);return oG(n).flatMap((s)=>{let i=sT(n,s),a=sG(i,e);if(a===null||a<iT)return[];if(s.startsWith(r))return[{ageMs:a,kind:"temporary index",path:i}];return s.startsWith(Qo)&&rG(i,o)?[{ageMs:a,kind:"base worktree",path:i}]:[]})}async function nG(t){try{return cT(await Ke(t,"worktrees"))}catch{return null}}function rG(t,e){if(e===null)return!1;try{let n=WF(sT(t,QF),"utf8").trim();if(!n.startsWith(oT))return!1;return cT(YF(n.slice(oT.length).trim())).startsWith(`${e}${XF}`)}catch{return!1}}function oG(t){try{return BF(t).filter((e)=>e.startsWith(Qo)||e.startsWith(au))}catch{return[]}}function sG(t,e){try{let n=JF(t);return n.isDirectory()?e-n.mtimeMs:null}catch{return null}}function cT(t){return KF(t)?VF(t):t}function iG(t){let e=Math.floor(t/iT);return e<1?"under an hour":e===1?"1 hour":`${e} hours`}var lT="knowledge size",uT="sleep",dT="ari sleep",aG="ari doctor";async function pT(t){try{let e=Fn(await kr(t));return[cG(e),lG(e)]}catch(e){if(!(e instanceof g))throw e;let n=e.hint===void 0||e.hint.length===0?"Fix it by hand":e.hint.replace(/\.$/,"");return[ft("knowledge",e.message,`${n}, then run '${aG}' again`)]}}function cG({activeBytes:t,maxBytes:e}){let n=`${t} of ${e} bytes of active knowledge`;if(t<=e)return X(lT,n);return it(lT,`${n}: over the budget`,dT)}function lG(t){if(!t.due)return X(uT,"nothing to consolidate");let e=t.reasons.map((n)=>uG(n,t));return it(uT,`sleep is due: ${e.join("; ")}`,dT)}function uG(t,e){switch(t){case"journals":return`journals of done tasks remain (${e.journaled.join(", ")})`;case"budget":return`active knowledge exceeds ${e.maxBytes} bytes`;case"candidates":{let{clusters:n,decisions:r,notes:o}=e.candidates;return`${n} cluster(s), ${o} note(s) and ${r} decision(s) are waiting for a proposal`}}}var Cp="receipts",dG=[{kind:"hooks",name:"hooks.json"},{kind:"mcp",name:"mcp.json"},{kind:"skill",name:"skills.json"}],pG="ari install";function Rp(t){let e={edited:0,fixes:[],matches:0,problems:[]};for(let o of t)for(let s of dG){if(s.kind==="hooks"&&o.scope==="user")continue;gG(o,s,e)}if(e.problems.length>0)return it(Cp,`${e.problems.join("; ")}; uninstall would remove only ari's entries instead of restoring files byte for byte`,[...new Set(e.fixes)].join("; "));let n=e.matches+e.edited;if(n===0)return X(Cp,"no receipts: nothing was installed through ari here");let r=e.edited===0?"":`; ${e.edited} edited since install, which uninstall keeps`;return X(Cp,`${e.matches} of ${n} match their files${r}`)}function gG(t,e,n){let r=Oy(t.receipts,e.name);if(r.state==="absent")return;if(r.state==="unreadable"){n.problems.push(`${r.path} cannot be read`),n.fixes.push(`rm ${Er(r.path)}`);return}for(let[o,s]of Object.entries(r.receipts))mG(t,e.kind,o,s,n)}function mG(t,e,n,r,o){let s=fG(t,e,n);if(s===null)return;let i=hG(t,n);if(i===void 0)return;let a=yG(s,t,i);if(a===null)return;if(i===null||!a){o.problems.push(`the receipt for ${n} (${t.scope}) names ari entries that are no longer there`),o.fixes.push(kG(e,s.agent,t.scope));return}if(i===r.installed)o.matches++;else o.edited++}function fG(t,e,n){if(e==="hooks"){let o=he.find((s)=>s.file===n);return o===void 0?null:{agent:o.name,hooks:o}}if(e==="mcp"){let o=Jt.find((s)=>s[t.scope]===n);return o===void 0?null:{agent:o.agent,managed:Te(o,t)}}let r=qt.find((o)=>o[t.scope]===n);return r===void 0?null:{agent:r.agent,managed:Ee(r,t)}}function hG(t,e){try{return q(t.base,e)}catch{return}}function yG(t,e,n){try{if(t.hooks!==void 0)return Ye(e.base,t.hooks);return t.managed===void 0?null:t.managed.managed(n)}catch{return null}}function kG(t,e,n){return Sr({agent:e,kind:t,scope:n})??pG}import{join as wG}from"path";var $o="active task",gT="tasks",SG="active.json",TG=10,EG=new Set(["active","blocked"]),mT="ari list",$G="then run 'ari doctor' again";async function fT(t,e){let n=await M(t);return[bG(t,e,n),...AG(t,e)]}function bG(t,e,n){let r=`rm ${Er(wG(n,SG))}`,o=hT(()=>ut(n));if(o.failure!==null)return ft($o,`the pointer of this worktree cannot be read: ${o.failure.message}`,r);if(o.value===null)return X($o,"no task is active in this worktree");return vG(t,e,o.value,r)}function vG(t,e,n,r){let{task:o}=n;if(!te(t).includes(o)){let i=hn(t).includes(o)?"its contract is missing":"no such task exists";return it($o,`the pointer of this worktree names "${o}", but ${i}`,r)}let s=hT(()=>lt(t,o,e).task);if(s.failure!==null||s.value===null){let i=s.failure??new g(`task "${o}" cannot be read`);return ft($o,`the pointer of this worktree names "${o}", which cannot be read: ${i.message}`,CG(i))}return xG(s.value,r)}function xG({contract:t,record:e},n){let r=t.id;if(EG.has(e.status))return X($o,`${r} (${e.status}, stage ${e.stage})`);return it($o,`the pointer of this worktree names "${r}", which is ${e.status}`,n)}function AG(t,e){let{invalid:n,tasks:r}=It(t,e);if(n.length===0)return[X(gT,`${r.length} task(s), every contract and record is readable`)];let o=n.slice(0,TG).map((i)=>ft(`task ${i.id}`,i.problem,yT(i.hint))),s=n.length-o.length;return s>0?[...o,ft(gT,`${s} more task(s) cannot be read`,mT)]:o}function hT(t){try{return{failure:null,value:t()}}catch(e){if(e instanceof g)return{failure:e,value:null};throw e}}function CG(t){return yT(t.hint??"")}function yT(t){return t.length===0?mT:`${t.replace(/\.$/,"")}, ${$G}`}var kT="git on PATH",RG="ari mcp serve",IG=5000,OG="ari doctor --json",_G="not inside a git working tree",PG="git is not on PATH",NG=["configuration","trust","project integrations","git hooks","agent binaries","tasks","temporary files","sleep and knowledge size"],DG=["trust","agent binaries","tasks","sleep and knowledge size"];async function wT({cwd:t,version:e}){let n=Bun.which("git"),r=n===null?null:await LG(t),o=[...await Qe("ari on PATH",async()=>[await QS(e)]),n===null?ft(kT,"git is not on PATH, so ari cannot read any repository","Install git"):X(kT,n)],s=r===null?await MG(t,n===null?PG:_G):await jG(r),i=[...o,...s.checks],a=WS(i);return{checks:i,ok:a.fail===0,root:r,skipped:s.skipped,summary:a,version:e}}async function LG(t){try{return await On(t)}catch(e){if(e instanceof g)return null;throw e}}async function MG(t,e){let n=await KS(t),r=await Ot("user",t);return{checks:[...Ap(n),...await Qe("ari mcp serve",()=>ST(t,n)),...await Qe("receipts",()=>[Rp([r])])],skipped:NG.map((s)=>({name:s,reason:e}))}}async function jG(t){let e=XS(t),{config:n}=e,r=await Qe("integrations",async()=>{let c=await Gs(t,n);return[...Ap(c.targets),...eT(c),...await ST(t,c.targets)]}),o=await Qe("receipts",async()=>[Rp(await GG(t))]),s=await Qe("temporary files",async()=>[await aT(t)]),i=n===null?{first:[],last:[]}:await FG(t,n),a=e.skipReason;return{checks:[e.check,...i.first,...r,...o,...i.last,...s],skipped:n===null&&a!==null?DG.map((c)=>({name:c,reason:a})):[]}}async function FG(t,e){let n=await Qe("trust",()=>[zS(t,e)]),r=await Qe("agent binaries",()=>VS(e)),o=await Qe("tasks",()=>fT(t,e)),s=await Qe("sleep",()=>pT(t));return{first:n,last:[...r,...o,...s]}}async function GG(t){return[await Ot("project",t),await Ot("user",t)]}async function ST(t,e){let n=e.some((o)=>o.kind==="mcp"&&o.status!=="missing"),r=Bun.which("ari");if(!n||r===null)return[];return[$c(await fp(r,t,IG),RG)]}async function Qe(t,e){try{return await e()}catch(n){return[HG(t,n)]}}function HG(t,e){if(e instanceof g){let r=e.hint===void 0||e.hint.length===0?"Fix it by hand":e.hint.replace(/\.$/,"");return ft(t,e.message,`${r}, then run 'ari doctor' again`)}let n=e instanceof Error?e.message:String(e);return ft(t,`the check stopped unexpectedly: ${n}`,OG)}var UG=26,ET=6,KG=" ".repeat(ET),BG={fail:"FAIL",ok:"ok",warn:"warn"};function Ip(t){return t.flatMap((e)=>{let n=`${WG(e.status,TT(BG[e.status],ET))}${TT(e.name,UG)}${e.detail}`;return e.hint===null||e.status==="ok"?[n]:[n,`${KG}fix: ${e.hint}`]})}function $T(t){let{fail:e,ok:n,warn:r}=t.summary,o=t.skipped.length===0?[]:["",...t.skipped.map((i)=>`skipped ${i.name}: ${i.reason}`)],s=`${n} ok, ${r} warning(s), ${e} failure(s)`;return[...Ip(t.checks),...o,"",s].join(`
190
- `)}function WG(t,e){switch(t){case"ok":return k.green(e);case"warn":return k.yellow(e);case"fail":return k.red(e)}}function TT(t,e){let n=Bun.stringWidth(t);return n>=e?`${t} `:`${t}${" ".repeat(e-n)}`}var VG=1,bT=E({description:"Check the setup without changing anything: ari, configuration, trust, integrations, tasks and memory",examples:["ari doctor","ari doctor --json"],json:!0,name:"doctor",run:async(t)=>{let e=await wT({cwd:process.cwd(),version:t.cli.version??""});return t.output.result(e,$T),e.ok?void 0:VG}});function Ac(t,e){let n=new Set,r=(o,s)=>{for(let i of e(o)){if(i===t)return[...s,t];if(n.has(i))continue;n.add(i);let a=r(i,[...s,i]);if(a)return a}return null};return r(t,[t])}function Cc(t){return`depends forms a cycle: ${t.join(" -> ")}`}var JG=["ari check","ari done"],qG=["ari next"],YG='ari new "<title>"',vT=["active","blocked"];function Op(t){let e=[...t.tasks].sort((u,d)=>I(u.contract.id,d.contract.id)),n=t.active?e.find((u)=>u.contract.id===t.active?.task):void 0;if(n?.record.status==="active")return XG(n,t.packs);if(n?.record.status==="blocked")return zG(n,t.packs);let r=e.filter((u)=>!t.claimed.has(u.contract.id)),s=r.filter((u)=>vT.includes(u.record.status)).find((u)=>Pp(u,t.packs)===null);if(s)return ZG(s,t.packs);let i=n1(r,t),a=o1(e,r.filter((u)=>!i.has(u.contract.id)));if(a)return t1(a,t.packs);let c=r1(e,r,t,i);if(c)return QG(c);let l=e.find((u)=>u.record.status==="draft");if(l)return e1(l);return{action:"new",commands:[YG],instruction:"Create a task and write its contract: scope, criteria and checks.",stage:null,task:null}}function XG(t,e){let n=_p(t,e);return{action:"continue",commands:[...JG],instruction:Vr(n,t.contract.id),stage:n.name,task:t.contract.id}}function zG(t,e){let n=t.record.question??"the task was blocked without a recorded question";return{action:"resolve",commands:[`ari resolve ${t.contract.id} --answer "<answer>"`],instruction:`A human must answer: ${n}`,stage:_p(t,e).name,task:t.contract.id}}function ZG(t,e){return{action:"start",commands:[`ari start ${t.contract.id}`],instruction:`Task "${t.contract.title}" is ${t.record.status}, but no worktree holds it; adopt it here.`,stage:_p(t,e).name,task:t.contract.id}}function QG(t){return{action:"fix",commands:[...qG],instruction:t.instruction,stage:null,task:t.id}}function t1(t,e){let n=e.find((r)=>r.name===t.contract.pack)?.stages[0];return{action:"start",commands:[`ari start ${t.contract.id}`],instruction:`Start "${t.contract.title}".`,stage:n?.name??null,task:t.contract.id}}function e1(t){return{action:"ready",commands:[`ari ready ${t.contract.id}`],instruction:`Complete the contract of "${t.contract.title}", then mark it ready.`,stage:null,task:t.contract.id}}function _p(t,e){let n=Pp(t,e);if(n!==null)throw new g(n.message,n.hint);let r=e.find((o)=>o.name===t.contract.pack)?.stages[t.record.stage];if(r)return r;throw Error(`Task "${t.contract.id}" has no stage ${t.record.stage}`)}function Pp(t,e){let n=e.find((r)=>r.name===t.contract.pack);if(!n)return{hint:"Fix the contract's pack",message:`Unknown pack "${t.contract.pack}" in task "${t.contract.id}"`};if(t.record.stage<n.stages.length)return null;return{hint:`Restore the stages of pack "${n.name}" in .ari/packs/${n.name}.yaml`,message:`Task "${t.contract.id}" is at stage ${t.record.stage}, but pack "${n.name}" has ${n.stages.length}`}}function n1(t,{packs:e,uncoveredLocks:n}){let o=t.filter((s)=>s.record.status==="ready").map((s)=>{let i=n.get(s.contract.id),a=i===void 0?[]:[`lock glob ${JSON.stringify(i)} matches no file that git tracks or would track`];return[s.contract.id,[...Br(s.contract,e),...a]]});return new Map(o.filter(([,s])=>s.length>0))}function r1(t,e,{invalid:n,packs:r},o){let s=new Map(t.map((p)=>[p.contract.id,p])),i=new Set(n.map((p)=>p.id)),a=(p)=>s.get(p)?.contract.depends??[],c=e.filter((p)=>p.record.status==="ready").flatMap((p)=>{let m=p.contract.id,f=p.contract.depends.find((S)=>!s.has(S)&&!i.has(S));if(f!==void 0)return[{id:m,instruction:`depends names the unknown task "${f}". Fix the depends of .ari/tasks/${m}.md`}];let y=Ac(m,a);return y?[{id:m,instruction:`${Cc(y)}. Remove one of these dependencies`}]:[]}),l=[...o].map(([p,m])=>({id:p,instruction:`The contract can no longer start: ${m.join("; ")}. Fix .ari/tasks/${p}.md`})),u=e.filter((p)=>vT.includes(p.record.status)).flatMap((p)=>{let m=Pp(p,r);return m===null?[]:[{id:p.contract.id,instruction:`${m.message}. ${m.hint}`}]});return[...n.map((p)=>({id:p.id,instruction:`${p.problem}. ${p.hint}`})),...u,...l,...c].sort((p,m)=>I(p.id,m.id))[0]}function o1(t,e){let n=new Map(t.map((i)=>[i.contract.id,i])),r=new Map,o=(i,a)=>{let c=r.get(i);if(c!==void 0)return c;let l=n.get(i);if(!l||a.has(i))return 0;let u=new Set([...a,i]),d=Math.max(-1,...l.contract.depends.map((p)=>o(p,u)))+1;return r.set(i,d),d};for(let i of t)o(i.contract.id,new Set);let s=(i)=>i.contract.depends.every((a)=>n.get(a)?.record.status==="done");return e.filter((i)=>i.record.status==="ready"&&s(i)).sort((i,a)=>(r.get(i.contract.id)??0)-(r.get(a.contract.id)??0)||I(i.contract.id,a.contract.id))[0]}import{realpathSync as s1}from"fs";import{resolve as i1}from"path";var a1="ENOENT";async function Hs(t){let e=xT(t),n=new Map;for(let r of await Kf(t)){if(xT(r)===e)continue;let o=c1(await M(r));if(o!==null&&!n.has(o.task))n.set(o.task,r)}return n}function c1(t){try{return ut(t)}catch(e){if(e instanceof g)return null;throw e}}function xT(t){try{return s1(t)}catch(e){if(e.code===a1)return i1(t);throw e}}var l1=8,u1=6,d1=10,AT=`
181
+ `,pv=`
182
+ `,XF=/\s+/g,gv=60,zF=40,mv="...",kv=["tasks","snapshot","rules"],ZF={rules:"Constraints and decisions:",snapshot:null,tasks:"Tasks:"},fv={active:0,ready:1},QF=`No Ariadne tasks yet. Create one with 'ari new "<title>"'.`,tG="Ariadne could not list the tasks of this repository. Run 'ari next' to see why.",eG="No task is active in this worktree and none is ready to start. Run 'ari next'.",nG="No task is active in this worktree. Run 'ari next' for the next action.";function wv(t){let e=[],{root:n,state:r}=t,o=Jp(e,"tasks",()=>Pt(n,t.config),null),s=Jp(e,"knowledge",()=>pe(n),[]),i=o?.tasks??[],a=i.filter((g)=>g.record.status==="active"),c=oG(i,a).map(sG),l=Jp(e,"snapshots",()=>lG(r,a),null),u=s.filter(iG).sort(aG).map(cG),d=rG(o===null?null:i.length+o.invalid.length,c.length),p=[...c.map((g)=>({part:"tasks",text:g})),...l===null?[]:[{part:"snapshot",text:l}],...u.map((g)=>({part:"rules",text:g}))];return{text:dG(d,p,t.config.context.briefBytes),warnings:e}}function rG(t,e){if(t===null)return tG;if(t===0)return QF;return e===0?eG:nG}function Jp(t,e,n,r){try{return n()}catch(o){let s=o instanceof Error?o.message:String(o);return t.push(`ari left the ${e} out of the session brief (${s})`),r}}function oG(t,e){let n=new Set(t.filter((o)=>o.record.status==="done").map((o)=>o.contract.id)),r=t.filter((o)=>o.record.status==="ready"&&o.contract.depends.every((s)=>n.has(s)));return[...e,...r].sort((o,s)=>(fv[o.record.status]??0)-(fv[s.record.status]??0)||O(o.contract.id,s.contract.id))}function sG({contract:t,record:e}){return`- ${t.id}: ${Xp(t.title)} (${t.pack}, ${e.status})`}function iG(t){return t.status==="active"&&pn(t)&&t.scope.length===0}function aG(t,e){return O(t.id,e.id)}function cG(t){return`- ${t.kind} \`${t.id}\`: ${Xp(t.text)}`}function lG(t,e){let n=new Set(e.map((s)=>s.contract.id));if(n.size===0)return null;let o=_o(Fr(t)).map((s)=>s.slice(0,-gn.length)).sort((s,i)=>Pr(i,s));for(let s of o.slice(0,zF)){let i=uG(t,s);if(i===null||i.kind!=="save"||!n.has(i.task))continue;let a=Xp(i.reason??i.trigger),c=a.length>gv?`${a.slice(0,gv-mv.length)}${mv}`:a;return`Latest snapshot of an active task: ${s} of "${i.task}" (${c}); 'ari snapshot show ${s}' prints what it saved.`}return null}function uG(t,e){try{return jo(t,e)}catch{return null}}function dG(t,e,n){let r=Yp(t,qp(e),null);if(yt(r)<=n)return r;let o=yt(`${yv}${hv(e.length)}`),s=[];for(let a of kv.flatMap((c)=>e.filter((l)=>l.part===c))){let c=[...s,a];if(yt(Yp(t,qp(c),null))+o<=n)s.push(a)}let i=e.length-s.length;return pG(Yp(t,qp(s),i===0?null:hv(i)),n)}function qp(t){let e={rules:[],snapshot:[],tasks:[]};for(let{part:n,text:r}of t)e[n].push(r);return e}function Yp(t,e,n){let r=kv.flatMap((o)=>{let s=e[o];if(s.length===0)return[];let i=ZF[o];return[i===null?s.join(pv):[i,...s].join(pv)]});return[t,...r,...n===null?[]:[n]].join(yv)}function hv(t){return`Left out to fit context.briefBytes: ${t} ${t===1?"item":"items"}. 'ari list' and 'ari knowledge list' show everything.`}function Xp(t){return t.replace(XF," ").trim()}function pG(t,e){let n=0,r=0;for(let o of t){if(n+=yt(o),n>e)break;r+=o.length}return t.slice(0,r)}import{resolve as Dv}from"path";var Sv=new RegExp([/\\\n/,/\\(?<escaped>[\s\S])/,/(?<![^ \t\r\n;&|()])#[^\n]*/,/'(?<single>[^']*)'?/,/"(?<double>(?:[^"\\$]+|\\[\s\S]|\$\(cat <<-?[ \t]*["']?(?<mark>\w+)[^\n]*\n[\s\S]*?\n[ \t]*\k<mark>\n\s*\)|\$)*)"?/,/\(\((?<arithmetic>(?:[^()\n]|\([^()\n]*\))*)\)\)/,/<<(?!<)(?<tabs>-?)[ \t]*(?<delimiter>(?:'[^'\n]*'|"[^"\n]*"|\\.|[^ \t\r\n'"\\`;&|()<>])+)/,/(?:(?<![^ \t\r\n;&|()<>])\d+)?[<>]&[ \t]*(?:\d+-?|-)(?![^ \t\r\n;&|()<>])/,/(?<output>(?:&|(?<![^ \t\r\n;&|()<>])\d+)?>(?!\()[>|&]?)/,/(?<input><<<|(?:(?<![^ \t\r\n;&|()<>])\d+)?<(?!\()>?)/,/(?<separator>&&|\|\||\|&|;;|[<>]?\(|[;&|)\n`])/,/(?<blank>[ \t\r]+)/,/(?<plain>[^ \t\r\n'"\\`;&|()<>#]+|[\s\S])/].map(({source:t})=>t).join("|"),"y"),gG=/[ \t\r\n]/,mG=/\$\(cat <<-?[ \t]*(["'])(\w+)\1\n[\s\S]*?\n[ \t]*\2\n\s*\)/g,fG=/\\[\s\S]/g,hG=/\\([$`"\\\n])/g,yG=/[$`]/,kG=/[$*?[]|\{./;var wG=/['"\\]/g,SG=/^\t+/;var vG=/[(`]/,bG=new Set(["-C","-c","--config-env","--exec-path","--git-dir","--namespace","--work-tree"]);function zp(t){let e=[],n=[],r=vv(""),o="words",s=null,i=0,a=(u,d)=>{s=(s??"")+u,r.literal&&=d},c=(u="words")=>{if(s!==null)r[o].push(s);s=null,o=u},l=(u)=>{if(c(),r.literal&&=!vG.test(u),r.words.length+r.inputs.length+r.outputs.length>0)e.push(r);r=vv(u)};while(i<t.length){Sv.lastIndex=i;let u=Sv.exec(t);if(u===null)break;let{arithmetic:d,blank:p,delimiter:g,double:f,escaped:y,input:S,output:I,plain:C,separator:q,single:G,tabs:N}=u.groups??{};if(i+=u[0].length,y!==void 0)a(y,!0);else if(G!==void 0)a(G,!0);else if(f!==void 0)a($G(f),EG(f));else if(d!==void 0)a(d,!1);else if(C!==void 0)a(C,!kG.test(C)&&(s!==null||!C.startsWith("~")));else if(p!==void 0&&s!==null)c();else if(I!==void 0)c("outputs");else if(S!==void 0)c("inputs");else if(g!==void 0)c(),n.push({delimiter:g.replace(wG,""),tabs:N!==""});else if(q!==void 0){if(q===`
183
+ `)for(let H of n.splice(0)){let{body:A,end:R}=TG(t,i,H);r.inputs.push(A),i=R}l(q)}}return l(""),e}function Zp(t){return zp(t).flatMap((e)=>[e,...[...e.words,...e.inputs].filter((n)=>gG.test(n)).flatMap(Zp)])}function Fc(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n]??"";if(!r.startsWith("-"))return{args:t.slice(n+1),directories:e,subcommand:r};if(bG.has(r))n+=1;if(r==="-C")e.push(t[n]??"")}return null}function Gr(t){return t.slice(t.lastIndexOf("/")+1)}function vv(t){return{before:t,inputs:[],literal:!0,outputs:[],words:[]}}function EG(t){return!yG.test(t.replace(mG,"").replace(fG,""))}function $G(t){return t.replace(hG,(e,n)=>n===`
184
+ `?"":n)}function TG(t,e,{delimiter:n,tabs:r}){for(let o=e;o<t.length;){let s=t.indexOf(`
185
+ `,o),i=s===-1?t.length:s,a=t.slice(o,i);if((r?a.replace(SG,""):a)===n)return{body:t.slice(e,o),end:i};o=i+1}return{body:t.slice(e),end:t.length}}import{basename as xG,isAbsolute as AG,join as CG,resolve as Hc}from"path";var RG=/^[A-Za-z_]\w*\+?=/,IG=new Set("! { builtin command do elif else env exec if nohup sudo then time until while".split(" ")),OG=new Map([["mkdir",["created","m mode"]],["rm",["removed",""]],["rmdir",["removed",""]],["tee",["written",""]],["touch",["written","A d r t date reference"]],["truncate",["written","r s reference size"]]]),_G=new Set("ari ariadne cat cd diff echo egrep file gh grep head jq ls popd printf pushd rg tail test wc".split(" ")),PG=new Set("add blame branch commit diff fetch grep log ls-files push show status tag".split(" ")),NG=new Set(["cd","popd","pushd"]),bv=new Set(["","&&",";",`
186
+ `]),DG="S suffix",LG=/^(?:-[a-z0-9E]*i|--in-place)/,MG=/^(?:-[a-zA-Z0-9]*[ef]|--expression|--file)/,jG="e f l expression file line-length",FG=/^-[a-zA-Z0-9]*[eE]/,GG="e E",HG=/^-\w+$/,UG=/^\.\w+$/,KG=/^(?:-[a-zA-Z]*t$|--target-directory)/,BG=/^(?:--staged|-[A-Za-z]*S)/,VG=/^(?:--worktree|-[A-Za-z]*W)/,Ev="of=",tg="--",Qp=".";function Tv(t,e){let n=e,r=e,o=!0,s=t.map((i,a)=>{let c=JG(i,n),[l="",u="-",...d]=Uc(i);if(!NG.has(l))return o=!1,c;return o&&=l==="cd"&&i.literal&&!u.startsWith("-")&&d.length===0,o&&=bv.has(i.before)&&bv.has(t[a+1]?.before??""),r=o?Hc(r,u):r,n=o?r:null,c});return{directory:r,steps:s}}function Uc({words:t}){let e=t.findIndex((n)=>!RG.test(n)&&!IG.has(n));return e===-1?[]:[Gr(t[e]??""),...t.slice(e+1)]}function Kc(t,e=""){let n=new Set(e.split(" ")),r=t.indexOf(tg),o=[],s=r===-1?t:t.slice(0,r);for(let i=0;i<s.length;i+=1){let a=s[i]??"";if(!a.startsWith("-"))o.push(a);else if(n.has(WG(a)))i+=1}return[...o,...r===-1?[]:t.slice(r+1)].filter((i)=>i.length>0)}function WG(t){if(t.startsWith("--"))return t.slice(2);return HG.test(t)?t.slice(-1):""}function JG(t,e){if(!t.literal)return{command:t,resolved:!1,targets:[]};let[n="",...r]=Uc(t),o=n==="git"?Fc(r):null,s=e===null?null:Hc(e,...o?.directories??[]),i=o===null?xv(n,r,e):qG(o.subcommand,o.args,s),a=[...Gc(e,"file",t.outputs),...Gc(s,"file",i?.written),...Gc(s,"directory",i?.created),...Gc(s,"removed",i?.removed)],c=a.filter((l)=>l!==null);return{command:t,resolved:i!==null&&c.length===a.length,targets:c}}function Gc(t,e,n=[]){return n.flatMap((r)=>{if(t===null&&!AG(r))return null;let o=Hc(t??r,r),s=e!=="removed"&&tc(o);if(s&&e==="directory")return[];return{kind:s?"directory":e,path:o}})}function xv(t,e,n){let[r,o]=OG.get(t)??[];if(r!==void 0)return{[r]:Kc(e,o)};switch(t){case"dd":return{written:e.filter((s)=>s.startsWith(Ev)).map((s)=>s.slice(Ev.length))};case"cp":case"ln":case"mv":return YG(t,e,n);case"sed":return{written:$v(e,jG,MG)??[]};case"perl":{let s=$v(e,GG,FG);return s===null?null:{written:s}}default:return _G.has(t)?{}:null}}function qG(t,e,n){switch(t){case"checkout":return e.includes(tg)?{removed:e.slice(e.indexOf(tg)+1)}:null;case"restore":return e.some((o)=>BG.test(o))&&!e.some((o)=>VG.test(o))?{}:{removed:Kc(e,"s source pathspec-from-file")};case"rm":case"mv":return xv(t,e,n);default:return PG.has(t)?{}:null}}function YG(t,e,n){if(e.some((a)=>KG.test(a)))return null;let r=Kc(e,DG),[o=Qp,s]=r.length<2?[Qp,r]:[r.at(-1),r.slice(0,-1)],i=o.endsWith("/")||tc(Hc(n??Qp,o));return{removed:t==="mv"?s:[],written:i?s.map((a)=>CG(o,xG(a))):[o]}}function $v(t,e,n){if(!t.some((s)=>LG.test(s)))return null;let r=Kc(t,e),o=r.length>1&&UG.test(r[0]??"")?r.slice(1):r;return t.some((s)=>n.test(s))?o:o.slice(1)}import{basename as Av,dirname as XG,join as Cv}from"path";var zG=[`${J}/tasks/*.md`,`${J}/designs/**`],ZG="x",QG=/\*\*.*/,t1=".git",e1=[/^(?:ari|hooks|info)(?:\/|$)/,/^(?:HEAD|commondir|config(?:\.worktree)?|gitdir|objects|packed-refs|refs|worktrees)$/,/^(?:objects|refs|worktrees)\/(?!.*\.lock$)/],n1="; pass the paths to change instead of their directory",r1="\x00",Bc=0,o1=1,Rv=128;async function Iv(t,e){let n=Ht(e),r=await t.governing(n),o=Pv(t.opened(),n);if(o!==null)return o;return r.flatMap((i)=>{let a=cn(i.root,n);return a===null||a.length===0?[]:li(i,a)??[]})[0]??null}async function Ov(t,e){let n=[],r=new Map;for(let{kind:o,path:s}of e){let a=o==="removed"&&Fd(s)!==null?Cv(Ht(XG(s)),Av(s)):Ht(s),c=await t.governing(a),l=Pv(t.opened(),a);if(l!==null)n.push(l);let u=o==="removed"?t.opened().filter(({root:d})=>cn(a,d)!==null):[];for(let d of new Set([...c,...u])){let p=r.get(d)??[];r.set(d,[...p,{file:cn(d.root,a)??"",kind:o}])}}for(let[o,s]of r)n.push(...await s1(o,s));return n}async function s1(t,e){let n=e.filter(({kind:a})=>a==="removed").map(({file:a})=>a),r=n.length===0?[]:await l1(t,n),o=n.flatMap((a)=>r.filter((u)=>a.length===0||u===a||u.startsWith(`${a}/`)).flatMap((u)=>{let d=li(t,u);return d===null?[]:`${d}${u===a?"":n1}`}).slice(0,1)),s=e.flatMap(({file:a,kind:c})=>{if(c==="removed"||a.length===0)return[];let l=c==="file"?li(t,a):i1(t,a),u=c==="file"?a:`${a}/`;return l===null?[]:[{guarded:_v(t,a)!==null,name:u,reason:l}]}),i=await u1(t.root,s.filter(({guarded:a})=>!a).map(({name:a})=>a));return[...o,...s.filter(({name:a})=>!i.has(a)).map(({reason:a})=>a)]}function _v(t,e){if(yo(e)&&!et(e,zG))return`${e} is written only by ari; use ari commands instead of editing it`;let n=t.workspace?.task??null;if(n===null)return null;return Object.hasOwn(n.record.lockHashes,e)||et(e,n.contract.lock)?`${e} is locked by task "${n.contract.id}" and must stay unchanged`:null}function li(t,e,n=et){let r=_v(t,e);if(r!==null||yo(e))return r;let o=t.fault??t.workspace?.drift??null;if(o!==null)return`ari cannot check ${e}: ${o}`;let s=t.workspace?.task??null;if(s===null||n(e,s.contract.scope))return null;let{id:i,scope:a}=s.contract;return`${e} is outside the scope of task "${i}" (${a.join(", ")}); change the scope with a contract edit and 'ari amend ${i} --reason <text>', or ask a human`}function i1(t,e){return li(t,`${e}/${ZG}`)===null?null:li(t,e,a1)}function a1(t,e){let n=t.split("/").length,r=e.map((o)=>o.replace(QG,"**").split("/").slice(0,n).join("/"));return et(t,r)}function Pv(t,e){return t.some(({gitDirectories:r,root:o})=>cn(Cv(o,t1),e)===""||r.some((s)=>c1(s,e)))?`${Av(e)} belongs to git and to ari's own state; use git and ari commands instead`:null}function c1(t,e){let n=cn(t,e);return n!==null&&e1.some((r)=>r.test(n))}async function l1({root:t,workspace:e},n){let r=await F(t,["--literal-pathspecs","ls-files","-z","-co","--exclude-standard","--",...n.map((s)=>s.length===0?".":s)],{allowedExitCodes:[Bc,Rv]}),o=r.exitCode===Bc?Ke(r.stdout):n;return[...Object.keys(e?.task?.record.lockHashes??{}),J,...o]}async function u1(t,e){if(e.length===0)return new Set;let n=await F(t,["check-ignore","-z","--stdin"],{allowedExitCodes:[Bc,o1,Rv],stdin:[...new Set(e)].join(r1)});return new Set(n.exitCode===Bc?Ke(n.stdout):[])}var d1="'ari approve' records a human approval; ask a person to run it, and pass text that contains these words in a file, as in 'git commit -F <file>'",p1="'ari trust' records that a person has read the commands in .ari/config.json; ask a person to run it, and to run 'ari trust' without --yes to read them first",g1="'ari uninstall' and 'ari hooks uninstall' remove the hooks that guard this repository; ask a person to run them",m1="'git commit --no-verify' skips ari's pre-commit scope check; commit without --no-verify, -n or core.hooksPath, and fix what the check reports",f1="run it as a plain command with literal paths, or ask a person to run it",h1=/(?:^|\/)(?:ari|ariadne)(?:@[^/]*)?$/,y1="approve",k1="trust",Nv="uninstall",w1="hooks",S1="git",v1="commit",b1="config",E1=/^core\.hookspath$/i,$1=/^(?:--config-env=)?core\.hookspath=|^GIT_CONFIG_KEY_\d+=core\.hookspath$/i,T1=/^(?:--)?unset/,x1=/^(?:--no-veri(?:f|fy)?|-[^-\smFcCtSu]*n\S*)$/,A1=/(?<![\w-])\.ari(?![\w.-])/,eg=/[\s'"`;&|()<>=,]+/,C1=[[/^(?:cp|dd|eval|ln|mkdir|mv|rm|rmdir|tee|touch|truncate|xargs)$/,null],[/^find$/,/^-(?:delete|exec(?:dir)?|ok(?:dir)?)$/],[/^git$/,/^(?:checkout|restore)$/],[/^sed$/,/^(?:-[a-zA-Z]*i|--in-place)/]],R1=/^(?:ba|da|fi|k|z)?sh$/,I1=/^-[a-z]*c$/,O1=/^(?:bun|deno|node|perl|php|python|ruby)[\d.]*$/,_1=/^(?:-[a-zA-Z]*[ceEip]|--eval|--print)$/;async function Lv(t,e,n){let{directory:r,steps:o}=Tv(zp(e),n),s=[...new Set([...await t.governing(n),...await t.governing(r)])],i=P1(Zp(e));if(i!==null&&(s.length>0||await N1(t,e,n)))return{kind:"deny",reason:i};let a=await Ov(t,o.flatMap(({targets:d})=>d));if(a.length>0)return{kind:"deny",reason:[...new Set(a)].join("; ")};let c=o.filter(({resolved:d})=>!d).flatMap((d)=>M1(d)??[])[0],l=s.filter(({fault:d,workspace:p})=>d!==null||p?.task!=null),u=c===void 0?null:F1(l,e,[n,r]);if(u===null)return{kind:"allow"};return{kind:"ask",reason:`the command mentions ${u}, which ari protects, and ari does not resolve what its '${c}' writes; ${f1}`}}function P1(t){if(t.some((e)=>Vc(e,y1)))return d1;if(t.some((e)=>Vc(e,k1)))return p1;if(t.some((e)=>Vc(e,Nv)||Vc(e,w1,Nv)))return g1;return t.some(D1)?m1:null}async function N1(t,e,n){for(let r of new Set(e.split(eg)))if((await t.governing(Dv(n,r))).length>0)return!0;return!1}function Vc({words:t},e,n){return t.some((r,o)=>{if(!h1.test(r))return!1;let[s,...i]=t.slice(o+1).filter((a)=>!a.startsWith("-"));return s===e&&(n===void 0||i.includes(n))})}function D1({words:t}){if(t.some((e)=>$1.test(e)))return!0;return t.some((e,n)=>{let r=Gr(e)===S1?Fc(t.slice(n+1)):null;if(r?.subcommand===b1)return L1(r.args);return r?.subcommand===v1&&r.args.some((o)=>x1.test(o))})}function L1(t){let e=t.findIndex((n)=>E1.test(n));return e!==-1&&(e<t.length-1||t.some((n)=>T1.test(n)))}function M1({command:t}){let[e]=Uc(t),n=t.words.flatMap((o)=>o.split(eg)).filter((o)=>o.length>0);return n.map(Gr).find((o,s)=>j1(o,e,n,s+1))??(!t.literal&&t.outputs.length>0?">":null)}function j1(t,e,n,r){let o=C1.find(([c])=>c.test(t))?.[1];if(o===null)return!0;if(o!==void 0)return n.slice(r).some((c)=>o.test(c));let s=R1.test(t);if(!s&&!O1.test(t))return!1;let i=n.slice(r),a=i.findIndex((c)=>!c.startsWith("-"));if(a===-1&&t===e)return!0;return s?i.some((c)=>I1.test(c)):i.slice(0,a===-1?i.length:a).some((c)=>_1.test(c))}function F1(t,e,n){if(t.length>0&&A1.test(e))return J;let r=new Set(e.split(eg));for(let{root:o,workspace:s}of t){let i=Object.keys(s?.task?.record.lockHashes??{}),a=new Set(i.map(Gr));for(let c of[...r].filter((l)=>a.has(Gr(l)))){let u=[o,...n].map((d)=>cn(o,Ht(Dv(d,c)))).find((d)=>d!==null&&i.includes(d));if(u!==void 0)return u}}return null}var H1="stop.json",U1=500,K1=20000,ge={kind:"allow"},B1={decision:{kind:"ask",reason:"ari could not check this in time; write a simpler command, or ask a person to run it"},expired:!0,warning:"ari hook ran out of time"},V1=Et({task:X(),tree:X()});async function Fv(t){let e=yk();if(Pn.has(t.event))return W1(J1(e,t));let n=await e.at(t.cwd);if(n===null)return Wc(ge);if(n.workspace===null)return Mv(t,n.fault??"");try{let r=[],o=await Y1(t,n.workspace,r);return{...Wc(o),warning:r.length===0?null:r.join("; ")}}catch(r){if(!(r instanceof m))throw r;return Mv(t,Hd(r))}}function Mv({event:t},e){return{...Wc(ge),warning:`ari hook skipped ${t}: ${e}`}}async function W1(t){let e=Promise.withResolvers(),n=setTimeout(e.resolve,K1,B1);try{return await Promise.race([e.promise,t.then(Wc)])}finally{clearTimeout(n)}}function Wc(t){return{decision:t,expired:!1,warning:null}}async function J1(t,e){let{command:n,cwd:r,event:o,paths:s}=e,i=await t.at(r);if(o==="before-shell"&&n!==null)return Lv(t,n,r);if(o==="before-edit"&&s.length>0)return q1(t,e);if(i===null)return ge;return{kind:"ask",reason:`ari found no ${o==="before-edit"?"path":"command"} in the hook payload`}}async function q1(t,e){let n=[];for(let r of e.paths){let o=await Iv(t,jv(e.cwd,r));if(o!==null)n.push(o)}return n.length===0?ge:{kind:"deny",reason:n.join("; ")}}async function Y1(t,e,n){switch(t.event){case"before-edit":case"before-shell":return ge;case"after-tool":return Jc(e,X1(t,e)),ge;case"stop":{let r=await z1(e);if(r.kind==="allow"&&e.config.knowledge.sleepOnStop)await Q1(e.root);return r}case"pre-compact":{let r=await Z1(e);if(r!==null)n.push(r);return Jc(e,{detail:{},type:"compact"}),await Mr(e.root),ge}case"session-start":return eH(e,n)}}function X1(t,e){let n=Ht(e.root),r=t.paths.flatMap((o)=>cn(n,Ht(jv(t.cwd,o)))??[]);if(r.length>0)return{detail:{paths:r},type:"edit"};if(t.command!==null)return{detail:{command:t.command.slice(0,U1)},type:"shell"};return{detail:t.tool===null?{}:{tool:t.tool},type:"tool"}}async function z1(t){let{task:e}=t;if(e===null||e.record.status!=="active")return ge;let n=e.contract.id,r=await Ae(t.root,[Er]);if(e.record.evidence.at(-1)?.treeHash===r)return ge;let o=G1(t.state,H1),s=nc(o,V1,null);if(s?.task===n&&s.tree===r)return ge;return Rr(o,`${JSON.stringify({task:n,tree:r})}
187
+ `),Jc(t,{detail:{blocked:!0},type:"stop"}),{kind:"block",reason:`Task "${n}" has changes that no gate has passed yet. Run 'ari check', fix what it reports, then 'ari done'. If you are stuck, run 'ari block ${n} --reason <question>' for a human.`}}async function Z1(t){if(t.task===null)return null;return(await Fo(t.root,t.task.contract.id,"pre-compact")).warning}async function Q1(t){try{await JS(t)}catch(e){let n=e instanceof Error?e.message:String(e);throw new m(`the sleep pass at stop failed (${n})`,"Run 'ari sleep' to see the failure, or set knowledge.sleepOnStop to false")}}function tH(t,e){if(!t.config.hooks.brief)return ge;try{let n=wv(t);return e.push(...n.warnings),{kind:"context",text:n.text}}catch(n){let r=n instanceof Error?n.message:String(n);return e.push(`ari could not build the session brief (${r})`),ge}}async function eH(t,e){if(t.task===null)return tH(t,e);Jc(t,{detail:{},type:"session"});let{text:n}=await tr(t.root,{id:t.task.contract.id});return n.trim().length===0?ge:{kind:"context",text:n}}function Jc(t,e){if(t.task===null)return;$r(t.state,{...e,at:new Date().toISOString(),task:t.task.contract.id})}var Go="git",nH={amp:"Amp",opencode:"OpenCode"},rH=".git/hooks";function ng(){return[...Ie.map((t)=>t.name),Go]}function Pe(t){let e=Ie.find((r)=>r.name===t);if(e!==void 0)return e;if(t===Go)throw new v("git hooks run 'ari scope --staged' and 'ari verify' directly","Run 'ari hooks install --agent git'");let n=nH[t];if(n!==void 0)throw new m(`${n} hooks run only as in-process plugins, which ari does not ship`,"Rely on the AGENTS.md block from 'ari init', 'ari hooks install --agent git' and 'ari verify' in CI");throw new v(`Unknown agent "${t}"`,`Choose one of: ${ng().join(", ")}`)}function Gv(t){if(t!==Go)Pe(t)}async function Ho(t,e){if(e===Go)return ac(t);return qk(t,Pe(e),await P(t))}async function Hv(t,e){if(e===Go)return cc(t);return pc(t,Pe(e),await P(t))}async function Uv(t){return[...Ie.map((n)=>({agent:n.name,events:Bs(n),file:n.file,installed:un(t,n),label:n.label,support:n.support})),{agent:Go,events:[...Gk],file:rH,installed:await To(t),label:"git",support:"git"}]}async function Kv(t,e,n,r){let o=Pe(t),s=oH(o,e);try{let{decision:i,expired:a,warning:c}=await Fv(o.parse(s,sH(n),r));return{expired:a,stdout:Yd(o,s,i),warning:c}}catch(i){if(!Pn.has(s))throw i;let a=`ari could not check this ${s} event: ${i instanceof Error?i.message:String(i)}`;return{expired:!1,stdout:Yd(o,s,{kind:"deny",reason:a}),warning:a}}}function oH(t,e){if(!Ok(e))throw new v(`Unknown hook event "${e}"`,`Choose one of: ${Wd.join(", ")}`);if(Bs(t).includes(e))return e;throw new v(`${t.label} has no ari adapter for "${e}"`,`Its adapter handles: ${Bs(t).join(", ")}`)}function sH(t){if(t.trim().length===0)return{};let e=null;try{e=JSON.parse(t)}catch{}if(z(e))return e;throw new m("The hook payload on stdin is not a JSON object","Agents call 'ari hook' with a JSON object")}import{homedir as Bv}from"os";import{join as iH}from"path";var Mn=["project","user"],aH=".ari",cH="receipts",lH="~/";function rr(t){let e=t??"project",n=Mn.find((r)=>r===e);if(n!==void 0)return n;throw new v(`Unknown scope "${e}"`,`Choose one of: ${Mn.join(", ")}`)}async function xt(t,e){if(t==="user")return{base:Bv(),receipts:iH(Bv(),aH,cH),scope:t};let n=await Jn(e);return{base:n,receipts:await P(n),scope:t}}function oe(t,e){return t==="user"?`${lH}${e}`:e}function ui(t,e,n){let r=t.find((o)=>o.agent===e);if(r!==void 0)return r;throw new v(`ari has no ${n} integration for "${e}"`,`Choose one of: ${t.map((o)=>o.agent).join(", ")}`)}function rg(t,e,n){return[...new Set(e)].map((r)=>ui(t,r,n))}import{isDeepStrictEqual as hH}from"util";function qc(t){let{base:e,file:n,receipts:r}=t,o=W(e,n),s=t.install(o),i=Ao(r.directory,n,r.store),a=t.managed(o)?void 0:o,c=i?.installed===o?i.original:a,l=Ce(e,n,s),u=W(e,n)??"";return Co(r.directory,n,c===void 0?null:{installed:u,original:c},r.store),l}function uH(t,e,n){if(e===null||!t.managed(e))return Hs;if(n?.installed!==e){let r=t.remove(e);return r===null?Us:xo(r,!1)}return n.original===null?Us:xo(n.original,!0)}function Yc(t,e,n){let{base:r,file:o,receipts:s}=t,i=Ao(s.directory,o,s.store),a=dc(r,o,uH(t,e.read(r,o),i),e);if(n)Co(s.directory,o,null,s.store);return a}function Xc(t){return Yc(t,uc,!0).action}function mn(t){return t.managed(W(t.base,t.file))}import{isDeepStrictEqual as dH}from"util";var Uo="# ari:begin",di="# ari:end",pi=`\r
188
+ `,fn=`
189
+ `,pH=1,gH=/^\r?\n/,mH=/\r$/;function Wv(t){return(t??"").split(fn).some((e)=>sg(e,Uo))}function Jv(t,e){let n=t??"";og(e.file,n);let r=n.includes(pi)?pi:fn,o=[`${Uo} managed by 'ari mcp install'; 'ari mcp uninstall' removes it`,...e.lines,di].join(r),s=Yv(e.file,n);if(s===null&&Vv(og(e.file,n),e.table)!==void 0)throw new m(`${e.file} already defines [${e.table.join(".")}] outside ari's managed block`,`Remove that table from ${e.file}, or keep it and do not install ari's`);let i=s===null?fH(n,o,r):n.slice(0,s.start)+o+n.slice(s.end),a;try{a=og(e.file,i)}catch(c){throw new m(`ari cannot add [${e.table.join(".")}] to ${e.file} without breaking it`,`Add the table yourself:
190
+ ${e.lines.join(fn)}`,pH,{cause:c})}if(dH(Vv(a,e.table),e.value))return i;throw new m(`ari cannot add [${e.table.join(".")}] to ${e.file}: the file defines it in another way`,`Add the table yourself:
191
+ ${e.lines.join(fn)}`)}function qv(t,e){let n=Yv(t,e);if(n===null)return e;let r=e.slice(0,n.start),o=e.slice(n.end).replace(gH,""),i=(r.endsWith(`${pi}${pi}`)?r.slice(0,-pi.length):r.endsWith(`${fn}${fn}`)?r.slice(0,-fn.length):r)+o;return i.trim().length===0?null:i}function fH(t,e,n){if(t.length===0)return`${e}${n}`;return`${t.endsWith(fn)?t:`${t}${n}`}${n}${e}${n}`}function Yv(t,e){let n=[],r=0;for(let i of e.split(fn)){let a=r+i.replace(mH,"").length;if(sg(i,Uo))n.push({end:a,kind:Uo,start:r});else if(sg(i,di))n.push({end:a,kind:di,start:r});r+=i.length+fn.length}let[o,s]=n;if(o===void 0)return null;if(n.length!==2||o.kind!==Uo||s?.kind!==di)throw new m(`${t} has a damaged ari block: expect one '${Uo}' line followed by one '${di}' line`,`Remove the ari marker lines and the lines between them from ${t}, then run the command again`);return{end:s.end,start:o.start}}function sg(t,e){let n=t.trim();return n===e||n.startsWith(`${e} `)}function og(t,e){try{return Bun.TOML.parse(e)}catch(n){let r=n instanceof Error?n.message:String(n);throw new m(`${t} is not valid TOML (${r})`,`Fix ${t}, then run the command again`)}}function Vv(t,e){return e.reduce((n,r)=>typeof n==="object"&&n!==null?n[r]:void 0,t)}var hn="ari",ig="ari",Zc=["mcp","serve"],gi="mcpServers",yH="mcp.json",Xv=900,kH=1000,wH=2,zc={command:ig,args:Zc},se=[{agent:"claude",entry:zc,format:"json",label:"Claude Code",project:".mcp.json",user:null,userHint:`Claude Code keeps user-scope servers in its own state file; run 'claude mcp add --scope user ${hn} -- ${ig} ${Zc.join(" ")}'`},{agent:"codex",entry:{...zc,tool_timeout_sec:Xv},format:"toml",label:"Codex CLI",project:".codex/config.toml",user:".codex/config.toml",userHint:null},{agent:"gemini",entry:{...zc,timeout:Xv*kH},format:"json",label:"Gemini CLI",project:".gemini/settings.json",user:".gemini/settings.json",userHint:null},{agent:"cursor",entry:{type:"stdio",...zc},format:"json",label:"Cursor",project:".cursor/mcp.json",user:".cursor/mcp.json",userHint:null}];function me(t){return ui(se,t,"MCP")}function Ne(t,e){return tl(t,e)}function Ko(t,e){let n=tl(t,e);return{...Qv(t,e,n.file),action:qc(n)}}function Qc(t,e){let n=tl(t,e);return{...Qv(t,e,n.file),action:Xc(n)}}function Zv(t,e){return se.map((n)=>({agent:n.agent,files:[t,e].flatMap((r)=>{let o=n[r.scope];if(o===null)return[];let s=mn(tl(n,r));return[{file:oe(r.scope,o),installed:s,scope:r.scope}]}),label:n.label}))}function Qv(t,e,n){return{agent:t.agent,file:oe(e.scope,n),scope:e.scope,server:hn}}function tl(t,e){let n=t[e.scope];if(n===null)throw new m(`ari does not write ${t.label}'s ${e.scope}-scope MCP configuration`,t.userHint??"");let r={directory:e.receipts,store:yH},o={base:e.base,file:n,receipts:r};return t.format==="toml"?{...o,...SH(t,n)}:{...o,...vH(t,n)}}function SH(t,e){let n={file:e,lines:[`[mcp_servers.${hn}]`,...bH(t.entry)],table:["mcp_servers",hn],value:t.entry};return{install:(r)=>Jv(r,n),managed:Wv,remove:(r)=>qv(e,r)}}function vH(t,e){let n=(o)=>{let s=o[gi]??{};if(z(s))return s;throw new m(`${e} has a "${gi}" value that is not an object`,`Fix ${e}`)},r=(o,s)=>o===null?`${JSON.stringify(s,null,wH)}
192
+ `:Xa(o,s);return{install:(o)=>{let s=o===null?{}:re(e,o),i=n(s),a=i[hn];if(a!==void 0&&!zv(a))throw new m(`${e} already has an MCP server named "${hn}" that ari did not write`,`Rename or remove mcpServers.${hn} in ${e}, then run the command again`);let c={...z(a)?a:{},...t.entry};return r(o,{...s,[gi]:{...i,[hn]:c}})},managed:(o)=>o!==null&&zv(n(re(e,o))[hn]),remove:(o)=>{let{[gi]:s,...i}=re(e,o),{[hn]:a,...c}=n(re(e,o));return r(o,Object.keys(c).length===0?i:{...i,[gi]:c})}}}function bH(t){let{args:e,command:n,...r}=t;return Object.entries({command:n,args:e,...r}).map(([o,s])=>`${o} = ${tb(s)}`)}function tb(t){if(Array.isArray(t))return`[${t.map(tb).join(", ")}]`;return typeof t==="number"?String(t):JSON.stringify(t)}function zv(t){if(!z(t)||t.command!==ig||!Array.isArray(t.args))return!1;return hH(t.args.slice(0,Zc.length),Zc)}import{existsSync as $H,readdirSync as TH,rmdirSync as xH}from"fs";import{dirname as ub,join as db}from"path";var ag="```",EH=["`ari approve`, `ari amend`, `ari resolve` and `ari trust` are for people. Never run them; ask instead.","`ari snapshot restore` is a person's decision when it would replace an approved design: an approval does not survive a changed design."];function yn(t=[]){return["## What only people do","",...[...EH,...t].map((e)=>`- ${e}`)].join(`
193
+ `)}function De(...t){return t.map((e)=>typeof e==="string"?e:e.join(`
194
+ `)).join(`
195
+
196
+ `)}var eb={body:De(["# Ariadne","",'This repository tracks work as Ariadne tasks. A task\'s contract (`.ari/tasks/<id>.md`) says what "done" means, and `ari` runs its checks. Never call a task finished on your own word: only `ari done` finishes a stage.'],["## The loop","","1. Run `ari next` and follow the one action it prints.","2. Change only files inside the task's `scope`. Locked files stay byte-identical.","3. Run `ari check` to evaluate the stage's gates. It records nothing.","4. Run `ari done`. It records the evidence and advances, or prints every failing gate and exits 1.","","A failed `ari done` spends an attempt (3 by default), and a spent budget blocks the task for a person, so run `ari check` first. The MCP tools `ari_next`, `ari_check` and `ari_done` return the same JSON as the commands.","","Also: `ariadne-design`, `ariadne-contract`, `ariadne-implement`, `ariadne-review`, `ariadne-memory`."],["## What the gates mean","","| Gate | Passes when |","| --- | --- |","| `criteria` | each criterion names an existing check |","| `checks` | each selected check exits as expected |","| `invariants` | every invariant exits 0 |","| `scope` | every changed file is in scope |","| `locked` | locked files are unchanged |","| `tests-unchanged` | test files in scope are unchanged in the stage |","| `regression` | a regression check fails on the base commit, passes now |","| `artifact` | the file has enough bytes; `sections`: each listed `##` section has a body; `traceable`: its `AC-n` ids are the contract's |","| `approval` | a person approved, and nothing changed since |","| `review` | the reviewer passed the change |","| `command` | the pack's command exits 0 |","","`contractChanged` or `gatesChanged` in `ari check` means the frozen contract or gates differ and `ari done` refuses: ask a person to amend."],["## What only people do","","- `ari approve`, `ari amend`, `ari resolve` and `ari trust` are for people: ask instead. So is `ari snapshot restore` over an approved design.","- On `ConfigNotTrusted`, ask a person to run `ari trust`; never set `ARI_TRUST_CONFIG`.",'- Stuck, or the contract is wrong: `ari block <id> --reason "<question>"`, then stop.',"- Never edit `.ari/config.json`, `.ari/tasks/*.json` or `.ari/knowledge/**`, and never use `git commit --no-verify`."]),description:"Work through this repository's Ariadne (ari) tasks, whose contracts and gates the ari CLI keeps. Use it whenever the repository has an .ari/ directory, before changing code there, and to pick up, check or finish a task.",name:"ariadne"};var nb={body:De(["# Write the contract","",'The contract (`.ari/tasks/<id>.md`) is what `ari` judges the work by, so write it with the person. Take the criteria from their request; never invent one. `ari new "<title>" --pack <pack> --scope "<globs>"` creates the draft. Choose the pack by the work:'],["| Work | Pack |","| --- | --- |","| a new feature | `feature` |","| a defect | `bugfix` |","| a change that keeps behaviour | `refactor` |","| unknown territory, findings first | `spike` |","| a quick, known change | `basic` |","| tests first | `tdd` |","| a specification to approve first | `spec-driven` |","| a design and a review without the structured design | `sdlc` |"],["Then complete the front matter:","",`${ag}markdown`,"---","title: Add profile inheritance","pack: feature","scope: [src/profiles/**]","lock: [src/profiles/inheritance.test.ts]","criteria:"," - id: AC-1"," text: A child profile's values override its parent's"," checks: [inheritance]","checks:"," inheritance:"," run: bun test src/profiles/inheritance.test.ts"," expect: pass","invariants: [bun run lint]","---",ag],["- Criterion ids are `AC-1`, `AC-2` and so on. The design's Acceptance criteria must list exactly these ids.","- Bind every criterion to at least one check, a shell command run from the repository root. Write it so that it fails before the change and passes after; `expect: regression` makes ari prove the failure on the base commit.","- `scope` lists globs: write `src/**`, never `src/`. `lock` keeps the files that define the work, such as tests, unchanged from the start."],["Run `ari ready <id>`; it lists every problem in the contract. `ari start <id>` then needs a clean working tree outside `.ari/`. After the start a changed contract needs a person to run `ari amend`."],yn()),description:"Use when a request has to become an ari task contract. Covers choosing the pack, writing scope, lock, criteria and checks, marking the task ready and starting it, and fixing a draft that ari ready rejects.",name:"ariadne-contract"};var rb={body:De(["# Design a feature","","Use this when a feature needs a design, or when `ari next` says the task is in its design stage. The design is `.ari/designs/<id>.md`. `ari check` reads its structure, never its meaning, so the meaning is your job."],["## Steps","","1. Search before you design: `ari knowledge search <query>`. Note the id of every entry that matters.",'2. With no task yet, run `ari new "<title>" --pack feature`, write the contract with the person (`ariadne-contract`), then `ari ready <id>` and `ari start <id>`. The contract comes first because the design must trace to its criteria `AC-1`, `AC-2` and so on.',"3. Fill the sections of the design in order. Problem. Context: one `- <knowledge id>: why it matters` line for each entry you consulted. Options: at least two, each with its cost. Decision: the option, and why it beats the others. Acceptance criteria: one `- AC-n: text` line for each criterion of the contract, no more and no fewer. Scope. Risks and open questions (`None` if there are none). Replace every placeholder.","4. When a choice is the person's (a trade-off, a missing requirement, a risk to accept), ask one question at a time and wait. Never invent requirements.","5. Run `ari check` until the artifact gate passes. It lists every empty or missing section and every criterion id that differs.",'6. Run `ari snapshot --reason "design ready"`, then stop and ask the person to run `ari approve <id>`. Editing the design after approval voids it.','7. After approval, run `ari done`, and record the decision: `ari note --global --kind decision "<what was decided and why>"`.'],["A criterion the design needs but the contract lacks is a change to the contract: ask a person to run `ari amend`. When ari's MCP server is connected, `ari_check`, `ari_snapshot`, `ari_note` and `ari_done` do the same and return the same documents."],yn()),description:"Use when asked to design, plan or scope a feature, or when an ari task is in a design stage (the feature or sdlc pack). Fills .ari/designs/<id>.md section by section until ari check passes, then asks a person to approve it.",name:"ariadne-design"};var ob={body:De(["# Implement the task","","Run `ari next` and obey the one action it prints; `ari show <id>` prints the stage and its instruction. Change only files inside the contract's `scope`, and never a locked one."],["| Pack and stage | What to do |","| --- | --- |","| `basic` implement | make the checks of every criterion pass |","| `tdd` red | write failing tests for each criterion, and do not implement |","| `tdd` green | the smallest change that passes; do not edit the tests |","| `tdd` refactor | improve the code, checks green, tests unchanged |","| `bugfix` reproduce | write a regression check that fails because of the bug; do not fix it |","| `bugfix` fix | fix it: the check passes here and still fails on the base commit |","| `refactor` refactor | restructure without changing behaviour; tests unchanged |","| `feature` or `sdlc` implement | implement the approved design until every check passes |"],['1. Work in small steps. Before you change the plan or the design, run `ari snapshot --reason "<why>"`; it saves the plan and the context pack, not code.',"2. Run `ari check` after each step. It runs the stage's gates and records nothing; fix what it reports.","3. Run `ari done` only when `ari check` passes. A failed `ari done` spends one of the task's attempts (3 by default), and the task blocks when they run out.",'4. When you are stuck, or the contract looks wrong, run `ari block <id> --reason "<question>"` and stop. Do not widen the scope, edit a locked file or weaken a check to pass a gate.','5. A surprise that cost you time is worth a line: `ari note "<text>"`, or `ari note --global --kind gotcha "<text>"` for the project.',"6. The last stage of `feature` and `sdlc` is review: load `ariadne-review`."],yn()),description:"Use when an ari task is in an implement stage, or runs the basic, tdd, bugfix or refactor pack. Covers following ari next, staying in scope, running ari check before ari done, and blocking the task instead of weakening a gate.",name:"ariadne-implement"};var sb={body:De(["# Memory","","Memory is files that ari keeps: task notes, the journal, `.ari/knowledge/*.md` and the ledgers under the git directory. Use the commands; never edit `.ari/knowledge/**`, `.ari/tasks/*.json` or a ledger."],["## Read","","- Before you design or decide: `ari knowledge search <query>`, and `ari knowledge show <id>` for one entry.","- After your context was reset or compacted: `ari context` prints the active task's contract, notes and relevant knowledge within a token budget (`--budget <tokens>` changes it). `ari snapshot list` then `ari snapshot show <id>` print the plan and context pack as last saved."],["## Write","",'- `ari note "<text>"` adds a note to the active task: progress, a finding, a dead end.','- `ari note --global --kind <kind> "<text>"` adds project knowledge that outlives the task. The kinds are `fact` (how things are), `decision` (what was chosen, and why), `constraint` (a rule that must hold), `pattern` (how it is done here) and `gotcha` (a trap that cost time). One idea per entry, in plain words. `--scope "<globs>"` ties it to files.',"- Never write a secret, a token or a credential into a note."],["## Housekeeping","","`ari sleep --if-due` consolidates memory when it is due and does nothing otherwise; every pass is logged and `ari sleep --undo` reverses the last one. `ari snapshot` saves the plan before a risky change, and identical state writes nothing."],yn()),description:"Use when you learn something worth keeping, before you design or decide, and after your context was reset or compacted. Covers ari note and its kinds, ari knowledge search, ari context, ari snapshot show and ari sleep.",name:"ariadne-memory"};var ib={body:De(["# Review the change","","`ari review` has the configured review agent judge the change in a temporary copy and prints its verdict and findings. It changes and records nothing. `ari done` in a review stage runs the review gate: it passes when the review command exits 0 or the review agent answers `pass`, and with neither configured a person approves."],["1. Run `ari check` first; review a change whose gates already pass.","2. Run `ari review`. Exit 1 means it failed, and any doubt fails it (an unreadable answer, a timeout, a changed file).","3. Fix every `critical` and `major` finding, which block, then run `ari review` again. Fix a `minor` one when it is cheap, otherwise say why you left it in `ari note`. An `info` finding needs no action.",'4. Never edit the contract or the review configuration to get a pass. When the review is wrong, say so with `ari block <id> --reason "<question>"`.',"5. When it passes, run `ari done`."],["## Argus candidates","","With `review.argus` configured, or `ari review --argus`, the review prompt lists candidates from a decision model. They are leads, never findings: check each against the code before you act. With `ari review --argus-verdicts` (or `review.argus.verdicts`) a reviewer may answer a lead in an optional `candidates` array of `{ id, verdict, rationale }`, where verdict is `confirmed`, `false_positive`, `deferred` or `uncertain`. Answer only a lead you checked against the code and reached a verdict on. A guess is worse than silence, because the answer is stored."],yn(["With no review command or agent configured, `ari approve` on the review stage is the person's review."])),description:"Use when an ari task reaches its review stage, when asked to review a change, or when ari review or the review gate reports findings. Covers ari review, what each severity means, the review gate and the optional Argus candidates and answers.",name:"ariadne-review"};var ab="SKILL.md",el="<!-- ari:managed by 'ari skills install'; 'ari skills uninstall' removes it -->";function cb({body:t,description:e,name:n}){let r=["---",`name: ${n}`,`description: ${e}`,"---","<!-- ari:managed by 'ari skills install'; 'ari skills uninstall' removes it -->",""].join(`
197
+ `);return{description:e,name:n,text:`${r}
198
+ ${t}
199
+ `}}var ot=[eb,rb,nb,ob,ib,sb].map(cb);function lb(t){if(t.length===0)return ot;let e=ot.map((r)=>r.name),n=t.find((r)=>!e.includes(r));if(n!==void 0)throw new v(`ari has no skill named "${n}"`,`Choose one of: ${e.join(", ")}`);return ot.filter((r)=>t.includes(r.name))}var AH="skills.json",fe=[{agent:"claude",label:"Claude Code",project:".claude/skills",user:".claude/skills"},{agent:"codex",label:"Codex CLI",project:".agents/skills",user:".agents/skills"},{agent:"gemini",label:"Gemini CLI",project:".gemini/skills",user:".gemini/skills"},{agent:"cursor",label:"Cursor",project:".cursor/skills",user:".cursor/skills"}];function Jt(t){return ui(fe,t,"skill")}function mi(t,e,n){return db(t[e],n,ab)}function ie(t,e,n){return ug(t,e,n)}function pb(t,e){for(let n of fe){let r=ot.find((o)=>mi(n,t.scope,o.name)===e);if(r!==void 0)return{skill:r,target:n}}return null}function Bo(t,e,n=ot){return n.map((r)=>{let o=ug(t,e,r),s=W(o.base,o.file);if(s!==null&&!o.managed(s))return{...cg(t,e,r),action:"refused",reason:mb(e,o.file)};return{...cg(t,e,r),action:qc(o)}})}function nl(t,e,n=ot){return n.map((r)=>{let o=ug(t,e,r),s=Xc(o);if(s==="removed")fb(e.base,ub(o.file));return{...cg(t,e,r),action:s}})}function rl(t,e){let n=t.filter((s)=>s.action==="refused"),[r]=n;if(r===void 0)return;let o=n.length===1?r.reason??"":`${n.length} skills exist and ari did not write them: ${n.map((s)=>s.file).join(", ")}`;throw new m(o,ol(n.length,e))}function ol(t,e){return`Move or remove ${t===1?"that skill":"those skills"}, then run 'ari skills install --agent ${e}' again`}function lg(t){if(t.every((e)=>e==="unchanged"))return"unchanged";if(t.every((e)=>e==="created"))return"created";if(t.every((e)=>e==="removed"))return"removed";return"updated"}function gb(t){let e=t.filter((r)=>r.action!=="unchanged");if(e.length===0)return{action:"unchanged",restored:null};let n=e.map((r)=>r.restored);return{action:e.every((r)=>r.action==="removed")?"removed":"updated",restored:n.find((r)=>r==="original")??n.find((r)=>r!==null)??null}}function cg(t,e,n){let r=oe(e.scope,mi(t,e.scope,n.name));return{agent:t.agent,file:r,scope:e.scope,skill:n.name}}function mb(t,e){return`${oe(t.scope,e)} exists and ari did not write it`}function ug(t,e,n){let r=mi(t,e.scope,n.name),o=(s)=>(s??"").includes(el);return{base:e.base,file:r,install:(s)=>{if(s===null||o(s))return n.text;throw new m(mb(e,r),ol(1,t.agent))},managed:o,receipts:{directory:e.receipts,store:AH},remove:()=>null}}function fb(t,e){let n=db(t,e);if(e==="."||!$H(n)||TH(n).length>0)return;xH(n),fb(t,ub(e))}var jt="AGENTS.md",dg="<!-- ari:begin -->",sl="<!-- ari:end -->",IH=/^ {0,3}(<!-- ari:(?:begin|end) -->)\s*$/,OH=/^ {0,3}(`{3,}(?=[^`]*$)|~{3,})/,_H=/^ {0,3}(`{3,}|~{3,})[ \t]*\r?$/,pg=`${J}/config.json`,PH="git",hb=`\r
200
+ `,gg=`
201
+ `,NH=[dg,"## Ariadne","","This repository tracks work as Ariadne (`ari`) tasks. Work in this loop:","","1. Run `ari next` and follow the one action it prints.","2. Change only files inside the active task's `scope`.","3. Run `ari check` to evaluate the current stage's gates.","4. Run `ari done`; it records evidence and advances. Fix what it reports and run it again.","",'Record learnings with `ari note "<text>"` and reload context with `ari context`. If you are stuck, ask a human with `ari block <id> --reason "<question>"`.',"When the task's pack starts with a design stage (the `feature` and `sdlc` packs), the design in `.ari/designs/<id>.md` comes first and a person approves it: run `ari snapshot` before you ask, and never run `ari approve` yourself.","Skills for designing, writing contracts, implementing, reviewing and memory (`ariadne`, `ariadne-design`, `ariadne-contract`, `ariadne-implement`, `ariadne-review`, `ariadne-memory`) load on demand from `.claude/skills`, `.agents/skills`, `.gemini/skills` or `.cursor/skills`; `ari skills list` shows them.","Edit task contracts (`.ari/tasks/*.md`) and designs, never other files under `.ari/`: ari writes them. `ari --help --json` describes every command.",sl];function mg(t){let e=fi(W(t,jt));return{action:Ce(t,jt,e),path:jt}}function fg(t,e){return Ce(t,pg,hg(W(t,pg),e))}function hg(t,e){let n=t??qy();if(e===null)return n;let r=re(pg,n);if(vr(r).pack===e)return n;return zn(n,{...r,pack:e})}async function yb(t,e={}){let n=[...e.agents??[],...e.gitHooks===!0?[PH]:[]],r=[...new Set(n)];for(let f of r)Gv(f);let o=rg(se,e.mcp??[],"MCP"),s=rg(fe,e.skills??[],"skill"),i=CH(RH(t,J))?Gt(t):[],a=e.pack===void 0?null:Ue(e.pack,i).name,c=fg(t,a),l=mg(t),u=[];for(let f of r)u.push(await Ho(t,f));let d={base:t,receipts:await P(t),scope:"project"},p=o.map((f)=>Ko(f,d)),g=s.flatMap((f)=>{let y=Bo(f,d);return rl(y,f.agent),y});return{agentsMd:l,config:c,hooks:u,mcp:p,pack:M(t).pack,root:t,skills:g}}function fi(t){let e=t??"",n=e.includes(hb)?hb:gg,r=NH.join(n),o=DH(e),[s,i]=o;if(s===void 0){let a=e.length===0?"":e.endsWith(n)?n:`${n}${n}`;return`${e}${a}${r}${n}`}if(o.length!==2||s.marker!==dg||i?.marker!==sl)throw new m(`${jt} has a damaged ari block: expect one ${dg} followed by one ${sl}`,`Remove the ari markers and the lines between them from ${jt}, then run 'ari init' again`);return`${e.slice(0,s.start)}${r}${e.slice(i.start+sl.length)}`}function DH(t){let e=[],n=null,r=0;for(let o of t.split(gg)){let s=OH.exec(o)?.[1];if(n===null&&s!==void 0)n={mark:s,markers:e.length};else if(n!==null&&LH(o,n.mark))e.length=n.markers,n=null;let i=IH.exec(o)?.[1];if(i!==void 0)e.push({marker:i,start:r+o.indexOf(i)});r+=o.length+gg.length}return e}function LH(t,e){return _H.exec(t)?.[1]?.startsWith(e)===!0}function Hr(t){return t.kind==="config"?"ari init":Sb("install",t)}function wb(t){return Sb("uninstall",t)}function Sb(t,{agent:e,kind:n,scope:r}){switch(n){case"hooks":return e===null?null:`ari hooks ${t} --agent ${e}`;case"git":return`ari hooks ${t} --agent git`;case"mcp":return e===null?null:`ari mcp ${t} --agent ${e}${kb(r)}`;case"skill":return e===null?null:`ari skills ${t} --agent ${e}${kb(r)}`;case"config":case"routing":return null}}function kb(t){return t==="user"?" --scope user":""}var bb=5000,MH=new Set(["created","updated","unchanged"]),jH="2025-11-25",Eb=2,FH="ari_next",GH=new Set(["hooks","mcp","skill","git"]),HH="<!-- ari:begin -->",$b=".ari/config.json",UH=".git/hooks",Tb="Install ari globally (bun add -g @r5n/ariadne), then run 'ari install' again";async function yg(t,e,n={}){let r=e.filter((a)=>MH.has(a.action)),o=await Promise.all(KH(r).map((a)=>BH(t,a)));if(!r.some((a)=>GH.has(a.kind)))return o;let s=n.ari===void 0?Bun.which("ari"):n.ari,i=s!==null&&r.some((a)=>a.kind==="mcp")?[await wg(s,t,n.timeoutMs??bb)]:[];return[kg(s),...i,...o]}function kg(t){return t===null?Vo("ari on PATH","ari is not on PATH, so agents cannot start it",Tb):Sg("ari on PATH",t)}function wg(t,e,n=bb){return qH(t,e,n)}function KH(t){let e=new Set;return t.filter((n)=>{let r=n.kind==="git"?"git":n.kind==="routing"?"config:.ari/config.json":`${n.kind}:${n.file}`;if(e.has(r))return!1;return e.add(r),!0})}async function BH(t,e){let n=il(e),r=e.kind==="routing"?$b:e.kind==="git"?UH:e.file??"";try{let o=await WH(t,e);return o===null?Sg(n,JH(e,r)):Vo(n,`${r}: ${o}`,VH(e))}catch(o){if(!(o instanceof Error))throw o;let s=o instanceof m&&o.hint!==void 0?o.hint:`Fix ${r}`;return Vo(n,o.message,s)}}function VH(t){let e=Hr(t);return e===null?"Run 'ari install' again to repair it":`Run '${e}' to repair it`}function il(t){switch(t.kind){case"hooks":return`${t.agent} hooks`;case"mcp":return`${t.agent} MCP server`;case"skill":return`${t.agent} skill`;case"git":return"git hooks";case"config":return t.file===jt?"AGENTS.md block":"configuration";case"routing":return"configuration"}}async function WH(t,e){let n=e.agent??"";switch(e.kind){case"hooks":return un(t,Pe(n))?null:"has no ari hook entries";case"mcp":{let r=Ne(me(n),await vb(t,e.scope));return r.managed(W(r.base,r.file))?null:"does not register the ari server"}case"skill":{let[r,o]=[Jt(n),await vb(t,e.scope)],s=ot.filter((i)=>{let a=ie(r,o,i),c=W(a.base,a.file)??"";return!(c.startsWith(`---
202
+ name: ${i.name}
203
+ `)&&c.includes(el))}).map((i)=>i.name);if(s.length===0)return null;return s.length===1?`${s.join("")} is not ari's skill`:`${s.join(", ")} are not ari's skills`}case"git":return await To(t)?null:"pre-commit and pre-push do not both run ari";case"config":if(e.file===jt)return(W(t,jt)??"").includes(HH)?null:"has no ari block";return M(t),null;case"routing":return M(t),null}}function JH(t,e){switch(t.kind){case"hooks":case"mcp":return e;case"skill":return`${e} (${ot.length} skills)`;case"git":return"pre-commit and pre-push run ari";case"config":case"routing":return t.file===jt?"AGENTS.md has the ari block":`${$b} is valid`}}async function vb(t,e){return xt(e,t)}async function qH(t,e,n){let o=Bun.spawn([t,"mcp","serve"],{cwd:e,detached:!0,env:{...process.env,...Fe},stderr:"pipe",stdin:"pipe",stdout:"pipe"}),s=()=>Ge(o.pid,"SIGKILL"),i=Qt(s),a=setTimeout(s,n);try{o.stdin.write(YH()),await o.stdin.flush();let c=await XH(o.stdout);return await o.stdin.end(),ZH("ari mcp serve",c,n,await new Response(o.stderr).text())}catch(c){return Vo("ari mcp serve",`'ari mcp serve' failed: ${c instanceof Error?c.message:String(c)}`,Tb)}finally{clearTimeout(a),s(),i()}}function YH(){return[{id:1,jsonrpc:"2.0",method:"initialize",params:{capabilities:{},clientInfo:{name:"ari-install",version:"1"},protocolVersion:jH}},{jsonrpc:"2.0",method:"notifications/initialized"},{id:Eb,jsonrpc:"2.0",method:"tools/list"}].map((e)=>`${JSON.stringify(e)}
204
+ `).join("")}async function XH(t){let e=new TextDecoder,n="";for await(let r of t){n+=e.decode(r,{stream:!0});let o=n.split(`
205
+ `);n=o.pop()??"";for(let s of o){let i=zH(s);if(i!==null&&i.id===Eb)return i}}return null}function zH(t){try{let e=JSON.parse(t);return z(e)?e:null}catch{return null}}function ZH(t,e,n,r){if(e===null){let s=r.trim().split(`
206
+ `).at(-1)??"",i=s.length>0?`stopped without answering: ${s}`:`did not answer within ${n} ms`;return Vo(t,i,"Run 'ari mcp serve' in this repository to see why")}let o=QH(e);if(!o.includes(FH))return Vo(t,"answered tools/list without ari's tools","Make sure 'ari' on PATH is @r5n/ariadne");return Sg(t,`answers, with ${o.length} tools`)}function QH(t){let e=t.result;if(!z(e)||!Array.isArray(e.tools))return[];return e.tools.flatMap((n)=>z(n)&&typeof n.name==="string"?[n.name]:[])}function Sg(t,e){return{detail:e,hint:null,name:t,ok:!0}}function Vo(t,e,n){return{detail:e,hint:n,name:t,ok:!1}}import{existsSync as Lb}from"fs";import{join as Mb}from"path";function vg(t,e,n=ot){return n.map((r)=>{let o=ie(t,e,r),s=mn(o);return{current:s&&W(o.base,o.file)===r.text,file:oe(e.scope,mi(t,e.scope,r.name)),installed:s,scope:e.scope,skill:r.name}})}function xb(t,e){return fe.map((n)=>({agent:n.agent,files:[t,e].flatMap((r)=>vg(n,r)),label:n.label}))}var at=["claude","codex","gemini","cursor","copilot"],or=["hooks","mcp","skill"],Ye={hooks:"hooks",mcp:"MCP server",skill:"skill"},$g="config",sr="agents-md",qe="git",cl="claude mcp add --scope user ari -- ari mcp serve",bg=".ari/config.json",tU="AGENTS.md",Ab=".claude/settings.json",Cb=["cursor","copilot"],Rb={cursor:["claude","codex"],gemini:["codex"]},eU=["claude","codex","gemini"],nU=":";function Ot(t,e){return`${t}${nU}${e}`}function ll(t){return at.includes(t)}function Ft(t,e){let n=t.agents.find((r)=>r.agent===e);if(n!==void 0)return n;throw Error(`No detected state for agent ${e}`)}function ul(t){let e=new Set(t.targets.filter(Ag).map((n)=>n.agent));return at.filter((n)=>Ft(t,n).path!==null||e.has(n))}function Ur(t,e,n,r){let o=t.initialised&&!r?[Pb(t,sr,"project")]:[],s=or.flatMap((i)=>at.filter((a)=>e.includes(a)).map((a)=>dU(t,a,i,n)));return[...o,...s,pU(t)]}function rU(t,e,n,r){let s=Ur(t,e,n,r).filter((a)=>a.skip===null&&a.problem===null).map((a)=>a.id),i=new Set(Wo(t,s).map(({id:a})=>a));return s.filter((a)=>!i.has(a))}function Ib(t,e,n,r){return Ur(t,e,n,r).map((o)=>o.id)}function Ob(t,e,n,r){let o=Ur(t,e,n,r),s=new Set(o.filter((i)=>i.status!=="current"&&i.elsewhere===null).map((i)=>i.id));return rU(t,e,n,r).filter((i)=>s.has(i))}function _b(t,e){let n=t.configured.map((s)=>({...s,configured:!0})),r=new Set(n.map((s)=>s.name)),o=e.filter((s)=>Ft(t,s).preset&&!r.has(s)).map((s)=>({configured:!1,model:null,name:s,roles:[]}));return[...n,...o]}function Tg(t,e){if(e.pack!==null&&!t.packs.some((d)=>d.name===e.pack))throw new v(`Unknown pack "${e.pack}"`,`Choose one of: ${t.packs.map((d)=>d.name).join(", ")}`);if(e.routing!==null)uU(t,e.routing,e.init);let n=e.init,r=Ur(t,e.agents,e.scope,n),o=new Set(e.targets),s=e.recommended?Wo(t,e.targets):[],i=new Map(s.map(({id:d,reason:p})=>[d,p])),a=n?[al($g,null,"config","project",bg,null),al(sr,null,"config","project",tU,null)]:[],c=new Set(r.filter((d)=>o.has(d.id)).map((d)=>d.kind)),l=r.flatMap((d)=>{if(!(o.has(d.id)||d.skip!==null&&c.has(d.kind)))return[];let g=e.recommended&&d.problem!==null?gU(d.problem):null,f=d.skip??i.get(d.id)??g;return[al(d.id,d.agent,d.kind,d.scope,d.file,f)]}),u=e.routing===null?[]:[al("routing",null,"routing","project",bg,null)];return{init:n,pack:e.pack,routing:e.routing,scope:e.scope,targets:[...a,...l,...u],warnings:dl(t,{...e,targets:e.targets.filter((d)=>!i.has(d))})}}function dl(t,e){let n=Ur(t,e.agents,e.scope,e.init),r=new Set(e.targets),o=new Set(n.filter((c)=>c.skip===null).map((c)=>c.id)),s=Nb(t),i=new Set([...[...r].filter((c)=>o.has(c)),...s]),a={answers:e,effective:i,installed:s,requested:r,state:t};return[...oU(a),...sU(a),...iU(a),...aU(a),...cU(a),...lU(a,n)]}function oU({answers:t,state:e}){return t.agents.flatMap((n)=>{let r=Ft(e,n);if(r.path!==null)return[];return[Jo("agent-not-found",`${r.label} was not found on PATH (looked for ${r.binaries.join(", ")})`,`ari writes its files anyway; they take effect once ${r.label} is installed`)]})}function sU({answers:t,requested:e}){if(t.scope!=="user"||!e.has(Ot("mcp","claude")))return[];return[Jo("claude-user-mcp","Claude Code keeps user-scope MCP servers in its own state file, which ari does not edit",`Run: ${cl}`)]}function iU({requested:t,state:e}){let n=e.hookManager;if(n===null||!t.has(qe))return[];return[Jo("git-hooks-managed",Db(n.name),n.hint)]}function aU({effective:t,installed:e,requested:n,state:r}){let o=Ot("hooks","claude");if(!t.has(o))return[];return Cb.flatMap((s)=>{let i=Ot("hooks",s);if(!t.has(i)||!(n.has(i)||n.has(o)))return[];let a=Ft(r,s).label,c=n.has(i)&&!e.has(i)?[i]:[],l=c.length>0?`Leave out ${a}'s hooks; it runs Claude Code's`:`Run 'ari hooks uninstall --agent ${s}', or leave out Claude Code's hooks`,u=`${a} also runs Claude Code's hooks from ${Ab}, so every ari hook would run twice there`;return[Jo("hooks-twice",u,l,c)]})}function cU({answers:t,effective:e,installed:n,requested:r,state:o}){return at.flatMap((s)=>{let i=Rb[s];if(i===void 0||!t.agents.includes(s))return[];let a=[s,...i].filter((y)=>e.has(Ot("skill",y)));if(a.length<2||!a.some((y)=>r.has(Ot("skill",y))))return[];let c=Ft(o,s).label,l=Ot("skill",s),u=r.has(l)&&!n.has(l)&&a.includes(s)?[l]:[],d=a.map((y)=>Eg(o,y)),p=a.filter((y)=>y!==s).map((y)=>Eg(o,y)),g=u.length>0?`Leave out ${c}'s own skill; it reads the copy in ${p.join(" and ")}`:a.includes(s)?`Run 'ari skills uninstall --agent ${s}'; ${c} reads the copy in ${p.join(" and ")}`:`The copies are identical; keep both while ${a.map((y)=>Ft(o,y).label).join(" and ")} need them`,f=`${c} reads ${d.join(" and ")}, so it would load the ariadne skills ${mU(a.length)}`;return[Jo("skill-twice",f,g,u)]})}function lU({requested:t},e){return e.flatMap((n)=>{if(n.problem===null||n.skip!==null||!t.has(n.id))return[];return[Jo("target-blocked",n.problem.message,n.problem.hint)]})}function Wo(t,e){let n=new Set(e),r=Nb(t),o=new Set([...n,...r]),s=o.has(Ot("hooks","claude")),i=Cb.flatMap((c)=>{let l=Ot("hooks",c);if(!s||!n.has(l)||r.has(l))return[];let u=`${Ft(t,c).label} runs Claude Code's hooks from ${Ab}`;return[{id:l,reason:u}]}),a=at.flatMap((c)=>{let l=Ot("skill",c),u=(Rb[c]??[]).find((g)=>o.has(Ot("skill",g)));if(u===void 0||!n.has(l)||r.has(l))return[];let d=Eg(t,u),p=`${Ft(t,c).label} also reads ${d}, where ${Ft(t,u).label}'s copy is`;return[{id:l,reason:p}]});return[...i,...a]}function uU(t,e,n){if(!t.initialised&&!n)throw new v("Routing needs .ari/config.json, which does not exist yet","Pass --init to create it in the same run, or run 'ari init' first");let r=new Set([...t.configured.map((s)=>s.name),...eU]);for(let[s,i]of[["--task-agent",e.task],["--review-agent",e.review]]){if(r.has(i.agent))continue;throw new v(`${s} names "${i.agent}", which is neither a configured agent nor a preset`,`Choose one of: ${[...r].join(", ")}`)}let o=t.routing.reviewCommand;if(o===null)return;throw new m(`review.command (${o}) runs the review gate, so ari cannot also set review.agent`,`Remove review.command from ${bg}, or leave the review agent out`,1,{tag:"ReviewCommandSet"})}function dU(t,e,n,r){let o=Ft(t,e),s=Ot(n,e),i=n==="hooks"?"project":r,a={agent:e,elsewhere:null,file:null,id:s,kind:n,problem:null,scope:i,status:null};if(!o.kinds.includes(n))return{...a,skip:`ari has no ${Ye[n]} integration for ${o.label}`};if(i==="user"&&!o.userScope.includes(n))return{...a,skip:`${o.label} keeps user-scope MCP servers itself; run '${cl}'`};let c=xg(t,s,i),l=i==="user"?"project":"user",u=n==="hooks"?void 0:t.targets.find((p)=>p.id===s&&p.scope===l),d=u!==void 0&&Ag(u)?u.scope:null;return{...a,elsewhere:d,file:c.file,problem:c.problem,skip:null,status:c.status}}function pU(t){let e=t.hookManager,n={agent:null,elsewhere:null,id:qe,kind:"git",scope:"project"};if(e!==null)return{...n,file:t.gitHooksDirectory,problem:null,skip:Db(e.name),status:null};return Pb(t,qe,"project")}function Pb(t,e,n){let r=xg(t,e,n),{agent:o,file:s,kind:i,problem:a,status:c}=r;return{agent:o,elsewhere:null,file:s,id:e,kind:i,problem:a,scope:n,skip:null,status:c}}function xg(t,e,n){let r=t.targets.find((o)=>o.id===e&&o.scope===n);if(r!==void 0)return r;throw Error(`No detected state for ${e} in the ${n} scope`)}function Nb(t){return new Set(t.targets.filter(Ag).map((e)=>e.id))}function Ag(t){return t.status!=="missing"&&t.agent!==null}function Eg(t,e){return xg(t,Ot("skill",e),"project").file}function Db(t){return`${t} manages this repository's git hooks, so ari leaves them alone`}function gU(t){return t.hint.length===0?t.message:`${t.message}. ${t.hint}`}function al(t,e,n,r,o,s){return{agent:e,file:o,id:t,kind:n,scope:r,skip:s}}function Jo(t,e,n,r=[]){return{code:t,drop:r,fix:n,message:e}}function mU(t){return t===2?"twice":`${t} times`}var fU={claude:["claude"],codex:["codex"],copilot:["copilot"],cursor:["cursor-agent","cursor"],gemini:["gemini"]},hU="<!-- ari:begin -->",yU=new Set(["EACCES","EISDIR","ELOOP","ENOTDIR","EPERM"]);async function yi(t,e){let n=Lb(Mb(t,rt)),r=e!==void 0?e:n?M(t):null,o=Lb(Mb(t,J))?Gt(t):[],s={project:await TU(t),user:await xt("user",t)},[i,a,c]=await Promise.all([Promise.all(at.map(kU)),Qd(t),Hk(t)]),l=[...n?[bU(t)]:[],...Ie.map((u)=>Rg(Ot("hooks",Cg(u.name)),Cg(u.name),"hooks","project",u.file,()=>un(t,u),()=>Ks(u,W(t,u.file))===W(t,u.file))),...pl("mcp",s),...pl("skill",s),...a===null?[await EU(t,c)]:[]];return{agents:i,configured:$U(r),gitHooksDirectory:c,hookManager:a,initialised:n,pack:r?.pack??null,packs:Tn(o).map(({description:u,name:d})=>({description:u,name:d})),root:t,routing:{review:r?.review.agent===void 0?null:{agent:r.review.agent,model:r.review.model??null},reviewCommand:r?.review.command??null,task:r?.routing.default??null},targets:l}}async function jb(t){let e={user:await xt("user",t)};return[...pl("mcp",e),...pl("skill",e)]}async function kU(t){let e=Ie.find((c)=>c.name===t),n=se.find((c)=>c.agent===t),r=fe.find((c)=>c.agent===t),o=fU[t],s=await Os(o),i=[...e===void 0?[]:["hooks"],...n===void 0?[]:["mcp"],...r===void 0?[]:["skill"]],a=[...n?.user==null?[]:["mcp"],...r?.user==null?[]:["skill"]];return{agent:t,binaries:o,kinds:i,label:e?.label??t,path:s.path,preset:Ve.some((c)=>c.name===t),support:e?.support??"partial",userScope:a,version:s.version}}function pl(t,e){return(t==="mcp"?se:fe).flatMap((r)=>Mn.flatMap((o)=>{let s=e[o];if(r[o]===null||s===void 0)return[];let i=Cg(r.agent);return[t==="mcp"?wU(i,o,s):SU(i,o,s)]}))}function wU(t,e,n){let r=se.find((i)=>i.agent===t);if(r===void 0)throw Error(`ari has no mcp target for ${t}`);let o=Ne(r,n),s=()=>o.install(W(o.base,o.file))===W(o.base,o.file);return Rg(Ot("mcp",t),t,"mcp",e,o.file,()=>mn(o),s)}function SU(t,e,n){let r=Jt(t),o=ot.map((c)=>ie(r,n,c)),s=()=>o.some((c)=>mn(c)),i=()=>o.map((c)=>{let l=W(c.base,c.file);return c.install(l)===l}).every(Boolean);return{...Rg(Ot("skill",t),t,"skill",e,r[e],s,i),parts:vU(t,n)}}function vU(t,e){return(hi(()=>vg(Jt(t),e),"").value??[]).map((r)=>({name:r.skill,status:gl(r.installed,r.current)}))}function Rg(t,e,n,r,o,s,i){let a={agent:e,file:oe(r,o),id:t,kind:n,scope:r},c=hi(s,a.file);if(c.problem!==null)return{...a,problem:c.problem,status:"outdated"};let l=c.value===!0,u=hi(i,a.file);if(u.problem!==null)return{...a,problem:u.problem,status:l?"outdated":"missing"};return{...a,problem:null,status:gl(l,u.value===!0)}}function bU(t){let e={agent:null,file:jt,id:sr,kind:"config",scope:"project"},n=hi(()=>W(t,jt),jt);if(n.problem!==null)return{...e,problem:n.problem,status:"outdated"};let r=n.value,o=(r??"").includes(hU),s=hi(()=>fi(r)===r,jt);if(s.problem!==null)return{...e,problem:s.problem,status:"outdated"};return{...e,problem:null,status:gl(o,s.value===!0)}}async function EU(t,e){let n={agent:null,file:e,id:qe,kind:"git",scope:"project"},r=await xU(()=>To(t),e);if(r.problem!==null)return{...n,problem:r.problem,status:"outdated"};let o=r.value===!0;try{let s=await Fs(t);return{...n,problem:null,status:gl(o,s.every((i)=>i.action==="unchanged"))}}catch(s){return{...n,problem:Ig(s,e),status:o?"outdated":"missing"}}}function $U(t){if(t===null)return[];return Object.entries(t.agents).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>({model:n.model??null,name:e,roles:Sr(n)}))}async function TU(t){return{base:t,receipts:await P(t),scope:"project"}}function gl(t,e){if(!t)return"missing";return e?"current":"outdated"}function hi(t,e){try{return{problem:null,value:t()}}catch(n){return{problem:Ig(n,e),value:null}}}async function xU(t,e){try{return{problem:null,value:await t()}}catch(n){return{problem:Ig(n,e),value:null}}}function Ig(t,e){if(t instanceof m)return{hint:t.hint??"",message:t.message};let n=t.code;if(t instanceof Error&&typeof n==="string"&&yU.has(n))return{hint:`Check that ${e} is a readable file, then run the command again`,message:`${e} cannot be read (${n})`};throw t}function Cg(t){let e=at.find((n)=>n===t);if(e!==void 0)return e;throw Error(`ari has no install support for ${t}`)}function Y(t,e){return{detail:e,hint:null,name:t,status:"ok"}}function ct(t,e,n){return{detail:e,hint:n,name:t,status:"warn"}}function St(t,e,n){return{detail:e,hint:n,name:t,status:"fail"}}function Fb(t){return{fail:t.filter((e)=>e.status==="fail").length,ok:t.filter((e)=>e.status==="ok").length,warn:t.filter((e)=>e.status==="warn").length}}function Xe(t){return`'${t.replaceAll("'","'\\''")}'`}function ml(t,e){return t.ok?Y(t.name,t.detail):St(t.name,t.detail,t.hint??e)}var AU="agent binaries",CU="ari agents detect";function Gb(t){let e=Object.keys(t.agents).sort(O);if(e.length===0)return[Y(AU,"none configured; 'ari agents add <preset>' adds one for ari run and ari review")];let n=IU(t);return e.map((r)=>RU(r,t.agents[r],n.has(r)))}function RU(t,e,n){let r=`agent ${t}`,s=[...new Set([e?.command[0],e?.reviewCommand?.[0]].filter((l)=>l!==void 0))].map((l)=>({binary:l,path:Bun.which(l)})),i=s.filter((l)=>l.path===null).map((l)=>l.binary);if(i.length===0)return Y(r,s.map((l)=>`${l.binary} at ${l.path}`).join("; "));let a=`${i.join(", ")} not found on PATH${n?", and the routing or review gate uses this agent":""}`,c=`Install ${i.join(" and ")} and put it on PATH, then run '${CU}'`;return n?St(r,a,c):ct(r,a,c)}function IU(t){let{review:e,routing:n}=t,o=[n.default,n.review,...Object.values(n.stages)].flatMap((s)=>s===null?[]:[s.agent]);return new Set([...o,...e.agent===void 0?[]:[e.agent]])}import{existsSync as Hb}from"fs";import{join as Ub}from"path";var fl="configuration",hl="trust",Kb="ari init",OU="ari doctor",_U=12;function Bb(t){if(!Hb(Ub(t,J)))return{check:St(fl,"ari is not set up in this repository: .ari/ does not exist",Kb),config:null,skipReason:"ari is not set up in this repository"};try{let e=M(t);if(!Hb(Ub(t,rt)))return{check:ct(fl,`${rt} is missing, so the defaults apply`,Kb),config:e,skipReason:null};return{check:Y(fl,`${rt} is valid (pack ${e.pack})`),config:e,skipReason:null}}catch(e){if(!(e instanceof m))throw e;return{check:St(fl,e.message,`Fix ${rt} by hand, then run '${OU}' again`),config:null,skipReason:"the configuration is not valid"}}}function Vb(t,e){let n=Be(t,e),r=So();switch(n.state){case"not-required":return Y(hl,"the configuration starts no commands, so nothing needs trust");case"trusted":return Y(hl,`trusted since ${n.trustedAt} (configuration ${n.sha256.slice(0,_U)})`);case"untrusted":case"changed":{let o=n.state==="changed"?`the commands changed since ${n.trustedAt}`:"nobody has trusted them on this machine";if(r)return Y(hl,`${o}, but ${xr}=1 lets ari run them`);return ct(hl,`${n.commands.length} configured command(s) are not trusted: ${o}, so ari run, ari review and command gates refuse to start them`,"ari trust")}}}var yl="ari on PATH",PU=/\d+(?:\.\d+)+[\w.+-]*/,Wb="bun add -g @r5n/ariadne";async function Jb(t){let e=kg(Bun.which("ari"));if(!e.ok)return St(yl,e.detail,Wb);let n=await Os(["ari"]),r=n.path??e.detail;if(n.version===null)return ct(yl,`${r} did not report a version`,`${r} --version`);let o=PU.exec(n.version)?.[0]??n.version;if(o===t)return Y(yl,`${r} (Ariadne ${o})`);return ct(yl,`${r} is Ariadne ${o}, but this is Ariadne ${t}`,`${Wb}@${t}`)}var NU="ari doctor",qb="git hooks",DU="agents",LU="ari hooks install --agent git",Og="ari install";function _g(t){return t.flatMap((e)=>{let n=FU(e);if(e.problem!==null)return[UU(n,e)];if(e.status==="missing")return e.kind==="config"?[KU(n,e)]:[];if(e.status==="current")return[Y(n,GU(e))];return[ct(n,HU(e),Xb(e))]})}function Yb(t){let e=at.filter((r)=>t.targets.some((o)=>o.agent===r&&o.status!=="missing"));return[...e.length===0?[ct(DU,"no agent is set up here: no hooks, MCP server or skill is installed",Og)]:e.flatMap((r)=>MU(t,r)),...jU(t)]}function MU(t,e){let n=t.agents.find((r)=>r.agent===e);if(n===void 0)return[];return n.kinds.flatMap((r)=>{if(t.targets.some((c)=>c.agent===e&&c.kind===r&&c.status!=="missing"))return[];let s=il({agent:e,file:null,kind:r}),i=Wo(t,[Ot(r,e)])[0];if(i!==void 0)return[Y(s,`not needed: ${i.reason}`)];let a=Hr({agent:e,kind:r,scope:"project"})??Og;return[ct(s,`${n.label} has no ${Ye[r]} installed`,a)]})}function jU(t){if(t.hookManager!==null)return[Y(qb,`${t.hookManager.name} manages them, so ari leaves them alone`)];let e=t.targets.find((n)=>n.id==="git");if(e===void 0||e.status!=="missing"||e.problem!==null)return[];return[ct(qb,"not installed: commits and pushes are not checked against the task's scope",LU)]}function FU(t){let e=il(t);return t.scope==="user"?`${e} (user)`:e}function GU(t){if(t.kind==="git")return"pre-commit and pre-push run ari";if(t.kind==="skill")return`${t.file}: ${t.parts?.length??0} skills`;return t.kind==="config"?`${t.file} has the ari block`:t.file}function HU(t){let e=t.kind==="skill"?t.parts??[]:[],n=e.filter((s)=>s.status==="missing").map((s)=>s.name),r=e.filter((s)=>s.status==="outdated").map((s)=>s.name);if(n.length+r.length===0)return`${t.file} is not what this ari installs now`;let o=[...n.length===0?[]:[`${n.join(", ")} ${n.length===1?"is":"are"} missing`],...r.length===0?[]:[`${r.join(", ")} ${r.length===1?"is":"are"} outdated`]];return`${t.file}: ${o.join("; ")}`}function UU(t,e){let n=e.problem?.message??"",r=e.kind==="skill"?e.problem?.hint??"":"";if(r.length>0)return St(t,n,r);return St(t,n,`Make ${e.file} a valid, readable file by hand, then run '${NU}' again`)}function KU(t,e){return ct(t,`${e.file} has no ari block, so agents are not told the loop`,Xb(e))}function Xb(t){return Hr(t)??Og}import{existsSync as BU,readdirSync as VU,readFileSync as WU,realpathSync as JU,statSync as qU}from"fs";import{tmpdir as YU}from"os";import{join as Qb,resolve as XU,sep as zU}from"path";var ZU=3600,QU=1000,tE=ZU*QU,zb="temporary files",tK=".git",Zb="gitdir:",eK="git worktree prune";async function eE(t,e=Date.now()){let n=await nK(t,e);if(n.length===0)return Y(zb,"no leftover ari-base-* or ari-index-* directory older than one hour");let r=n.map((i)=>`${i.path} (${i.kind}, ${aK(i.ageMs)} old)`),o=n.map((i)=>i.kind==="base worktree"?`git worktree remove --force ${Xe(i.path)}`:`rm -r ${Xe(i.path)}`),s=n.some((i)=>i.kind==="base worktree")?[eK]:[];return ct(zb,`${n.length} directory(ies) left behind by an interrupted run: ${r.join("; ")}`,[...o,...s].join(" && "))}async function nK(t,e){let n=YU(),r=La(t),o=await rK(t);return sK(n).flatMap((s)=>{let i=Qb(n,s),a=iK(i,e);if(a===null||a<tE)return[];if(s.startsWith(r))return[{ageMs:a,kind:"temporary index",path:i}];return s.startsWith(Cs)&&oK(i,o)?[{ageMs:a,kind:"base worktree",path:i}]:[]})}async function rK(t){try{return nE(await sn(t,"worktrees"))}catch{return null}}function oK(t,e){if(e===null)return!1;try{let n=WU(Qb(t,tK),"utf8").trim();if(!n.startsWith(Zb))return!1;return nE(XU(n.slice(Zb.length).trim())).startsWith(`${e}${zU}`)}catch{return!1}}function sK(t){try{return VU(t).filter((e)=>e.startsWith(Cs)||e.startsWith(wd))}catch{return[]}}function iK(t,e){try{let n=qU(t);return n.isDirectory()?e-n.mtimeMs:null}catch{return null}}function nE(t){return BU(t)?JU(t):t}function aK(t){let e=Math.floor(t/tE);return e<1?"under an hour":e===1?"1 hour":`${e} hours`}var rE="knowledge size",oE="sleep",sE="ari sleep",cK="ari doctor";async function iE(t){try{let e=er(await jr(t));return[lK(e),uK(e)]}catch(e){if(!(e instanceof m))throw e;let n=e.hint===void 0||e.hint.length===0?"Fix it by hand":e.hint.replace(/\.$/,"");return[St("knowledge",e.message,`${n}, then run '${cK}' again`)]}}function lK({activeBytes:t,maxBytes:e}){let n=`${t} of ${e} bytes of active knowledge`;if(t<=e)return Y(rE,n);return ct(rE,`${n}: over the budget`,sE)}function uK(t){if(!t.due)return Y(oE,"nothing to consolidate");let e=t.reasons.map((n)=>dK(n,t));return ct(oE,`sleep is due: ${e.join("; ")}`,sE)}function dK(t,e){switch(t){case"journals":return`journals of done tasks remain (${e.journaled.join(", ")})`;case"budget":return`active knowledge exceeds ${e.maxBytes} bytes`;case"candidates":{let{clusters:n,decisions:r,notes:o}=e.candidates;return`${n} cluster(s), ${o} note(s) and ${r} decision(s) are waiting for a proposal`}}}var Pg="receipts",pK=[{kind:"hooks",name:"hooks.json"},{kind:"mcp",name:"mcp.json"},{kind:"skill",name:"skills.json"}],gK="ari install";function Ng(t){let e={edited:0,fixes:[],matches:0,problems:[]};for(let o of t)for(let s of pK){if(s.kind==="hooks"&&o.scope==="user")continue;mK(o,s,e)}if(e.problems.length>0)return ct(Pg,`${e.problems.join("; ")}; uninstall would remove only ari's entries instead of restoring files byte for byte`,[...new Set(e.fixes)].join("; "));let n=e.matches+e.edited;if(n===0)return Y(Pg,"no receipts: nothing was installed through ari here");let r=e.edited===0?"":`; ${e.edited} edited since install, which uninstall keeps`;return Y(Pg,`${e.matches} of ${n} match their files${r}`)}function mK(t,e,n){let r=Bk(t.receipts,e.name);if(r.state==="absent")return;if(r.state==="unreadable"){n.problems.push(`${r.path} cannot be read`),n.fixes.push(`rm ${Xe(r.path)}`);return}for(let[o,s]of Object.entries(r.receipts))fK(t,e.kind,o,s,n)}function fK(t,e,n,r,o){let s=hK(t,e,n);if(s===null)return;let i=yK(t,n);if(i===void 0)return;let a=kK(s,t,i);if(a===null)return;if(i===null||!a){o.problems.push(`the receipt for ${n} (${t.scope}) names ari entries that are no longer there`),o.fixes.push(wK(e,s.agent,t.scope));return}if(i===r.installed)o.matches++;else o.edited++}function hK(t,e,n){if(e==="hooks"){let o=Ie.find((s)=>s.file===n);return o===void 0?null:{agent:o.name,hooks:o}}if(e==="mcp"){let o=se.find((s)=>s[t.scope]===n);return o===void 0?null:{agent:o.agent,managed:Ne(o,t)}}let r=pb(t,n);return r===null?null:{agent:r.target.agent,managed:ie(r.target,t,r.skill)}}function yK(t,e){try{return W(t.base,e)}catch{return}}function kK(t,e,n){try{if(t.hooks!==void 0)return un(e.base,t.hooks);return t.managed===void 0?null:t.managed.managed(n)}catch{return null}}function wK(t,e,n){return Hr({agent:e,kind:t,scope:n})??gK}import{accessSync as SK,constants as vK,existsSync as bK}from"fs";import{dirname as cE}from"path";function qo(t){if(t.kind==="restore")return t.written.flatMap(({before:o,path:s})=>o===null?[]:aE(s,o));let{artifacts:e,context:n,contract:r}=t;return[...Bt(r.text)===r.sha256?[]:["the contract text does not match its SHA-256"],...e.flatMap(({file:o,path:s})=>aE(s,o)),...Z(n.text)===n.sha256?[]:["the context pack does not match its SHA-256"]]}function aE(t,e){return Z(Dr(e))===e.sha256?[]:[`${t} does not match its SHA-256`]}var lE="snapshots";async function uE(t){let e=await P(t),n=Fr(e),r=Ln(e),o=r.unreadable.map(({id:c,problem:l})=>({detail:`${c} cannot be read (${l})`,fix:`rm ${Xe(nr(e,c))}`})),s=r.entries.flatMap((c)=>{let l=qo(c);if(l.length===0)return[];return[{detail:`${c.id} is not intact (${l.join("; ")})`,fix:`rm ${Xe(nr(e,c.id))}`}]}),i=$K(n),a=[...o,...s,...i===null?[]:[{detail:`${i} is not writable, so automatic snapshots can only warn`,fix:`chmod u+w ${Xe(i)}`}]];if(a.length===0)return Y(lE,EK(r.entries.length,new Set(r.entries.map((c)=>c.task)).size));return ct(lE,a.map((c)=>c.detail).join("; "),a.map((c)=>c.fix).join(" && "))}function EK(t,e){if(t===0)return"no snapshots yet; the directory can be written";return`${t} ${t===1?"entry":"entries"} for ${e} ${e===1?"task":"tasks"}, all intact; the directory can be written`}function $K(t){let e=TK(t);try{return SK(e,vK.W_OK),null}catch{return e}}function TK(t){let e=t;while(!bK(e)&&cE(e)!==e)e=cE(e);return e}import{join as xK}from"path";var Yo="active task",dE="tasks",AK="active.json",CK=10,RK=new Set(["active","blocked"]),pE="ari list",IK="then run 'ari doctor' again";async function gE(t,e){let n=await P(t);return[OK(t,e,n),...NK(t,e)]}function OK(t,e,n){let r=`rm ${Xe(xK(n,AK))}`,o=mE(()=>gt(n));if(o.failure!==null)return St(Yo,`the pointer of this worktree cannot be read: ${o.failure.message}`,r);if(o.value===null)return Y(Yo,"no task is active in this worktree");return _K(t,e,o.value,r)}function _K(t,e,n,r){let{task:o}=n;if(!de(t).includes(o)){let i=In(t).includes(o)?"its contract is missing":"no such task exists";return ct(Yo,`the pointer of this worktree names "${o}", but ${i}`,r)}let s=mE(()=>it(t,o,e).task);if(s.failure!==null||s.value===null){let i=s.failure??new m(`task "${o}" cannot be read`);return St(Yo,`the pointer of this worktree names "${o}", which cannot be read: ${i.message}`,DK(i))}return PK(s.value,r)}function PK({contract:t,record:e},n){let r=t.id;if(RK.has(e.status))return Y(Yo,`${r} (${e.status}, stage ${e.stage})`);return ct(Yo,`the pointer of this worktree names "${r}", which is ${e.status}`,n)}function NK(t,e){let{invalid:n,tasks:r}=Pt(t,e);if(n.length===0)return[Y(dE,`${r.length} task(s), every contract and record is readable`)];let o=n.slice(0,CK).map((i)=>St(`task ${i.id}`,i.problem,fE(i.hint))),s=n.length-o.length;return s>0?[...o,St(dE,`${s} more task(s) cannot be read`,pE)]:o}function mE(t){try{return{failure:null,value:t()}}catch(e){if(e instanceof m)return{failure:e,value:null};throw e}}function DK(t){return fE(t.hint??"")}function fE(t){return t.length===0?pE:`${t.replace(/\.$/,"")}, ${IK}`}var hE="git on PATH",LK="ari mcp serve",MK=5000,jK="ari doctor --json",FK="not inside a git working tree",GK="git is not on PATH",HK=["configuration","trust","project integrations","git hooks","agent binaries","tasks","temporary files","sleep and knowledge size","snapshots"],UK=["trust","agent binaries","tasks","sleep and knowledge size","snapshots"];async function yE({cwd:t,version:e}){let n=Bun.which("git"),r=n===null?null:await KK(t),o=[...await ze("ari on PATH",async()=>[await Jb(e)]),n===null?St(hE,"git is not on PATH, so ari cannot read any repository","Install git"):Y(hE,n)],s=r===null?await BK(t,n===null?GK:FK):await VK(r),i=[...o,...s.checks],a=Fb(i);return{checks:i,ok:a.fail===0,root:r,skipped:s.skipped,summary:a,version:e}}async function KK(t){try{return await Jn(t)}catch(e){if(e instanceof m)return null;throw e}}async function BK(t,e){let n=await jb(t),r=await xt("user",t);return{checks:[..._g(n),...await ze("ari mcp serve",()=>kE(t,n)),...await ze("receipts",()=>[Ng([r])])],skipped:HK.map((s)=>({name:s,reason:e}))}}async function VK(t){let e=Bb(t),{config:n}=e,r=await ze("integrations",async()=>{let c=await yi(t,n);return[..._g(c.targets),...Yb(c),...await kE(t,c.targets)]}),o=await ze("receipts",async()=>[Ng(await JK(t))]),s=await ze("temporary files",async()=>[await eE(t)]),i=n===null?{first:[],last:[]}:await WK(t,n),a=e.skipReason;return{checks:[e.check,...i.first,...r,...o,...i.last,...s],skipped:n===null&&a!==null?UK.map((c)=>({name:c,reason:a})):[]}}async function WK(t,e){let n=await ze("trust",()=>[Vb(t,e)]),r=await ze("agent binaries",()=>Gb(e)),o=await ze("tasks",()=>gE(t,e)),s=await ze("sleep",()=>iE(t)),i=await ze("snapshots",async()=>[await uE(t)]);return{first:n,last:[...r,...o,...s,...i]}}async function JK(t){return[await xt("project",t),await xt("user",t)]}async function kE(t,e){let n=e.some((o)=>o.kind==="mcp"&&o.status!=="missing"),r=Bun.which("ari");if(!n||r===null)return[];return[ml(await wg(r,t,MK),LK)]}async function ze(t,e){try{return await e()}catch(n){return[qK(t,n)]}}function qK(t,e){if(e instanceof m){let r=e.hint===void 0||e.hint.length===0?"Fix it by hand":e.hint.replace(/\.$/,"");return St(t,e.message,`${r}, then run 'ari doctor' again`)}let n=e instanceof Error?e.message:String(e);return St(t,`the check stopped unexpectedly: ${n}`,jK)}var YK=26,SE=6,XK=" ".repeat(SE),zK={fail:"FAIL",ok:"ok",warn:"warn"};function Dg(t){return t.flatMap((e)=>{let n=`${ZK(e.status,wE(zK[e.status],SE))}${wE(e.name,YK)}${e.detail}`;return e.hint===null||e.status==="ok"?[n]:[n,`${XK}fix: ${e.hint}`]})}function vE(t){let{fail:e,ok:n,warn:r}=t.summary,o=t.skipped.length===0?[]:["",...t.skipped.map((i)=>`skipped ${i.name}: ${i.reason}`)],s=`${n} ok, ${r} warning(s), ${e} failure(s)`;return[...Dg(t.checks),...o,"",s].join(`
207
+ `)}function ZK(t,e){switch(t){case"ok":return w.green(e);case"warn":return w.yellow(e);case"fail":return w.red(e)}}function wE(t,e){let n=Bun.stringWidth(t);return n>=e?`${t} `:`${t}${" ".repeat(e-n)}`}var QK=1,bE=E({description:"Check the setup without changing anything: ari, configuration, trust, integrations, tasks and memory",examples:["ari doctor","ari doctor --json"],json:!0,name:"doctor",run:async(t)=>{let e=await yE({cwd:process.cwd(),version:t.cli.version??""});return t.output.result(e,vE),e.ok?void 0:QK}});function kl(t,e){let n=new Set,r=(o,s)=>{for(let i of e(o)){if(i===t)return[...s,t];if(n.has(i))continue;n.add(i);let a=r(i,[...s,i]);if(a)return a}return null};return r(t,[t])}function wl(t){return`depends forms a cycle: ${t.join(" -> ")}`}var tB=["ari check","ari done"],eB=["ari next"],nB='ari new "<title>"',EE=["active","blocked"];function Lg(t){let e=[...t.tasks].sort((u,d)=>O(u.contract.id,d.contract.id)),n=t.active?e.find((u)=>u.contract.id===t.active?.task):void 0;if(n?.record.status==="active")return rB(n,t.packs);if(n?.record.status==="blocked")return oB(n,t.packs);let r=e.filter((u)=>!t.claimed.has(u.contract.id)),s=r.filter((u)=>EE.includes(u.record.status)).find((u)=>jg(u,t.packs)===null);if(s)return sB(s,t.packs);let i=lB(r,t),a=dB(e,r.filter((u)=>!i.has(u.contract.id)));if(a)return aB(a,t.packs);let c=uB(e,r,t,i);if(c)return iB(c);let l=e.find((u)=>u.record.status==="draft");if(l)return cB(l);return{action:"new",commands:[nB],instruction:"Create a task and write its contract: scope, criteria and checks.",stage:null,task:null}}function rB(t,e){let n=Mg(t,e);return{action:"continue",commands:[...tB],instruction:mo(n,t.contract.id),stage:n.name,task:t.contract.id}}function oB(t,e){let n=t.record.question??"the task was blocked without a recorded question";return{action:"resolve",commands:[`ari resolve ${t.contract.id} --answer "<answer>"`],instruction:`A human must answer: ${n}`,stage:Mg(t,e).name,task:t.contract.id}}function sB(t,e){return{action:"start",commands:[`ari start ${t.contract.id}`],instruction:`Task "${t.contract.title}" is ${t.record.status}, but no worktree holds it; adopt it here.`,stage:Mg(t,e).name,task:t.contract.id}}function iB(t){return{action:"fix",commands:[...eB],instruction:t.instruction,stage:null,task:t.id}}function aB(t,e){let n=e.find((r)=>r.name===t.contract.pack)?.stages[0];return{action:"start",commands:[`ari start ${t.contract.id}`],instruction:`Start "${t.contract.title}".`,stage:n?.name??null,task:t.contract.id}}function cB(t){return{action:"ready",commands:[`ari ready ${t.contract.id}`],instruction:`Complete the contract of "${t.contract.title}", then mark it ready.`,stage:null,task:t.contract.id}}function Mg(t,e){let n=jg(t,e);if(n!==null)throw new m(n.message,n.hint);let r=e.find((o)=>o.name===t.contract.pack)?.stages[t.record.stage];if(r)return r;throw Error(`Task "${t.contract.id}" has no stage ${t.record.stage}`)}function jg(t,e){let n=e.find((r)=>r.name===t.contract.pack);if(!n)return{hint:"Fix the contract's pack",message:`Unknown pack "${t.contract.pack}" in task "${t.contract.id}"`};if(t.record.stage<n.stages.length)return null;return{hint:`Restore the stages of pack "${n.name}" in .ari/packs/${n.name}.yaml`,message:`Task "${t.contract.id}" is at stage ${t.record.stage}, but pack "${n.name}" has ${n.stages.length}`}}function lB(t,{packs:e,uncoveredLocks:n}){let o=t.filter((s)=>s.record.status==="ready").map((s)=>{let i=n.get(s.contract.id),a=i===void 0?[]:[`lock glob ${JSON.stringify(i)} matches no file that git tracks or would track`];return[s.contract.id,[...uo(s.contract,e),...a]]});return new Map(o.filter(([,s])=>s.length>0))}function uB(t,e,{invalid:n,packs:r},o){let s=new Map(t.map((p)=>[p.contract.id,p])),i=new Set(n.map((p)=>p.id)),a=(p)=>s.get(p)?.contract.depends??[],c=e.filter((p)=>p.record.status==="ready").flatMap((p)=>{let g=p.contract.id,f=p.contract.depends.find((S)=>!s.has(S)&&!i.has(S));if(f!==void 0)return[{id:g,instruction:`depends names the unknown task "${f}". Fix the depends of .ari/tasks/${g}.md`}];let y=kl(g,a);return y?[{id:g,instruction:`${wl(y)}. Remove one of these dependencies`}]:[]}),l=[...o].map(([p,g])=>({id:p,instruction:`The contract can no longer start: ${g.join("; ")}. Fix .ari/tasks/${p}.md`})),u=e.filter((p)=>EE.includes(p.record.status)).flatMap((p)=>{let g=jg(p,r);return g===null?[]:[{id:p.contract.id,instruction:`${g.message}. ${g.hint}`}]});return[...n.map((p)=>({id:p.id,instruction:`${p.problem}. ${p.hint}`})),...u,...l,...c].sort((p,g)=>O(p.id,g.id))[0]}function dB(t,e){let n=new Map(t.map((i)=>[i.contract.id,i])),r=new Map,o=(i,a)=>{let c=r.get(i);if(c!==void 0)return c;let l=n.get(i);if(!l||a.has(i))return 0;let u=new Set([...a,i]),d=Math.max(-1,...l.contract.depends.map((p)=>o(p,u)))+1;return r.set(i,d),d};for(let i of t)o(i.contract.id,new Set);let s=(i)=>i.contract.depends.every((a)=>n.get(a)?.record.status==="done");return e.filter((i)=>i.record.status==="ready"&&s(i)).sort((i,a)=>(r.get(i.contract.id)??0)-(r.get(a.contract.id)??0)||O(i.contract.id,a.contract.id))[0]}import{join as pB}from"path";var $E=Error("the design already exists");function TE(t,e,n,r){let o=new Set;return gB(e).flatMap((s)=>{let i=Ro(s.path,n);if(o.has(i))return[];return o.add(i),[{created:mB(t,i,Qh(r,s.sections??[])),path:i}]})}function gB(t){return t.stages.flatMap((e)=>e.gates.flatMap((n)=>n.kind==="artifact"&&n.sections!==void 0?[n]:[]))}function mB(t,e,n){if(Te(t,e))throw new m(`Cannot write the design template to ${e}: a directory on its way is a symbolic link`,"Replace the link with a real directory, or write the design by hand");try{return Yn(pB(t,e),n,()=>$E),!0}catch(r){if(r===$E)return!1;let o=r instanceof Error?r.message:String(r);throw new m(`The task was created, but the design template could not be written to ${e} (${o})`,`Write ${e} by hand with the sections of the pack`)}}import{realpathSync as fB}from"fs";import{resolve as hB}from"path";var yB="ENOENT";async function ki(t){let e=xE(t),n=new Map;for(let r of await Py(t)){if(xE(r)===e)continue;let o=kB(await P(r));if(o!==null&&!n.has(o.task))n.set(o.task,r)}return n}function kB(t){try{return gt(t)}catch(e){if(e instanceof m)return null;throw e}}function xE(t){try{return fB(t)}catch(e){if(e.code===yB)return hB(t);throw e}}var wB=8,SB=6,vB=10,AE=`
191
208
  scope: []
192
- `,p1="decision",Np=10,RT={active:(t)=>`Finish it with 'ari done', or block it with 'ari block ${t} --reason <text>'`,blocked:(t)=>`A human answers it with 'ari resolve ${t} --answer <text>'`},g1=()=>new Date().toISOString();async function IT(t,e,n={}){let r=await oe(t),o=e.trim(),s=$s(o,l1);if(s.length===0)throw new g(`The title "${e}" has no letters or digits to build a task id from`,'Run ari new "<title>"');let i=sr(n.pack??r.config.pack,r.projectPacks).name,a=[...n.scope??[]],c=a.find((p)=>er(p)!==null);if(c!==void 0)throw new g(`Scope glob ${JSON.stringify(c)} ${er(c)}`,"Pass globs relative to the root");let l=bs(s,Mh(t)),u=m1(th(o,i),a),d=Tu(l,tn(n)());return Lh(t,r.state,d,u),{contractPath:bt(l),id:l,task:{contract:na(l,u,r.config),record:d}}}async function OT(t,e,n={}){let r=await oe(t),{task:o}=lt(t,e,r.config),s=tn(n)();Eu(o.record,s);let i=[...Br(o.contract,r.packs),...T1(o.contract,t),...Mp(r,o.contract)];Dp(e,i,`Fix ${bt(e)}, then run 'ari ready ${e}'`);let a=Ft(t,r.state,e,(c)=>Eu(c,s));return{contract:o.contract,record:a}}async function bo(t,e,n={}){let r=await oe(t),{contractText:o,task:s}=lt(t,e,r.config),{contract:i}=s,a=tn(n)();if($1(r,e),await y1(r,e),Lp(s.record.status))return h1(r,s,a);let c=await Yi(t),l=await ln(t,i.lock),u=await Ts(t,r.config,i),d={contractHash:un(o),gatesHash:Oc(r,i),lockHashes:l,stageTestHashes:u},p=(y)=>uh(y,c,d,a);p(s.record),Dp(e,Br(i,r.packs),`Fix ${bt(e)}, then start it again`),E1(r,i),await k1(t,e),GT(i,l);let m=Ft(t,r.state,e,p);Nu(r.state,{since:a,task:e});let f={contract:i,record:m};return{..._c(f,Kn(r,i)),task:f}}async function _T(t,e={}){let n=await oe(t),{contractText:r,task:o}=UT(n),s=Kn(n,o.contract),i=Tn(o,s),a=await vd({config:n.config,pack:s,root:t,task:o}),c=a.every((d)=>d.ok);ar(n.state,BT("check",o,i,a,tn(e)()));let l=un(r)!==o.record.contractHash,u=Oc(n,o.contract)!==o.record.gatesHash;return{contractChanged:l,gates:a,gatesChanged:u,ok:c,stage:i.name,task:o}}async function PT(t,e={}){let n=await oe(t),r=UT(n),{task:o}=r,{contract:s}=o;KT(n,r);let i=Kn(n,s),a=Tn(o,i),c=await ge(t,[ir]),l=await vd({config:n.config,pack:i,root:t,task:o}),u=tn(e)();ar(n.state,BT("done",o,a,l,u));let d=s.budget.attempts,p={budget:d,gates:l,stage:a.name},m=Gh(n.state,s.id),f=(N)=>Ft(t,n.state,s.id,(U)=>(v1(o.record,U),N({...U,knowledgeUsed:x1(U.knowledgeUsed,m)})));if(!l.every((N)=>N.ok)){let N=f((_)=>ph(_,{at:u,gates:l,stage:a.name,treeHash:c},d)),U=N.status==="blocked"?"blocked":"failed";return{...p,attempts:N.attempts,next:null,outcome:U,task:{contract:s,record:N}}}let y=await Ts(t,n.config,s),S={at:u,gates:l,stage:a.name,testHashes:y,treeHash:c},R=f((N)=>{let U=dh(N,S,i.stages.length,y);return U.status==="done"?aa(U,m):U}),v=R.status==="done",H={contract:s,record:R};if(v)return Fh(n.state),ma(n.state,s.id),{...p,attempts:R.attempts,next:null,outcome:"done",task:H};let J=_c(H,i);return{...p,attempts:R.attempts,next:J,outcome:"advanced",task:H}}async function NT(t,e,n,r={}){let o=await oe(t),{contractText:s,task:i}=lt(t,e,o.config),{contract:a,record:c}=i,l=Lp(c.status);if(r.onto!==void 0&&!l)throw new g(`Task "${e}" is ${c.status}; only an active or blocked task has a base to move`,`Run 'ari amend ${e} --reason <text>' without --onto`);let u=await ln(t,a.lock),d=c.status!=="draft"&&c.status!=="done";if(d){let R=[...Br(a,o.packs),...Mp(o,a)];Dp(e,R,`Fix ${bt(e)}, then run 'ari amend ${e}' again`)}if(l)w1(i,Kn(o,a));let p=d?Tn(i,Kn(o,a)).name:null;if(l)GT(a,u);let m=l?await Ts(t,o.config,a):{...c.stageTestHashes},y={base:r.onto===void 0?null:await Uf(t,"HEAD",await Hr(t,r.onto)),contractHash:un(s),gatesHash:Oc(o,a),lockHashes:u,reason:n,stage:p,stageTestHashes:m},S=tn(r)();return $u(c,y,S),{contract:a,record:Ft(t,o.state,e,(R)=>$u(R,y,S))}}async function DT(t,e,n,r={}){let o=await oe(t),{task:s}=lt(t,e,o.config),i=tn(r)(),a=Ft(t,o.state,e,(c)=>gh(c,n,i));return{contract:s.contract,record:a}}async function LT(t,e,n,r={}){let o=await oe(t),{task:s}=lt(t,e,o.config),i=tn(r)();bu(s.record,n,i);let a=n.trim(),c=o.config.knowledge.maxEntryBytes,l=vt(a);if(l>c)throw new g(`The answer is ${l} bytes, but a knowledge entry holds at most ${c}`,"Shorten the answer, or raise knowledge.maxEntryBytes in .ari/config.json");let u=$s(a,u1),d=bs(u.length>0?u:p1,Ve(t));ga(t,{created:i.slice(0,d1),id:d,kind:"decision",scope:[...s.contract.scope],sources:[e],status:"active",supersededBy:null,supersedes:[],text:a});let p=Ft(t,o.state,e,(m)=>bu(m,n,i));return{knowledgeId:d,task:{contract:s.contract,record:p}}}async function MT(t,e,n,r={}){let o=await oe(t),s=lt(t,e,o.config),{contract:i,record:a}=s.task,c=Kn(o,i);if(a.status==="active")KT(o,s);let l=Tn(s.task,c),u=await xd(t,l,e),d=tn(r)(),p=Ft(t,o.state,e,(m)=>(b1(a,m),mh(m,{...u,by:n,stage:l.name},d)));return{contract:i,record:p}}async function jT(t,e,n={}){let r=await oe(t),o=n.task??HT(r),{task:s}=lt(t,o,r.config),i=tn(n)(),a=Ft(t,r.state,o,(c)=>fh(c,e,i));return{contract:s.contract,record:a}}async function Rc(t){let e=await oe(t),n=ut(e.state),r=n===null?null:f1(e,n.task);if(r!==null&&Lp(r.record.status))return Op({...{claimed:new Set,invalid:[],uncoveredLocks:new Map},active:n,packs:e.packs,tasks:[r]});let{invalid:o,tasks:s}=It(t,e.config),i=new Set((await Hs(t)).keys()),a=await S1(t,s);return Op({active:n,claimed:i,invalid:o,packs:e.packs,tasks:s,uncoveredLocks:a})}async function Ic(t,e={}){let n=await oe(t),r=It(t,n.config),{statuses:o}=e;if(o===void 0)return r;return{invalid:r.invalid,tasks:r.tasks.filter((s)=>o.includes(s.record.status))}}async function $n(t,e){let n=await oe(t),{task:r}=lt(t,e,n.config),s=r.record.status==="active"||r.record.status==="blocked"?_c(r,Kn(n,r.contract)):null;return{active:ut(n.state)?.task===e,instruction:s?.instruction??null,stage:s?.stage??null,task:r}}async function oe(t){let e=L(t),n=me(t);return{config:e,packs:pn(n),projectPacks:n,root:t,state:await M(t)}}function tn(t){return t.clock??g1}function Oc(t,e){let n=t.packs.find((r)=>r.name===e.pack);return n===void 0?null:ia(n,t.config)}function Kn(t,e){return sr(e.pack,t.projectPacks)}function _c(t,e){let n=Tn(t,e);return{instruction:Vr(n,t.contract.id),stage:n.name}}function m1(t,e){if(e.length===0)return t;if(!t.includes(AT))throw Error("The contract template has no empty scope line");return t.replace(AT,()=>`
193
- scope: ${Kr(e)}
194
- `)}function Dp(t,e,n){if(e.length===0)return;let r=e.map((o)=>` - ${o}`).join(`
195
- `);throw new g(`The contract of "${t}" has ${e.length} problem(s):
196
- ${r}`,n)}function Lp(t){return t==="active"||t==="blocked"}function f1(t,e){return te(t.root).includes(e)?lt(t.root,e,t.config).task:null}function h1(t,e,n){let r=e.contract.id;if(ut(t.state)?.task!==r)Nu(t.state,{since:n,task:r});return{..._c(e,Kn(t,e.contract)),task:e}}async function y1(t,e){let n=(await Hs(t.root)).get(e);if(n===void 0)return;throw new g(`Task "${e}" is already held by the worktree at ${n}`,"Continue it there, or run 'ari next' here for other work")}async function k1(t,e){let n=Wt(await pe(t,"HEAD"));if(n.length===0)return;let r=n.length-Np,o=r>0?` and ${r} more`:"",s=(await zi(t)).filter((a)=>n.includes(a)),i=s.length===0?"":`; git hides ${s.slice(0,Np).join(", ")} until you run 'git update-index --no-skip-worktree <path>' or 'git update-index --no-assume-unchanged <path>', so keep local settings in an ignored file instead`;throw new g(`Task "${e}" cannot start with uncommitted changes outside .ari: ${n.slice(0,Np).join(", ")}${o}`,`Commit, stash or ignore them, then run 'ari start ${e}'; the scope gate counts every change since the start commit${i}`)}function w1(t,e){let{evidence:n,id:r}=t.record,o=n.findIndex((i,a)=>i.stage!==e.stages[a]?.name),s=n[o];if(s===void 0)return;throw new g(`Task "${r}" passed stage "${s.stage}", which pack "${e.name}" does not have as stage ${o+1}`,"Keep the pack that the passed stages belong to, or create a follow-up with 'ari new'")}async function S1(t,e){let n=e.filter((s)=>s.record.status==="ready"&&s.contract.lock.length>0),r=n.flatMap((s)=>s.contract.lock),o=Object.keys(await ln(t,r));return new Map(n.flatMap((s)=>{let i=FT(s.contract,o);return i===void 0?[]:[[s.contract.id,i]]}))}function FT(t,e){return t.lock.find((n)=>!e.some((r)=>Z(r,[n])))}function GT(t,e){let n=FT(t,Object.keys(e));if(n===void 0)return;throw new g(`Lock glob ${JSON.stringify(n)} of task "${t.id}" matches no file that git tracks or would track`,`Fix the lock list in ${bt(t.id)}: escape [ ] { } * ? with a backslash, and lock only files that are not ignored`)}function Mp(t,e){let{tasks:n}=It(t.root,t.config),r=new Map(n.map((s)=>[s.contract.id,s.contract.depends]));r.set(e.id,e.depends.filter((s)=>s!==e.id));let o=Ac(e.id,(s)=>r.get(s)??[]);return o===null?[]:[Cc(o)]}function T1(t,e){let n=new Set(te(e));return t.depends.filter((r)=>r.trim().length>0&&r!==t.id&&!n.has(r)).map((r)=>`depends names the unknown task "${r}"`)}function E1(t,e){let n=new Set(te(t.root)),r=e.depends.filter((s)=>!n.has(s)||lt(t.root,s,t.config).task.record.status!=="done");if(r.length===0)return;let o=Mp(t,e).map((s)=>`; ${s}`);throw new g(`Task "${e.id}" depends on unfinished tasks: ${r.join(", ")}${o.join("")}`,"Finish those tasks first; 'ari next' shows the order")}function $1(t,e){let n=ut(t.state);if(n===null||n.task===e||!te(t.root).includes(n.task))return;let{status:r}=lt(t.root,n.task,t.config).task.record;if(r!=="active"&&r!=="blocked")return;throw new g(`Task "${n.task}" is already ${r} in this worktree; one task runs per worktree`,RT[r](n.task))}function HT(t){let e=ut(t.state);if(e!==null)return e.task;throw new g("No task is active in this worktree","Run 'ari next' to see what to do")}function UT(t){let e=HT(t),n=lt(t.root,e,t.config),{question:r,status:o}=n.task.record;if(o==="active")return n;if(o==="blocked")throw new g(`Task "${e}" is blocked: ${r??"no question was recorded"}`,RT.blocked(e));throw new g(`Task "${e}" is ${o}, not active`,"Run 'ari next' to see what to do")}function KT(t,{contractText:e,task:n}){let{contract:r}=n;if(un(e)!==n.record.contractHash)throw new g(`The contract of "${r.id}" changed after it was frozen`,`Run 'ari amend ${r.id} --reason <text>' to accept the change`);if(Oc(t,r)!==n.record.gatesHash)throw new g(`The gates of "${r.id}" changed after they were frozen: its pack, or the test globs, regression setup or review command of .ari/config.json`,`Run 'ari amend ${r.id} --reason <text>' to accept the change`)}function b1(t,e){if(t.stage===e.stage)return;throw new g(`Task "${e.id}" moved to another stage while its approval was recorded`,`Review the current stage, then run 'ari approve ${e.id}' again`)}function v1(t,e){if(ht(CT(t))===ht(CT(e)))return;throw new g(`Task "${e.id}" changed while its gates ran, so their result no longer applies`,"Run 'ari done' again; another ari command changed its status, stage, approvals, contract or frozen hashes")}function CT(t){let{approvals:e,attempts:n,base:r,contractHash:o,gatesHash:s,lockHashes:i,stage:a,stageTestHashes:c,status:l}=t,u=t.evidence.length;return{approvals:e,attempts:n,base:r,contractHash:o,gatesHash:s,lockHashes:i,stage:a,stageTestHashes:c,stages:u,status:l}}function x1(t,e){let n=e.flatMap((r)=>{let o=r.detail[Jr];return r.type==="context"&&Array.isArray(o)?o:[]});return[...new Set([...t,...n])].sort(I)}function BT(t,e,n,r,o){let s=r.filter((i)=>!i.ok).map((i)=>i.gate);return{at:o,detail:{failing:s,ok:s.length===0,stage:n.name},task:e.contract.id,type:t}}var A1=20,C1=`
209
+ `,bB="decision",Fg=10,RE={active:(t)=>`Finish it with 'ari done', or block it with 'ari block ${t} --reason <text>'`,blocked:(t)=>`A human answers it with 'ari resolve ${t} --answer <text>'`},EB=()=>new Date().toISOString();async function IE(t,e,n={}){let r=await he(t),o=e.trim(),s=zs(o,wB);if(s.length===0)throw new m(`The title "${e}" has no letters or digits to build a task id from`,'Run ari new "<title>"');let i=Ue(n.pack??r.config.pack,r.projectPacks),a=[...n.scope??[]],c=a.find((f)=>wr(f)!==null);if(c!==void 0)throw new m(`Scope glob ${JSON.stringify(c)} ${wr(c)}`,"Pass globs relative to the root");let l=Zs(s,Xy(t)),u=$B(Jh(o,i.name),a),d=ld(l,kn(n)());Yy(t,r.state,d,u);let p=TE(t,i,l,o),g={contract:Aa(l,u,r.config),record:d};return{contractPath:It(l),designs:p,id:l,task:g}}async function OE(t,e,n={}){let r=await he(t),{task:o}=it(t,e,r.config),s=kn(n)();ud(o.record,s);let i=[...uo(o.contract,r.packs),...OB(o.contract,t),...Ug(r,o.contract)];Gg(e,i,`Fix ${It(e)}, then run 'ari ready ${e}'`);let a=Vt(t,r.state,e,(c)=>ud(c,s));return{contract:o.contract,record:a}}async function Xo(t,e,n={}){let r=await he(t),{contractText:o,task:s}=it(t,e,r.config),{contract:i}=s,a=kn(n)();if(PB(r,e),await AB(r,e),Hg(s.record.status))return xB(r,s,a);let c=await Fa(t),l=await An(t,i.lock),u=await Ys(t,r.config,i),d={contractHash:Bt(o),gatesHash:bl(r,i),lockHashes:l,stageTestHashes:u},p=(y)=>ly(y,c,d,a);p(s.record),Gg(e,uo(i,r.packs),`Fix ${It(e)}, then start it again`),_B(r,i),await CB(t,e),GE(i,l);let g=Vt(t,r.state,e,p);Cd(r.state,{since:a,task:e});let f={contract:i,record:g};return{...El(f,ir(r,i)),task:f}}async function _E(t,e={}){let n=await he(t),{contractText:r,task:o}=UE(n),s=ir(n,o.contract),i=Nn(o,s),a=await wp({config:n.config,pack:s,root:t,task:o}),c=a.every((d)=>d.ok);$r(n.state,BE("check",o,i,a,kn(e)()));let l=Bt(r)!==o.record.contractHash,u=bl(n,o.contract)!==o.record.gatesHash;return{contractChanged:l,gates:a,gatesChanged:u,ok:c,stage:i.name,task:o}}async function PE(t,e={}){let n=await he(t),r=UE(n),{task:o}=r,{contract:s}=o;KE(n,r);let i=ir(n,s),a=Nn(o,i),c=await Ae(t,[Er]),l=await wp({config:n.config,pack:i,root:t,task:o}),u=kn(e)();$r(n.state,BE("done",o,a,l,u));let d=s.budget.attempts,p={budget:d,gates:l,stage:a.name},g=Qy(n.state,s.id),f=(N)=>Vt(t,n.state,s.id,(H)=>(DB(o.record,H),N({...H,knowledgeUsed:LB(H.knowledgeUsed,g)})));if(!l.every((N)=>N.ok)){let N=f((A)=>dy(A,{at:u,gates:l,stage:a.name,treeHash:c},d)),H=N.status==="blocked"?"blocked":"failed";return{...p,attempts:N.attempts,next:null,outcome:H,task:{contract:s,record:N}}}let y=await Ys(t,n.config,s),S={at:u,gates:l,stage:a.name,testHashes:y,treeHash:c},I=f((N)=>{let H=uy(N,S,i.stages.length,y);return H.status==="done"?_a(H,g):H}),C=I.status==="done",q={contract:s,record:I};if(C)return Zy(n.state),Va(n.state,s.id),{...p,attempts:I.attempts,next:null,outcome:"done",task:q};let G=El(q,i);return{...p,attempts:I.attempts,next:G,outcome:"advanced",task:q}}async function NE(t,e,n,r={}){let o=await he(t),{contractText:s,task:i}=it(t,e,o.config),{contract:a,record:c}=i,l=Hg(c.status);if(r.onto!==void 0&&!l)throw new m(`Task "${e}" is ${c.status}; only an active or blocked task has a base to move`,`Run 'ari amend ${e} --reason <text>' without --onto`);let u=await An(t,a.lock),d=c.status!=="draft"&&c.status!=="done";if(d){let I=[...uo(a,o.packs),...Ug(o,a)];Gg(e,I,`Fix ${It(e)}, then run 'ari amend ${e}' again`)}if(l)RB(i,ir(o,a));let p=d?Nn(i,ir(o,a)).name:null;if(l)GE(a,u);let g=l?await Ys(t,o.config,a):{...c.stageTestHashes},y={base:r.onto===void 0?null:await _y(t,"HEAD",await fo(t,r.onto)),contractHash:Bt(s),gatesHash:bl(o,a),lockHashes:u,reason:n,stage:p,stageTestHashes:g},S=kn(r)();return dd(c,y,S),{contract:a,record:Vt(t,o.state,e,(I)=>dd(I,y,S))}}async function DE(t,e,n,r={}){let o=await he(t),{task:s}=it(t,e,o.config),i=kn(r)(),a=Vt(t,o.state,e,(c)=>py(c,n,i));return{contract:s.contract,record:a}}async function LE(t,e,n,r={}){let o=await he(t),{task:s}=it(t,e,o.config),i=kn(r)();pd(s.record,n,i);let a=n.trim(),c=o.config.knowledge.maxEntryBytes,l=yt(a);if(l>c)throw new m(`The answer is ${l} bytes, but a knowledge entry holds at most ${c}`,"Shorten the answer, or raise knowledge.maxEntryBytes in .ari/config.json");let u=zs(a,SB),d=Zs(u.length>0?u:bB,an(t));Ba(t,{created:i.slice(0,vB),id:d,kind:"decision",scope:[...s.contract.scope],sources:[e],status:"active",supersededBy:null,supersedes:[],text:a});let p=Vt(t,o.state,e,(g)=>pd(g,n,i));return{knowledgeId:d,task:{contract:s.contract,record:p}}}async function ME(t,e,n,r={}){let o=await he(t),s=it(t,e,o.config),{contract:i,record:a}=s.task,c=ir(o,i);if(a.status==="active")KE(o,s);let l=Nn(s.task,c),u=await Sp(t,l,e),d=kn(r)(),p=Vt(t,o.state,e,(g)=>(NB(a,g),gy(g,{...u,by:n,stage:l.name},d)));return{contract:i,record:p}}async function jE(t,e,n={}){let r=await he(t),o=n.task??HE(r),{task:s}=it(t,o,r.config),i=kn(n)(),a=Vt(t,r.state,o,(c)=>my(c,e,i));return{contract:s.contract,record:a}}async function Sl(t){let e=await he(t),n=gt(e.state),r=n===null?null:TB(e,n.task);if(r!==null&&Hg(r.record.status))return Lg({...{claimed:new Set,invalid:[],uncoveredLocks:new Map},active:n,packs:e.packs,tasks:[r]});let{invalid:o,tasks:s}=Pt(t,e.config),i=new Set((await ki(t)).keys()),a=await IB(t,s);return Lg({active:n,claimed:i,invalid:o,packs:e.packs,tasks:s,uncoveredLocks:a})}async function vl(t,e={}){let n=await he(t),r=Pt(t,n.config),{statuses:o}=e;if(o===void 0)return r;return{invalid:r.invalid,tasks:r.tasks.filter((s)=>o.includes(s.record.status))}}async function jn(t,e){let n=await he(t),{task:r}=it(t,e,n.config),s=r.record.status==="active"||r.record.status==="blocked"?El(r,ir(n,r.contract)):null;return{active:gt(n.state)?.task===e,instruction:s?.instruction??null,stage:s?.stage??null,task:r}}async function he(t){let e=M(t),n=Gt(t);return{config:e,packs:Tn(n),projectPacks:n,root:t,state:await P(t)}}function kn(t){return t.clock??EB}function bl(t,e){let n=t.packs.find((r)=>r.name===e.pack);return n===void 0?null:Oa(n,t.config)}function ir(t,e){return Ue(e.pack,t.projectPacks)}function El(t,e){let n=Nn(t,e);return{instruction:mo(n,t.contract.id),stage:n.name}}function $B(t,e){if(e.length===0)return t;if(!t.includes(AE))throw Error("The contract template has no empty scope line");return t.replace(AE,()=>`
210
+ scope: ${lo(e)}
211
+ `)}function Gg(t,e,n){if(e.length===0)return;let r=e.map((o)=>` - ${o}`).join(`
212
+ `);throw new m(`The contract of "${t}" has ${e.length} problem(s):
213
+ ${r}`,n)}function Hg(t){return t==="active"||t==="blocked"}function TB(t,e){return de(t.root).includes(e)?it(t.root,e,t.config).task:null}function xB(t,e,n){let r=e.contract.id;if(gt(t.state)?.task!==r)Cd(t.state,{since:n,task:r});return{...El(e,ir(t,e.contract)),task:e}}async function AB(t,e){let n=(await ki(t.root)).get(e);if(n===void 0)return;throw new m(`Task "${e}" is already held by the worktree at ${n}`,"Continue it there, or run 'ari next' here for other work")}async function CB(t,e){let n=ne(await xe(t,"HEAD"));if(n.length===0)return;let r=n.length-Fg,o=r>0?` and ${r} more`:"",s=(await Ha(t)).filter((a)=>n.includes(a)),i=s.length===0?"":`; git hides ${s.slice(0,Fg).join(", ")} until you run 'git update-index --no-skip-worktree <path>' or 'git update-index --no-assume-unchanged <path>', so keep local settings in an ignored file instead`;throw new m(`Task "${e}" cannot start with uncommitted changes outside .ari: ${n.slice(0,Fg).join(", ")}${o}`,`Commit, stash or ignore them, then run 'ari start ${e}'; the scope gate counts every change since the start commit${i}`)}function RB(t,e){let{evidence:n,id:r}=t.record,o=n.findIndex((i,a)=>i.stage!==e.stages[a]?.name),s=n[o];if(s===void 0)return;throw new m(`Task "${r}" passed stage "${s.stage}", which pack "${e.name}" does not have as stage ${o+1}`,"Keep the pack that the passed stages belong to, or create a follow-up with 'ari new'")}async function IB(t,e){let n=e.filter((s)=>s.record.status==="ready"&&s.contract.lock.length>0),r=n.flatMap((s)=>s.contract.lock),o=Object.keys(await An(t,r));return new Map(n.flatMap((s)=>{let i=FE(s.contract,o);return i===void 0?[]:[[s.contract.id,i]]}))}function FE(t,e){return t.lock.find((n)=>!e.some((r)=>et(r,[n])))}function GE(t,e){let n=FE(t,Object.keys(e));if(n===void 0)return;throw new m(`Lock glob ${JSON.stringify(n)} of task "${t.id}" matches no file that git tracks or would track`,`Fix the lock list in ${It(t.id)}: escape [ ] { } * ? with a backslash, and lock only files that are not ignored`)}function Ug(t,e){let{tasks:n}=Pt(t.root,t.config),r=new Map(n.map((s)=>[s.contract.id,s.contract.depends]));r.set(e.id,e.depends.filter((s)=>s!==e.id));let o=kl(e.id,(s)=>r.get(s)??[]);return o===null?[]:[wl(o)]}function OB(t,e){let n=new Set(de(e));return t.depends.filter((r)=>r.trim().length>0&&r!==t.id&&!n.has(r)).map((r)=>`depends names the unknown task "${r}"`)}function _B(t,e){let n=new Set(de(t.root)),r=e.depends.filter((s)=>!n.has(s)||it(t.root,s,t.config).task.record.status!=="done");if(r.length===0)return;let o=Ug(t,e).map((s)=>`; ${s}`);throw new m(`Task "${e.id}" depends on unfinished tasks: ${r.join(", ")}${o.join("")}`,"Finish those tasks first; 'ari next' shows the order")}function PB(t,e){let n=gt(t.state);if(n===null||n.task===e||!de(t.root).includes(n.task))return;let{status:r}=it(t.root,n.task,t.config).task.record;if(r!=="active"&&r!=="blocked")return;throw new m(`Task "${n.task}" is already ${r} in this worktree; one task runs per worktree`,RE[r](n.task))}function HE(t){let e=gt(t.state);if(e!==null)return e.task;throw new m("No task is active in this worktree","Run 'ari next' to see what to do")}function UE(t){let e=HE(t),n=it(t.root,e,t.config),{question:r,status:o}=n.task.record;if(o==="active")return n;if(o==="blocked")throw new m(`Task "${e}" is blocked: ${r??"no question was recorded"}`,RE.blocked(e));throw new m(`Task "${e}" is ${o}, not active`,"Run 'ari next' to see what to do")}function KE(t,{contractText:e,task:n}){let{contract:r}=n;if(Bt(e)!==n.record.contractHash)throw new m(`The contract of "${r.id}" changed after it was frozen`,`Run 'ari amend ${r.id} --reason <text>' to accept the change`);if(bl(t,r)!==n.record.gatesHash)throw new m(`The gates of "${r.id}" changed after they were frozen: its pack, or the test globs, regression setup or review command of .ari/config.json`,`Run 'ari amend ${r.id} --reason <text>' to accept the change`)}function NB(t,e){if(t.stage===e.stage)return;throw new m(`Task "${e.id}" moved to another stage while its approval was recorded`,`Review the current stage, then run 'ari approve ${e.id}' again`)}function DB(t,e){if(pt(CE(t))===pt(CE(e)))return;throw new m(`Task "${e.id}" changed while its gates ran, so their result no longer applies`,"Run 'ari done' again; another ari command changed its status, stage, approvals, contract or frozen hashes")}function CE(t){let{approvals:e,attempts:n,base:r,contractHash:o,gatesHash:s,lockHashes:i,stage:a,stageTestHashes:c,status:l}=t,u=t.evidence.length;return{approvals:e,attempts:n,base:r,contractHash:o,gatesHash:s,lockHashes:i,stage:a,stageTestHashes:c,stages:u,status:l}}function LB(t,e){let n=e.flatMap((r)=>{let o=r.detail[ho];return r.type==="context"&&Array.isArray(o)?o:[]});return[...new Set([...t,...n])].sort(O)}function BE(t,e,n,r,o){let s=r.filter((i)=>!i.ok).map((i)=>i.gate);return{at:o,detail:{failing:s,ok:s.length===0,stage:n.name},task:e.contract.id,type:t}}var MB=20,jB=`
197
214
 
198
- `,R1=["advanced","done","failed"];async function jp(t,e={}){let n=await PT(t,e),r=n.outcome==="done"?await yr(t):null;return{...n,sleep:r}}async function WT(t,e){let n=L(t),r=(a)=>gr(n,{agent:e.agent,model:e.model,role:"task",route:I1(n,a)});for(let a of O1(n,e))gr(n,{agent:e.agent,model:e.model,role:"task",route:a});await Ln({config:n,root:t},"run an agent");let o=await N1(t,e),s=[],i=null;for(;;){let a=await $n(t,o),c=r(a.stage??""),l=await L1(t,o,i),u=a.task.record.history.length,d=await ja(c,l,{cwd:t,environment:Ma(c.config),stdout:e.output??"inherit",trust:{config:n,root:t}}),p=await _1(t,o,u)??await jp(t,{clock:e.clock}),m=p.gates.filter((f)=>!f.ok).map((f)=>f.gate);if(s.push({agent:c.name,agentExitCode:d.exitCode,failing:m,model:c.model,outcome:p.outcome,stage:p.stage,timedOut:d.timedOut}),p.outcome==="done"||p.outcome==="blocked")return{agent:e.agent??null,outcome:p.outcome,task:o,turns:s};i=p.outcome==="failed"?p:null}}function I1(t,e){return t.routing.stages[e]??t.routing.default}function O1(t,e){if(e.agent!==void 0)return[null];let n=[t.routing.default,...Object.values(t.routing.stages)].filter((r)=>r!==null);return n.length===0?[null]:n}async function _1(t,e,n){let r=await $n(t,e),{contract:o,record:s}=r.task,i=s.history.slice(n).findLast((c)=>R1.includes(c.type)),a=P1(s.status,i?.type);if(a===null)return null;return{attempts:s.attempts,budget:o.budget.attempts,gates:i?.type==="failed"?s.lastFailure?.gates??[]:[],outcome:a,stage:i?.stage??r.stage??""}}function P1(t,e){if(t==="done"||t==="blocked")return t;if(e==="failed")return"failed";return e==="advanced"?"advanced":null}async function N1(t,e){if(e.task===void 0)return D1(t,e.clock);let n=await $n(t,e.task),{question:r,status:o}=n.task.record,s=n.task.contract.id;switch(o){case"ready":return(await bo(t,s,{clock:e.clock})).task.contract.id;case"active":if(!n.active)await bo(t,s,{clock:e.clock});return s;case"blocked":throw new g(`Task "${s}" is blocked: ${r??"no question was recorded"}`,VT(s));case"draft":throw new g(`Task "${s}" is a draft`,`Complete its contract, then run 'ari ready ${s}'`);case"done":throw new g(`Task "${s}" is already done`,"Run 'ari next' to see what to do")}}async function D1(t,e){let n=await Rc(t);if(n.task!==null&&n.action==="continue")return n.task;if(n.task!==null&&n.action==="start")return(await bo(t,n.task,{clock:e})).task.contract.id;if(n.task!==null&&n.action==="resolve")throw new g(`Task "${n.task}" is blocked`,VT(n.task));throw new g(`No task can run: ${n.instruction}`,`Run ${n.commands.map((r)=>`'${r}'`).join(", ")}`)}function VT(t){return`A human answers it with 'ari resolve ${t} --answer <text>'`}async function L1(t,e,n){let r=await $n(t,e),o=(await ao(t,{id:e})).text,s=`Current stage: ${r.stage??"none"}. ${r.instruction??""}`.trim(),i=[`Work only inside the scope of task "${e}". Do not edit files under .ari/ other than the task contract.`,"When the stage's work is complete, stop. Ariadne then runs 'ari done' and sends you any failures."].join(`
199
- `),a=n===null?[]:[M1(n)];return[o,s,...a,i].join(C1)}function M1(t){let e=t.gates.filter((n)=>!n.ok).flatMap((n)=>j1(n));return[`'ari done' failed (attempt ${t.attempts} of ${t.budget}):`,...e].join(`
200
- `)}function j1(t){let e=t.details.slice(0,A1).map((r)=>` - ${r}`),n=t.checks.filter((r)=>!r.ok).map((r)=>` ${r.name} output:
201
- ${r.outputTail}`);return[`- ${t.gate}: ${t.summary}`,...e,...n]}var $r=["draft","ready","active","blocked","done"],F1="fact";function JT(t){return{id:t.contract.id,pack:t.contract.pack,status:t.record.status,title:t.contract.title}}async function Pc(t){return Rc(t)}async function Nc(t,e){let n=await Ic(t,e.length===0?{}:{statuses:e});return{invalid:n.invalid,tasks:n.tasks.map(JT)}}async function Dc(t,e){return $n(t,e)}async function Lc(t,e){let n=await IT(t,e.title,{pack:e.pack,scope:e.scope});return{contractPath:n.contractPath,...JT(n.task)}}async function Mc(t,e){let n=await OT(t,e);return{id:n.contract.id,status:n.record.status}}async function jc(t,e){let n=await bo(t,e),{record:r}=n.task;return{base:r.base,id:r.id,instruction:n.instruction,stage:n.stage}}async function Fc(t,e,n){let r=await DT(t,e,n);return{id:r.contract.id,question:r.record.question,status:r.record.status}}async function Gc(t){let e=await _T(t);return{data:{contractChanged:e.contractChanged,gates:e.gates,gatesChanged:e.gatesChanged,ok:e.ok,stage:e.stage,task:e.task.contract.id},failed:!e.ok}}async function Hc(t){let e=await jp(t);return{data:{attempts:e.attempts,budget:e.budget,gates:e.gates,next:e.next,outcome:e.outcome,sleep:e.sleep,stage:e.stage,task:e.task.contract.id},failed:e.outcome!=="done"&&e.outcome!=="advanced"}}async function Uc(t,e){let{global:n,kind:r,scope:o,text:s}=e;if(!n&&(r!==void 0||o!==void 0))throw new T("--kind and --scope apply only to knowledge entries","Add --global, or drop them");let i=r??F1;if(!Jk(i))throw new T(`--kind must be one of ${Qt.join(", ")}, got "${i}"`,"Pass --kind fact");if(n)return{entry:await Yk(t,{kind:i,scope:[...o??[]],text:s}),target:"knowledge"};let a=await jT(t,s),c=a.record.notes.length-1,l=a.record.notes[c];return{at:l?.at??"",index:c,target:"task",task:a.contract.id,text:l?.text??s}}async function Kc(t,e){let{budget:n}=e;if(n!==void 0&&(!Number.isInteger(n)||n<=0))throw new T(`--budget must be a positive whole number of tokens, got ${n}`,"Pass --budget 6000");return ao(t,{budget:n,id:e.id})}function Bc(t,e,n){return Xk(t,e,{all:n})}function qT(t){return t.map((e)=>{let n=$r.find((r)=>r===e);if(n!==void 0)return n;throw new T(`Unknown status "${e}"`,`Choose from ${$r.join(", ")}`)})}async function YT(t,e={}){let n=e.staged??!1,{config:r,drift:o,task:s}=await ya(t);if(s===null){let d=r.requireTask?"config.requireTask is true, but no task is active in this worktree":null;return{checked:[],ok:d===null,outside:[],reason:d,staged:n,task:null}}let i=Wt(n?await G1(t):await pe(t,s.record.base??"HEAD")),a=i.filter((d)=>!Z(d,s.contract.scope)),c=kt(a.length,"changed file lies","changed files lie"),l=a.length===0?null:`${a.length} ${c} outside the scope of "${s.contract.id}"`,u=i.length===0?null:o??l;return{checked:i,ok:u===null,outside:a,reason:u,staged:n,task:s.contract.id}}async function G1(t){let e=await P(t,["diff","--cached","--name-only","--no-renames","-z"]);return Oe(e.stdout)}var Fp=1,XT=E({description:"Print the one next action",examples:["ari next","ari next --json"],json:!0,name:"next",run:async(t)=>{t.output.result(await Pc(await O()),H1)}}),zT=E({description:"Evaluate the active task's current stage without recording an attempt",examples:["ari check"],json:!0,name:"check",run:async(t)=>{let e=await Gc(await O());return t.output.result(e.data,(n)=>{let r=n.ok?`Stage ${n.stage} passes`:`Stage ${n.stage} fails`,s=[...n.contractChanged?["contract"]:[],...n.gatesChanged?["gates (its pack, test globs, regression setup or review command)"]:[]].map((i)=>`The ${i} changed since it was frozen; run 'ari amend ${n.task} --reason <text>' before 'ari done'`);return[ba(n.gates),`${r} for "${n.task}"`,...s].join(`
202
- `)}),e.failed?Fp:void 0}}),ZT=E({description:"Evaluate the current stage's gates, record evidence and advance",examples:["ari done","ari done --json"],json:!0,name:"done",run:async(t)=>{let e=await Hc(await O());return t.output.result(e.data,U1),e.failed?Fp:void 0}}),QT=E({args:j({staged:{default:!1,description:"Check only staged files (the pre-commit hook)",type:"boolean"}}),description:"Check that changed files lie inside the active task's scope",examples:["ari scope","ari scope --staged"],json:!0,name:"scope",run:async(t)=>{let e=await YT(await O(),{staged:t.args.staged});return t.output.result(e,K1),e.ok?void 0:Fp}});function H1(t){return[t.instruction,...t.commands.map((e)=>` ${e}`)].join(`
203
- `)}function U1(t){switch(t.outcome){case"done":return`Task "${t.task}" is done`;case"advanced":return`Stage ${t.stage} passed. Next stage ${t.next?.stage??""}: ${t.next?.instruction??""}`;case"failed":return[ba(t.gates.filter((e)=>!e.ok)),`Stage ${t.stage} failed: attempt ${t.attempts} of ${t.budget}`].join(`
204
- `);case"blocked":return[ba(t.gates.filter((e)=>!e.ok)),`Task "${t.task}" is blocked: attempt budget exhausted; a human answers with 'ari resolve ${t.task} --answer <text>'`].join(`
205
- `)}}function K1(t){if(t.task===null)return t.ok?"No active task; scope passes":`Scope fails: ${t.reason??""}`;if(t.ok){let e=kt(t.checked.length,"changed file lies","changed files lie");return`${t.checked.length} ${e} inside the scope of "${t.task}"`}return[`${t.reason??""}:`,...t.outside.map((e)=>` ${e}`)].join(`
206
- `)}function tE(t,e,n){let r=`ari hooks ${t} --agent`;return E({args:j({agent:{description:`Agent: ${ep().join(", ")}`,type:"string"}}),description:e,examples:[`${r} claude`,`${r} git`],json:!0,name:t,run:async(o)=>{let s=Dn(o.args.agent,"--agent",`${r} <name>`);o.output.result(await n(await O(),s),V1)}})}var B1=E({description:"List the agents ari has hook adapters for and whether they are installed here",examples:["ari hooks list --json"],json:!0,name:"list",run:async(t)=>{let e=await eS(await O());t.output.result({agents:e},({agents:n})=>n.map(J1).join(`
207
- `))}}),eE=E({description:"Install, uninstall and list agent and git hook integrations",name:"hooks",subcommands:[tE("install","Install ari hooks into an agent's project settings or into git",mo),tE("uninstall","Remove ari hooks from an agent's project settings or from git, and nothing else",tS),B1]}),nE=E({description:"Answer an agent hook: reads the agent's JSON payload on stdin and prints its decision",examples:["ari hook claude before-edit < payload.json"],name:"hook",positionals:at({agent:{description:"Agent name",required:!0},event:{description:"before-edit, before-shell, after-tool, stop, pre-compact or session-start",required:!0}}),run:async(t)=>{let e=process.stdin.isTTY?"":await Bun.stdin.text(),n=await nS(t.positionals.agent,t.positionals.event,e,process.cwd());if(n.warning!==null)process.stderr.write(`${n.warning}
215
+ `,FB=["advanced","done","failed"];async function Kg(t,e={}){let n=await PE(t,e),r=n.outcome==="done"?await Mr(t):null,o=n.outcome==="advanced"?await Fo(t,n.task.contract.id,"stage",e):{id:null,warning:null};return{...n,sleep:r,snapshot:o.id,snapshotWarning:o.warning}}async function VE(t,e){let n=M(t),r=(a)=>Cr(n,{agent:e.agent,model:e.model,role:"task",route:GB(n,a)});for(let a of HB(n,e))Cr(n,{agent:e.agent,model:e.model,role:"task",route:a});await Xn({config:n,root:t},"run an agent");let o=await BB(t,e),s=[],i=null;for(;;){let a=await jn(t,o),c=r(a.stage??""),l=await WB(t,o,i),u=a.task.record.history.length,d=await Ya(c,l,{cwd:t,environment:qa(c.config),stdout:e.output??"inherit",trust:{config:n,root:t}}),p=await UB(t,o,u)??await Kg(t,{clock:e.clock}),g=p.gates.filter((f)=>!f.ok).map((f)=>f.gate);if(s.push({agent:c.name,agentExitCode:d.exitCode,failing:g,model:c.model,outcome:p.outcome,stage:p.stage,timedOut:d.timedOut}),p.outcome==="done"||p.outcome==="blocked")return{agent:e.agent??null,outcome:p.outcome,task:o,turns:s};i=p.outcome==="failed"?p:null}}function GB(t,e){return t.routing.stages[e]??t.routing.default}function HB(t,e){if(e.agent!==void 0)return[null];let n=[t.routing.default,...Object.values(t.routing.stages)].filter((r)=>r!==null);return n.length===0?[null]:n}async function UB(t,e,n){let r=await jn(t,e),{contract:o,record:s}=r.task,i=s.history.slice(n).findLast((c)=>FB.includes(c.type)),a=KB(s.status,i?.type);if(a===null)return null;return{attempts:s.attempts,budget:o.budget.attempts,gates:i?.type==="failed"?s.lastFailure?.gates??[]:[],outcome:a,stage:i?.stage??r.stage??""}}function KB(t,e){if(t==="done"||t==="blocked")return t;if(e==="failed")return"failed";return e==="advanced"?"advanced":null}async function BB(t,e){if(e.task===void 0)return VB(t,e.clock);let n=await jn(t,e.task),{question:r,status:o}=n.task.record,s=n.task.contract.id;switch(o){case"ready":return(await Xo(t,s,{clock:e.clock})).task.contract.id;case"active":if(!n.active)await Xo(t,s,{clock:e.clock});return s;case"blocked":throw new m(`Task "${s}" is blocked: ${r??"no question was recorded"}`,WE(s));case"draft":throw new m(`Task "${s}" is a draft`,`Complete its contract, then run 'ari ready ${s}'`);case"done":throw new m(`Task "${s}" is already done`,"Run 'ari next' to see what to do")}}async function VB(t,e){let n=await Sl(t);if(n.task!==null&&n.action==="continue")return n.task;if(n.task!==null&&n.action==="start")return(await Xo(t,n.task,{clock:e})).task.contract.id;if(n.task!==null&&n.action==="resolve")throw new m(`Task "${n.task}" is blocked`,WE(n.task));throw new m(`No task can run: ${n.instruction}`,`Run ${n.commands.map((r)=>`'${r}'`).join(", ")}`)}function WE(t){return`A human answers it with 'ari resolve ${t} --answer <text>'`}async function WB(t,e,n){let r=await jn(t,e),o=(await tr(t,{id:e})).text,s=`Current stage: ${r.stage??"none"}. ${r.instruction??""}`.trim(),i=[`Work only inside the scope of task "${e}". Do not edit files under .ari/ other than the task contract.`,"When the stage's work is complete, stop. Ariadne then runs 'ari done' and sends you any failures."].join(`
216
+ `),a=n===null?[]:[JB(n)];return[o,s,...a,i].join(jB)}function JB(t){let e=t.gates.filter((n)=>!n.ok).flatMap((n)=>qB(n));return[`'ari done' failed (attempt ${t.attempts} of ${t.budget}):`,...e].join(`
217
+ `)}function qB(t){let e=t.details.slice(0,MB).map((r)=>` - ${r}`),n=t.checks.filter((r)=>!r.ok).map((r)=>` ${r.name} output:
218
+ ${r.outputTail}`);return[`- ${t.gate}: ${t.summary}`,...e,...n]}async function JE(t,e={}){let n=e.task===void 0?void 0:qn(e.task),r=Ln(await P(t));return{entries:r.entries.filter((o)=>n===void 0||o.task===n).map(YB),unreadable:r.unreadable}}async function qE(t,e){let n=jo(await P(t),e),r=qo(n);return{entry:n,integrity:{ok:r.length===0,problems:r}}}function YB(t){let{at:e,id:n,kind:r,pruned:o,task:s}=t;if(t.kind==="restore")return{artifacts:t.written.map((i)=>i.path),at:e,estimatedTokens:null,id:n,kind:r,pruned:o,reason:null,restores:t.restores,stage:null,status:null,task:s,trigger:null};return{artifacts:t.artifacts.map((i)=>i.path),at:e,estimatedTokens:t.context.estimatedTokens,id:n,kind:r,pruned:o,reason:t.reason,restores:null,stage:t.record.stageName,status:t.record.status,task:s,trigger:t.trigger}}var Kr=["draft","ready","active","blocked","done"],XB="fact";function YE(t){return{id:t.contract.id,pack:t.contract.pack,status:t.record.status,title:t.contract.title}}async function $l(t){return Sl(t)}async function Tl(t,e){let n=await vl(t,e.length===0?{}:{statuses:e});return{invalid:n.invalid,tasks:n.tasks.map(YE)}}async function xl(t,e){return jn(t,e)}async function Al(t,e){let n=await IE(t,e.title,{pack:e.pack,scope:e.scope}),r=n.designs.length===0?{}:{designs:n.designs};return{contractPath:n.contractPath,...r,...YE(n.task)}}async function Cl(t,e){let n=await OE(t,e);return{id:n.contract.id,status:n.record.status}}async function Rl(t,e){let n=await Xo(t,e),{record:r}=n.task;return{base:r.base,id:r.id,instruction:n.instruction,stage:n.stage}}async function Il(t,e,n){let r=await DE(t,e,n);return{id:r.contract.id,question:r.record.question,status:r.record.status}}async function Ol(t){let e=await _E(t);return{data:{contractChanged:e.contractChanged,gates:e.gates,gatesChanged:e.gatesChanged,ok:e.ok,stage:e.stage,task:e.task.contract.id},failed:!e.ok}}async function _l(t){let e=await Kg(t),n={attempts:e.attempts,budget:e.budget,gates:e.gates,next:e.next,outcome:e.outcome,sleep:e.sleep,stage:e.stage,task:e.task.contract.id,...e.snapshot===null?{}:{snapshot:e.snapshot}},r=e.snapshotWarning===null?[]:[e.snapshotWarning],o=e.outcome!=="done"&&e.outcome!=="advanced";return{data:n,failed:o,...r.length===0?{}:{warnings:r}}}async function Pl(t,e){let{global:n,kind:r,scope:o,text:s}=e;if(!n&&(r!==void 0||o!==void 0))throw new v("--kind and --scope apply only to knowledge entries","Add --global, or drop them");let i=r??XB;if(!dS(i))throw new v(`--kind must be one of ${le.join(", ")}, got "${i}"`,"Pass --kind fact");if(n)return{entry:await gS(t,{kind:i,scope:[...o??[]],text:s}),target:"knowledge"};let a=await jE(t,s),c=a.record.notes.length-1,l=a.record.notes[c];return{at:l?.at??"",index:c,target:"task",task:a.contract.id,text:l?.text??s}}async function Nl(t,e){let{budget:n}=e;if(n!==void 0&&(!Number.isInteger(n)||n<=0))throw new v(`--budget must be a positive whole number of tokens, got ${n}`,"Pass --budget 6000");return tr(t,{budget:n,id:e.id})}function Dl(t,e,n){return mS(t,e,{all:n})}async function Ll(t,e){return Vp(t,e)}async function Ml(t,e){return JE(t,{task:e})}async function jl(t,e){return qE(t,e)}function XE(t){return t.map((e)=>{let n=Kr.find((r)=>r===e);if(n!==void 0)return n;throw new v(`Unknown status "${e}"`,`Choose from ${Kr.join(", ")}`)})}async function zE(t,e={}){let n=e.staged??!1,{config:r,drift:o,task:s}=await za(t);if(s===null){let d=r.requireTask?"config.requireTask is true, but no task is active in this worktree":null;return{checked:[],ok:d===null,outside:[],reason:d,staged:n,task:null}}let i=ne(n?await zB(t):await xe(t,s.record.base??"HEAD")),a=i.filter((d)=>!et(d,s.contract.scope)),c=wt(a.length,"changed file lies","changed files lie"),l=a.length===0?null:`${a.length} ${c} outside the scope of "${s.contract.id}"`,u=i.length===0?null:o??l;return{checked:i,ok:u===null,outside:a,reason:u,staged:n,task:s.contract.id}}async function zB(t){let e=await F(t,["diff","--cached","--name-only","--no-renames","-z"]);return Ke(e.stdout)}var Bg=1,ZE=E({description:"Print the one next action",examples:["ari next","ari next --json"],json:!0,name:"next",run:async(t)=>{t.output.result(await $l(await _()),ZB)}}),QE=E({description:"Evaluate the active task's current stage without recording an attempt",examples:["ari check"],json:!0,name:"check",run:async(t)=>{let e=await Ol(await _());return t.output.result(e.data,(n)=>{let r=n.ok?`Stage ${n.stage} passes`:`Stage ${n.stage} fails`,s=[...n.contractChanged?["contract"]:[],...n.gatesChanged?["gates (its pack, test globs, regression setup or review command)"]:[]].map((i)=>`The ${i} changed since it was frozen; run 'ari amend ${n.task} --reason <text>' before 'ari done'`);return[oc(n.gates),`${r} for "${n.task}"`,...s].join(`
219
+ `)}),e.failed?Bg:void 0}}),t$=E({description:"Evaluate the current stage's gates, record evidence and advance",examples:["ari done","ari done --json"],json:!0,name:"done",run:async(t)=>{let e=await _l(await _());for(let n of e.warnings??[])process.stderr.write(`${n}
220
+ `);return t.output.result(e.data,QB),e.failed?Bg:void 0}}),e$=E({args:j({staged:{default:!1,description:"Check only staged files (the pre-commit hook)",type:"boolean"}}),description:"Check that changed files lie inside the active task's scope",examples:["ari scope","ari scope --staged"],json:!0,name:"scope",run:async(t)=>{let e=await zE(await _(),{staged:t.args.staged});return t.output.result(e,e2),e.ok?void 0:Bg}});function ZB(t){return[t.instruction,...t.commands.map((e)=>` ${e}`)].join(`
221
+ `)}function QB(t){let e=t.snapshot===void 0?[]:[`Snapshot ${t.snapshot} saved`];return[t2(t),...e].join(`
222
+ `)}function t2(t){switch(t.outcome){case"done":return`Task "${t.task}" is done`;case"advanced":return`Stage ${t.stage} passed. Next stage ${t.next?.stage??""}: ${t.next?.instruction??""}`;case"failed":return[oc(t.gates.filter((e)=>!e.ok)),`Stage ${t.stage} failed: attempt ${t.attempts} of ${t.budget}`].join(`
223
+ `);case"blocked":return[oc(t.gates.filter((e)=>!e.ok)),`Task "${t.task}" is blocked: attempt budget exhausted; a human answers with 'ari resolve ${t.task} --answer <text>'`].join(`
224
+ `)}}function e2(t){if(t.task===null)return t.ok?"No active task; scope passes":`Scope fails: ${t.reason??""}`;if(t.ok){let e=wt(t.checked.length,"changed file lies","changed files lie");return`${t.checked.length} ${e} inside the scope of "${t.task}"`}return[`${t.reason??""}:`,...t.outside.map((e)=>` ${e}`)].join(`
225
+ `)}function n$(t,e,n){let r=`ari hooks ${t} --agent`;return E({args:j({agent:{description:`Agent: ${ng().join(", ")}`,type:"string"}}),description:e,examples:[`${r} claude`,`${r} git`],json:!0,name:t,run:async(o)=>{let s=ln(o.args.agent,"--agent",`${r} <name>`);o.output.result(await n(await _(),s),o2)}})}var n2=E({description:"List the agents ari has hook adapters for and whether they are installed here",examples:["ari hooks list --json"],json:!0,name:"list",run:async(t)=>{let e=await Uv(await _());t.output.result({agents:e},({agents:n})=>n.map(s2).join(`
226
+ `))}}),r$=E({description:"Install, uninstall and list agent and git hook integrations",name:"hooks",subcommands:[n$("install","Install ari hooks into an agent's project settings or into git",Ho),n$("uninstall","Remove ari hooks from an agent's project settings or from git, and nothing else",Hv),n2]}),o$=E({description:"Answer an agent hook: reads the agent's JSON payload on stdin and prints its decision",examples:["ari hook claude before-edit < payload.json"],name:"hook",positionals:st({agent:{description:"Agent name",required:!0},event:{description:"before-edit, before-shell, after-tool, stop, pre-compact or session-start",required:!0}}),run:async(t)=>{let e=process.stdin.isTTY?"":await Bun.stdin.text(),n=await Kv(t.positionals.agent,t.positionals.event,e,process.cwd());if(n.warning!==null)process.stderr.write(`${n.warning}
208
227
  `);if(n.stdout.length>0)process.stdout.write(`${n.stdout}
209
- `);if(n.expired)await W1()}});async function W1(){return await new Promise((t)=>process.stdout.write("",()=>t())),process.exit()}function V1(t){if("files"in t)return t.files.map((n)=>`git ${n.hook}: ${n.action} (${n.path})`).join(`
210
- `);let e="events"in t?`: ${t.events.join(", ")}`:"";return`${t.agent} hooks ${t.action} in ${t.file}${e}`}function J1(t){let e=t.installed?"installed":"not installed";return`${t.agent} ${t.support} ${e} ${t.file} ${t.events.join(", ")}`}var rE=E({args:j({agents:{description:"Install agent hooks, comma-separated (claude,codex,gemini,cursor,copilot,git)",type:"string"},gitHooks:{default:!1,description:"Install the pre-commit and pre-push git hooks",type:"boolean"},mcp:{description:"Register ari's MCP server, comma-separated (claude,codex,gemini,cursor)",type:"string"},pack:{description:"Default methodology pack for new tasks",type:"string"},skills:{description:"Install the ariadne skill, comma-separated (claude,codex,gemini,cursor)",type:"string"}}),description:"Create .ari/ and the AGENTS.md block, and optionally install hooks, MCP servers and skills",examples:["ari init","ari init --pack tdd --agents claude,codex --git-hooks","ari init --agents claude --mcp claude --skills claude"],json:!0,name:"init",run:async(t)=>{let e=await O(),n=await ur(e,()=>ES(e,{agents:wn(t.args.agents),gitHooks:t.args.gitHooks,mcp:wn(t.args.mcp),pack:t.args.pack,skills:wn(t.args.skills)}));t.output.result(n,q1)}});function q1(t){let e=t.hooks.flatMap((n)=>("files"in n)?n.files.map((r)=>`git ${r.hook}: ${r.action} (${r.path})`):[`${n.agent} hooks: ${n.action} (${n.file})`]);return[`.ari/config.json: ${t.config} (pack ${t.pack})`,`${t.agentsMd.path}: ${t.agentsMd.action}`,...e,...t.mcp.map((n)=>`${n.agent} MCP server: ${n.action} (${n.file})`),...t.skills.map((n)=>`${n.agent} skill: ${n.action} (${n.file})`),'Next: ari new "<title>"'].join(`
211
- `)}var Y1="--hooks, --mcp, --skills or --git-hooks";function oE(t){let e=new Set([...t.hooks===!0?["hooks"]:[],...t.mcp===!0?["mcp"]:[],...t.skills===!0?["skill"]:[],...t.gitHooks===!0?["git"]:[]]);return{agents:t.agent===void 0?void 0:z1(t.agent),init:t.init,kinds:e.size===0?void 0:e,pack:Us(t.pack,"--pack"),routing:Z1(t),scope:t.scope===void 0?void 0:ho(t.scope)}}function sE(t){return Object.values(t).some((e)=>e!==void 0)}function Gp(t,e){return[...Hn.filter((r)=>e.has(r)).flatMap((r)=>t.map((o)=>wt(r,o))),...e.has("git")?[je]:[]]}function Hp(t,e,n){let r=[],o=e.init===!0||e.pack!==void 0;if(!t.initialised&&!o)r.push("--init");let s=e.kinds!==void 0&&[...e.kinds].every((u)=>u==="git"),i=e.agents??(s||!n?[]:wc(t)),a=n&&e.agents===void 0&&!s&&i.length===0;if(e.agents===void 0&&!s&&(!n||a))r.push("--agent");if(e.kinds===void 0&&!n)r.push(Y1);if(r.length>0)throw X1(r,a);let c=e.scope??"project",l=e.kinds===void 0;return{agents:i,init:o,pack:e.pack??null,recommended:l,routing:e.routing??null,scope:c,targets:l?DS(t,i,c,o):Gp(i,e.kinds??new Set)}}function X1(t,e){let n=t.join(" and ");return new T(`ari install needs ${n} when it cannot ask${e?"; no agent was found on PATH":""}`,`For example: ari install ${t.includes("--init")?"--init ":""}--agent claude,codex --yes. --yes installs every supported target; see 'ari install --help'`)}function z1(t){let e=[...new Set(t.split(",").map((n)=>n.trim()).filter((n)=>n.length>0))];if(e.length===0)throw new T("--agent needs at least one agent",`Choose from: ${et.join(", ")}`);return e.map((n)=>{if(kc(n))return n;throw new T(`ari install has no agent "${n}"`,`Choose from: ${et.join(", ")}`)})}function Z1(t){let e=Us(t.taskAgent,"--task-agent"),n=Us(t.reviewAgent,"--review-agent"),r=Us(t.taskModel,"--task-model"),o=Us(t.reviewModel,"--review-model");if(e===void 0&&n===void 0){let s=r!==void 0?"--task-model":o!==void 0?"--review-model":null;if(s===null)return;throw new T(`${s} needs --task-agent and --review-agent`,"Pass both agents to set the routing")}if(e===void 0||n===void 0)throw new T(`Routing needs ${e===void 0?"--task-agent":"--review-agent"} as well`,"Pass --task-agent and --review-agent together");return{review:{agent:n,model:o??null},task:{agent:e,model:r??null}}}function Us(t,e){if(t===void 0)return;let n=t.trim();if(n.length>0)return n;throw new T(`${e} must not be empty`,`Leave ${e} out, or give it a value`)}import{join as lE}from"path";import{isDeepStrictEqual as Kp}from"util";var Q1=1,tH=":",iE="routing.default",eH="review.agent";function cE(t,e){let n=Vt(Q,t),r=Up(n,"agents"),o=Up(n,"routing"),s=Up(n,"review"),i=nH(r,e),a=i.flatMap(({entry:m,name:f})=>m===null?[]:[[f,m]]),c=iH(o.default,iE,e.task)?o.default:sH(e.task),l=aH(s,e.review)?s:cH(s,e.review),u={...n,agents:{...r,...Object.fromEntries(a)},review:l,routing:{...o,default:c}},d=Bi(u);if(d!==null)throw new g(`ari cannot set the routing: ${d}`,`Fix ${Q}, then run 'ari install' again`,1,{tag:"InvalidConfig"});return{changes:[...i.map(({action:m,name:f,roles:y})=>({action:m,agent:f,detail:`${y.join(" and ")} agent`,key:`agents.${f}`})),{action:aE(o.default,c),agent:e.task.agent,detail:`tasks: ${br(e.task)}`,key:iE},{action:aE(s.agent===void 0?void 0:s,l),agent:e.review.agent,detail:`reviews: ${br(e.review)}`,key:eH}],next:Nn(t,u)}}function nH(t,e){let n=new Map;for(let[r,o]of[[e.task,"task"],[e.review,"review"]])n.set(r.agent,[...n.get(r.agent)??[],o]);return[...n].map(([r,o])=>rH(r,o,t[r]))}function br(t){return t.model===null?`${t.agent} (CLI default model)`:`${t.agent} (${t.model})`}function rH(t,e,n){let r=Ie.find((l)=>l.name===t),o=e.length>1?"both":e[0]??"task";if(n===void 0){if(r!==void 0)return{action:"created",entry:jr(r,o,void 0),name:t,roles:e};throw new T(`No agent named "${t}" is configured, and ari has no preset of that name`,`Choose a configured agent, or one of the presets: ${Ie.map((l)=>l.name).join(", ")}`)}let s=oH(n);if(e.every((l)=>s.includes(l)))return{action:"unchanged",entry:null,name:t,roles:e};let i=Y(n)&&typeof n.model==="string"?n.model:void 0,a=r!==void 0&&Mr.some((l)=>Kp(n,jr(r,l,i)));if(r!==void 0&&a)return{action:"updated",entry:jr(r,"both",i),name:t,roles:e};let c=e.filter((l)=>!s.includes(l));throw new g(`agents.${t} has no ${c.join(" or ")} role`,`Add ${c.map((l)=>`"${l}"`).join(" and ")} to agents.${t}.roles in ${Q}, or choose another agent`,Q1,{tag:"AgentRoleMismatch"})}function oH(t){if(!Y(t)||!Array.isArray(t.roles))return ru;return t.roles.filter((e)=>typeof e==="string")}function Up(t,e){let n=t[e];return Y(n)?n:{}}function sH(t){return t.model===null?t.agent:`${t.agent}${tH}${t.model}`}function iH(t,e,n){if(t===void 0||t===null)return!1;try{return Kp(qo(t,e),n)}catch{return!1}}function aH(t,e){return t.agent===e.agent&&(t.model??null)===e.model}function cH(t,e){let{model:n,...r}=t;return{...r,agent:e.agent,...e.model===null?{}:{model:e.model}}}function aE(t,e){if(t===void 0||t===null)return"created";return Kp(t,e)?"unchanged":"updated"}var lH=new Set(["created","updated","unchanged"]),uH="Fix the cause, then run 'ari install' again; it keeps what is already done";async function Vc(t,e,n,r={}){let o={mode:n,plan:e,root:t,scopes:await wH(t),view:kH(n)},s=[],i=!1;for(let a of e.targets){if(i||a.skip!==null){s.push(Ks(a,i?"pending":"skipped",i?null:a.skip));continue}r.start?.(a);try{let c=await dH(o,a);s.push(...c),r.done?.(a,c)}catch(c){let l={...Ks(a,"failed",TH(c)),hint:EH(c)};s.push(l),r.failed?.(a,l),i=!0}}return{failed:i,rows:s}}async function dH(t,e){if(e.id===wp)return[Wc(e,pH(t))];if(e.id===Un)return[Wc(e,gH(t))];let{agent:n}=e;switch(e.kind){case"hooks":return[Wc(e,await mH(t,uE(n)))];case"mcp":case"skill":return[Wc(e,fH(t,e.kind,uE(n),e.scope))];case"git":return hH(t,e);case"routing":return yH(t,e);case"config":throw Error(`ari has no configuration target "${e.id}"`)}}function pH({mode:t,plan:e,root:n,view:r}){if(t==="apply")return dp(n,e.pack);return Jc(r,n,Q,(o)=>pp(o,e.pack))}function gH({mode:t,root:e,view:n}){if(t==="apply")return up(e).action;return Jc(n,e,_t,Fs)}async function mH({mode:t,root:e,view:n},r){let o=Se(r);if(t==="preview")return Jc(n,e,o.file,(i)=>fs(o,i));let s=await mo(e,r);return"action"in s?s.action:"unchanged"}function fH({mode:t,scopes:e,view:n},r,o,s){let i=e[s];if(t==="apply")return r==="mcp"?ko(ne(o),i).action:wo(re(o),i).action;let a=r==="mcp"?Te(ne(o),i):Ee(re(o),i);return Jc(n,a.base,a.file,(c)=>a.install(c))}async function hH({mode:t,root:e},n){return(t==="apply"?(await Aa(e)).files:await ds(e)).map(({action:o,path:s})=>({...Ks(n,Bp(o),null),file:s}))}function yH({mode:t,plan:e,root:n,view:r},o){let s=e.routing;if(s===null)return[];let i=t==="apply"?q(n,Q):r.read(n,Q);if(i===null)throw new g(`${Q} does not exist, so ari cannot set the routing`,"Run 'ari init' first");let a=cE(i,s);if(t==="apply")fe(n,Q,a.next);else r.write(n,Q,a.next);return a.changes.map((c)=>({...Ks(o,Bp(c.action),null),agent:c.agent,detail:c.detail,key:c.key}))}function Jc(t,e,n,r){let o=t.read(e,n),s=r(o);return t.write(e,n,s),ss(o,s)}function kH(t){let e=new Map;return{read:(n,r)=>e.get(lE(n,r))??q(n,r),write:(n,r,o)=>{if(t==="preview")e.set(lE(n,r),o)}}}async function wH(t){return{project:{base:t,receipts:await M(t),scope:"project"},user:await Ot("user",t)}}function Wc(t,e){return Ks(t,Bp(e),null)}function Ks(t,e,n){let r=t.file===null?null:t.file;return{action:e,agent:t.agent,detail:null,file:r===null?null:SH(t.scope,r),hint:null,key:null,kind:t.kind,reason:n,scope:t.scope,undo:lH.has(e)?bS(t):null}}function SH(t,e){return t==="user"&&!e.startsWith("~/")?ee(t,e):e}function Bp(t){return t==="removed"?"updated":t}function uE(t){if(t!==null)return t;throw Error("This target needs an agent")}function TH(t){return t instanceof Error?t.message:String(t)}function EH(t){if(t instanceof g&&t.hint!==void 0&&t.hint.length>0)return t.hint;return uH}import{rmSync as $H}from"fs";var bH="knowledge",dE="Every 'ari sleep' pass and '--apply' writes an entry under <git-path>/ari/sleep/",vH=()=>new Date().toISOString();async function gE(t,e,n={}){let r=await M(t),o=(n.clock??vH)();return fr(r,()=>{let s=hE(t,r,e);for(let c of s.restore)rs(ye(t,c.id),Wd(c.original));for(let c of s.remove)$H(ye(t,c.id),{force:!0});for(let{notes:c,task:l}of s.unpromote)Ft(t,r,l,(u)=>kh(u,c));let i=yE(s),a=lo(r,o,{kind:"undo",removed:i.removed,restored:i.restored,undoes:s.target.id,unpromoted:i.unpromoted});return{...i,ledger:a.id}})}async function mE(t,e){let n=await M(t);return{...yE(hE(t,n,e)),dryRun:!0}}async function fE(t,e){let n=As(t,e);if(n.status==="active")throw new g(`Knowledge entry "${e}" is already active`,"Run 'ari knowledge list --all' to see archived entries");let r=await M(t);return fr(r,()=>{let o=ye(t,e),s=uo(o),i=_s(r),a=Ps(i),c=i.filter(co).filter((l)=>!a.has(l.id)).reverse().flatMap((l)=>l.archived).find((l)=>l.id===e&&l.sha256===s)?.original;if(c===void 0)xs(t,{...n,status:"active",supersededBy:null});else rs(o,Wd(c));return As(t,e)})}function hE(t,e,n){let r=xH(_s(e),n),o=[],s=r.archived.filter((a)=>{let c=Vd(ye(t,a.id));if(c===a.sha256)return!0;if(c!==a.original.sha256)o.push(`${pE(a.id)} ${c===null?"is missing":"changed after sleep archived it"}`);return!1}),i=r.created.filter((a)=>{let c=Vd(ye(t,a.id));if(c===null)return!1;if(c===a.sha256)return!0;return o.push(`${pE(a.id)} changed after sleep created it`),!1});if(o.length>0){let a=o.map((c)=>` - ${c}`).join(`
212
- `);throw new g(`Cannot undo sleep entry ${r.id}; ${o.length} file(s) are not as it left them:
213
- ${a}`,"Nothing was changed. Restore those files from git, undo the later sleep entries first, or use 'ari knowledge restore <id>' for a single entry")}return{remove:i,restore:s,target:r,unpromote:AH(t,r.promoted)}}function xH(t,e){let n=Ps(t);if(e===void 0){let s=t.filter(co).findLast((i)=>!n.has(i.id)&&qc(i));if(s!==void 0)return s;throw new g("The sleep ledger has no entry that changed knowledge and is not undone yet",dE)}let r=Bd(e)?t.find((s)=>s.id===e):void 0;if(r===void 0){let s=t.length===0?"none yet":t.map((i)=>i.id).join(", ");throw new g(`The sleep ledger has no entry "${e}"`,`Known entries: ${s}`)}if(!co(r))throw new g(`Ledger entry ${e} records an undo itself`,"Run 'ari sleep' or 'ari knowledge restore <id>' instead");let o=n.get(e);if(o!==void 0)throw new g(`Sleep entry ${e} was already undone by ${o}`,dE);if(!qc(r))throw new g(`Sleep entry ${e} changed no knowledge entry, so there is nothing to undo`,"Journals that sleep pruned cannot be restored");return r}function qc(t){return t.archived.length>0||t.created.length>0||t.promoted.length>0}function AH(t,e){let n=new Set(hn(t));return e.flatMap(({notes:r,task:o})=>{if(!n.has(o))return[];let s=yn(t,o),i=r.filter((a)=>s.notes[a]?.promoted===!0);return i.length===0?[]:[{notes:i,task:o}]})}function yE(t){return{journalsNotRestored:t.target.pruned.map((e)=>e.task),removed:t.remove.map(({id:e,sha256:n})=>({id:e,sha256:n})),restored:t.restore.map(({id:e,original:n})=>({id:e,sha256:n.sha256})),undoes:t.target.id,unpromoted:t.unpromote}}function pE(t){return`${W}/${bH}/${t}.md`}var CH=3,kE=new Set(["active","blocked"]);async function wE(t){let e=Yc(()=>L(t));if(e===null)return[];let n=await M(t),r=Yc(()=>It(t,e)),o=r?.tasks??[],s=Yc(()=>ut(n))?.task??null,i=await RH(t,o,s),a=o.some((l)=>l.contract.id===s&&kE.has(l.record.status));return["ari next",...o.length+(r?.invalid.length??0)>0?["ari list"]:[],...i.slice(0,CH).map((l)=>`ari start ${l}`),...a?["ari context"]:[],...await OH(t,n)]}async function RH(t,e,n){let r=e.filter((s)=>kE.has(s.record.status)&&s.contract.id!==n);if(r.length===0)return[];let o=await IH(t);return r.map((s)=>s.contract.id).filter((s)=>!o.has(s))}async function IH(t){try{return await Hs(t)}catch{return new Map}}async function OH(t,e){let n=await NH(()=>_H(t)),r=Yc(()=>PH(e));return[...n===!0?["ari sleep"]:[],...r===!0?["ari sleep --undo"]:[]]}async function _H(t){return Fn(await kr(t,{candidates:!1})).due}function PH(t){let e=_s(t),n=Ps(e);return e.some((r)=>co(r)&&!n.has(r.id)&&qc(r))}async function NH(t){try{return await t()}catch(e){if(e instanceof g)return null;throw e}}function Yc(t){try{return t()}catch(e){if(e instanceof g)return null;throw e}}import{homedir as DH}from"os";var Bs=72,LH="ari install",MH="ari uninstall",SE=44,jH=28,TE=8,FH="Kept: .ari/ data, the AGENTS.md block, routing and trust",GH=[["ari next","what to do now"],["ari list","every task and where it stands"],["ari start ","adopt a task that no worktree holds"],["ari context","the context pack of the active task"],["ari sleep --undo","undo the last memory consolidation"],["ari sleep","consolidate memory, which is due"]],bE=['ari new "Describe the first task"',"ari next"],Vp=20,EE=26,Wp=13,vE=8,vr=11,xE=34,$E=12,HH=/\d+(?:\.\d+)+[\w.+-]*/,AE="\u2026",UH="~",Xc=".ari/config.json",CE=new Set(["created","updated"]),Ht=" ",KH=`${k.green("\u2713")} installed ${k.yellow("\u2191")} update ${k.dim("\xB7")} not installed ${k.dim("\u2013")} not supported`,BH={created:"create",failed:"fail",pending:"not run",skipped:"skip",unchanged:"unchanged",updated:"update"};function RE(t,e){let n=t.initialised?`set up, pack ${t.pack??"basic"}`:`not set up yet (${k.yellow(".ari/config.json is missing")})`,r=t.targets.find((a)=>a.id==="agents-md"),o=[vo("Repository",oU(t.root)),vo("Ariadne",`${e} \xB7 ${n}`),...r===void 0?[]:[vo("AGENTS.md",`${DE(r)} ari block`)],...eU(t),vo("Git hooks",nU(t))],s=k.dim([nt("Agent",Vp),nt("On PATH",Wp),...Hn.map((a)=>nt(rU(a),vE))].join("")),i=et.map((a)=>QH(t,Pt(t,a)));return[...o,"",s,...i,"",KH].map($e).join(`
214
- `)}function IE(t,e,n){let r=new Map,o=[];for(let c of t){if(c.kind==="routing")continue;if(c.action==="skipped"){let u=xr(c.reason??"",Bs-Ht.length*2).map((d)=>`${Ht}${Ht}${k.dim(d)}`);o.push(`${Ht}${Bn(e,c)}`,...u);continue}let l=ZH(e,c);r.set(l,[...r.get(l)??[],YH(c)])}let s=[...r].flatMap(([c,l])=>[k.bold(c),...l]),i=n===null?[]:zH(t,n),a=o.length===0?[]:[k.bold("Skipped"),...o];return[...s,...i,...a].map($e).join(`
215
- `)}function OE(t,e){let[n]=e;if(n===void 0)return"";if(n.kind==="routing"){let o=e.filter((i)=>CE.has(i.action)).map((i)=>i.key??""),s=o.length===0?"unchanged":"updated";return $e(`${nt("Routing",EE)}${xo(s,!1)}${o.join(", ")||Xc}`)}let r=e.map((o)=>o.file??"").join(", ");return $e(`${nt(Bn(t,n),EE)}${xo(n.action,!1)}${r}`)}function _E(t){return t.map((e)=>{let n=e.ok?k.green("\u2713"):k.red("\u2717"),r=e.ok?k.dim(e.detail):k.red(e.detail);return $e(`${n} ${nt(e.name,Vp)}${r}`)}).join(`
216
- `)}function Ar(t,e){return[...xr(t,Bs),...xr(e,Bs).map((r)=>k.dim(r))].join(`
217
- `)}function xr(t,e){let n=[];for(let r of t.split(`
218
- `)){let o="";for(let s of r.split(" ")){let i=o.length===0?s:`${o} ${s}`;if(Bun.stringWidth(i)>e&&o.length>0)n.push(o),o=s;else o=i}if(o.length>0)n.push(o)}return n}function Jp(t){let e=["created","updated","unchanged","skipped","failed","pending"].map((o)=>[o,t.targets.filter((s)=>s.action===o).length]).filter(([,o])=>o>0).map(([o,s])=>`${s} ${o==="pending"?"not run":o}`),n=t.checks.filter((o)=>!o.ok).length,r=t.checks.length===0?[]:[`${t.checks.length-n} of ${t.checks.length} checks passed`];return[e.join(" \xB7 "),...r,"",k.bold("Next"),...t.next.map((o)=>`${Ht}${o}`)].map($e).join(`
219
- `)}function qp(t){let e=new Set,n=t.targets.flatMap((o)=>{if(o.undo===null||e.has(o.undo))return[];return e.add(o.undo),[`${nt(o.undo,SE)}${WH(o)}`]});if(n.length===0)return[];let r=n.length-TE;return[`${nt(MH,SE)}everything ari installed`,...n.slice(0,TE),...r>0?[`and ${r} more: see "undo" in --json`]:[],FH].map($e)}function Yp(t){return t.resume.map((e)=>$e(`${nt(e,jH)}${VH(e)}`))}function WH(t){if(t.kind==="git")return"git hooks";let e=t.kind==="hooks"||t.kind==="mcp"||t.kind==="skill"?Fe[t.kind]:t.kind;return`${t.agent??""} ${e}`.trim()}function VH(t){return GH.find(([n])=>n.endsWith(" ")?t.startsWith(n):t===n)?.[1]??""}function JH(t){let e=qp(t),n=Yp(t);return[...e.length===0?[]:["","To undo",...e.map((r)=>`${Ht}${r}`)],...n.length===0?[]:["","To get back to your tasks",...n.map((r)=>`${Ht}${r}`)]]}function PE(t){let e=t.targets.map((a)=>{let c=[a.agent,a.kind,a.key].filter((d)=>d!==null).join(" "),l=a.reason===null?"":`: ${a.reason}`,u=a.hint===null?"":` (${a.hint})`;return`${nt(a.action,vr)}${nt(a.file??"-",xE)} ${c}${l}${u}`}),n=t.warnings.flatMap((a)=>[`warning: ${a.message}`,` ${a.fix}`]),r=t.check?Ip(t.checks.map((a)=>$c(a,LH))):t.checks.map((a)=>`check ${a.ok?"ok":"FAILED"}: ${a.name}: ${a.detail}${a.hint===null?"":` (${a.hint})`}`),o=t.check?[qH(t)]:t.dryRun?["Dry run: nothing was written"]:t.upToDate?["Everything is up to date"]:[],s=t.ok&&!t.dryRun,i=s?t.next.map((a)=>`next: ${a}`):[];return[...e,...n,...r,...o,...i,...s?JH(t):[]].join(`
220
- `)}function qH(t){if(t.ok)return"Up to date: nothing would change and every check passed";return t.upToDate?"Up to date, but a check failed":"Not up to date"}function Bn(t,e){if(e.kind==="git")return"git hooks";if(e.kind==="config")return e.file==="AGENTS.md"?"ari block":"configuration";if(e.kind==="routing")return"routing";return`${e.agent===null?"":`${NE(t,e.agent)} `}${Fe[e.kind]}`}function xo(t,e){let n=nt(e?BH[t]:t,vr);switch(t){case"created":return k.green(n);case"updated":return k.yellow(n);case"failed":return k.red(n);case"unchanged":case"skipped":case"pending":return k.dim(n)}}function $e(t){if(Bun.stringWidth(t)<=Bs)return t;return`${Bun.sliceAnsi(t,0,Bs-1)}${AE}`}function zc(t){if(t.path===null)return"not found";let e=HH.exec(t.version??"")?.[0]??t.version??"found";return e.length>$E?`${e.slice(0,$E-1)}${AE}`:e}function YH(t){let e=t.kind==="config"&&t.file==="AGENTS.md"?"ari block":XH[t.kind],n=t.action==="failed"?k.red(t.reason??""):k.dim(e);return`${Ht}${xo(t.action,!0)}${nt(t.file??"",xE)} ${n}`}var XH={config:"configuration",git:"git hook",hooks:"hooks",mcp:"MCP server",routing:"routing",skill:"skill"};function zH(t,e){let n=t.filter((l)=>l.kind==="routing"),r=n.find((l)=>l.action==="failed"),o=n.some((l)=>l.action==="pending"),s=(l)=>n.filter((u)=>(u.key??"").startsWith(l)&&CE.has(u.action)).map((u)=>u.key??""),i=s("agents."),a=[...s("routing."),...s("review.")],c=r!==void 0?[`${Ht}${xo("failed",!0)}${k.red(r.reason??"")}`]:o?[`${Ht}${xo("pending",!0)}${Xc}`]:i.length+a.length===0?[`${Ht}${xo("unchanged",!0)}${Xc}`]:[...i.length===0?[]:[`${Ht}${k.green(nt("add",vr))}${i.join(", ")}`],...a.length===0?[]:[`${Ht}${k.yellow(nt("set",vr))}${a.join(", ")}`]];return[`${k.bold("Routing")} ${k.dim(Xc)}`,`${Ht}${nt("tasks",vr)}${br(e.task)}`,`${Ht}${nt("reviews",vr)}${br(e.review)}`,...c]}function ZH(t,e){if(e.agent!==null)return NE(t,e.agent);return e.kind==="git"?"Git hooks":"Repository"}function NE(t,e){return t.agents.find((n)=>n.agent===e)?.label??e}function QH(t,e){let n=e.path===null?k.dim(nt("not found",Wp)):nt(zc(e),Wp),r=Hn.map((o)=>nt(tU(t,e.agent,o),vE));return[nt(e.label,Vp),n,...r].join("")}function tU(t,e,n){if(!Pt(t,e).kinds.includes(n))return k.dim("\u2013");let r=t.targets.filter((i)=>i.agent===e&&i.kind===n);if(r.some((i)=>i.problem!==null))return k.red("!");let o=r.filter((i)=>i.status!=="missing");if(o.length===0)return k.dim("\xB7");let s=o.some((i)=>i.status==="outdated")?k.yellow("\u2191"):k.green("\u2713");if(o.length>1)return`${s} both`;return o[0]?.scope==="user"?`${s} user`:s}function eU(t){let{review:e,task:n}=t.routing;if(n===null&&e===null)return[];let r=n===null?"tasks: not set":`tasks ${br(n)}`,o=e===null?"reviews: not set":`reviews ${br(e)}`;return[vo("Routing",r),vo("",o)]}function nU(t){if(t.hookManager!==null)return k.dim(`managed by ${t.hookManager.name}`);let e=t.targets.find((n)=>n.id==="git");if(e===void 0)return k.dim("\xB7");if(e.problem!==null)return`${k.red("!")} ${e.problem.message}`;return`${DE(e)} ${e.status==="missing"?"not installed":"pre-commit, pre-push"}`}function DE(t){if(t.problem!==null)return k.red("!");if(t.status==="current")return k.green("\u2713");return t.status==="outdated"?k.yellow("\u2191"):k.dim("\xB7")}function rU(t){return t==="mcp"?"MCP":t==="hooks"?"Hooks":"Skill"}function vo(t,e){return`${nt(t,vr+1)}${e}`}function oU(t){let e=DH();return t===e||t.startsWith(`${e}/`)?`${UH}${t.slice(e.length)}`:t}function nt(t,e){let n=Bun.stringWidth(t);return n>=e?`${t} `:`${t}${" ".repeat(e-n)}`}var sU="install plan",iU=new Set(["created","updated"]),aU=/^[\w@%+=:,./-]+$/,Xp=6;function LE(t,e,n){let r=e.filter((a)=>iU.has(a.action));if(r.length===0)return null;let o=[...new Set(r.map((a)=>Bn(t,a)))],s=o.slice(0,Xp).join(", "),i=o.length>Xp?` and ${o.length-Xp} more`:"";return{detail:`${r.length} file(s) would change: ${s}${i}`,hint:cU(n),name:sU,ok:!1}}function cU(t){return["ari install",...[["--init",t.init],["--pack",t.pack],["--agent",t.agent],["--hooks",t.hooks],["--mcp",t.mcp],["--skills",t.skills],["--git-hooks",t.gitHooks],["--scope",t.scope],["--task-agent",t.taskAgent],["--task-model",t.taskModel],["--review-agent",t.reviewAgent],["--review-model",t.reviewModel]].flatMap(([r,o])=>{if(o===void 0||o===!1)return[];return o===!0?[r]:[`${r} ${lU(o)}`]}),"--yes"].join(" ")}function lU(t){return aU.test(t)?t:`'${t.replaceAll("'","'\\''")}'`}var ME="basic",uU=2,dU="CLI default";async function HE(t,e){let{init:n,pack:r}=await pU(t,e),o=e.agents??await gU(t);EU(t,{agents:o,init:n,scope:"project",targets:[]},["agent-not-found"]);let s=e.scope??await mU(t,o);if(s==="user"&&o.includes("claude"))Ao("Claude Code keeps user-scope MCP servers in its own state file, which ari does not edit",`Run: ${yc}`);let i=e.kinds===void 0?await fU(t,o,s,n):Gp(o,e.kinds),a=e.routing??await kU(t,o,t.initialised||n);return{agents:o,init:n,pack:r,recommended:!1,routing:a,scope:s,targets:i}}async function pU(t,e){let n=e.init===!0||e.pack!==void 0;if(t.initialised||n)return{init:n,pack:e.pack??null};if(Ao(".ari/config.json is missing, so ari is not set up in this repository","Setting it up writes .ari/config.json and a short block in AGENTS.md"),!await ue({initialValue:!0,message:"Set up ari in this repository?"}))return pt.info(k.dim("Skipped. Routing needs the setup, so that step is skipped too.")),{init:!1,pack:null};let o=await Xn({initialValue:ME,message:"Default methodology pack for new tasks",options:t.packs.map(({description:s,name:i})=>({hint:s,label:i,value:i}))});return{init:!0,pack:o===ME?null:o}}async function gU(t){return Ei({initialValues:wc(t),message:"Which agents do you use in this repository?",options:et.map((e)=>{let n=Pt(t,e),r=n.path===null?"not on PATH":zc(n),o=n.support==="verified"?"hooks verified":"hooks in part",s=n.kinds.filter((i)=>i!=="hooks").map((i)=>Fe[i]);return{hint:`${r} \xB7 ${[o,...s].join(", ")}`,label:n.label,value:e}}),required:!1})}async function mU(t,e){if(!e.some((r)=>Pt(t,r).userScope.length>0))return"project";let n=e.includes("claude")?"; Claude Code's MCP server stays per repository":"";return Xn({initialValue:"project",message:"Where should MCP servers and skills go?",options:[{hint:"commit them so the whole team gets them",label:"This repository",value:"project"},{hint:`every repository on this machine${n}`,label:"Your home directory",value:"user"}]})}async function fU(t,e,n,r){await hU(t);let o=Tr(t,e,n,r).filter((u)=>u.skip===null);for(let u of o.filter((d)=>d.problem!==null))Ao(u.problem?.message??"",u.problem?.hint??"");let s=o.filter((u)=>u.problem===null);if(s.length===0)return pt.info(k.dim("There is nothing to install for these agents.")),t.hookManager===null?[]:[je];let i=s.map((u)=>u.id),a=new Map(To(t,i).map(({id:u,reason:d})=>[u,d])),c=await Ei({initialValues:LS(t,e,n,r),message:"What should ari install?",options:s.map((u)=>({hint:a.get(u.id)??u.file??void 0,label:SU(t,u),value:u.id})),required:!1}),l=await yU(t,{agents:e,init:r,scope:n,targets:c});return t.hookManager===null?l:[...l,je]}async function hU(t){let e=t.hookManager;if(e===null)return;if(Ao(`${e.name} manages this repository's git hooks, so ari will not write .git/hooks`,"Add these lines to it, or commits and pushes skip ari's checks"),St(e.lines.join(`
221
- `),"Git hook lines",{format:(r)=>r}),!await ue({initialValue:!0,message:"Continue without git hooks?"}))throw new dt}async function yU(t,e){let n=[...e.targets],r=Sc(t,KE({...e,targets:n})).filter((o)=>o.code==="hooks-twice"||o.code==="skill-twice");for(let o of r){if(Ao(o.message,o.fix),o.drop.length===0)continue;let s=o.drop.map((i)=>UE(t,i)).join(" and ");if(await ue({initialValue:!0,message:`Leave out the ${s}?`}))n=n.filter((i)=>!o.drop.includes(i))}return n}async function kU(t,e,n){let r=MS(t,e);if(!n||r.length<uU)return null;if(t.routing.reviewCommand!==null)return pt.info(k.dim("Routing skipped: review.command runs the review gate, so ari leaves review.agent alone.")),null;if(St(r.map((u)=>wU(t,u)).join(`
222
- `),"Agents for 'ari run' and 'ari review'",{format:(u)=>u}),!await ue({initialValue:!1,message:"Run tasks and reviews on different agents or models?"}))return null;let s=await jE("Which agent implements tasks?",r,t.routing.task?.agent??null),i=await FE(`Model for ${s} on tasks`,GE(t.routing.task,s)),a=r.find((u)=>u.name!==s)?.name??null,c=await jE("Which agent reviews changes?",r,t.routing.review?.agent??a),l=await FE(`Model for ${c} on reviews`,GE(t.routing.review,c));return{review:{agent:c,model:l},task:{agent:s,model:i}}}async function jE(t,e,n){let r=e.some((o)=>o.name===n)?n:e[0]?.name;return Xn({initialValue:r??void 0,message:t,options:e.map((o)=>({hint:o.configured?`configured, ${o.roles.join(" and ")}`:"preset",label:o.name,value:o.name}))})}async function FE(t,e){let r=(await Nl({initialValue:e??"",message:t,placeholder:dU})??"").trim();return r.length===0?null:r}function GE(t,e){return t!==null&&t.agent===e?t.model:null}function wU(t,e){let n=t.agents.find((i)=>i.agent===e.name),r=n===void 0?"":n.path===null?k.dim(" not on PATH"):k.dim(` ${zc(n)}`),o=e.configured?`configured: ${e.roles.join(", ")}`:"preset, not configured yet",s=e.model===null?"":k.dim(` model ${e.model}`);return $e(`${e.name.padEnd(10)}${o}${s}${r}`)}function SU(t,e){return`${UE(t,e.id)}${TU(e)}`}function UE(t,e){if(e===je)return"Git hooks";if(e===Un)return"AGENTS.md block";let[n,r]=e.split(":"),o=et.find((a)=>a===r),s=Hn.find((a)=>a===n);return`${o===void 0?r??"":Pt(t,o).label} ${s===void 0?n??"":Fe[s]}`}function TU(t){if(t.elsewhere!==null&&t.status==="missing")return k.dim(` (${t.elsewhere} scope)`);if(t.status==="current")return k.green(" \u2713");return t.status==="outdated"?k.yellow(" \u2191"):""}function KE(t){return{...t,pack:null,recommended:!1,routing:null}}function EU(t,e,n){for(let r of Sc(t,KE(e)))if(n.includes(r.code))Ao(r.message,r.fix)}function Ao(t,e){pt.warn(Ar(t,e))}var $U=1,Ws=new Set(["created","updated"]),Cr={format:(t)=>t},bU=j({agent:{description:`Agents to set up, comma-separated: ${et.join(", ")}`,type:"string"},check:{description:"Write nothing and exit 1 unless the plan is up to date and every check passes (for CI)",type:"boolean"},dryRun:{alias:"d",description:"Show the plan and write nothing",type:"boolean"},gitHooks:{description:"Install the pre-commit and pre-push git hooks",type:"boolean"},hooks:{description:"Install each agent's hooks",type:"boolean"},init:{description:"Create .ari/config.json and the AGENTS.md block when they are missing",type:"boolean"},mcp:{description:"Register ari's MCP server with each agent",type:"boolean"},pack:{description:"Default methodology pack when setting up (implies --init)",type:"string"},reviewAgent:{description:"Agent for the review gate and 'ari review' (with --task-agent)",type:"string"},reviewModel:{description:"Model for the review agent (default: the agent CLI's own)",type:"string"},scope:{description:"Where MCP servers and skills go: project or user (default: project)",type:"string"},skills:{description:"Install the ariadne skill for each agent",type:"boolean"},taskAgent:{description:"Agent that 'ari run' gives tasks to (with --review-agent)",type:"string"},taskModel:{description:"Model for the task agent (default: the agent CLI's own)",type:"string"},yes:{alias:"y",description:"Accept the recommended defaults: found agents, every supported target, no questions",type:"boolean"}}),VE=E({args:bU,description:"Set up ari here: configuration, hooks, MCP server, skill, git hooks and agent routing, in one guided step",examples:["ari install","ari install --yes","ari install --init --agent claude,codex --yes --dry-run","ari install --init --agent claude,codex --yes --check","ari install --agent claude,codex --hooks --mcp --skills --task-agent claude --review-agent codex --review-model gpt-5.5"],json:!0,name:"install",prompts:!0,run:async(t)=>vU(t)});async function vU(t){let e=await O(),n=oE(t.args),r=t.args.yes===!0,o=t.args.check===!0,s=t.args.dryRun===!0||o,i=t.interactive,a=i&&!r,c=t.cli.version??"";if(i)Zn(`${k.bold("ari install")} ${k.dim(`Ariadne ${c}`)}`);let l=i?await JE("Looking at this repository",()=>Gs(e)):await Gs(e);if(i)St(RE(l,c),"This repository",Cr);if(a&&!sE(n)){let S=await RU(l,e);if(S!==null)return Zc(t,l,S,{check:o,dryRun:s,upToDate:!0,visual:i})}let u=await WE(i,()=>a?HE(l,n):Hp(l,n,r)),d=Sp(l,u),p=await Vc(e,d,"preview");if(i)PU(l,d,p.rows,!a);let m=p.rows.some((S)=>Ws.has(S.action));if(p.failed||s){let S=p.rows.map(s?AU:CU),R=o&&!p.failed?await xU(i,l,p.rows,t.args):[],v=o&&!p.failed&&!m;return Zc(t,l,{checks:R,plan:d,rows:S},{check:o,dryRun:s,upToDate:v,visual:i})}if(!m){let S=await Qc(i,e,p.rows);return Zc(t,l,{checks:S,plan:d,rows:p.rows},{check:o,dryRun:s,upToDate:!0,visual:i})}if(a)await WE(i,()=>NU());let f=await ur(e,()=>Vc(e,d,"apply",i?DU(l):{})),y=f.failed?[]:await Qc(i,e,f.rows);return Zc(t,l,{checks:y,plan:d,rows:f.rows},{check:o,dryRun:s,upToDate:!1,visual:i})}async function xU(t,e,n,r){let o=await Qc(t,e.root,n.filter((i)=>i.action==="unchanged")),s=LE(e,n,r);if(s===null)return o;if(t)pt.error(Ar(`${s.name}: ${s.detail}`,s.hint??""));return[s,...o]}function AU(t){return Ws.has(t.action)?{...t,undo:null}:t}function CU(t){return Ws.has(t.action)?{...t,action:"pending",undo:null}:t}async function RU(t,e){if(!t.initialised)return null;let n=IU(t);if(n===null||n.agents.length===0)return null;let r=Sp(t,n),o=await Vc(e,r,"preview");if(o.failed||o.rows.some((s)=>Ws.has(s.action)))return null;return{checks:await Qc(!0,e,o.rows),plan:r,rows:o.rows}}function IU(t){try{return Hp(t,OU(),!0)}catch{return null}}function OU(){return{agents:void 0,init:void 0,kinds:void 0,pack:void 0,routing:void 0,scope:void 0}}async function Zc(t,e,n,r){let o=n.rows.some((i)=>i.action==="failed")||n.checks.some((i)=>!i.ok)||r.check&&!r.upToDate,s={check:r.check,checks:n.checks,dryRun:r.dryRun,next:bE,ok:!o,resume:r.dryRun||o?[]:await wE(e.root),root:e.root,routing:n.plan.routing,targets:n.rows,upToDate:r.upToDate,warnings:n.plan.warnings.map(({code:i,fix:a,message:c})=>({code:i,fix:a,message:c}))};if(r.visual)_U(e,s);return t.output.result(s,r.visual?void 0:PE),o?$U:0}function _U(t,e){let n=e.targets.find((r)=>r.action==="failed");if(n!==void 0){pt.error(Ar(`${Bn(t,n)}: ${n.reason??""}`,n.hint??"")),Xt(e.targets.some((r)=>Ws.has(r.action))&&!e.dryRun?"Stopped; run 'ari install' again to finish":"Nothing was written");return}if(e.check){Xt(e.ok?"Up to date: nothing would change and every check passed":"Not up to date, or a check failed");return}if(e.dryRun){Xt("Dry run: nothing was written");return}if(e.upToDate){St(Jp(e),"Everything is up to date",Cr),BE(e),Xt(k.dim("To add an agent: ari install --agent <name>"));return}St(Jp(e),e.ok?"Done":"Done, with problems",Cr),BE(e),Xt(e.ok?"ari is ready":"Fix the failed checks, then run 'ari install' again")}function BE(t){let e=qp(t);if(e.length>0)St(e.join(`
223
- `),"To undo",Cr);let n=Yp(t);if(n.length>0)St(n.join(`
224
- `),"To get back to your tasks",Cr)}function PU(t,e,n,r){if(r)for(let o of e.warnings)pt.warn(Ar(o.message,o.fix));St(IE(n,t,e.routing),"Plan",Cr)}async function NU(){if(await ue({initialValue:!0,message:"Write these changes?"}))return;throw new dt}async function WE(t,e){try{return await e()}catch(n){if(t&&n instanceof dt)Bo("Cancelled, nothing changed");throw n}}async function Qc(t,e,n){if(!t)return gp(e,n);let r=await JE("Checking the installation",()=>gp(e,n));if(r.length===0)return r;let o=r.filter((s)=>!s.ok);St(_E(r),o.length===0?"Self-check passed":"Self-check found problems",Cr);for(let s of o)pt.error(Ar(`${s.name}: ${s.detail}`,s.hint??""));return r}function DU(t){let e=$i();return{done:(n,r)=>e.stop(OE(t,r)),failed:(n,r)=>e.error(`${Bn(t,r)} failed${n.file===null?"":` (${n.file})`}`),start:(n)=>e.start(`Writing ${n.file??Bn(t,{agent:n.agent,file:n.file,kind:n.kind})}`)}}async function JE(t,e){let n=$i();n.start(t);try{let r=await e();return n.clear(),r}catch(r){throw n.error(t),r}}var Co=at({id:{description:"Task id",required:!0}}),qE=E({description:"Validate a draft contract and mark it ready",examples:["ari ready add-profile-inheritance"],json:!0,name:"ready",positionals:Co,run:async(t)=>{let e=await Mc(await O(),t.positionals.id);t.output.result(e,({id:n})=>`Task "${n}" is ready; run 'ari start ${n}'`)}}),YE=E({description:"Start a ready task in this worktree, or adopt one that no worktree holds",examples:["ari start add-profile-inheritance"],json:!0,name:"start",positionals:Co,run:async(t)=>{let e=await jc(await O(),t.positionals.id);t.output.result(e,({id:n,instruction:r,stage:o})=>`Task "${n}" is active at stage ${o}
228
+ `);if(n.expired)await r2()}});async function r2(){return await new Promise((t)=>process.stdout.write("",()=>t())),process.exit()}function o2(t){if("files"in t)return t.files.map((n)=>`git ${n.hook}: ${n.action} (${n.path})`).join(`
229
+ `);let e="events"in t?`: ${t.events.join(", ")}`:"";return`${t.agent} hooks ${t.action} in ${t.file}${e}`}function s2(t){let e=t.installed?"installed":"not installed";return`${t.agent} ${t.support} ${e} ${t.file} ${t.events.join(", ")}`}var s$=E({args:j({agents:{description:"Install agent hooks, comma-separated (claude,codex,gemini,cursor,copilot,git)",type:"string"},gitHooks:{default:!1,description:"Install the pre-commit and pre-push git hooks",type:"boolean"},mcp:{description:"Register ari's MCP server, comma-separated (claude,codex,gemini,cursor)",type:"string"},pack:{description:"Default methodology pack for new tasks",type:"string"},skills:{description:"Install ari's skills, comma-separated (claude,codex,gemini,cursor)",type:"string"}}),description:"Create .ari/ and the AGENTS.md block, and optionally install hooks, MCP servers and skills",examples:["ari init","ari init --pack tdd --agents claude,codex --git-hooks","ari init --agents claude --mcp claude --skills claude"],json:!0,name:"init",run:async(t)=>{let e=await _(),n=await Ir(e,()=>yb(e,{agents:We(t.args.agents),gitHooks:t.args.gitHooks,mcp:We(t.args.mcp),pack:t.args.pack,skills:We(t.args.skills)}));t.output.result(n,i2)}});function i2(t){let e=t.hooks.flatMap((n)=>("files"in n)?n.files.map((r)=>`git ${r.hook}: ${r.action} (${r.path})`):[`${n.agent} hooks: ${n.action} (${n.file})`]);return[`.ari/config.json: ${t.config} (pack ${t.pack})`,`${t.agentsMd.path}: ${t.agentsMd.action}`,...e,...t.mcp.map((n)=>`${n.agent} MCP server: ${n.action} (${n.file})`),...t.skills.map((n)=>`${n.agent} skill ${n.skill}: ${n.action} (${n.file})`),'Next: ari new "<title>"'].join(`
230
+ `)}var a2="--hooks, --mcp, --skills or --git-hooks";function i$(t){let e=new Set([...t.hooks===!0?["hooks"]:[],...t.mcp===!0?["mcp"]:[],...t.skills===!0?["skill"]:[],...t.gitHooks===!0?["git"]:[]]);return{agents:t.agent===void 0?void 0:l2(t.agent),init:t.init,kinds:e.size===0?void 0:e,pack:wi(t.pack,"--pack"),routing:u2(t),scope:t.scope===void 0?void 0:rr(t.scope)}}function a$(t){return Object.values(t).some((e)=>e!==void 0)}function Vg(t,e){return[...or.filter((r)=>e.has(r)).flatMap((r)=>t.map((o)=>Ot(r,o))),...e.has("git")?[qe]:[]]}function Wg(t,e,n){let r=[],o=e.init===!0||e.pack!==void 0;if(!t.initialised&&!o)r.push("--init");let s=e.kinds!==void 0&&[...e.kinds].every((u)=>u==="git"),i=e.agents??(s||!n?[]:ul(t)),a=n&&e.agents===void 0&&!s&&i.length===0;if(e.agents===void 0&&!s&&(!n||a))r.push("--agent");if(e.kinds===void 0&&!n)r.push(a2);if(r.length>0)throw c2(r,a);let c=e.scope??"project",l=e.kinds===void 0;return{agents:i,init:o,pack:e.pack??null,recommended:l,routing:e.routing??null,scope:c,targets:l?Ib(t,i,c,o):Vg(i,e.kinds??new Set)}}function c2(t,e){let n=t.join(" and ");return new v(`ari install needs ${n} when it cannot ask${e?"; no agent was found on PATH":""}`,`For example: ari install ${t.includes("--init")?"--init ":""}--agent claude,codex --yes. --yes installs every supported target; see 'ari install --help'`)}function l2(t){let e=[...new Set(t.split(",").map((n)=>n.trim()).filter((n)=>n.length>0))];if(e.length===0)throw new v("--agent needs at least one agent",`Choose from: ${at.join(", ")}`);return e.map((n)=>{if(ll(n))return n;throw new v(`ari install has no agent "${n}"`,`Choose from: ${at.join(", ")}`)})}function u2(t){let e=wi(t.taskAgent,"--task-agent"),n=wi(t.reviewAgent,"--review-agent"),r=wi(t.taskModel,"--task-model"),o=wi(t.reviewModel,"--review-model");if(e===void 0&&n===void 0){let s=r!==void 0?"--task-model":o!==void 0?"--review-model":null;if(s===null)return;throw new v(`${s} needs --task-agent and --review-agent`,"Pass both agents to set the routing")}if(e===void 0||n===void 0)throw new v(`Routing needs ${e===void 0?"--task-agent":"--review-agent"} as well`,"Pass --task-agent and --review-agent together");return{review:{agent:n,model:o??null},task:{agent:e,model:r??null}}}function wi(t,e){if(t===void 0)return;let n=t.trim();if(n.length>0)return n;throw new v(`${e} must not be empty`,`Leave ${e} out, or give it a value`)}import{join as d$}from"path";import{isDeepStrictEqual as qg}from"util";var d2=1,p2=":",c$="routing.default",g2="review.agent";function u$(t,e){let n=re(rt,t),r=Jg(n,"agents"),o=Jg(n,"routing"),s=Jg(n,"review"),i=m2(r,e),a=i.flatMap(({entry:g,name:f})=>g===null?[]:[[f,g]]),c=k2(o.default,c$,e.task)?o.default:y2(e.task),l=w2(s,e.review)?s:S2(s,e.review),u={...n,agents:{...r,...Object.fromEntries(a)},review:l,routing:{...o,default:c}},d=Ea(u);if(d!==null)throw new m(`ari cannot set the routing: ${d}`,`Fix ${rt}, then run 'ari install' again`,1,{tag:"InvalidConfig"});return{changes:[...i.map(({action:g,name:f,roles:y})=>({action:g,agent:f,detail:`${y.join(" and ")} agent`,key:`agents.${f}`})),{action:l$(o.default,c),agent:e.task.agent,detail:`tasks: ${Br(e.task)}`,key:c$},{action:l$(s.agent===void 0?void 0:s,l),agent:e.review.agent,detail:`reviews: ${Br(e.review)}`,key:g2}],next:zn(t,u)}}function m2(t,e){let n=new Map;for(let[r,o]of[[e.task,"task"],[e.review,"review"]])n.set(r.agent,[...n.get(r.agent)??[],o]);return[...n].map(([r,o])=>f2(r,o,t[r]))}function Br(t){return t.model===null?`${t.agent} (CLI default model)`:`${t.agent} (${t.model})`}function f2(t,e,n){let r=Ve.find((l)=>l.name===t),o=e.length>1?"both":e[0]??"task";if(n===void 0){if(r!==void 0)return{action:"created",entry:Eo(r,o,void 0),name:t,roles:e};throw new v(`No agent named "${t}" is configured, and ari has no preset of that name`,`Choose a configured agent, or one of the presets: ${Ve.map((l)=>l.name).join(", ")}`)}let s=h2(n);if(e.every((l)=>s.includes(l)))return{action:"unchanged",entry:null,name:t,roles:e};let i=z(n)&&typeof n.model==="string"?n.model:void 0,a=r!==void 0&&bo.some((l)=>qg(n,Eo(r,l,i)));if(r!==void 0&&a)return{action:"updated",entry:Eo(r,"both",i),name:t,roles:e};let c=e.filter((l)=>!s.includes(l));throw new m(`agents.${t} has no ${c.join(" or ")} role`,`Add ${c.map((l)=>`"${l}"`).join(" and ")} to agents.${t}.roles in ${rt}, or choose another agent`,d2,{tag:"AgentRoleMismatch"})}function h2(t){if(!z(t)||!Array.isArray(t.roles))return Wu;return t.roles.filter((e)=>typeof e==="string")}function Jg(t,e){let n=t[e];return z(n)?n:{}}function y2(t){return t.model===null?t.agent:`${t.agent}${p2}${t.model}`}function k2(t,e,n){if(t===void 0||t===null)return!1;try{return qg(Ss(t,e),n)}catch{return!1}}function w2(t,e){return t.agent===e.agent&&(t.model??null)===e.model}function S2(t,e){let{model:n,...r}=t;return{...r,agent:e.agent,...e.model===null?{}:{model:e.model}}}function l$(t,e){if(t===void 0||t===null)return"created";return qg(t,e)?"unchanged":"updated"}var v2=new Set(["created","updated","unchanged"]),b2="Fix the cause, then run 'ari install' again; it keeps what is already done";async function Fl(t,e,n,r={}){let o={mode:n,plan:e,root:t,scopes:await _2(t),view:O2(n)},s=[],i=!1;for(let a of e.targets){if(i||a.skip!==null){s.push(vi(a,i?"pending":"skipped",i?null:a.skip));continue}r.start?.(a);try{let c=await E2(o,a);s.push(...c),r.done?.(a,c)}catch(c){let l={...vi(a,"failed",N2(c)),hint:D2(c)};s.push(l),r.failed?.(a,l),i=!0}}return{failed:i,rows:s}}async function E2(t,e){if(e.id===$g)return[Si(e,$2(t))];if(e.id===sr)return[Si(e,T2(t))];let{agent:n}=e;switch(e.kind){case"hooks":return[Si(e,await x2(t,Yg(n)))];case"mcp":return[Si(e,A2(t,Yg(n),e.scope))];case"skill":return[Si(e,C2(t,Yg(n),e.scope))];case"git":return R2(t,e);case"routing":return I2(t,e);case"config":throw Error(`ari has no configuration target "${e.id}"`)}}function $2({mode:t,plan:e,root:n,view:r}){if(t==="apply")return fg(n,e.pack);return bi(r,n,rt,(o)=>hg(o,e.pack))}function T2({mode:t,root:e,view:n}){if(t==="apply")return mg(e).action;return bi(n,e,jt,fi)}async function x2({mode:t,root:e,view:n},r){let o=Pe(r);if(t==="preview")return bi(n,e,o.file,(i)=>Ks(o,i));let s=await Ho(e,r);return"action"in s?s.action:"unchanged"}function A2({mode:t,scopes:e,view:n},r,o){let s=e[o];if(t==="apply")return Ko(me(r),s).action;let i=Ne(me(r),s);return bi(n,i.base,i.file,(a)=>i.install(a))}function C2({mode:t,scopes:e,view:n},r,o){let s=e[o],i=Jt(r);if(t==="apply"){let c=Bo(i,s);return rl(c,r),lg(c.flatMap((l)=>l.action==="refused"?[]:[l.action]))}let a=ot.map((c)=>{let l=ie(i,s,c);return bi(n,l.base,l.file,(u)=>l.install(u))});return lg(a)}async function R2({mode:t,root:e},n){return(t==="apply"?(await ac(e)).files:await Fs(e)).map(({action:o,path:s})=>({...vi(n,Xg(o),null),file:s}))}function I2({mode:t,plan:e,root:n,view:r},o){let s=e.routing;if(s===null)return[];let i=t==="apply"?W(n,rt):r.read(n,rt);if(i===null)throw new m(`${rt} does not exist, so ari cannot set the routing`,"Run 'ari init' first");let a=u$(i,s);if(t==="apply")Ce(n,rt,a.next);else r.write(n,rt,a.next);return a.changes.map((c)=>({...vi(o,Xg(c.action),null),agent:c.agent,detail:c.detail,key:c.key}))}function bi(t,e,n,r){let o=t.read(e,n),s=r(o);return t.write(e,n,s),Ns(o,s)}function O2(t){let e=new Map;return{read:(n,r)=>e.get(d$(n,r))??W(n,r),write:(n,r,o)=>{if(t==="preview")e.set(d$(n,r),o)}}}async function _2(t){return{project:{base:t,receipts:await P(t),scope:"project"},user:await xt("user",t)}}function Si(t,e){return vi(t,Xg(e),null)}function vi(t,e,n){let r=t.file===null?null:t.file;return{action:e,agent:t.agent,detail:null,file:r===null?null:P2(t.scope,r),hint:null,key:null,kind:t.kind,reason:n,scope:t.scope,undo:v2.has(e)?wb(t):null}}function P2(t,e){return t==="user"&&!e.startsWith("~/")?oe(t,e):e}function Xg(t){return t==="removed"?"updated":t}function Yg(t){if(t!==null)return t;throw Error("This target needs an agent")}function N2(t){return t instanceof Error?t.message:String(t)}function D2(t){if(t instanceof m&&t.hint!==void 0&&t.hint.length>0)return t.hint;return b2}import{rmSync as L2}from"fs";var M2="knowledge",p$="Every 'ari sleep' pass and '--apply' writes an entry under <git-path>/ari/sleep/",j2=()=>new Date().toISOString();async function m$(t,e,n={}){let r=await P(t),o=(n.clock??j2)();return Nr(r,()=>{let s=y$(t,r,e);for(let c of s.restore)Tr(Oe(t,c.id),Dr(c.original));for(let c of s.remove)L2(Oe(t,c.id),{force:!0});for(let{notes:c,task:l}of s.unpromote)Vt(t,r,l,(u)=>yy(u,c));let i=k$(s),a=No(r,o,{kind:"undo",removed:i.removed,restored:i.restored,undoes:s.target.id,unpromoted:i.unpromoted});return{...i,ledger:a.id}})}async function f$(t,e){let n=await P(t);return{...k$(y$(t,n,e)),dryRun:!0}}async function h$(t,e){let n=ei(t,e);if(n.status==="active")throw new m(`Knowledge entry "${e}" is already active`,"Run 'ari knowledge list --all' to see archived entries");let r=await P(t);return Nr(r,()=>{let o=Oe(t,e),s=Lo(o),i=ii(r),a=ai(i),c=i.filter(Po).filter((l)=>!a.has(l.id)).reverse().flatMap((l)=>l.archived).find((l)=>l.id===e&&l.sha256===s)?.original;if(c===void 0)ti(t,{...n,status:"active",supersededBy:null});else Tr(o,Dr(c));return ei(t,e)})}function y$(t,e,n){let r=F2(ii(e),n),o=[],s=r.archived.filter((a)=>{let c=Mp(Oe(t,a.id));if(c===a.sha256)return!0;if(c!==a.original.sha256)o.push(`${g$(a.id)} ${c===null?"is missing":"changed after sleep archived it"}`);return!1}),i=r.created.filter((a)=>{let c=Mp(Oe(t,a.id));if(c===null)return!1;if(c===a.sha256)return!0;return o.push(`${g$(a.id)} changed after sleep created it`),!1});if(o.length>0){let a=o.map((c)=>` - ${c}`).join(`
231
+ `);throw new m(`Cannot undo sleep entry ${r.id}; ${o.length} file(s) are not as it left them:
232
+ ${a}`,"Nothing was changed. Restore those files from git, undo the later sleep entries first, or use 'ari knowledge restore <id>' for a single entry")}return{remove:i,restore:s,target:r,unpromote:G2(t,r.promoted)}}function F2(t,e){let n=ai(t);if(e===void 0){let s=t.filter(Po).findLast((i)=>!n.has(i.id)&&Gl(i));if(s!==void 0)return s;throw new m("The sleep ledger has no entry that changed knowledge and is not undone yet",p$)}let r=ri(e)?t.find((s)=>s.id===e):void 0;if(r===void 0){let s=t.length===0?"none yet":t.map((i)=>i.id).join(", ");throw new m(`The sleep ledger has no entry "${e}"`,`Known entries: ${s}`)}if(!Po(r))throw new m(`Ledger entry ${e} records an undo itself`,"Run 'ari sleep' or 'ari knowledge restore <id>' instead");let o=n.get(e);if(o!==void 0)throw new m(`Sleep entry ${e} was already undone by ${o}`,p$);if(!Gl(r))throw new m(`Sleep entry ${e} changed no knowledge entry, so there is nothing to undo`,"Journals that sleep pruned cannot be restored");return r}function Gl(t){return t.archived.length>0||t.created.length>0||t.promoted.length>0}function G2(t,e){let n=new Set(In(t));return e.flatMap(({notes:r,task:o})=>{if(!n.has(o))return[];let s=On(t,o),i=r.filter((a)=>s.notes[a]?.promoted===!0);return i.length===0?[]:[{notes:i,task:o}]})}function k$(t){return{journalsNotRestored:t.target.pruned.map((e)=>e.task),removed:t.remove.map(({id:e,sha256:n})=>({id:e,sha256:n})),restored:t.restore.map(({id:e,original:n})=>({id:e,sha256:n.sha256})),undoes:t.target.id,unpromoted:t.unpromote}}function g$(t){return`${J}/${M2}/${t}.md`}var H2=3,w$=new Set(["active","blocked"]);async function S$(t){let e=Hl(()=>M(t));if(e===null)return[];let n=await P(t),r=Hl(()=>Pt(t,e)),o=r?.tasks??[],s=Hl(()=>gt(n))?.task??null,i=await U2(t,o,s),a=o.some((l)=>l.contract.id===s&&w$.has(l.record.status));return["ari next",...o.length+(r?.invalid.length??0)>0?["ari list"]:[],...i.slice(0,H2).map((l)=>`ari start ${l}`),...a?["ari context"]:[],...await B2(t,n)]}async function U2(t,e,n){let r=e.filter((s)=>w$.has(s.record.status)&&s.contract.id!==n);if(r.length===0)return[];let o=await K2(t);return r.map((s)=>s.contract.id).filter((s)=>!o.has(s))}async function K2(t){try{return await ki(t)}catch{return new Map}}async function B2(t,e){let n=await J2(()=>V2(t)),r=Hl(()=>W2(e));return[...n===!0?["ari sleep"]:[],...r===!0?["ari sleep --undo"]:[]]}async function V2(t){return er(await jr(t,{candidates:!1})).due}function W2(t){let e=ii(t),n=ai(e);return e.some((r)=>Po(r)&&!n.has(r.id)&&Gl(r))}async function J2(t){try{return await t()}catch(e){if(e instanceof m)return null;throw e}}function Hl(t){try{return t()}catch(e){if(e instanceof m)return null;throw e}}import{homedir as q2}from"os";var Ei=72,Y2="ari install",X2="ari uninstall",v$=44,z2=28,b$=8,Z2="Kept: .ari/ data, the AGENTS.md block, routing and trust",Q2=[["ari next","what to do now"],["ari list","every task and where it stands"],["ari start ","adopt a task that no worktree holds"],["ari context","the context pack of the active task"],["ari sleep --undo","undo the last memory consolidation"],["ari sleep","consolidate memory, which is due"]],T$=['ari new "Describe the first task"',"ari next"],Zg=20,E$=26,zg=13,x$=8,Vr=11,A$=34,$$=12,tV=/\d+(?:\.\d+)+[\w.+-]*/,C$="\u2026",eV="~",Ul=".ari/config.json",R$=new Set(["created","updated"]),qt=" ",nV=`${w.green("\u2713")} installed ${w.yellow("\u2191")} update ${w.dim("\xB7")} not installed ${w.dim("\u2013")} not supported`,rV={created:"create",failed:"fail",pending:"not run",skipped:"skip",unchanged:"unchanged",updated:"update"};function I$(t,e){let n=t.initialised?`set up, pack ${t.pack??"basic"}`:`not set up yet (${w.yellow(".ari/config.json is missing")})`,r=t.targets.find((a)=>a.id==="agents-md"),o=[zo("Repository",yV(t.root)),zo("Ariadne",`${e} \xB7 ${n}`),...r===void 0?[]:[zo("AGENTS.md",`${L$(r)} ari block`)],...mV(t),zo("Git hooks",fV(t))],s=w.dim([ut("Agent",Zg),ut("On PATH",zg),...or.map((a)=>ut(hV(a),x$))].join("")),i=at.map((a)=>pV(t,Ft(t,a)));return[...o,"",s,...i,"",nV].map(Le).join(`
233
+ `)}function O$(t,e,n){let r=new Map,o=[];for(let c of t){if(c.kind==="routing")continue;if(c.action==="skipped"){let u=Wr(c.reason??"",Ei-qt.length*2).map((d)=>`${qt}${qt}${w.dim(d)}`);o.push(`${qt}${ar(e,c)}`,...u);continue}let l=dV(e,c);r.set(l,[...r.get(l)??[],cV(c)])}let s=[...r].flatMap(([c,l])=>[w.bold(c),...l]),i=n===null?[]:uV(t,n),a=o.length===0?[]:[w.bold("Skipped"),...o];return[...s,...i,...a].map(Le).join(`
234
+ `)}function _$(t,e){let[n]=e;if(n===void 0)return"";if(n.kind==="routing"){let o=e.filter((i)=>R$.has(i.action)).map((i)=>i.key??""),s=o.length===0?"unchanged":"updated";return Le(`${ut("Routing",E$)}${Zo(s,!1)}${o.join(", ")||Ul}`)}let r=e.map((o)=>o.file??"").join(", ");return Le(`${ut(ar(t,n),E$)}${Zo(n.action,!1)}${r}`)}function P$(t){return t.map((e)=>{let n=e.ok?w.green("\u2713"):w.red("\u2717"),r=e.ok?w.dim(e.detail):w.red(e.detail);return Le(`${n} ${ut(e.name,Zg)}${r}`)}).join(`
235
+ `)}function Jr(t,e){return[...Wr(t,Ei),...Wr(e,Ei).map((r)=>w.dim(r))].join(`
236
+ `)}function Wr(t,e){let n=[];for(let r of t.split(`
237
+ `)){let o="";for(let s of r.split(" ")){let i=o.length===0?s:`${o} ${s}`;if(Bun.stringWidth(i)>e&&o.length>0)n.push(o),o=s;else o=i}if(o.length>0)n.push(o)}return n}function Qg(t){let e=["created","updated","unchanged","skipped","failed","pending"].map((o)=>[o,t.targets.filter((s)=>s.action===o).length]).filter(([,o])=>o>0).map(([o,s])=>`${s} ${o==="pending"?"not run":o}`),n=t.checks.filter((o)=>!o.ok).length,r=t.checks.length===0?[]:[`${t.checks.length-n} of ${t.checks.length} checks passed`];return[e.join(" \xB7 "),...r,"",w.bold("Next"),...t.next.map((o)=>`${qt}${o}`)].map(Le).join(`
238
+ `)}function tm(t){let e=new Set,n=t.targets.flatMap((o)=>{if(o.undo===null||e.has(o.undo))return[];return e.add(o.undo),[`${ut(o.undo,v$)}${oV(o)}`]});if(n.length===0)return[];let r=n.length-b$;return[`${ut(X2,v$)}everything ari installed`,...n.slice(0,b$),...r>0?[`and ${r} more: see "undo" in --json`]:[],Z2].map(Le)}function em(t){return t.resume.map((e)=>Le(`${ut(e,z2)}${sV(e)}`))}function oV(t){if(t.kind==="git")return"git hooks";let e=t.kind==="hooks"||t.kind==="mcp"||t.kind==="skill"?Ye[t.kind]:t.kind;return`${t.agent??""} ${e}`.trim()}function sV(t){return Q2.find(([n])=>n.endsWith(" ")?t.startsWith(n):t===n)?.[1]??""}function iV(t){let e=tm(t),n=em(t);return[...e.length===0?[]:["","To undo",...e.map((r)=>`${qt}${r}`)],...n.length===0?[]:["","To get back to your tasks",...n.map((r)=>`${qt}${r}`)]]}function N$(t){let e=t.targets.map((a)=>{let c=[a.agent,a.kind,a.key].filter((d)=>d!==null).join(" "),l=a.reason===null?"":`: ${a.reason}`,u=a.hint===null?"":` (${a.hint})`;return`${ut(a.action,Vr)}${ut(a.file??"-",A$)} ${c}${l}${u}`}),n=t.warnings.flatMap((a)=>[`warning: ${a.message}`,` ${a.fix}`]),r=t.check?Dg(t.checks.map((a)=>ml(a,Y2))):t.checks.map((a)=>`check ${a.ok?"ok":"FAILED"}: ${a.name}: ${a.detail}${a.hint===null?"":` (${a.hint})`}`),o=t.check?[aV(t)]:t.dryRun?["Dry run: nothing was written"]:t.upToDate?["Everything is up to date"]:[],s=t.ok&&!t.dryRun,i=s?t.next.map((a)=>`next: ${a}`):[];return[...e,...n,...r,...o,...i,...s?iV(t):[]].join(`
239
+ `)}function aV(t){if(t.ok)return"Up to date: nothing would change and every check passed";return t.upToDate?"Up to date, but a check failed":"Not up to date"}function ar(t,e){if(e.kind==="git")return"git hooks";if(e.kind==="config")return e.file==="AGENTS.md"?"ari block":"configuration";if(e.kind==="routing")return"routing";return`${e.agent===null?"":`${D$(t,e.agent)} `}${Ye[e.kind]}`}function Zo(t,e){let n=ut(e?rV[t]:t,Vr);switch(t){case"created":return w.green(n);case"updated":return w.yellow(n);case"failed":return w.red(n);case"unchanged":case"skipped":case"pending":return w.dim(n)}}function Le(t){if(Bun.stringWidth(t)<=Ei)return t;return`${Bun.sliceAnsi(t,0,Ei-1)}${C$}`}function Kl(t){if(t.path===null)return"not found";let e=tV.exec(t.version??"")?.[0]??t.version??"found";return e.length>$$?`${e.slice(0,$$-1)}${C$}`:e}function cV(t){let e=t.kind==="config"&&t.file==="AGENTS.md"?"ari block":lV[t.kind],n=t.action==="failed"?w.red(t.reason??""):w.dim(e);return`${qt}${Zo(t.action,!0)}${ut(t.file??"",A$)} ${n}`}var lV={config:"configuration",git:"git hook",hooks:"hooks",mcp:"MCP server",routing:"routing",skill:`${ot.length} skills`};function uV(t,e){let n=t.filter((l)=>l.kind==="routing"),r=n.find((l)=>l.action==="failed"),o=n.some((l)=>l.action==="pending"),s=(l)=>n.filter((u)=>(u.key??"").startsWith(l)&&R$.has(u.action)).map((u)=>u.key??""),i=s("agents."),a=[...s("routing."),...s("review.")],c=r!==void 0?[`${qt}${Zo("failed",!0)}${w.red(r.reason??"")}`]:o?[`${qt}${Zo("pending",!0)}${Ul}`]:i.length+a.length===0?[`${qt}${Zo("unchanged",!0)}${Ul}`]:[...i.length===0?[]:[`${qt}${w.green(ut("add",Vr))}${i.join(", ")}`],...a.length===0?[]:[`${qt}${w.yellow(ut("set",Vr))}${a.join(", ")}`]];return[`${w.bold("Routing")} ${w.dim(Ul)}`,`${qt}${ut("tasks",Vr)}${Br(e.task)}`,`${qt}${ut("reviews",Vr)}${Br(e.review)}`,...c]}function dV(t,e){if(e.agent!==null)return D$(t,e.agent);return e.kind==="git"?"Git hooks":"Repository"}function D$(t,e){return t.agents.find((n)=>n.agent===e)?.label??e}function pV(t,e){let n=e.path===null?w.dim(ut("not found",zg)):ut(Kl(e),zg),r=or.map((o)=>ut(gV(t,e.agent,o),x$));return[ut(e.label,Zg),n,...r].join("")}function gV(t,e,n){if(!Ft(t,e).kinds.includes(n))return w.dim("\u2013");let r=t.targets.filter((i)=>i.agent===e&&i.kind===n);if(r.some((i)=>i.problem!==null))return w.red("!");let o=r.filter((i)=>i.status!=="missing");if(o.length===0)return w.dim("\xB7");let s=o.some((i)=>i.status==="outdated")?w.yellow("\u2191"):w.green("\u2713");if(o.length>1)return`${s} both`;return o[0]?.scope==="user"?`${s} user`:s}function mV(t){let{review:e,task:n}=t.routing;if(n===null&&e===null)return[];let r=n===null?"tasks: not set":`tasks ${Br(n)}`,o=e===null?"reviews: not set":`reviews ${Br(e)}`;return[zo("Routing",r),zo("",o)]}function fV(t){if(t.hookManager!==null)return w.dim(`managed by ${t.hookManager.name}`);let e=t.targets.find((n)=>n.id==="git");if(e===void 0)return w.dim("\xB7");if(e.problem!==null)return`${w.red("!")} ${e.problem.message}`;return`${L$(e)} ${e.status==="missing"?"not installed":"pre-commit, pre-push"}`}function L$(t){if(t.problem!==null)return w.red("!");if(t.status==="current")return w.green("\u2713");return t.status==="outdated"?w.yellow("\u2191"):w.dim("\xB7")}function hV(t){return t==="mcp"?"MCP":t==="hooks"?"Hooks":"Skill"}function zo(t,e){return`${ut(t,Vr+1)}${e}`}function yV(t){let e=q2();return t===e||t.startsWith(`${e}/`)?`${eV}${t.slice(e.length)}`:t}function ut(t,e){let n=Bun.stringWidth(t);return n>=e?`${t} `:`${t}${" ".repeat(e-n)}`}var kV="install plan",wV=new Set(["created","updated"]),SV=/^[\w@%+=:,./-]+$/,nm=6;function M$(t,e,n){let r=e.filter((a)=>wV.has(a.action));if(r.length===0)return null;let o=[...new Set(r.map((a)=>ar(t,a)))],s=o.slice(0,nm).join(", "),i=o.length>nm?` and ${o.length-nm} more`:"";return{detail:`${r.length} file(s) would change: ${s}${i}`,hint:vV(n),name:kV,ok:!1}}function vV(t){return["ari install",...[["--init",t.init],["--pack",t.pack],["--agent",t.agent],["--hooks",t.hooks],["--mcp",t.mcp],["--skills",t.skills],["--git-hooks",t.gitHooks],["--scope",t.scope],["--task-agent",t.taskAgent],["--task-model",t.taskModel],["--review-agent",t.reviewAgent],["--review-model",t.reviewModel]].flatMap(([r,o])=>{if(o===void 0||o===!1)return[];return o===!0?[r]:[`${r} ${bV(o)}`]}),"--yes"].join(" ")}function bV(t){return SV.test(t)?t:`'${t.replaceAll("'","'\\''")}'`}var j$="basic",EV=2,$V="CLI default";async function U$(t,e){let{init:n,pack:r}=await TV(t,e),o=e.agents??await xV(t);LV(t,{agents:o,init:n,scope:"project",targets:[]},["agent-not-found"]);let s=e.scope??await AV(t,o);if(s==="user"&&o.includes("claude"))Qo("Claude Code keeps user-scope MCP servers in its own state file, which ari does not edit",`Run: ${cl}`);let i=e.kinds===void 0?await CV(t,o,s,n):Vg(o,e.kinds),a=e.routing??await OV(t,o,t.initialised||n);return{agents:o,init:n,pack:r,recommended:!1,routing:a,scope:s,targets:i}}async function TV(t,e){let n=e.init===!0||e.pack!==void 0;if(t.initialised||n)return{init:n,pack:e.pack??null};if(Qo(".ari/config.json is missing, so ari is not set up in this repository","Setting it up writes .ari/config.json and a short block in AGENTS.md"),!await Ee({initialValue:!0,message:"Set up ari in this repository?"}))return bt.info(w.dim("Skipped. Routing needs the setup, so that step is skipped too.")),{init:!1,pack:null};let o=await gr({initialValue:j$,message:"Default methodology pack for new tasks",options:t.packs.map(({description:s,name:i})=>({hint:s,label:i,value:i}))});return{init:!0,pack:o===j$?null:o}}async function xV(t){return ea({initialValues:ul(t),message:"Which agents do you use in this repository?",options:at.map((e)=>{let n=Ft(t,e),r=n.path===null?"not on PATH":Kl(n),o=n.support==="verified"?"hooks verified":"hooks in part",s=n.kinds.filter((i)=>i!=="hooks").map((i)=>Ye[i]);return{hint:`${r} \xB7 ${[o,...s].join(", ")}`,label:n.label,value:e}}),required:!1})}async function AV(t,e){if(!e.some((r)=>Ft(t,r).userScope.length>0))return"project";let n=e.includes("claude")?"; Claude Code's MCP server stays per repository":"";return gr({initialValue:"project",message:"Where should MCP servers and skills go?",options:[{hint:"commit them so the whole team gets them",label:"This repository",value:"project"},{hint:`every repository on this machine${n}`,label:"Your home directory",value:"user"}]})}async function CV(t,e,n,r){await RV(t);let o=Ur(t,e,n,r).filter((u)=>u.skip===null);for(let u of o.filter((d)=>d.problem!==null))Qo(u.problem?.message??"",u.problem?.hint??"");let s=o.filter((u)=>u.problem===null);if(s.length===0)return bt.info(w.dim("There is nothing to install for these agents.")),t.hookManager===null?[]:[qe];let i=s.map((u)=>u.id),a=new Map(Wo(t,i).map(({id:u,reason:d})=>[u,d])),c=await ea({initialValues:Ob(t,e,n,r),message:"What should ari install?",options:s.map((u)=>({hint:a.get(u.id)??PV(u),label:NV(t,u),value:u.id})),required:!1}),l=await IV(t,{agents:e,init:r,scope:n,targets:c});return t.hookManager===null?l:[...l,qe]}async function RV(t){let e=t.hookManager;if(e===null)return;if(Qo(`${e.name} manages this repository's git hooks, so ari will not write .git/hooks`,"Add these lines to it, or commits and pushes skip ari's checks"),Nt(e.lines.join(`
240
+ `),"Git hook lines",{format:(r)=>r}),!await Ee({initialValue:!0,message:"Continue without git hooks?"}))throw new vt}async function IV(t,e){let n=[...e.targets],r=dl(t,B$({...e,targets:n})).filter((o)=>o.code==="hooks-twice"||o.code==="skill-twice");for(let o of r){if(Qo(o.message,o.fix),o.drop.length===0)continue;let s=o.drop.map((i)=>K$(t,i)).join(" and ");if(await Ee({initialValue:!0,message:`Leave out the ${s}?`}))n=n.filter((i)=>!o.drop.includes(i))}return n}async function OV(t,e,n){let r=_b(t,e);if(!n||r.length<EV)return null;if(t.routing.reviewCommand!==null)return bt.info(w.dim("Routing skipped: review.command runs the review gate, so ari leaves review.agent alone.")),null;if(Nt(r.map((u)=>_V(t,u)).join(`
241
+ `),"Agents for 'ari run' and 'ari review'",{format:(u)=>u}),!await Ee({initialValue:!1,message:"Run tasks and reviews on different agents or models?"}))return null;let s=await F$("Which agent implements tasks?",r,t.routing.task?.agent??null),i=await G$(`Model for ${s} on tasks`,H$(t.routing.task,s)),a=r.find((u)=>u.name!==s)?.name??null,c=await F$("Which agent reviews changes?",r,t.routing.review?.agent??a),l=await G$(`Model for ${c} on reviews`,H$(t.routing.review,c));return{review:{agent:c,model:l},task:{agent:s,model:i}}}async function F$(t,e,n){let r=e.some((o)=>o.name===n)?n:e[0]?.name;return gr({initialValue:r??void 0,message:t,options:e.map((o)=>({hint:o.configured?`configured, ${o.roles.join(" and ")}`:"preset",label:o.name,value:o.name}))})}async function G$(t,e){let r=(await Tu({initialValue:e??"",message:t,placeholder:$V})??"").trim();return r.length===0?null:r}function H$(t,e){return t!==null&&t.agent===e?t.model:null}function _V(t,e){let n=t.agents.find((i)=>i.agent===e.name),r=n===void 0?"":n.path===null?w.dim(" not on PATH"):w.dim(` ${Kl(n)}`),o=e.configured?`configured: ${e.roles.join(", ")}`:"preset, not configured yet",s=e.model===null?"":w.dim(` model ${e.model}`);return Le(`${e.name.padEnd(10)}${o}${s}${r}`)}function PV(t){if(t.file===null)return;return t.kind==="skill"?`${t.file} \xB7 ${ot.length} skills`:t.file}function NV(t,e){return`${K$(t,e.id)}${DV(e)}`}function K$(t,e){if(e===qe)return"Git hooks";if(e===sr)return"AGENTS.md block";let[n,r]=e.split(":"),o=at.find((a)=>a===r),s=or.find((a)=>a===n);return`${o===void 0?r??"":Ft(t,o).label} ${s===void 0?n??"":Ye[s]}`}function DV(t){if(t.elsewhere!==null&&t.status==="missing")return w.dim(` (${t.elsewhere} scope)`);if(t.status==="current")return w.green(" \u2713");return t.status==="outdated"?w.yellow(" \u2191"):""}function B$(t){return{...t,pack:null,recommended:!1,routing:null}}function LV(t,e,n){for(let r of dl(t,B$(e)))if(n.includes(r.code))Qo(r.message,r.fix)}function Qo(t,e){bt.warn(Jr(t,e))}var MV=1,$i=new Set(["created","updated"]),qr={format:(t)=>t},jV=j({agent:{description:`Agents to set up, comma-separated: ${at.join(", ")}`,type:"string"},check:{description:"Write nothing and exit 1 unless the plan is up to date and every check passes (for CI)",type:"boolean"},dryRun:{alias:"d",description:"Show the plan and write nothing",type:"boolean"},gitHooks:{description:"Install the pre-commit and pre-push git hooks",type:"boolean"},hooks:{description:"Install each agent's hooks",type:"boolean"},init:{description:"Create .ari/config.json and the AGENTS.md block when they are missing",type:"boolean"},mcp:{description:"Register ari's MCP server with each agent",type:"boolean"},pack:{description:"Default methodology pack when setting up (implies --init)",type:"string"},reviewAgent:{description:"Agent for the review gate and 'ari review' (with --task-agent)",type:"string"},reviewModel:{description:"Model for the review agent (default: the agent CLI's own)",type:"string"},scope:{description:"Where MCP servers and skills go: project or user (default: project)",type:"string"},skills:{description:"Install ari's skills for each agent",type:"boolean"},taskAgent:{description:"Agent that 'ari run' gives tasks to (with --review-agent)",type:"string"},taskModel:{description:"Model for the task agent (default: the agent CLI's own)",type:"string"},yes:{alias:"y",description:"Accept the recommended defaults: found agents, every supported target, no questions",type:"boolean"}}),J$=E({args:jV,description:"Set up ari here: configuration, hooks, MCP server, skills, git hooks and agent routing, in one guided step",examples:["ari install","ari install --yes","ari install --init --agent claude,codex --yes --dry-run","ari install --init --agent claude,codex --yes --check","ari install --agent claude,codex --hooks --mcp --skills --task-agent claude --review-agent codex --review-model gpt-5.5"],json:!0,name:"install",prompts:!0,run:async(t)=>FV(t)});async function FV(t){let e=await _(),n=i$(t.args),r=t.args.yes===!0,o=t.args.check===!0,s=t.args.dryRun===!0||o,i=t.interactive,a=i&&!r,c=t.cli.version??"";if(i)fr(`${w.bold("ari install")} ${w.dim(`Ariadne ${c}`)}`);let l=i?await q$("Looking at this repository",()=>yi(e)):await yi(e);if(i)Nt(I$(l,c),"This repository",qr);if(a&&!a$(n)){let S=await KV(l,e);if(S!==null)return Bl(t,l,S,{check:o,dryRun:s,upToDate:!0,visual:i})}let u=await W$(i,()=>a?U$(l,n):Wg(l,n,r)),d=Tg(l,u),p=await Fl(e,d,"preview");if(i)JV(l,d,p.rows,!a);let g=p.rows.some((S)=>$i.has(S.action));if(p.failed||s){let S=p.rows.map(s?HV:UV),I=o&&!p.failed?await GV(i,l,p.rows,t.args):[],C=o&&!p.failed&&!g;return Bl(t,l,{checks:I,plan:d,rows:S},{check:o,dryRun:s,upToDate:C,visual:i})}if(!g){let S=await Vl(i,e,p.rows);return Bl(t,l,{checks:S,plan:d,rows:p.rows},{check:o,dryRun:s,upToDate:!0,visual:i})}if(a)await W$(i,()=>qV());let f=await Ir(e,()=>Fl(e,d,"apply",i?YV(l):{})),y=f.failed?[]:await Vl(i,e,f.rows);return Bl(t,l,{checks:y,plan:d,rows:f.rows},{check:o,dryRun:s,upToDate:!1,visual:i})}async function GV(t,e,n,r){let o=await Vl(t,e.root,n.filter((i)=>i.action==="unchanged")),s=M$(e,n,r);if(s===null)return o;if(t)bt.error(Jr(`${s.name}: ${s.detail}`,s.hint??""));return[s,...o]}function HV(t){return $i.has(t.action)?{...t,undo:null}:t}function UV(t){return $i.has(t.action)?{...t,action:"pending",undo:null}:t}async function KV(t,e){if(!t.initialised)return null;let n=BV(t);if(n===null||n.agents.length===0)return null;let r=Tg(t,n),o=await Fl(e,r,"preview");if(o.failed||o.rows.some((s)=>$i.has(s.action)))return null;return{checks:await Vl(!0,e,o.rows),plan:r,rows:o.rows}}function BV(t){try{return Wg(t,VV(),!0)}catch{return null}}function VV(){return{agents:void 0,init:void 0,kinds:void 0,pack:void 0,routing:void 0,scope:void 0}}async function Bl(t,e,n,r){let o=n.rows.some((i)=>i.action==="failed")||n.checks.some((i)=>!i.ok)||r.check&&!r.upToDate,s={check:r.check,checks:n.checks,dryRun:r.dryRun,next:T$,ok:!o,resume:r.dryRun||o?[]:await S$(e.root),root:e.root,routing:n.plan.routing,targets:n.rows,upToDate:r.upToDate,warnings:n.plan.warnings.map(({code:i,fix:a,message:c})=>({code:i,fix:a,message:c}))};if(r.visual)WV(e,s);return t.output.result(s,r.visual?void 0:N$),o?MV:0}function WV(t,e){let n=e.targets.find((r)=>r.action==="failed");if(n!==void 0){bt.error(Jr(`${ar(t,n)}: ${n.reason??""}`,n.hint??"")),ce(e.targets.some((r)=>$i.has(r.action))&&!e.dryRun?"Stopped; run 'ari install' again to finish":"Nothing was written");return}if(e.check){ce(e.ok?"Up to date: nothing would change and every check passed":"Not up to date, or a check failed");return}if(e.dryRun){ce("Dry run: nothing was written");return}if(e.upToDate){Nt(Qg(e),"Everything is up to date",qr),V$(e),ce(w.dim("To add an agent: ari install --agent <name>"));return}Nt(Qg(e),e.ok?"Done":"Done, with problems",qr),V$(e),ce(e.ok?"ari is ready":"Fix the failed checks, then run 'ari install' again")}function V$(t){let e=tm(t);if(e.length>0)Nt(e.join(`
242
+ `),"To undo",qr);let n=em(t);if(n.length>0)Nt(n.join(`
243
+ `),"To get back to your tasks",qr)}function JV(t,e,n,r){if(r)for(let o of e.warnings)bt.warn(Jr(o.message,o.fix));Nt(O$(n,t,e.routing),"Plan",qr)}async function qV(){if(await Ee({initialValue:!0,message:"Write these changes?"}))return;throw new vt}async function W$(t,e){try{return await e()}catch(n){if(t&&n instanceof vt)ys("Cancelled, nothing changed");throw n}}async function Vl(t,e,n){if(!t)return yg(e,n);let r=await q$("Checking the installation",()=>yg(e,n));if(r.length===0)return r;let o=r.filter((s)=>!s.ok);Nt(P$(r),o.length===0?"Self-check passed":"Self-check found problems",qr);for(let s of o)bt.error(Jr(`${s.name}: ${s.detail}`,s.hint??""));return r}function YV(t){let e=na();return{done:(n,r)=>e.stop(_$(t,r)),failed:(n,r)=>e.error(`${ar(t,r)} failed${n.file===null?"":` (${n.file})`}`),start:(n)=>e.start(`Writing ${n.file??ar(t,{agent:n.agent,file:n.file,kind:n.kind})}`)}}async function q$(t,e){let n=na();n.start(t);try{let r=await e();return n.clear(),r}catch(r){throw n.error(t),r}}var ts=st({id:{description:"Task id",required:!0}}),Y$=E({description:"Validate a draft contract and mark it ready",examples:["ari ready add-profile-inheritance"],json:!0,name:"ready",positionals:ts,run:async(t)=>{let e=await Cl(await _(),t.positionals.id);t.output.result(e,({id:n})=>`Task "${n}" is ready; run 'ari start ${n}'`)}}),X$=E({description:"Start a ready task in this worktree, or adopt one that no worktree holds",examples:["ari start add-profile-inheritance"],json:!0,name:"start",positionals:ts,run:async(t)=>{let e=await Rl(await _(),t.positionals.id);t.output.result(e,({id:n,instruction:r,stage:o})=>`Task "${n}" is active at stage ${o}
225
244
  ${r}
226
- Then: ari check, ari done`)}}),XE=E({args:j({onto:{description:"Move the base to the merge base of HEAD and this ref",type:"string"},reason:{description:"Why the contract or locked files changed",type:"string"}}),description:"Accept a changed contract: re-freeze its hashes and withdraw the stage's approvals",examples:['ari amend add-profile-inheritance --reason "Widen scope to the loader"'],json:!0,name:"amend",positionals:Co,run:async(t)=>{let e=Dn(t.args.reason,"--reason",`ari amend ${t.positionals.id} --reason <text>`),n=await NT(await O(),t.positionals.id,e,{onto:t.args.onto}),r={base:n.record.base,id:n.contract.id,reason:e,status:n.record.status};t.output.result(r,({id:o})=>`Task "${o}" amended`)}}),zE=E({args:j({reason:{description:"The question for a human",type:"string"}}),description:"Block the active task with a question for a human",examples:['ari block add-profile-inheritance --reason "Should child profiles inherit secrets?"'],json:!0,name:"block",positionals:Co,run:async(t)=>{let e=Dn(t.args.reason,"--reason",`ari block ${t.positionals.id} --reason <question>`),n=await Fc(await O(),t.positionals.id,e);t.output.result(n,({id:r})=>`Task "${r}" is blocked; a human answers with 'ari resolve ${r} --answer <text>'`)}}),ZE=E({args:j({answer:{description:"The answer to the task's question",type:"string"}}),description:"Answer a blocked task's question, record it as a decision and resume the task",examples:['ari resolve add-profile-inheritance --answer "No; secrets stay per profile"'],json:!0,name:"resolve",positionals:Co,run:async(t)=>{let e=Dn(t.args.answer,"--answer",`ari resolve ${t.positionals.id} --answer <text>`),n=await LT(await O(),t.positionals.id,e),{contract:r,record:o}=n.task,s={id:r.id,knowledgeId:n.knowledgeId,status:o.status};t.output.result(s,({id:i,knowledgeId:a})=>`Task "${i}" is active again; decision ${a} recorded`)}}),QE=E({description:"Record a human approval for the task's current stage (as git user.name)",examples:["ari approve add-profile-inheritance"],json:!0,name:"approve",positionals:Co,run:async(t)=>{let e=await O(),n=await Hf(e);if(n===null)throw new g("git user.name is not set",`Run 'git config user.name "<your name>"'`);let r=await MT(e,t.positionals.id,n),o=r.record.approvals.at(-1),s={by:n,id:r.contract.id,stage:o?.stage??null};t.output.result(s,({id:i,stage:a})=>`Approved stage ${a??"unknown"} of "${i}" as ${n}`)}});import{stripVTControlCharacters as LU}from"util";var t$=1,MU=2,jU=4,e$="Error",FU="Call the tool with the arguments its inputSchema describes";function n$(t){if(t instanceof b){let r=`Invalid arguments: ${t.message}`;return{error:{_tag:"UsageError",causes:[],exitCode:MU,hint:FU,message:r}}}if(!(t instanceof Error))return{error:{_tag:e$,causes:[],exitCode:t$,message:tl(String(t))}};let e=t instanceof g,n=e&&typeof t.hint==="string"?{hint:tl(t.hint)}:{};return{error:{_tag:e?t._tag:t.name||e$,causes:GU(t),exitCode:e?t.exitCode:t$,message:tl(t.message),...n}}}function GU(t){let e=[],n=new Set([t]),r=t.cause;while(r!==void 0&&!n.has(r)&&e.length<jU)n.add(r),e.push(tl(r instanceof Error?r.message:String(r))),r=r instanceof Error?r.cause:void 0;return e}function tl(t){return LU(t)}var l$=["2026-07-28"],rl=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],il="2.0",HU=-32700,ol=-32600,UU=-32601,Ro=-32602,KU=-32603,BU=-32022,sl="_meta",nl="io.modelcontextprotocol/protocolVersion",r$="io.modelcontextprotocol/clientCapabilities",WU="io.modelcontextprotocol/serverInfo",VU="complete",o$=3600000,s$="public",JU="2025-06-18",i$={tools:{listChanged:!1}},u$=[...l$,...rl];function d$(t){let e={legacy:null},n=(c)=>{let l=qU(c);if("error"in l)return se(l.error);let u=l.value,d=!("method"in u)&&(("result"in u)||("error"in u));if(!("id"in u)||d)return se(null);let p=YU(u);if("error"in p)return se(p.error);let{id:m,method:f,params:y}=p.value,S=!XU(y);if(S&&f==="initialize")return se(r(m,y));if(S&&f==="ping")return se(el(m,{}));let R=zU(m,y,e.legacy);if("error"in R)return se(R.error);switch(f){case"server/discover":return R.value.kind==="modern"?se(a(m,R.value,o())):se(c$(m,f));case"tools/list":return se(a(m,R.value,s(R.value)));case"tools/call":return i(m,R.value,y);default:return se(c$(m,f))}},r=(c,l)=>{let u=l.protocolVersion,d=typeof u==="string"&&rl.includes(u)?u:rl[0]??"";e.legacy=d;let{info:p,instructions:m}=t;return el(c,{capabilities:i$,instructions:m,protocolVersion:d,serverInfo:p})},o=()=>({cacheScope:s$,capabilities:i$,instructions:t.instructions,supportedVersions:u$,ttlMs:o$}),s=(c)=>{let l=t.tools.map(({annotations:u,description:d,inputSchema:p,name:m,title:f})=>({annotations:u,description:d,inputSchema:p,name:m,title:f}));return c.kind==="modern"?{cacheScope:s$,tools:l,ttlMs:o$}:{tools:l}},i=(c,l,u)=>{let{arguments:d={},name:p}=u;if(typeof p!=="string")return se(ie(c,Ro,"tools/call needs a tool name"));let m=t.tools.find((y)=>y.name===p);if(m===void 0)return se(ie(c,Ro,`Unknown tool: ${p}`));if(!Y(d))return se(ie(c,Ro,"tools/call arguments must be an object"));let f=async()=>{try{let y=await m.call(await t.root(),d);return a(c,l,a$(l,y.data,y.failed))}catch(y){return a(c,l,a$(l,n$(y),!0))}};return{kind:"queued",run:()=>f().catch((y)=>QU(c,y))}},a=(c,l,u)=>{if(l.kind==="legacy")return el(c,u);let d={[WU]:t.info};return el(c,{...u,[sl]:d,resultType:VU})};return{receive:n}}function se(t){return{kind:"now",message:t}}function a$(t,e,n){let r=[{text:JSON.stringify(e,null,2),type:"text"}],o=t.kind==="modern"||t.version>=JU;return{content:r,isError:n,...o?{structuredContent:e}:{}}}function qU(t){let e;try{e=JSON.parse(t)}catch{return{error:ie(null,HU,"Parse error: each line must hold one JSON-RPC message")}}if(Array.isArray(e))return{error:ie(null,ol,"JSON-RPC batches are not supported")};if(!Y(e))return{error:ie(null,ol,"A JSON-RPC message must be an object")};return{value:e}}function YU(t){let{id:e,jsonrpc:n,method:r,params:o={}}=t;if(!(typeof e==="string"||typeof e==="number"&&Number.isInteger(e)))return{error:ie(null,ol,"A request id must be a string or an integer")};if(n!==il||typeof r!=="string")return{error:ie(e,ol,'A request needs "jsonrpc": "2.0" and a method name')};if(!Y(o))return{error:ie(e,Ro,"params must be an object")};return{value:{id:e,method:r,params:o}}}function XU(t){return Y(t[sl])&&nl in t[sl]}function zU(t,e,n){let r=e[sl];if(Y(r)&&nl in r){let s=r[nl];if(typeof s!=="string"||!l$.includes(s))return{error:ZU(t,s)};if(!Y(r[r$]))return{error:ie(t,Ro,`_meta needs "${r$}"`)};return{value:{kind:"modern",version:s}}}if(n!==null)return{value:{kind:"legacy",version:n}};let o=`Missing _meta "${nl}"; clients of protocol ${rl[0]} and earlier send initialize first`;return{error:ie(t,Ro,o)}}function ZU(t,e){return{error:{code:BU,data:{requested:e,supported:u$},message:"Unsupported protocol version"},id:t,jsonrpc:il}}function c$(t,e){return ie(t,UU,`Method not found: ${e}`)}function QU(t,e){return ie(t,KU,`Internal error: ${e instanceof Error?e.message:String(e)}`)}function el(t,e){return{id:t,jsonrpc:il,result:e}}function ie(t,e,n){return{error:{code:e,message:n},id:t,jsonrpc:il}}var Wn="arguments",Vs={destructiveHint:!1,readOnlyHint:!0},Js={destructiveHint:!1,readOnlyHint:!1},p$={readOnlyHint:!1},S$={description:"Task id",type:"string"},zp={items:{type:"string"},type:"array"};function be(t){let{properties:e,required:n=[],...r}=t,o={additionalProperties:!1,properties:e,...n.length===0?{}:{required:[...n]},type:"object"};return{...r,inputSchema:o}}function en(t){return{data:t,failed:!1}}function ve(t,e){return C(t,Wn,Object.keys(e))}function nn(t,e){return ot(t,`${Wn}.${e}`)}function g$(t,e){return t===void 0?void 0:D(t,`${Wn}.${e}`,x)}var Io={},Oo={id:S$},m$={status:{...zp,description:"Only tasks with these statuses",items:{enum:$r}}},f$={pack:{description:"Methodology pack (defaults to config.pack)",type:"string"},scope:{...zp,description:"Globs of the files the task may change"},title:{description:"Task title",type:"string"}},h$={global:{description:"Write a project knowledge entry instead of a task note",type:"boolean"},kind:{description:"Knowledge entry kind, with global",enum:Qt},scope:{...zp,description:"Globs the knowledge entry applies to, with global"},text:{description:"The note",type:"string"}},y$={budget:{description:"Token budget (default: context.budget)",minimum:1,type:"integer"},id:{description:"Task id (default: the active task)",type:"string"}},k$={id:S$,reason:{description:"The question for a human",type:"string"}},w$={all:{description:"Include archived entries",type:"boolean"},query:{description:"Words to search for",type:"string"}},T$=[be({annotations:Vs,call:async(t,e)=>(ve(e,Io),en(await Pc(t))),description:"Start here: the one next action for this repository's Ariadne tasks. Loop: ari_next, change only files in the task's scope, ari_check, then ari_done until it passes.",name:"ari_next",properties:Io,title:"Next action"}),be({annotations:Vs,call:async(t,e)=>{let n=ve(e,m$),r=F(n.status,[],(o)=>D(o,`${Wn}.status`,(s,i)=>V($r,s,i)));return en(await Nc(t,r))},description:"List tasks (id, title, pack, status) and contracts or records that cannot be read.",name:"ari_list",properties:m$,title:"List tasks"}),be({annotations:Vs,call:async(t,e)=>en(await Dc(t,nn(ve(e,Oo).id,"id"))),description:"Show a task's contract, record, current stage and stage instruction.",name:"ari_show",properties:Oo,required:["id"],title:"Show task"}),be({annotations:Js,call:async(t,e)=>{let n=ve(e,f$),r=n.pack===void 0?void 0:nn(n.pack,"pack"),o=g$(n.scope,"scope")??[];return en(await Lc(t,{pack:r,scope:o,title:nn(n.title,"title")}))},description:"Create a draft task contract from a title. Then edit .ari/tasks/<id>.md (scope, criteria bound to checks) and call ari_ready.",name:"ari_new",properties:f$,required:["title"],title:"New task"}),be({annotations:Js,call:async(t,e)=>en(await Mc(t,nn(ve(e,Oo).id,"id"))),description:"Validate a draft contract, its pack and its dependencies, and mark it ready.",name:"ari_ready",properties:Oo,required:["id"],title:"Ready task"}),be({annotations:Js,call:async(t,e)=>en(await jc(t,nn(ve(e,Oo).id,"id"))),description:"Start a ready task in this worktree (needs no uncommitted changes outside .ari/), or adopt an active task no worktree holds.",name:"ari_start",properties:Oo,required:["id"],title:"Start task"}),be({annotations:p$,call:async(t,e)=>(ve(e,Io),Gc(t)),description:"Evaluate the active task's current stage gates without recording an attempt. isError is true while a gate fails.",name:"ari_check",properties:Io,title:"Check stage"}),be({annotations:p$,call:async(t,e)=>(ve(e,Io),Hc(t)),description:"Finish the current stage: run its gates, record the evidence and advance. isError is true when a gate fails; a failure uses an attempt, so run ari_check first.",name:"ari_done",properties:Io,title:"Finish stage"}),be({annotations:Js,call:async(t,e)=>{let n=ve(e,h$),r=F(n.global,!1,(i)=>Mt(i,`${Wn}.global`)),o=n.kind===void 0?void 0:V(Qt,n.kind,`${Wn}.kind`),s=g$(n.scope,"scope");return en(await Uc(t,{global:r,kind:o,scope:s,text:nn(n.text,"text")}))},description:"Record a learning: a note on the active task, or with global a project knowledge entry (kind fact, decision, constraint, pattern or gotcha).",name:"ari_note",properties:h$,required:["text"],title:"Add note"}),be({annotations:Vs,call:async(t,e)=>{let n=ve(e,y$),r=n.id===void 0?void 0:nn(n.id,"id"),o=n.budget===void 0?void 0:Zt(n.budget,`${Wn}.budget`);return en(await Kc(t,{budget:o,id:r}))},description:"The task's context pack: contract, last failure, constraints, notes and knowledge within a budget.",name:"ari_context",properties:y$,title:"Task context"}),be({annotations:Js,call:async(t,e)=>{let n=ve(e,k$);return en(await Fc(t,nn(n.id,"id"),nn(n.reason,"reason")))},description:"Block the active task with a question for a human when the contract is wrong or you are stuck. Only a human answers it.",name:"ari_block",properties:k$,required:["id","reason"],title:"Block task"}),be({annotations:Vs,call:async(t,e)=>{let n=ve(e,w$),r=F(n.all,!1,(o)=>Mt(o,`${Wn}.all`));return en(Bc(t,nn(n.query,"query"),r))},description:"Search the project's knowledge entries, ranked with BM25.",name:"ari_knowledge_search",properties:w$,required:["query"],title:"Search knowledge"})];var E$=`
227
- `,tK=/\r$/,eK={name:"ari",title:"Ariadne",version:ji},nK=["Ariadne tracks this repository's work as tasks with contracts and gates that it evaluates itself.","Loop: call ari_next and follow its action, change only files inside the active task's scope, call ari_check, then ari_done until it passes.","Ask a human with ari_block when stuck. Approving a stage, amending a contract and answering a blocked task are for humans only (ari approve, ari amend, ari resolve)."].join(" ");function rK(t){return d$({info:eK,instructions:nK,root:()=>On(t),tools:T$})}async function b$(t){let e=rK(t.cwd),n=(a)=>{if(a!==null)t.write(`${JSON.stringify(a)}${E$}`)},r=Promise.resolve(),o=(a)=>{if(a.kind==="now")n(a.message);else r=r.then(async()=>n(await a.run()))},s=new TextDecoder,i="";for await(let a of t.input){i+=s.decode(a,{stream:!0});let c=i.split(E$);i=c.pop()??"";for(let l of c)$$(e,l,o)}$$(e,i+s.decode(),o),await r}function $$(t,e,n){let r=e.replace(tK,"");if(r.trim().length>0)n(t.receive(r))}function al(t,e){let{agents:n,example:r,group:o,noun:s}=t,i=(c,l)=>{let u=`ari ${o} ${c} --agent`;return E({args:j({agent:{description:`Agent: ${n.join(", ")}`,type:"string"},scope:{description:`Where to write: ${fo.join(" or ")} (default: project)`,type:"string"}}),description:e[c],examples:[`${u} ${r.project}`,`${u} ${r.user} --scope user`],json:!0,name:c,run:async(d)=>{let p=t.target(Dn(d.args.agent,"--agent",`${u} <name>`)),m=await Ot(ho(d.args.scope),process.cwd()),f=l(p,m);d.output.result(f,(y)=>`${y.agent} ${s} ${y.action} in ${y.file} (${y.scope} scope)`)}})},a=E({description:e.list,examples:[`ari ${o} list --json`],json:!0,name:"list",run:async(c)=>{let l=process.cwd(),u=t.summaries(await Ot("project",l),await Ot("user",l));c.output.result({agents:u},({agents:d})=>d.map(oK).join(`
228
- `))}});return[i("install",t.install),i("uninstall",t.uninstall),a]}function oK(t){let e=t.files.map((n)=>`${n.scope} ${n.installed?"installed":"not installed"} ${n.file}`);return`${t.agent} ${e.join("; ")}`}var sK=`ari mcp serve speaks the Model Context Protocol on stdin and stdout; an agent starts it. Press Ctrl-D to stop.
229
- `,iK=E({description:"Serve the task loop to an agent as a stdio MCP server",examples:["ari mcp serve"],name:"serve",run:async()=>{if(process.stdin.isTTY)process.stderr.write(sK);await b$({cwd:process.cwd(),input:Bun.stdin.stream(),write:(t)=>{process.stdout.write(t)}})}}),aK=al({agents:Jt.map((t)=>t.agent),example:{project:"claude",user:"codex"},group:"mcp",install:ko,noun:'MCP server "ari"',summaries:dS,target:ne,uninstall:lc},{install:"Register 'ari mcp serve' in an agent's MCP configuration",list:"List the agents ari can register its MCP server with, and where it is registered",uninstall:"Remove ari's MCP server from an agent's configuration, and nothing else"}),v$=E({description:"Serve ari's task tools to agents over MCP, and register the server with them",name:"mcp",subcommands:[iK,...aK]});var x$=1;async function A$(t,e){let n=L(t),r=gr(n,{...e,role:"review",route:lK(n)}),o=e.task??await uK(t),s=await $n(t,o),i=s.stage??s.task.record.status,{contractText:a}=lt(t,o,n),c=cK(n,e),l={config:n,contractText:a,root:t,stage:i,task:s.task,...c===null?{}:{argus:c}},{evidence:u,...d}=await $d(l,r);return{...d,stage:i,task:o}}function cK(t,e){if(e.argus===!1)return null;let n=t.review.argus;if(n===void 0&&e.argus!==!0)return null;if(n===void 0)throw new g("--argus needs review.argus in .ari/config.json",'Add "review": { "argus": { "config": "<path of the argus config>" } } to .ari/config.json, or leave out --argus',x$,{tag:"ArgusNotConfigured"});return{argus:n,explicit:e.argus===!0,...e.notify?{notify:e.notify}:{}}}function lK(t){if(t.routing.review!==null)return t.routing.review;let{agent:e,model:n}=t.review;return e===void 0?null:{agent:e,model:n??null}}async function uK(t){let e=ut(await M(t));if(e!==null)return e.task;throw new g("No task is active in this worktree","Pass --task <id>, or run 'ari next' to see what to do",x$,{tag:"NoActiveTask"})}var dK=1,C$=E({args:j({agent:{description:"Review agent from config.agents (default: routing.review, then review.agent)",type:"string"},argus:{description:"Add (--argus, fails when argus cannot answer) or leave out (--no-argus) argus candidates; see review.argus",type:"boolean"},model:{description:"Model for the review agent",type:"string"},task:{description:"Task id (default: the active task)",type:"string"}}),description:"Have a review agent judge a task's change in a temporary copy; any doubt fails the review",examples:["ari review","ari review --agent codex --model gpt-5.5 --json","ari review --argus"],json:!0,name:"review",run:async(t)=>{let e=await A$(await O(),{agent:qe(t.args.agent,"--agent"),argus:t.args.argus,model:qe(t.args.model,"--model"),notify:(n)=>pt.info(n),task:qe(t.args.task,"--task")});return t.output.result(e,pK),e.ok?void 0:dK}});function pK(t){let e=t.model===null?"":` (${t.model})`,n=`Review of "${t.task}" by ${t.agent}${e}: ${t.ok?"pass":"FAIL"}`,r=t.findings.map((i)=>` - ${Ha(i)}`),o=t.problems.map((i)=>` ! ${i}`),s=(t.argus===void 0?[]:Fa(t.argus)).map((i)=>` ~ ${i}`);return[n,...o,...s,...r].join(`
230
- `)}var gK=1,R$=E({args:j({agent:{description:"Agent name from config.agents (default: the routing for each stage)",type:"string"},model:{description:"Model for the agent, overriding its model and the routing's",type:"string"},task:{description:"Task id (defaults to the active task, then the next startable one)",type:"string"}}),description:"Drive a task headlessly with an agent until it is done, blocked or out of attempts",examples:["ari run --agent claude","ari run --agent codex --model gpt-5.5 --task add-profile-inheritance --json","ari run --json"],json:!0,name:"run",run:async(t)=>{let e=await WT(await O(),{agent:qe(t.args.agent,"--agent"),model:qe(t.args.model,"--model"),output:t.json?"stderr":"inherit",task:t.args.task});return t.output.result(e,mK),e.outcome==="done"?void 0:gK}});function mK(t){return[...t.turns.map((n,r)=>`turn ${r+1}: stage ${n.stage}, ${n.agent}${n.model===null?"":` (${n.model})`} ${n.timedOut?"timed out":`exit ${n.agentExitCode}`}, ${n.outcome}${n.failing.length===0?"":` (${n.failing.join(", ")})`}`),`Task "${t.task}" is ${t.outcome}`].join(`
231
- `)}var I$=E({description:`Install the ${Me} skill, which teaches an agent the task loop`,name:"skills",subcommands:al({agents:qt.map((t)=>t.agent),example:{project:"claude",user:"codex"},group:"skills",install:wo,noun:`skill "${Me}"`,summaries:kS,target:re,uninstall:pc},{install:`Write the ${Me} skill into an agent's skills directory`,list:`List the agents ari can install the ${Me} skill for, and where it is installed`,uninstall:`Remove the ${Me} skill that ari installed, and nothing else`})});var O$=E({args:j({pack:{description:"Methodology pack (defaults to config.pack)",type:"string"},scope:{description:"Scope globs, comma-separated",type:"string"}}),description:"Create a task contract from a title",examples:['ari new "Add profile inheritance" --pack tdd --scope "src/profiles/**"'],json:!0,name:"new",positionals:at({title:{description:"Task title",required:!0}}),run:async(t)=>{let e=await Lc(await O(),{pack:t.args.pack,scope:wn(t.args.scope),title:t.positionals.title});t.output.result(e,({contractPath:n,id:r})=>`Created task "${r}" at ${n}
232
- Complete its scope, criteria and checks, then run 'ari ready ${r}'`)}}),_$=E({args:j({status:{description:`Only these statuses, comma-separated (${$r.join(",")})`,type:"string"}}),description:"List tasks and any unreadable contracts or records",examples:["ari list","ari list --status ready,active --json"],json:!0,name:"list",run:async(t)=>{let e=qT(wn(t.args.status));t.output.result(await Nc(await O(),e),fK)}}),P$=E({description:"Show a task's contract, record and current stage",examples:["ari show add-profile-inheritance --json"],json:!0,name:"show",positionals:at({id:{description:"Task id",required:!0}}),run:async(t)=>{t.output.result(await Dc(await O(),t.positionals.id),hK)}});function fK(t){if(t.tasks.length===0&&t.invalid.length===0)return'No tasks yet. Run ari new "<title>"';let e=t.tasks.map((r)=>`${r.id} ${r.status} ${r.pack} ${r.title}`),n=t.invalid.map((r)=>`${r.id} unreadable ${r.problem}`);return[...e,...n].join(`
233
- `)}function hK(t){let{contract:e,record:n}=t.task,r=t.stage===null?[]:[`Stage: ${t.stage}${t.active?" (active here)":""}`],o=t.instruction===null?[]:[`Instruction: ${t.instruction}`],s=n.question===null?[]:[`Question: ${n.question}`];return[`${e.id}: ${e.title}`,`Status: ${n.status} Pack: ${e.pack} Attempts: ${n.attempts}/${e.budget.attempts}`,...r,...o,...s,`Scope: ${e.scope.join(", ")||"none"}`,...e.criteria.map((i)=>`${i.id}: ${i.text} [${i.checks.join(", ")}]`),...e.checks.map((i)=>`check ${i.name} (expect ${i.expect}): ${i.run}`)].join(`
234
- `)}var yK=1,kK=12,D$=E({args:j({revoke:{default:!1,description:"Forget the trust record of this repository",type:"boolean"},yes:{alias:"y",default:!1,description:"Trust the commands without asking",type:"boolean"}}),description:"Show, grant or revoke trust in the commands that .ari makes ari run",examples:["ari trust","ari trust --yes","ari trust --revoke","ari trust --json"],json:!0,name:"trust",run:async(t)=>{if(t.args.revoke&&t.args.yes)throw new T("--revoke and --yes conflict","Pass only one of them");let e=await O(),n=L(e),r=Zr();if(t.args.revoke){let c=my(e),l={...De(e,n),action:c?"revoked":"none",environment:r};t.output.result(l,N$);return}let o=De(e,n),s=kn(o)&&(t.args.yes||await wK(t.json,o)),i=s?Qr(e,n):o,a={...i,action:s?"trusted":"none",environment:r};return t.output.result(a,N$),kn(i)&&!r?yK:void 0}});async function wK(t,e){if(!Jn({json:t}))return!1;return md(e.root,e.commands)}function N$(t){let e=[`Trust for ${t.root}: ${SK(t)}`,...gd(t.commands)],n=[...t.action==="trusted"?["Trusted the commands above"]:[],...t.action==="revoked"?["Revoked the trust record of this repository"]:[],...t.environment?[`${lr}=1 is set, so ari runs these commands without a record`]:[],...kn(t)&&t.action!=="revoked"?["Review the commands above, then run 'ari trust --yes' or answer the prompt in a terminal"]:[]];return[...e,...n].join(`
235
- `)}function SK(t){switch(t.state){case"trusted":return`trusted since ${t.trustedAt} (configuration ${t.sha256.slice(0,kK)})`;case"changed":return`not trusted: the commands changed since ${t.trustedAt}`;case"untrusted":return"not trusted";case"not-required":return"nothing to trust, the configuration starts no commands"}}var TK="Fix the cause, then run 'ari uninstall' again; it keeps what is already done",EK="as it was before the install, byte for byte",$K="only ari's entries: the file changed after the install, so your edits stay";async function Zp(t,e,n,r){let o={bases:n,mode:r,preview:nd(),root:t},s=[];for(let i of e.targets){if(i.skip!==null){s.push(cl(i,"skipped",{reason:i.skip}));continue}try{s.push(...await bK(o,i))}catch(a){let c=cl(i,"failed",{hint:NK(a),reason:PK(a)});s.push({...c,file:CK(i)})}}return s}async function bK(t,e){if(e.kind==="git")return AK(t,e);let n=_K(e.agent),r=OK(t,e.scope),o=t.mode==="preview"?t.preview:nd(),s=await vK(t,e,n,r,o);if(t.mode==="apply")await xK(t,e,n,r);return[RK(e,s,L$(e.kind,n,e.scope))]}async function vK(t,e,n,r,o){if(e.kind==="hooks"){let i=Qp(t);return id(i,Se(n),{forget:!1,state:await M(i),view:o})}let s=e.kind==="mcp"?Te(ne(n),r):Ee(re(n),r);return rp(s,o,!1)}async function xK(t,e,n,r){if(e.kind==="hooks"){let o=Qp(t);_a(o,Se(n),await M(o));return}if(e.kind==="mcp")lc(ne(n),r);else pc(re(n),r)}async function AK(t,e){let n=Qp(t),r=await ps(n);if(t.mode==="apply")await Ca(n);return r.map(({action:o,path:s})=>({...cl(e,o==="removed"?"removed":"unchanged",{}),file:s}))}function CK(t){return t.agent===null?null:L$(t.kind,t.agent,t.scope)}function L$(t,e,n){if(t==="hooks")return Se(e).file;let r=t==="mcp"?ne(e)[n]:re(e)[n];return ee(n,r??"")}function RK(t,e,n){let r=IK(e),o=e.restored===null?null:e.restored==="original"?EK:$K;return{...cl(t,r,{detail:o}),file:n}}function IK({action:t}){return t==="removed"?"removed":t==="unchanged"?"unchanged":"restored"}function cl(t,e,n){return{action:e,agent:t.agent,detail:n.detail??null,file:null,hint:n.hint??null,kind:t.kind,reason:n.reason??null,scope:t.scope}}function OK(t,e){let n=t.bases[e];if(n!==void 0)return n;throw Error(`The ${e} scope is not part of this uninstall`)}function Qp({root:t}){if(t!==null)return t;throw Error("This uninstall target needs a repository")}function _K(t){if(t!==null)return t;throw Error("This uninstall target needs an agent")}function PK(t){return t instanceof Error?t.message:String(t)}function NK(t){return t instanceof g&&t.hint!==void 0&&t.hint.length>0?t.hint:TK}var DK=[{how:"Delete the directory yourself: rm -r .ari",what:".ari/: tasks, knowledge, configuration and routing, packs"},{how:"Delete the lines from <!-- ari:begin --> to <!-- ari:end --> by hand",what:"The ari block in AGENTS.md"},{how:'Delete the directory yourself: rm -r "$(git rev-parse --git-path ari)"',what:"Journals, the active-task pointer and the sleep ledger under the git directory"},{how:"Run 'ari trust --revoke' in this repository",what:"The trust record for this repository on this machine"}],LK=[{how:"Delete the directory yourself: rm -r ~/.ari",what:"~/.ari: the trust records and the receipts of anything still installed"}];function M$(t){return t==="project"?DK:LK}var MK=["git","skill","mcp","hooks"],jK=["skill","mcp"],FK=new Set(["hooks","git"]),GK=[...et].reverse(),j$="ari does not write this",HK={claude:"Claude Code keeps user-scope MCP servers itself; run 'claude mcp remove --scope user ari'"};async function F$(t,e){if(e==="user")return{user:await Ot("user",process.cwd())};if(t===null)throw Error("A project-scope uninstall needs a repository root");return{project:{base:t,receipts:await M(t),scope:e}}}function G$(t){if(t.scope!=="user"||t.kinds===void 0)return;if(![...t.kinds].some((e)=>FK.has(e)))return;throw new T("--hooks and --git-hooks belong to a repository, so they cannot go with --scope user","Use --mcp or --skills with --scope user, or drop --scope")}async function H$(t,e,n){let{scope:r}=e,o=r==="user"?jK:MK,s=[];for(let i of o.filter((a)=>e.kinds?.has(a)??!0))s.push(...i==="git"?await KK(t,e):UK(i,t,e,n));return{scope:r,targets:s}}function UK(t,e,n,r){let{agents:o,scope:s}=n,i=r[s];if(i===void 0)return[];return GK.filter((a)=>o?.includes(a)??!0).flatMap((a)=>{let c=BK(t,a,s);if(c===void 0)return[];let l={agent:a,kind:t,scope:s};if(c===null)return o===void 0?[]:[{...l,skip:WK(t,a,s)}];return JK(()=>VK(t,a,e,i),!0)||o!==void 0?[{...l,skip:null}]:[]})}async function KK(t,e){let n=e.kinds?.has("git")===!0;if(t===null||e.agents!==void 0&&!n)return[];return(await ps(t)).some(({action:o})=>o==="removed")||n?[{agent:null,kind:"git",scope:"project",skip:null}]:[]}function BK(t,e,n){if(t==="hooks"){let o=he.find((s)=>s.name===e);return o===void 0?void 0:n==="project"?o.file:null}return(t==="mcp"?Jt:qt).find((o)=>o.agent===e)?.[n]}function WK(t,e,n){if(t==="mcp")return HK[e]??`${j$} ${e}'s ${n}-scope MCP configuration`;return`${j$} ${e}'s ${n}-scope ${t}`}function VK(t,e,n,r){if(t==="mcp")return En(Te(ne(e),r));if(t==="skill")return En(Ee(re(e),r));let o=he.find((s)=>s.name===e);return n!==null&&o!==void 0&&Ye(n,o)}function JK(t,e){try{return t()}catch{return e}}var ll=" ",U$=11,qK=34,YK=66,K$=72,XK=["removed","restored","unchanged","skipped","failed"],zK={failed:"failed",removed:"remove",restored:"restore",skipped:"skip",unchanged:"unchanged"};function B$(t){return t.targets.length===0}function ZK(t){if(t.kind==="git")return"git hook";return`${t.agent??""} ${Fe[t.kind]}`.trim()}function W$(t){return t.flatMap((e)=>J$(e,!0)).join(`
236
- `)}function QK(t){return t.targets.flatMap((e)=>J$(e,t.dryRun)).join(`
237
- `)}function tg(t){return t.flatMap((e)=>[...xr(e.what,K$),...xr(e.how,K$-ll.length).map((n)=>k.dim(`${ll}${n}`))]).join(`
238
- `)}function eg(t){let e=XK.flatMap((n)=>{let r=t.filter((o)=>o.action===n).length;return r===0?[]:[`${r} ${n}`]});return e.length===0?"Nothing to remove":e.join(", ")}function V$(t){let e=t.dryRun?"Dry run: nothing was written":eg(t.targets),n=B$(t)?[]:[QK(t),""],r=B$(t)?[]:["","Kept",tg(t.kept)];return[...n,e,...r].join(`
239
- `)}function J$(t,e){let n=nt(e?zK[t.action]:t.action,U$),r=nt(t.file??"",qK),o=`${ll}${tB(t.action,n)}${r}${k.dim(ZK(t))}`,s=[t.detail,t.reason,t.hint].flatMap((i)=>i===null?[]:xr(i,YK).map((a)=>`${ll}${" ".repeat(U$)}${k.dim(a)}`));return[$e(o),...s]}function tB(t,e){switch(t){case"removed":case"restored":return k.green(e);case"failed":return k.red(e);case"skipped":return k.yellow(e);case"unchanged":return k.dim(e)}}var eB=1,ng={format:(t)=>t},nB=j({agent:{description:`Only these agents, comma-separated: ${et.join(", ")}`,type:"string"},dryRun:{alias:"d",description:"Show what would be removed and write nothing",type:"boolean"},gitHooks:{description:"Remove the pre-commit and pre-push git hooks",type:"boolean"},hooks:{description:"Remove each agent's hooks",type:"boolean"},mcp:{description:"Remove ari's MCP server from each agent",type:"boolean"},scope:{description:"Where MCP servers and skills were installed: project or user (default: project)",type:"string"},skills:{description:"Remove the ariadne skill from each agent",type:"boolean"},yes:{alias:"y",description:"Remove without asking",type:"boolean"}}),Y$=E({args:nB,description:"Remove what 'ari install' put here: agent hooks, MCP server, skill and git hooks, giving every file back as it was",examples:["ari uninstall --dry-run","ari uninstall --yes","ari uninstall --agent claude --yes","ari uninstall --mcp --scope user --yes"],json:!0,name:"uninstall",prompts:!0,run:async(t)=>rB(t)});async function rB(t){let e=aB(t.args),n=t.args.dryRun===!0,r=t.args.yes===!0;if(!t.interactive&&!r&&!n)throw lB();let o=t.interactive,s=e.scope==="project"?await O():null,i=await F$(s,e.scope);if(o)Zn(`${k.bold("ari uninstall")} ${k.dim(`Ariadne ${t.cli.version??""}`)}`);let a=await H$(s,e,i),c=await Zp(s,a,i,"preview");if(o&&c.length>0)St(W$(c),"Plan",ng);let l=c.some((d)=>d.action==="removed"||d.action==="restored");if(n)return q$(t,s,e,c,{dryRun:n,visual:o});if(l&&o&&!r)await iB(()=>sB());let u=await Zp(s,a,i,"apply");return q$(t,s,e,u,{dryRun:!1,visual:o})}function q$(t,e,n,r,o){let s=r.some((a)=>a.action==="failed"),i={dryRun:o.dryRun,kept:[...M$(n.scope)],ok:!s,root:e,scope:n.scope,targets:r};if(o.visual)oB(i);return t.output.result(i,o.visual?void 0:V$),s?eB:0}function oB(t){if(t.targets.length===0){Xt("Nothing to remove");return}if(t.dryRun){Xt("Dry run: nothing was written");return}St(eg(t.targets),t.ok?"Done":"Done, with problems",ng),St(tg(t.kept),"Kept",ng),Xt(t.ok?"ari is out of this setup":"Fix the failed rows, then run 'ari uninstall' again")}async function sB(){if(await ue({initialValue:!0,message:"Remove these?"}))return;throw new dt}async function iB(t){try{await t()}catch(e){if(e instanceof dt)Bo("Cancelled, nothing changed");throw e}}function aB(t){let e=new Set([...t.hooks===!0?["hooks"]:[],...t.mcp===!0?["mcp"]:[],...t.skills===!0?["skill"]:[],...t.gitHooks===!0?["git"]:[]]),n={agents:t.agent===void 0?void 0:cB(t.agent),kinds:e.size===0?void 0:e,scope:ho(t.scope)};return G$(n),n}function cB(t){let e=[...new Set(wn(t))];if(e.length===0)throw new T("--agent needs at least one agent",`Choose from: ${et.join(", ")}`);return e.map((n)=>{if(kc(n))return n;throw new T(`ari uninstall has no agent "${n}"`,`Choose from: ${et.join(", ")}`)})}function lB(){return new T("ari uninstall needs --yes or --dry-run when it cannot ask","Run 'ari uninstall --dry-run' to see what it would remove, then 'ari uninstall --yes'")}var X$=E({name:"context",description:"Print the context pack of a task within a token budget",args:j({budget:{description:"Token budget (default: context.budget from .ari/config.json)",type:"number"}}),positionals:at({id:{description:"Task id (default: the active task of this worktree)"}}),json:!0,examples:["ari context","ari context add-profile-inheritance --budget 2000","ari context --json"],run:async(t)=>{let e=await Kc(await O(),{budget:t.args.budget,id:t.positionals.id});t.output.result(e,({text:n})=>n)}});var uB=" ",dB=E({name:"list",description:"List project knowledge entries",args:j({all:{default:!1,description:"Include archived entries",type:"boolean"}}),json:!0,examples:["ari knowledge list","ari knowledge list --all --json"],run:async(t)=>{let e=Od(await O(),{all:t.args.all});t.output.result(e,hB)}}),pB=E({name:"search",description:"Rank knowledge entries against a query with BM25",args:j({all:{default:!1,description:"Include archived entries",type:"boolean"}}),positionals:at({query:{description:"Words to search for",required:!0,variadic:!0}}),json:!0,examples:["ari knowledge search profile resolution"],run:async(t)=>{let e=t.positionals.query.join(uB),n=Bc(await O(),e,t.args.all);t.output.result(n,yB)}}),gB=E({name:"show",description:"Show one knowledge entry and how many done tasks used it",positionals:at({id:{description:"Knowledge entry id",required:!0}}),json:!0,run:async(t)=>{let e=await O(),{tasks:n}=await Ic(e);t.output.result(zk(e,t.positionals.id,n),kB)}}),mB=E({name:"archive",description:"Archive a knowledge entry",args:j({force:{default:!1,description:"Allow archiving a constraint or decision",type:"boolean"}}),positionals:at({id:{description:"Knowledge entry id",required:!0}}),json:!0,run:async(t)=>{let e=await O(),n=Zk(e,t.positionals.id,{force:t.args.force});t.output.result(n,(r)=>`Archived ${r.kind} ${r.id}`)}}),fB=E({name:"restore",description:"Restore an archived knowledge entry, byte for byte when the sleep ledger holds its original",positionals:at({id:{description:"Knowledge entry id",required:!0}}),json:!0,examples:["ari knowledge restore build-uses-bun"],run:async(t)=>{let e=await fE(await O(),t.positionals.id);t.output.result(e,(n)=>`Restored ${n.kind} ${n.id}`)}}),z$=E({name:"knowledge",description:"List, search, show, archive and restore project knowledge",subcommands:[dB,pB,gB,mB,fB]});function Z$(t){let e=t.status==="active"?"":` [${t.status}]`,n=t.text.split(`
240
- `)[0]??"";return`${t.id} (${t.kind})${e}: ${n}`}function hB(t){return t.entries.length===0?"No knowledge entries":t.entries.map(Z$).join(`
241
- `)}function yB(t){if(t.matches.length===0)return`No knowledge entry matches "${t.query}"`;return t.matches.map((e)=>`${e.score.toFixed(2)} ${Z$(e.entry)}`).join(`
242
- `)}function kB(t){let{entry:e}=t,n=(r)=>r.length===0?"none":r.join(", ");return[`${e.id} (${e.kind}, ${e.status})`,`Scope: ${n(e.scope)}`,`Sources: ${n(e.sources)}`,`Created: ${e.created}`,`Used by done tasks: ${t.uses}`,...e.supersedes.length===0?[]:[`Supersedes: ${n(e.supersedes)}`],...e.supersededBy===null?[]:[`Superseded by: ${e.supersededBy}`],"",e.text].join(`
243
- `)}var wB=" ",Q$=E({name:"note",description:"Add a note to the active task, or a project knowledge entry with --global",args:j({global:{default:!1,description:"Write a project knowledge entry instead of a task note",type:"boolean"},kind:{description:`Entry kind with --global: ${Qt.join(", ")} (default: fact)`,type:"string"},scope:{description:"Comma-separated globs the entry applies to, with --global (default: everywhere)",type:"string"}}),positionals:at({text:{description:"The note text",required:!0,variadic:!0}}),json:!0,examples:['ari note "The fixture needs a real git repository"','ari note --global --kind constraint --scope "packages/atlas/src/**" "Profile resolution stays synchronous"'],run:async(t)=>{let{global:e,kind:n,scope:r}=t.args,o={global:e,kind:n,scope:r===void 0?void 0:qk(r),text:t.positionals.text.join(wB)};t.output.result(await Uc(await O(),o),SB)}});function SB(t){return t.target==="task"?`Added note ${t.index} to ${t.task}`:`Added ${t.entry.kind} ${t.entry.id} to .ari/knowledge`}var rg="HEAD~1",TB={fail:"fail",pass:"pass",regression:"pass"};async function tb(t,e={}){let n=L(t),r=e.since??rg,o=await Hr(t,r),s=Wt(await pe(t,o)),{tasks:i}=It(t,n),a=i.filter((u)=>u.record.status==="done"&&s.some((d)=>Z(d,u.contract.scope))),c=Ne(t),l=[];for(let u of a){let d=await $B(t,u),p=c.filter((m)=>m.sources.includes(u.contract.id)).map((m)=>m.id);l.push({checks:d,knowledge:p,ok:d.every((m)=>m.ok),task:u.contract.id})}return{changed:s.length,commit:o,regressed:l.filter((u)=>!u.ok).map((u)=>u.task),since:r,tasks:l}}function EB(t){return{command:t.command,exitCode:t.exitCode,expect:t.expect,name:t.name,ok:t.ok,outputTail:t.outputTail,timedOut:t.timedOut}}async function $B(t,e){let n=[];for(let r of e.contract.checks){let[o]=await Le([vB(r)],bB(e,r),t);if(o!==void 0)n.push(EB(o))}return n}function bB(t,e){return(t.record.evidence.at(-1)?.gates.flatMap((r)=>r.checks)??[]).findLast((r)=>r.name===e.name)?.expect??TB[e.expect]}function vB(t){return{name:t.name,run:t.run,timeoutSeconds:t.timeoutSeconds}}var xB=1,eb=E({name:"replay",description:"Re-run the checks of done tasks whose scope changed since a reference",args:j({since:{default:rg,description:"Reference to compare with",type:"string"}}),json:!0,examples:["ari replay","ari replay --since origin/develop --json"],run:async(t)=>{let e=await tb(await O(),{since:t.args.since});return t.output.result(e,AB),e.regressed.length===0?void 0:xB}});function AB(t){let e=`Replayed ${t.tasks.length} done tasks against ${t.since} (${t.changed} changed files)`,n=t.tasks.flatMap((r)=>{if(r.ok)return[`ok ${r.task}`];let o=r.checks.filter((i)=>!i.ok),s=r.knowledge.length===0?[]:[` cited by: ${r.knowledge.join(", ")}`];return[`REGRESSED ${r.task}`,...o.flatMap((i)=>[` ${i.name} should ${i.expect}: ${i.command}`,CB(i.outputTail)]),...s]});return[e,...n].join(`
244
- `)}function CB(t){return t.trimEnd().split(`
245
+ Then: ari check, ari done`)}}),z$=E({args:j({onto:{description:"Move the base to the merge base of HEAD and this ref",type:"string"},reason:{description:"Why the contract or locked files changed",type:"string"}}),description:"Accept a changed contract: re-freeze its hashes and withdraw the stage's approvals",examples:['ari amend add-profile-inheritance --reason "Widen scope to the loader"'],json:!0,name:"amend",positionals:ts,run:async(t)=>{let e=ln(t.args.reason,"--reason",`ari amend ${t.positionals.id} --reason <text>`),n=await NE(await _(),t.positionals.id,e,{onto:t.args.onto}),r={base:n.record.base,id:n.contract.id,reason:e,status:n.record.status};t.output.result(r,({id:o})=>`Task "${o}" amended`)}}),Z$=E({args:j({reason:{description:"The question for a human",type:"string"}}),description:"Block the active task with a question for a human",examples:['ari block add-profile-inheritance --reason "Should child profiles inherit secrets?"'],json:!0,name:"block",positionals:ts,run:async(t)=>{let e=ln(t.args.reason,"--reason",`ari block ${t.positionals.id} --reason <question>`),n=await Il(await _(),t.positionals.id,e);t.output.result(n,({id:r})=>`Task "${r}" is blocked; a human answers with 'ari resolve ${r} --answer <text>'`)}}),Q$=E({args:j({answer:{description:"The answer to the task's question",type:"string"}}),description:"Answer a blocked task's question, record it as a decision and resume the task",examples:['ari resolve add-profile-inheritance --answer "No; secrets stay per profile"'],json:!0,name:"resolve",positionals:ts,run:async(t)=>{let e=ln(t.args.answer,"--answer",`ari resolve ${t.positionals.id} --answer <text>`),n=await LE(await _(),t.positionals.id,e),{contract:r,record:o}=n.task,s={id:r.id,knowledgeId:n.knowledgeId,status:o.status};t.output.result(s,({id:i,knowledgeId:a})=>`Task "${i}" is active again; decision ${a} recorded`)}}),tT=E({description:"Record a human approval for the task's current stage (as git user.name)",examples:["ari approve add-profile-inheritance"],json:!0,name:"approve",positionals:ts,run:async(t)=>{let e=await _(),n=await Oy(e);if(n===null)throw new m("git user.name is not set",`Run 'git config user.name "<your name>"'`);let r=await ME(e,t.positionals.id,n),o=r.record.approvals.at(-1),s=await Fo(e,r.contract.id,"approve");if(s.warning!==null)process.stderr.write(`${s.warning}
246
+ `);let i={by:n,id:r.contract.id,stage:o?.stage??null,...s.id===null?{}:{snapshot:s.id}};t.output.result(i,({id:a,snapshot:c,stage:l})=>{let u=`Approved stage ${l??"unknown"} of "${a}" as ${n}`;return c===void 0?u:`${u}
247
+ Snapshot ${c} saved`})}});import{stripVTControlCharacters as XV}from"util";var eT=1,zV=2,ZV=4,nT="Error",QV="Call the tool with the arguments its inputSchema describes";function rT(t){if(t instanceof b){let r=`Invalid arguments: ${t.message}`;return{error:{_tag:"UsageError",causes:[],exitCode:zV,hint:QV,message:r}}}if(!(t instanceof Error))return{error:{_tag:nT,causes:[],exitCode:eT,message:Wl(String(t))}};let e=t instanceof m,n=e&&typeof t.hint==="string"?{hint:Wl(t.hint)}:{};return{error:{_tag:e?t._tag:t.name||nT,causes:tW(t),exitCode:e?t.exitCode:eT,message:Wl(t.message),...n}}}function tW(t){let e=[],n=new Set([t]),r=t.cause;while(r!==void 0&&!n.has(r)&&e.length<ZV)n.add(r),e.push(Wl(r instanceof Error?r.message:String(r))),r=r instanceof Error?r.cause:void 0;return e}function Wl(t){return XV(t)}var uT=["2026-07-28"],Yl=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],Zl="2.0",eW=-32700,Xl=-32600,nW=-32601,es=-32602,rW=-32603,oW=-32022,zl="_meta",ql="io.modelcontextprotocol/protocolVersion",oT="io.modelcontextprotocol/clientCapabilities",sW="io.modelcontextprotocol/serverInfo",iW="complete",sT=3600000,iT="public",aW="2025-06-18",aT={tools:{listChanged:!1}},dT=[...uT,...Yl];function pT(t){let e={legacy:null},n=(c)=>{let l=cW(c);if("error"in l)return ye(l.error);let u=l.value,d=!("method"in u)&&(("result"in u)||("error"in u));if(!("id"in u)||d)return ye(null);let p=lW(u);if("error"in p)return ye(p.error);let{id:g,method:f,params:y}=p.value,S=!uW(y);if(S&&f==="initialize")return ye(r(g,y));if(S&&f==="ping")return ye(Jl(g,{}));let I=dW(g,y,e.legacy);if("error"in I)return ye(I.error);switch(f){case"server/discover":return I.value.kind==="modern"?ye(a(g,I.value,o())):ye(lT(g,f));case"tools/list":return ye(a(g,I.value,s(I.value)));case"tools/call":return i(g,I.value,y);default:return ye(lT(g,f))}},r=(c,l)=>{let u=l.protocolVersion,d=typeof u==="string"&&Yl.includes(u)?u:Yl[0]??"";e.legacy=d;let{info:p,instructions:g}=t;return Jl(c,{capabilities:aT,instructions:g,protocolVersion:d,serverInfo:p})},o=()=>({cacheScope:iT,capabilities:aT,instructions:t.instructions,supportedVersions:dT,ttlMs:sT}),s=(c)=>{let l=t.tools.map(({annotations:u,description:d,inputSchema:p,name:g,title:f})=>({annotations:u,description:d,inputSchema:p,name:g,title:f}));return c.kind==="modern"?{cacheScope:iT,tools:l,ttlMs:sT}:{tools:l}},i=(c,l,u)=>{let{arguments:d={},name:p}=u;if(typeof p!=="string")return ye(ke(c,es,"tools/call needs a tool name"));let g=t.tools.find((y)=>y.name===p);if(g===void 0)return ye(ke(c,es,`Unknown tool: ${p}`));if(!z(d))return ye(ke(c,es,"tools/call arguments must be an object"));let f=async()=>{try{let y=await g.call(await t.root(),d);return a(c,l,cT(l,y.data,y.failed))}catch(y){return a(c,l,cT(l,rT(y),!0))}};return{kind:"queued",run:()=>f().catch((y)=>gW(c,y))}},a=(c,l,u)=>{if(l.kind==="legacy")return Jl(c,u);let d={[sW]:t.info};return Jl(c,{...u,[zl]:d,resultType:iW})};return{receive:n}}function ye(t){return{kind:"now",message:t}}function cT(t,e,n){let r=[{text:JSON.stringify(e,null,2),type:"text"}],o=t.kind==="modern"||t.version>=aW;return{content:r,isError:n,...o?{structuredContent:e}:{}}}function cW(t){let e;try{e=JSON.parse(t)}catch{return{error:ke(null,eW,"Parse error: each line must hold one JSON-RPC message")}}if(Array.isArray(e))return{error:ke(null,Xl,"JSON-RPC batches are not supported")};if(!z(e))return{error:ke(null,Xl,"A JSON-RPC message must be an object")};return{value:e}}function lW(t){let{id:e,jsonrpc:n,method:r,params:o={}}=t;if(!(typeof e==="string"||typeof e==="number"&&Number.isInteger(e)))return{error:ke(null,Xl,"A request id must be a string or an integer")};if(n!==Zl||typeof r!=="string")return{error:ke(e,Xl,'A request needs "jsonrpc": "2.0" and a method name')};if(!z(o))return{error:ke(e,es,"params must be an object")};return{value:{id:e,method:r,params:o}}}function uW(t){return z(t[zl])&&ql in t[zl]}function dW(t,e,n){let r=e[zl];if(z(r)&&ql in r){let s=r[ql];if(typeof s!=="string"||!uT.includes(s))return{error:pW(t,s)};if(!z(r[oT]))return{error:ke(t,es,`_meta needs "${oT}"`)};return{value:{kind:"modern",version:s}}}if(n!==null)return{value:{kind:"legacy",version:n}};let o=`Missing _meta "${ql}"; clients of protocol ${Yl[0]} and earlier send initialize first`;return{error:ke(t,es,o)}}function pW(t,e){return{error:{code:oW,data:{requested:e,supported:dT},message:"Unsupported protocol version"},id:t,jsonrpc:Zl}}function lT(t,e){return ke(t,nW,`Method not found: ${e}`)}function gW(t,e){return ke(t,rW,`Internal error: ${e instanceof Error?e.message:String(e)}`)}function Jl(t,e){return{id:t,jsonrpc:Zl,result:e}}function ke(t,e,n){return{error:{code:e,message:n},id:t,jsonrpc:Zl}}var cr="arguments",Yr={destructiveHint:!1,readOnlyHint:!0},Ti={destructiveHint:!1,readOnlyHint:!1},mW={destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1},gT={readOnlyHint:!1},$T={description:"Task id",type:"string"},rm={items:{type:"string"},type:"array"};function Yt(t){let{properties:e,required:n=[],...r}=t,o={additionalProperties:!1,properties:e,...n.length===0?{}:{required:[...n]},type:"object"};return{...r,inputSchema:o}}function we(t){return{data:t,failed:!1}}function Xt(t,e){return T(t,cr,Object.keys(e))}function ae(t,e){return nt(t,`${cr}.${e}`)}function mT(t,e){return t===void 0?void 0:L(t,`${cr}.${e}`,x)}var ns={},rs={id:$T},fT={status:{...rm,description:"Only tasks with these statuses",items:{enum:Kr}}},hT={pack:{description:"Methodology pack (defaults to config.pack)",type:"string"},scope:{...rm,description:"Globs of the files the task may change"},title:{description:"Task title",type:"string"}},yT={global:{description:"Write a project knowledge entry instead of a task note",type:"boolean"},kind:{description:"Knowledge entry kind, with global",enum:le},scope:{...rm,description:"Globs the knowledge entry applies to, with global"},text:{description:"The note",type:"string"}},kT={budget:{description:"Token budget (default: context.budget)",minimum:1,type:"integer"},id:{description:"Task id (default: the active task)",type:"string"}},wT={reason:{description:"Why the snapshot is taken, for example 'design ready'",type:"string"},task:{description:"Task id (default: the active task)",type:"string"}},ST={task:{description:"Only the entries of this task",type:"string"}},vT={id:{description:"Snapshot id, as ari_snapshot_list shows it",type:"string"}},bT={id:$T,reason:{description:"The question for a human",type:"string"}},ET={all:{description:"Include archived entries",type:"boolean"},query:{description:"Words to search for",type:"string"}},TT=[Yt({annotations:Yr,call:async(t,e)=>(Xt(e,ns),we(await $l(t))),description:"Start here: the one next action for this repository's Ariadne tasks. Loop: ari_next, change only files in the task's scope, ari_check, then ari_done until it passes.",name:"ari_next",properties:ns,title:"Next action"}),Yt({annotations:Yr,call:async(t,e)=>{let n=Xt(e,fT),r=D(n.status,[],(o)=>L(o,`${cr}.status`,(s,i)=>K(Kr,s,i)));return we(await Tl(t,r))},description:"List tasks (id, title, pack, status) and contracts or records that cannot be read.",name:"ari_list",properties:fT,title:"List tasks"}),Yt({annotations:Yr,call:async(t,e)=>we(await xl(t,ae(Xt(e,rs).id,"id"))),description:"Show a task's contract, record, current stage and stage instruction.",name:"ari_show",properties:rs,required:["id"],title:"Show task"}),Yt({annotations:Ti,call:async(t,e)=>{let n=Xt(e,hT),r=n.pack===void 0?void 0:ae(n.pack,"pack"),o=mT(n.scope,"scope")??[];return we(await Al(t,{pack:r,scope:o,title:ae(n.title,"title")}))},description:"Create a draft task contract from a title. Then edit .ari/tasks/<id>.md (scope, criteria bound to checks) and call ari_ready.",name:"ari_new",properties:hT,required:["title"],title:"New task"}),Yt({annotations:Ti,call:async(t,e)=>we(await Cl(t,ae(Xt(e,rs).id,"id"))),description:"Validate a draft contract, its pack and its dependencies, and mark it ready.",name:"ari_ready",properties:rs,required:["id"],title:"Ready task"}),Yt({annotations:Ti,call:async(t,e)=>we(await Rl(t,ae(Xt(e,rs).id,"id"))),description:"Start a ready task in this worktree (needs no uncommitted changes outside .ari/), or adopt an active task no worktree holds.",name:"ari_start",properties:rs,required:["id"],title:"Start task"}),Yt({annotations:gT,call:async(t,e)=>(Xt(e,ns),Ol(t)),description:"Evaluate the active task's current stage gates without recording an attempt. isError is true while a gate fails.",name:"ari_check",properties:ns,title:"Check stage"}),Yt({annotations:gT,call:async(t,e)=>(Xt(e,ns),_l(t)),description:"Finish the current stage: run its gates, record the evidence and advance. isError is true when a gate fails; a failure uses an attempt, so run ari_check first.",name:"ari_done",properties:ns,title:"Finish stage"}),Yt({annotations:Ti,call:async(t,e)=>{let n=Xt(e,yT),r=D(n.global,!1,(i)=>$t(i,`${cr}.global`)),o=n.kind===void 0?void 0:K(le,n.kind,`${cr}.kind`),s=mT(n.scope,"scope");return we(await Pl(t,{global:r,kind:o,scope:s,text:ae(n.text,"text")}))},description:"Record a learning: a note on the active task, or with global a project knowledge entry (kind fact, decision, constraint, pattern or gotcha).",name:"ari_note",properties:yT,required:["text"],title:"Add note"}),Yt({annotations:Yr,call:async(t,e)=>{let n=Xt(e,kT),r=n.id===void 0?void 0:ae(n.id,"id"),o=n.budget===void 0?void 0:Kt(n.budget,`${cr}.budget`);return we(await Nl(t,{budget:o,id:r}))},description:"The task's context pack: contract, last failure, constraints, notes and knowledge within a budget.",name:"ari_context",properties:kT,title:"Task context"}),Yt({annotations:Ti,call:async(t,e)=>{let n=Xt(e,bT);return we(await Il(t,ae(n.id,"id"),ae(n.reason,"reason")))},description:"Block the active task with a question for a human when the contract is wrong or you are stuck. Only a human answers it.",name:"ari_block",properties:bT,required:["id","reason"],title:"Block task"}),Yt({annotations:Yr,call:async(t,e)=>{let n=Xt(e,ET),r=D(n.all,!1,(o)=>$t(o,`${cr}.all`));return we(Dl(t,ae(n.query,"query"),r))},description:"Search the project's knowledge entries, ranked with BM25.",name:"ari_knowledge_search",properties:ET,required:["query"],title:"Search knowledge"}),Yt({annotations:mW,call:async(t,e)=>{let n=Xt(e,wT),r=n.task===void 0?void 0:ae(n.task,"task"),o=n.reason===void 0?void 0:ae(n.reason,"reason");return we(await Ll(t,{reason:o,task:r}))},description:"Save the plan (contract, stage, design files, notes) and the context pack of a task before a risky change or when a design is ready. Writes nothing when nothing changed since the last snapshot. Restoring one is for humans only.",name:"ari_snapshot",properties:wT,title:"Save snapshot"}),Yt({annotations:Yr,call:async(t,e)=>{let n=Xt(e,ST),r=n.task===void 0?void 0:ae(n.task,"task");return we(await Ml(t,r))},description:"List the saved snapshots and restores, oldest first, optionally of one task.",name:"ari_snapshot_list",properties:ST,title:"List snapshots"}),Yt({annotations:Yr,call:async(t,e)=>we(await jl(t,ae(Xt(e,vT).id,"id"))),description:"Show a snapshot: its plan summary, design files and the context pack it saved. Use it after a reset or compaction to get back what you knew.",name:"ari_snapshot_show",properties:vT,required:["id"],title:"Show snapshot"})];var xT=`
248
+ `,fW=/\r$/,hW={name:"ari",title:"Ariadne",version:ya},yW=["Ariadne tracks this repository's work as tasks with contracts and gates that it evaluates itself.","Loop: call ari_next and follow its action, change only files inside the active task's scope, call ari_check, then ari_done until it passes.","Save the plan with ari_snapshot before a risky change and read it back with ari_snapshot_show after a reset.","Ask a human with ari_block when stuck. Approving a stage, amending a contract, answering a blocked task and restoring a snapshot are for humans only (ari approve, ari amend, ari resolve, ari snapshot restore)."].join(" ");function kW(t){return pT({info:hW,instructions:yW,root:()=>Jn(t),tools:TT})}async function CT(t){let e=kW(t.cwd),n=(a)=>{if(a!==null)t.write(`${JSON.stringify(a)}${xT}`)},r=Promise.resolve(),o=(a)=>{if(a.kind==="now")n(a.message);else r=r.then(async()=>n(await a.run()))},s=new TextDecoder,i="";for await(let a of t.input){i+=s.decode(a,{stream:!0});let c=i.split(xT);i=c.pop()??"";for(let l of c)AT(e,l,o)}AT(e,i+s.decode(),o),await r}function AT(t,e,n){let r=e.replace(fW,"");if(r.trim().length>0)n(t.receive(r))}function RT(t,e){let{agents:n,example:r,group:o,noun:s}=t,i=(c,l)=>{let u=`ari ${o} ${c} --agent`;return E({args:j({agent:{description:`Agent: ${n.join(", ")}`,type:"string"},scope:{description:`Where to write: ${Mn.join(" or ")} (default: project)`,type:"string"}}),description:e[c],examples:[`${u} ${r.project}`,`${u} ${r.user} --scope user`],json:!0,name:c,run:async(d)=>{let p=t.target(ln(d.args.agent,"--agent",`${u} <name>`)),g=await xt(rr(d.args.scope),process.cwd()),f=l(p,g);d.output.result(f,(y)=>`${y.agent} ${s} ${y.action} in ${y.file} (${y.scope} scope)`)}})},a=E({description:e.list,examples:[`ari ${o} list --json`],json:!0,name:"list",run:async(c)=>{let l=process.cwd(),u=t.summaries(await xt("project",l),await xt("user",l));c.output.result({agents:u},({agents:d})=>d.map(wW).join(`
249
+ `))}});return[i("install",t.install),i("uninstall",t.uninstall),a]}function wW(t){let e=t.files.map((n)=>`${n.scope} ${n.installed?"installed":"not installed"} ${n.file}`);return`${t.agent} ${e.join("; ")}`}var SW=`ari mcp serve speaks the Model Context Protocol on stdin and stdout; an agent starts it. Press Ctrl-D to stop.
250
+ `,vW=E({description:"Serve the task loop to an agent as a stdio MCP server",examples:["ari mcp serve"],name:"serve",run:async()=>{if(process.stdin.isTTY)process.stderr.write(SW);await CT({cwd:process.cwd(),input:Bun.stdin.stream(),write:(t)=>{process.stdout.write(t)}})}}),bW=RT({agents:se.map((t)=>t.agent),example:{project:"claude",user:"codex"},group:"mcp",install:Ko,noun:'MCP server "ari"',summaries:Zv,target:me,uninstall:Qc},{install:"Register 'ari mcp serve' in an agent's MCP configuration",list:"List the agents ari can register its MCP server with, and where it is registered",uninstall:"Remove ari's MCP server from an agent's configuration, and nothing else"}),IT=E({description:"Serve ari's task tools to agents over MCP, and register the server with them",name:"mcp",subcommands:[vW,...bW]});var OT=1;async function _T(t,e){let n=M(t),r=Cr(n,{...e,role:"review",route:$W(n)}),o=e.task??await TW(t),s=await jn(t,o),i=s.stage??s.task.record.status,{contractText:a}=it(t,o,n),c=EW(n,e),l={config:n,contractText:a,root:t,stage:i,task:s.task,...c===null?{}:{argus:c}},{evidence:u,...d}=await yp(l,r);return{...d,stage:i,task:o}}function EW(t,e){if(e.argus===!1&&e.argusVerdicts===!0)throw new v("--argus-verdicts needs argus evidence, and --no-argus leaves it out","Pass only one of them");if(e.argus===!1)return null;let n=t.review.argus,r=e.argusVerdicts===!0&&e.argus!==!0?"--argus-verdicts":"--argus";if(n===void 0&&e.argus!==!0&&e.argusVerdicts!==!0)return null;if(n===void 0)throw new m(`${r} needs review.argus in .ari/config.json`,`Add "review": { "argus": { "config": "<path of the argus config>" } } to .ari/config.json, or leave out ${r}`,OT,{tag:"ArgusNotConfigured"});let{verdicts:o,...s}=n;return{argus:e.argusVerdicts??o===!0?{...s,verdicts:!0}:s,explicit:e.argus===!0,verdictsExplicit:e.argusVerdicts===!0,...e.notify?{notify:e.notify}:{}}}function $W(t){if(t.routing.review!==null)return t.routing.review;let{agent:e,model:n}=t.review;return e===void 0?null:{agent:e,model:n??null}}async function TW(t){let e=gt(await P(t));if(e!==null)return e.task;throw new m("No task is active in this worktree","Pass --task <id>, or run 'ari next' to see what to do",OT,{tag:"NoActiveTask"})}var xW=1,PT=E({args:j({agent:{description:"Review agent from config.agents (default: routing.review, then review.agent)",type:"string"},argus:{description:"Add (--argus, fails when argus cannot answer) or leave out (--no-argus) argus candidates; see review.argus",type:"boolean"},argusVerdicts:{description:"Send the review agent's answers about argus candidates back to argus (--argus-verdicts, fails when argus cannot answer) or not (--no-argus-verdicts); see review.argus.verdicts",type:"boolean"},model:{description:"Model for the review agent",type:"string"},task:{description:"Task id (default: the active task)",type:"string"}}),description:"Have a review agent judge a task's change in a temporary copy; any doubt fails the review",examples:["ari review","ari review --agent codex --model gpt-5.5 --json","ari review --argus","ari review --argus-verdicts"],json:!0,name:"review",run:async(t)=>{let e=await _T(await _(),{agent:Re(t.args.agent,"--agent"),argus:t.args.argus,argusVerdicts:t.args.argusVerdicts,model:Re(t.args.model,"--model"),notify:(n)=>bt.info(n),task:Re(t.args.task,"--task")});return t.output.result(e,AW),e.ok?void 0:xW}});function AW(t){let e=t.model===null?"":` (${t.model})`,n=`Review of "${t.task}" by ${t.agent}${e}: ${t.ok?"pass":"FAIL"}`,r=t.findings.map((i)=>` - ${Ec(i)}`),o=t.problems.map((i)=>` ! ${i}`),s=(t.argus===void 0?[]:Sc(t.argus)).map((i)=>` ~ ${i}`);return[n,...o,...s,...r].join(`
251
+ `)}var CW=1,NT=E({args:j({agent:{description:"Agent name from config.agents (default: the routing for each stage)",type:"string"},model:{description:"Model for the agent, overriding its model and the routing's",type:"string"},task:{description:"Task id (defaults to the active task, then the next startable one)",type:"string"}}),description:"Drive a task headlessly with an agent until it is done, blocked or out of attempts",examples:["ari run --agent claude","ari run --agent codex --model gpt-5.5 --task add-profile-inheritance --json","ari run --json"],json:!0,name:"run",run:async(t)=>{let e=await VE(await _(),{agent:Re(t.args.agent,"--agent"),model:Re(t.args.model,"--model"),output:t.json?"stderr":"inherit",task:t.args.task});return t.output.result(e,RW),e.outcome==="done"?void 0:CW}});function RW(t){return[...t.turns.map((n,r)=>`turn ${r+1}: stage ${n.stage}, ${n.agent}${n.model===null?"":` (${n.model})`} ${n.timedOut?"timed out":`exit ${n.agentExitCode}`}, ${n.outcome}${n.failing.length===0?"":` (${n.failing.join(", ")})`}`),`Task "${t.task}" is ${t.outcome}`].join(`
252
+ `)}var IW=1,OW=ot.map((t)=>t.name),_W=fe.map((t)=>t.agent),PW=j({agent:{description:`Agent: ${_W.join(", ")}`,type:"string"},scope:{description:`Where to write: ${Mn.join(" or ")} (default: project)`,type:"string"},skill:{description:`Skills, comma-separated (default: all): ${OW.join(", ")}`,type:"string"}}),NW={install:"Write ari's skills into an agent's skills directory, one directory for each skill",uninstall:"Remove the skills that ari installed, and nothing else"};function DT(t){let e=`ari skills ${t} --agent`;return E({args:PW,description:NW[t],examples:[`${e} claude`,`${e} codex --scope user`,`${e} claude --skill ariadne-design,ariadne-memory`],json:!0,name:t,run:async(n)=>{let r=Jt(ln(n.args.agent,"--agent",`${e} <name>`)),o=await xt(rr(n.args.scope),process.cwd()),s=lb(We(n.args.skill)),i=t==="install"?Bo(r,o,s):nl(r,o,s);return n.output.result(i,(a)=>LW(a,r.agent)),i.some((a)=>a.action==="refused")?IW:void 0}})}var DW=E({description:"List ari's skills, and for each agent which of them are installed and current",examples:["ari skills list --json"],json:!0,name:"list",run:async(t)=>{let e=process.cwd(),n=xb(await xt("project",e),await xt("user",e)),r=ot.map(({description:o,name:s})=>({description:o,name:s}));t.output.result({skills:r,agents:n},(o)=>MW(o.skills,o.agents))}}),LT=E({description:"Install ari's skills, which teach an agent the task loop, designs, contracts, review and memory",name:"skills",subcommands:[DT("install"),DT("uninstall"),DW]});function LW(t,e){let n=t.map((o)=>o.action==="refused"?`${o.agent} skill "${o.skill}" refused: ${o.reason??""}`:`${o.agent} skill "${o.skill}" ${o.action} in ${o.file} (${o.scope} scope)`),r=t.filter((o)=>o.action==="refused").length;return r===0?n.join(`
253
+ `):[...n,ol(r,e)].join(`
254
+ `)}function MW(t,e){let n=t.map((o)=>`${o.name} ${o.description}`),r=e.flatMap((o)=>Mn.map((s)=>`${o.agent} ${s} ${jW(o.files.filter((i)=>i.scope===s))}`));return[...n,"",...r].join(`
255
+ `)}function jW(t){if(!t.some((s)=>s.installed))return"not installed";let e=t.filter((s)=>s.current).length,n=t.filter((s)=>!s.installed).map((s)=>s.skill),r=t.filter((s)=>s.installed&&!s.current).map((s)=>s.skill);return[`${e} of ${t.length} current`,...n.length===0?[]:[`missing ${n.join(", ")}`],...r.length===0?[]:[`outdated ${r.join(", ")}`]].join("; ")}import{readFileSync as FW}from"fs";import{join as MT}from"path";var GW=()=>new Date().toISOString(),xi="Nothing was changed.",HW="it lies outside .ari/designs/, and a restore writes only designs";async function jT(t,e,n={}){let r=M(t),o=await P(t),s=jo(o,e);if(!Wp(s))throw new m(`Snapshot entry ${e} records a restore, not a saved plan`,"Restore an entry that 'ari snapshot list' shows as a save");let i=qo(s);if(i.length>0)throw new m(`Snapshot ${e} is not intact: ${i.join("; ")}`,`${xi} Restore another snapshot, or delete the entry file`);let{contractText:a,task:c}=it(t,s.task,r);UW(s,c.record.status,Bt(a));let l=Ue(c.contract.pack,Gt(t)),u=new Set(Nc(l,s.task)),d=s.artifacts.filter(({path:A})=>!u.has(A)).map(({path:A})=>A);if(d.length>0)throw new m(`Snapshot ${e} names ${d.join(", ")}, which ${d.length===1?"is":"are"} not an artifact path of pack "${l.name}"`,`${xi} The entry was edited or the pack changed; delete the entry file`);let p=s.artifacts.filter(({path:A})=>Up(A)),g=s.artifacts.filter(({path:A})=>!Up(A)).map(({path:A})=>({path:A,reason:HW})),f=KW(t,p),y=n.dryRun===!0,{estimatedTokens:S,knowledge:I,sha256:C,text:q}=s.context,G=f.write.map(({artifact:A,before:R})=>({before:R?.sha256??null,path:A.path,sha256:A.file.sha256})),N={context:{estimatedTokens:S,knowledge:I,sha256:C,text:q},dryRun:y,ledger:null,notRestored:g,notice:f.write.length===0?null:BW(s.task),snapshot:e,task:s.task,unchanged:f.unchanged,written:G};if(y||f.write.length===0)return N;let H=(n.clock??GW)();return Lc(o,()=>{for(let{artifact:Q}of f.write)Tr(MT(t,Q.path),Dr(Q.file));let A=Ln(o).entries.filter((Q)=>Q.task===s.task),B=A.filter((Q)=>Q.id!==e).slice(0,Math.max(0,A.length+1-r.snapshots.keep)).map((Q)=>Q.id),_t=Mc(o,H,{kind:"restore",pruned:B,restores:e,task:s.task,written:f.write.map(({artifact:Q,before:Xr})=>({before:Xr,path:Q.path,sha256:Q.file.sha256}))});return jc(o,B),{...N,ledger:_t.id}})}function UW(t,e,n){if(e==="done")throw new m(`Task "${t.task}" is done, so its plan is final and snapshot ${t.id} cannot be restored`,`${xi} 'ari snapshot show ${t.id}' prints what the snapshot held`);if(n===t.contract.sha256)return;throw new m(`The contract of "${t.task}" changed since snapshot ${t.id} was taken, so the designs of that plan may no longer fit it`,`${xi} Run 'ari amend ${t.task} --reason <text>' if the change was intended and take a new snapshot, or put the contract back from 'ari snapshot show ${t.id}' first`)}function KW(t,e){let n=[],r={unchanged:[],write:[]};for(let o of e){let s=MT(t,o.path),i=$e(s);if(i?.isSymbolicLink()===!0||Te(t,o.path)){n.push(`${o.path} is a symbolic link or lies behind one`);continue}if(i!==null&&!i.isFile()){n.push(`${o.path} is not a regular file`);continue}let a=i===null?null:Do(FW(s));if(a?.sha256===o.file.sha256)r.unchanged.push(o.path);else r.write.push({artifact:o,before:a})}if(n.length===0)return r;throw new m(`A restore would write through a path that is not an ordinary file: ${n.join("; ")}`,`${xi} Replace it with a regular file or remove it, then restore again`)}function BW(t){return`An approval covers the exact bytes it was given for, so an approval of the previous bytes no longer applies to the restored files; a human runs 'ari approve ${t}' again after reviewing them`}function GT(t){let e=t.warnings.map((o)=>`warning: ${o}`);if(!t.saved)return[`Nothing changed since snapshot ${t.id} of task "${t.task}"; no new snapshot was written`,...e].join(`
256
+ `);let n=t.stage===null?t.status:`stage ${t.stage}`,r=t.pruned.length===0?[]:[`Pruned the oldest: ${t.pruned.join(", ")}`];return[`Saved snapshot ${t.id} of task "${t.task}" (${n}, ${os(t.artifacts.length,"artifact")}, context of about ${t.context.estimatedTokens} tokens)`,...r,...e].join(`
257
+ `)}function HT(t){let e=t.entries.map(VW),n=t.unreadable.map(({id:r,problem:o})=>`${r} unreadable ${o}`);if(e.length===0&&n.length===0)return"No snapshots yet. Run 'ari snapshot' to save one";return[...e,...n].join(`
258
+ `)}function UT({entry:t,integrity:e}){let n=e.ok?[]:[`Integrity: ${e.problems.join("; ")}`];if(t.kind==="restore")return[...FT(t),...WW(t),...n].join(`
259
+ `);let{artifacts:r,context:o,contract:s,notes:i,record:a}=t,c=r.map(({file:l,path:u})=>` ${u} ${l.sha256}`);return[...FT(t),`Reason: ${t.reason??"none"}`,`Pack: ${a.pack}; stage ${a.stageName??"none"} (${a.stage+1}); status ${a.status}`,`Contract: ${s.sha256}`,`Artifacts: ${c.length===0?"none":""}`.trimEnd(),...c,`Notes: ${i.length}`,`Context pack: about ${o.estimatedTokens} tokens of ${o.budget}; knowledge ${o.knowledge.join(", ")||"none"}`,...t.pruned.length===0?[]:[`Pruned: ${t.pruned.join(", ")}`],...n,"",o.text].join(`
260
+ `)}function KT(t){let e=t.dryRun?"Would write":"Wrote",n=t.written.map((i)=>` ${e.toLowerCase()} ${i.path}`),r=t.unchanged.map((i)=>` unchanged ${i}`),o=t.notRestored.map((i)=>` not restored ${i.path}: ${i.reason}`);return[t.dryRun?`Dry run: restoring snapshot ${t.snapshot} would write ${os(t.written.length,"file")}`:`Restored snapshot ${t.snapshot} of task "${t.task}": ${os(t.written.length,"file")} written`,...n,...r,...o,...t.notice===null?[]:[t.notice],...t.ledger===null?[]:[`Logged as ${t.ledger}`],"",t.context.text].join(`
261
+ `)}function VW(t){if(t.kind==="restore")return`${t.id} restore of ${t.restores??"?"} ${t.task} ${os(t.artifacts.length,"file")}`;let e=`${t.stage??"none"} (${t.status??"none"})`,n=t.reason===null?"":` ${t.reason}`;return`${t.id} save ${t.trigger??""} ${t.task} ${e} ${os(t.artifacts.length,"artifact")}${n}`}function FT(t){let e=t.kind==="save"?`save, ${t.trigger}`:`restore of ${t.restores}`;return[`Snapshot ${t.id} (${e}) of task "${t.task}"`,`Taken: ${t.at}`]}function WW(t){let e=t.written.map((n)=>` ${n.path} now ${n.sha256}; before ${n.before?.sha256??"absent"}`);return[`Wrote ${os(e.length,"file")}:`,...e,...t.pruned.length===0?[]:[`Pruned: ${t.pruned.join(", ")}`]]}function os(t,e){return`${t} ${t===1?e:`${e}s`}`}var JW={description:"Task id (default: the active task)",type:"string"},qW=E({args:j({task:{description:"Only the entries of this task",type:"string"}}),description:"List saved snapshots and restores, oldest first",examples:["ari snapshot list","ari snapshot list --task add-profile-inheritance --json"],json:!0,name:"list",run:async(t)=>{t.output.result(await Ml(await _(),t.args.task),HT)}}),YW=E({description:"Print a snapshot's plan summary and the context pack it saved",examples:["ari snapshot show 20261202T101530123Z --json"],json:!0,name:"show",positionals:st({id:{description:"Snapshot id, as 'ari snapshot list' prints it",required:!0}}),run:async(t)=>{t.output.result(await jl(await _(),t.positionals.id),UT)}}),XW=E({args:j({dryRun:{default:!1,description:"Show what would be written and write nothing",type:"boolean"}}),description:"Write a snapshot's design files back byte for byte and print its saved context pack",examples:["ari snapshot restore 20261202T101530123Z --dry-run","ari snapshot restore 20261202T101530123Z"],json:!0,name:"restore",positionals:st({id:{description:"Snapshot id, as 'ari snapshot list' prints it",required:!0}}),run:async(t)=>{let e=await jT(await _(),t.positionals.id,{dryRun:t.args.dryRun});t.output.result(e,KT)}}),BT=E({args:j({reason:{description:"Why the snapshot is taken",type:"string"},task:JW}),description:"Save the plan and context pack of a task, and list, show and restore saved ones",examples:["ari snapshot",'ari snapshot --reason "Before the design review"',"ari snapshot list"],json:!0,name:"snapshot",run:async(t)=>{let e=await Ll(await _(),{reason:Re(t.args.reason,"--reason"),task:t.args.task});t.output.result(e,GT)},subcommands:[qW,YW,XW]});var VT=E({args:j({pack:{description:"Methodology pack (defaults to config.pack)",type:"string"},scope:{description:"Scope globs, comma-separated",type:"string"}}),description:"Create a task contract from a title",examples:['ari new "Add profile inheritance" --pack tdd --scope "src/profiles/**"'],json:!0,name:"new",positionals:st({title:{description:"Task title",required:!0}}),run:async(t)=>{let e=await Al(await _(),{pack:t.args.pack,scope:We(t.args.scope),title:t.positionals.title});t.output.result(e,({contractPath:n,designs:r,id:o})=>[`Created task "${o}" at ${n}`,...(r??[]).map(zW),`Complete its scope, criteria and checks, then run 'ari ready ${o}'`].join(`
262
+ `))}}),WT=E({args:j({status:{description:`Only these statuses, comma-separated (${Kr.join(",")})`,type:"string"}}),description:"List tasks and any unreadable contracts or records",examples:["ari list","ari list --status ready,active --json"],json:!0,name:"list",run:async(t)=>{let e=XE(We(t.args.status));t.output.result(await Tl(await _(),e),ZW)}}),JT=E({description:"Show a task's contract, record and current stage",examples:["ari show add-profile-inheritance --json"],json:!0,name:"show",positionals:st({id:{description:"Task id",required:!0}}),run:async(t)=>{t.output.result(await xl(await _(),t.positionals.id),QW)}});function zW({created:t,path:e}){return t?`Wrote the design template to ${e}`:`Kept the existing design at ${e}`}function ZW(t){if(t.tasks.length===0&&t.invalid.length===0)return'No tasks yet. Run ari new "<title>"';let e=t.tasks.map((r)=>`${r.id} ${r.status} ${r.pack} ${r.title}`),n=t.invalid.map((r)=>`${r.id} unreadable ${r.problem}`);return[...e,...n].join(`
263
+ `)}function QW(t){let{contract:e,record:n}=t.task,r=t.stage===null?[]:[`Stage: ${t.stage}${t.active?" (active here)":""}`],o=t.instruction===null?[]:[`Instruction: ${t.instruction}`],s=n.question===null?[]:[`Question: ${n.question}`];return[`${e.id}: ${e.title}`,`Status: ${n.status} Pack: ${e.pack} Attempts: ${n.attempts}/${e.budget.attempts}`,...r,...o,...s,`Scope: ${e.scope.join(", ")||"none"}`,...e.criteria.map((i)=>`${i.id}: ${i.text} [${i.checks.join(", ")}]`),...e.checks.map((i)=>`check ${i.name} (expect ${i.expect}): ${i.run}`)].join(`
264
+ `)}var tJ=1,eJ=12,YT=E({args:j({revoke:{default:!1,description:"Forget the trust record of this repository",type:"boolean"},yes:{alias:"y",default:!1,description:"Trust the commands without asking",type:"boolean"}}),description:"Show, grant or revoke trust in the commands that .ari makes ari run",examples:["ari trust","ari trust --yes","ari trust --revoke","ari trust --json"],json:!0,name:"trust",run:async(t)=>{if(t.args.revoke&&t.args.yes)throw new v("--revoke and --yes conflict","Pass only one of them");let e=await _(),n=M(e),r=So();if(t.args.revoke){let c=sk(e),l={...Be(e,n),action:c?"revoked":"none",environment:r};t.output.result(l,qT);return}let o=Be(e,n),s=_n(o)&&(t.args.yes||await nJ(t.json,o)),i=s?vo(e,n):o,a={...i,action:s?"trusted":"none",environment:r};return t.output.result(a,qT),_n(i)&&!r?tJ:void 0}});async function nJ(t,e){if(!ur({json:t}))return!1;return Nd(e.root,e.commands)}function qT(t){let e=[`Trust for ${t.root}: ${rJ(t)}`,...Pd(t.commands)],n=[...t.action==="trusted"?["Trusted the commands above"]:[],...t.action==="revoked"?["Revoked the trust record of this repository"]:[],...t.environment?[`${xr}=1 is set, so ari runs these commands without a record`]:[],..._n(t)&&t.action!=="revoked"?["Review the commands above, then run 'ari trust --yes' or answer the prompt in a terminal"]:[]];return[...e,...n].join(`
265
+ `)}function rJ(t){switch(t.state){case"trusted":return`trusted since ${t.trustedAt} (configuration ${t.sha256.slice(0,eJ)})`;case"changed":return`not trusted: the commands changed since ${t.trustedAt}`;case"untrusted":return"not trusted";case"not-required":return"nothing to trust, the configuration starts no commands"}}var oJ="Fix the cause, then run 'ari uninstall' again; it keeps what is already done",sJ="as it was before the install, byte for byte",iJ="only ari's entries: the file changed after the install, so your edits stay";async function om(t,e,n,r){let o={bases:n,mode:r,preview:tp(),root:t},s=[];for(let i of e.targets){if(i.skip!==null){s.push(Ql(i,"skipped",{reason:i.skip}));continue}try{s.push(...await aJ(o,i))}catch(a){let c=Ql(i,"failed",{hint:yJ(a),reason:hJ(a)});s.push({...c,file:dJ(i)})}}return s}async function aJ(t,e){if(e.kind==="git")return uJ(t,e);let n=fJ(e.agent),r=mJ(t,e.scope),o=t.mode==="preview"?t.preview:tp(),s=await cJ(t,e,n,r,o);if(t.mode==="apply")await lJ(t,e,n,r);return[pJ(e,s,XT(e.kind,n,e.scope))]}async function cJ(t,e,n,r,o){if(e.kind==="hooks"){let i=sm(t);return op(i,Pe(n),{forget:!1,state:await P(i),view:o})}if(e.kind==="mcp")return Yc(Ne(me(n),r),o,!1);let s=Jt(n);return gb(ot.map((i)=>Yc(ie(s,r,i),o,!1)))}async function lJ(t,e,n,r){if(e.kind==="hooks"){let o=sm(t);pc(o,Pe(n),await P(o));return}if(e.kind==="mcp")Qc(me(n),r);else nl(Jt(n),r)}async function uJ(t,e){let n=sm(t),r=await Gs(n);if(t.mode==="apply")await cc(n);return r.map(({action:o,path:s})=>({...Ql(e,o==="removed"?"removed":"unchanged",{}),file:s}))}function dJ(t){return t.agent===null?null:XT(t.kind,t.agent,t.scope)}function XT(t,e,n){if(t==="hooks")return Pe(e).file;let r=t==="mcp"?me(e)[n]:Jt(e)[n];return oe(n,r??"")}function pJ(t,e,n){let r=gJ(e),o=e.restored===null?null:e.restored==="original"?sJ:iJ;return{...Ql(t,r,{detail:o}),file:n}}function gJ({action:t}){return t==="removed"?"removed":t==="unchanged"?"unchanged":"restored"}function Ql(t,e,n){return{action:e,agent:t.agent,detail:n.detail??null,file:null,hint:n.hint??null,kind:t.kind,reason:n.reason??null,scope:t.scope}}function mJ(t,e){let n=t.bases[e];if(n!==void 0)return n;throw Error(`The ${e} scope is not part of this uninstall`)}function sm({root:t}){if(t!==null)return t;throw Error("This uninstall target needs a repository")}function fJ(t){if(t!==null)return t;throw Error("This uninstall target needs an agent")}function hJ(t){return t instanceof Error?t.message:String(t)}function yJ(t){return t instanceof m&&t.hint!==void 0&&t.hint.length>0?t.hint:oJ}var kJ=[{how:"Delete the directory yourself: rm -r .ari",what:".ari/: tasks, knowledge, configuration and routing, packs"},{how:"Delete the lines from <!-- ari:begin --> to <!-- ari:end --> by hand",what:"The ari block in AGENTS.md"},{how:'Delete the directory yourself: rm -r "$(git rev-parse --git-path ari)"',what:"Journals, the active-task pointer and the sleep ledger under the git directory"},{how:"Run 'ari trust --revoke' in this repository",what:"The trust record for this repository on this machine"}],wJ=[{how:"Delete the directory yourself: rm -r ~/.ari",what:"~/.ari: the trust records and the receipts of anything still installed"}];function zT(t){return t==="project"?kJ:wJ}var SJ=["git","skill","mcp","hooks"],vJ=["skill","mcp"],bJ=new Set(["hooks","git"]),EJ=[...at].reverse(),ZT="ari does not write this",$J={claude:"Claude Code keeps user-scope MCP servers itself; run 'claude mcp remove --scope user ari'"};async function QT(t,e){if(e==="user")return{user:await xt("user",process.cwd())};if(t===null)throw Error("A project-scope uninstall needs a repository root");return{project:{base:t,receipts:await P(t),scope:e}}}function tx(t){if(t.scope!=="user"||t.kinds===void 0)return;if(![...t.kinds].some((e)=>bJ.has(e)))return;throw new v("--hooks and --git-hooks belong to a repository, so they cannot go with --scope user","Use --mcp or --skills with --scope user, or drop --scope")}async function ex(t,e,n){let{scope:r}=e,o=r==="user"?vJ:SJ,s=[];for(let i of o.filter((a)=>e.kinds?.has(a)??!0))s.push(...i==="git"?await xJ(t,e):TJ(i,t,e,n));return{scope:r,targets:s}}function TJ(t,e,n,r){let{agents:o,scope:s}=n,i=r[s];if(i===void 0)return[];return EJ.filter((a)=>o?.includes(a)??!0).flatMap((a)=>{let c=AJ(t,a,s);if(c===void 0)return[];let l={agent:a,kind:t,scope:s};if(c===null)return o===void 0?[]:[{...l,skip:CJ(t,a,s)}];return IJ(()=>RJ(t,a,e,i),!0)||o!==void 0?[{...l,skip:null}]:[]})}async function xJ(t,e){let n=e.kinds?.has("git")===!0;if(t===null||e.agents!==void 0&&!n)return[];return(await Gs(t)).some(({action:o})=>o==="removed")||n?[{agent:null,kind:"git",scope:"project",skip:null}]:[]}function AJ(t,e,n){if(t==="hooks"){let o=Ie.find((s)=>s.name===e);return o===void 0?void 0:n==="project"?o.file:null}return(t==="mcp"?se:fe).find((o)=>o.agent===e)?.[n]}function CJ(t,e,n){if(t==="mcp")return $J[e]??`${ZT} ${e}'s ${n}-scope MCP configuration`;return`${ZT} ${e}'s ${n}-scope ${t}`}function RJ(t,e,n,r){if(t==="mcp")return mn(Ne(me(e),r));if(t==="skill"){let s=Jt(e);return ot.some((i)=>mn(ie(s,r,i)))}let o=Ie.find((s)=>s.name===e);return n!==null&&o!==void 0&&un(n,o)}function IJ(t,e){try{return t()}catch{return e}}var tu=" ",nx=11,OJ=34,_J=66,rx=72,PJ=["removed","restored","unchanged","skipped","failed"],NJ={failed:"failed",removed:"remove",restored:"restore",skipped:"skip",unchanged:"unchanged"};function ox(t){return t.targets.length===0}function DJ(t){if(t.kind==="git")return"git hook";return`${t.agent??""} ${Ye[t.kind]}`.trim()}function sx(t){return t.flatMap((e)=>ax(e,!0)).join(`
266
+ `)}function LJ(t){return t.targets.flatMap((e)=>ax(e,t.dryRun)).join(`
267
+ `)}function im(t){return t.flatMap((e)=>[...Wr(e.what,rx),...Wr(e.how,rx-tu.length).map((n)=>w.dim(`${tu}${n}`))]).join(`
268
+ `)}function am(t){let e=PJ.flatMap((n)=>{let r=t.filter((o)=>o.action===n).length;return r===0?[]:[`${r} ${n}`]});return e.length===0?"Nothing to remove":e.join(", ")}function ix(t){let e=t.dryRun?"Dry run: nothing was written":am(t.targets),n=ox(t)?[]:[LJ(t),""],r=ox(t)?[]:["","Kept",im(t.kept)];return[...n,e,...r].join(`
269
+ `)}function ax(t,e){let n=ut(e?NJ[t.action]:t.action,nx),r=ut(t.file??"",OJ),o=`${tu}${MJ(t.action,n)}${r}${w.dim(DJ(t))}`,s=[t.detail,t.reason,t.hint].flatMap((i)=>i===null?[]:Wr(i,_J).map((a)=>`${tu}${" ".repeat(nx)}${w.dim(a)}`));return[Le(o),...s]}function MJ(t,e){switch(t){case"removed":case"restored":return w.green(e);case"failed":return w.red(e);case"skipped":return w.yellow(e);case"unchanged":return w.dim(e)}}var jJ=1,cm={format:(t)=>t},FJ=j({agent:{description:`Only these agents, comma-separated: ${at.join(", ")}`,type:"string"},dryRun:{alias:"d",description:"Show what would be removed and write nothing",type:"boolean"},gitHooks:{description:"Remove the pre-commit and pre-push git hooks",type:"boolean"},hooks:{description:"Remove each agent's hooks",type:"boolean"},mcp:{description:"Remove ari's MCP server from each agent",type:"boolean"},scope:{description:"Where MCP servers and skills were installed: project or user (default: project)",type:"string"},skills:{description:"Remove ari's skills from each agent",type:"boolean"},yes:{alias:"y",description:"Remove without asking",type:"boolean"}}),lx=E({args:FJ,description:"Remove what 'ari install' put here: agent hooks, MCP server, skills and git hooks, giving every file back as it was",examples:["ari uninstall --dry-run","ari uninstall --yes","ari uninstall --agent claude --yes","ari uninstall --mcp --scope user --yes"],json:!0,name:"uninstall",prompts:!0,run:async(t)=>GJ(t)});async function GJ(t){let e=BJ(t.args),n=t.args.dryRun===!0,r=t.args.yes===!0;if(!t.interactive&&!r&&!n)throw WJ();let o=t.interactive,s=e.scope==="project"?await _():null,i=await QT(s,e.scope);if(o)fr(`${w.bold("ari uninstall")} ${w.dim(`Ariadne ${t.cli.version??""}`)}`);let a=await ex(s,e,i),c=await om(s,a,i,"preview");if(o&&c.length>0)Nt(sx(c),"Plan",cm);let l=c.some((d)=>d.action==="removed"||d.action==="restored");if(n)return cx(t,s,e,c,{dryRun:n,visual:o});if(l&&o&&!r)await KJ(()=>UJ());let u=await om(s,a,i,"apply");return cx(t,s,e,u,{dryRun:!1,visual:o})}function cx(t,e,n,r,o){let s=r.some((a)=>a.action==="failed"),i={dryRun:o.dryRun,kept:[...zT(n.scope)],ok:!s,root:e,scope:n.scope,targets:r};if(o.visual)HJ(i);return t.output.result(i,o.visual?void 0:ix),s?jJ:0}function HJ(t){if(t.targets.length===0){ce("Nothing to remove");return}if(t.dryRun){ce("Dry run: nothing was written");return}Nt(am(t.targets),t.ok?"Done":"Done, with problems",cm),Nt(im(t.kept),"Kept",cm),ce(t.ok?"ari is out of this setup":"Fix the failed rows, then run 'ari uninstall' again")}async function UJ(){if(await Ee({initialValue:!0,message:"Remove these?"}))return;throw new vt}async function KJ(t){try{await t()}catch(e){if(e instanceof vt)ys("Cancelled, nothing changed");throw e}}function BJ(t){let e=new Set([...t.hooks===!0?["hooks"]:[],...t.mcp===!0?["mcp"]:[],...t.skills===!0?["skill"]:[],...t.gitHooks===!0?["git"]:[]]),n={agents:t.agent===void 0?void 0:VJ(t.agent),kinds:e.size===0?void 0:e,scope:rr(t.scope)};return tx(n),n}function VJ(t){let e=[...new Set(We(t))];if(e.length===0)throw new v("--agent needs at least one agent",`Choose from: ${at.join(", ")}`);return e.map((n)=>{if(ll(n))return n;throw new v(`ari uninstall has no agent "${n}"`,`Choose from: ${at.join(", ")}`)})}function WJ(){return new v("ari uninstall needs --yes or --dry-run when it cannot ask","Run 'ari uninstall --dry-run' to see what it would remove, then 'ari uninstall --yes'")}var ux=E({name:"context",description:"Print the context pack of a task within a token budget",args:j({budget:{description:"Token budget (default: context.budget from .ari/config.json)",type:"number"}}),positionals:st({id:{description:"Task id (default: the active task of this worktree)"}}),json:!0,examples:["ari context","ari context add-profile-inheritance --budget 2000","ari context --json"],run:async(t)=>{let e=await Nl(await _(),{budget:t.args.budget,id:t.positionals.id});t.output.result(e,({text:n})=>n)}});var JJ=" ",qJ=E({name:"list",description:"List project knowledge entries",args:j({all:{default:!1,description:"Include archived entries",type:"boolean"}}),json:!0,examples:["ari knowledge list","ari knowledge list --all --json"],run:async(t)=>{let e=Tp(await _(),{all:t.args.all});t.output.result(e,QJ)}}),YJ=E({name:"search",description:"Rank knowledge entries against a query with BM25",args:j({all:{default:!1,description:"Include archived entries",type:"boolean"}}),positionals:st({query:{description:"Words to search for",required:!0,variadic:!0}}),json:!0,examples:["ari knowledge search profile resolution"],run:async(t)=>{let e=t.positionals.query.join(JJ),n=Dl(await _(),e,t.args.all);t.output.result(n,tq)}}),XJ=E({name:"show",description:"Show one knowledge entry and how many done tasks used it",positionals:st({id:{description:"Knowledge entry id",required:!0}}),json:!0,run:async(t)=>{let e=await _(),{tasks:n}=await vl(e);t.output.result(fS(e,t.positionals.id,n),eq)}}),zJ=E({name:"archive",description:"Archive a knowledge entry",args:j({force:{default:!1,description:"Allow archiving a constraint or decision",type:"boolean"}}),positionals:st({id:{description:"Knowledge entry id",required:!0}}),json:!0,run:async(t)=>{let e=await _(),n=hS(e,t.positionals.id,{force:t.args.force});t.output.result(n,(r)=>`Archived ${r.kind} ${r.id}`)}}),ZJ=E({name:"restore",description:"Restore an archived knowledge entry, byte for byte when the sleep ledger holds its original",positionals:st({id:{description:"Knowledge entry id",required:!0}}),json:!0,examples:["ari knowledge restore build-uses-bun"],run:async(t)=>{let e=await h$(await _(),t.positionals.id);t.output.result(e,(n)=>`Restored ${n.kind} ${n.id}`)}}),dx=E({name:"knowledge",description:"List, search, show, archive and restore project knowledge",subcommands:[qJ,YJ,XJ,zJ,ZJ]});function px(t){let e=t.status==="active"?"":` [${t.status}]`,n=t.text.split(`
270
+ `)[0]??"";return`${t.id} (${t.kind})${e}: ${n}`}function QJ(t){return t.entries.length===0?"No knowledge entries":t.entries.map(px).join(`
271
+ `)}function tq(t){if(t.matches.length===0)return`No knowledge entry matches "${t.query}"`;return t.matches.map((e)=>`${e.score.toFixed(2)} ${px(e.entry)}`).join(`
272
+ `)}function eq(t){let{entry:e}=t,n=(r)=>r.length===0?"none":r.join(", ");return[`${e.id} (${e.kind}, ${e.status})`,`Scope: ${n(e.scope)}`,`Sources: ${n(e.sources)}`,`Created: ${e.created}`,`Used by done tasks: ${t.uses}`,...e.supersedes.length===0?[]:[`Supersedes: ${n(e.supersedes)}`],...e.supersededBy===null?[]:[`Superseded by: ${e.supersededBy}`],"",e.text].join(`
273
+ `)}var nq=" ",gx=E({name:"note",description:"Add a note to the active task, or a project knowledge entry with --global",args:j({global:{default:!1,description:"Write a project knowledge entry instead of a task note",type:"boolean"},kind:{description:`Entry kind with --global: ${le.join(", ")} (default: fact)`,type:"string"},scope:{description:"Comma-separated globs the entry applies to, with --global (default: everywhere)",type:"string"}}),positionals:st({text:{description:"The note text",required:!0,variadic:!0}}),json:!0,examples:['ari note "The fixture needs a real git repository"','ari note --global --kind constraint --scope "packages/atlas/src/**" "Profile resolution stays synchronous"'],run:async(t)=>{let{global:e,kind:n,scope:r}=t.args,o={global:e,kind:n,scope:r===void 0?void 0:pS(r),text:t.positionals.text.join(nq)};t.output.result(await Pl(await _(),o),rq)}});function rq(t){return t.target==="task"?`Added note ${t.index} to ${t.task}`:`Added ${t.entry.kind} ${t.entry.id} to .ari/knowledge`}var lm="HEAD~1",oq={fail:"fail",pass:"pass",regression:"pass"};async function mx(t,e={}){let n=M(t),r=e.since??lm,o=await fo(t,r),s=ne(await xe(t,o)),{tasks:i}=Pt(t,n),a=i.filter((u)=>u.record.status==="done"&&s.some((d)=>et(d,u.contract.scope))),c=pe(t),l=[];for(let u of a){let d=await iq(t,u),p=c.filter((g)=>g.sources.includes(u.contract.id)).map((g)=>g.id);l.push({checks:d,knowledge:p,ok:d.every((g)=>g.ok),task:u.contract.id})}return{changed:s.length,commit:o,regressed:l.filter((u)=>!u.ok).map((u)=>u.task),since:r,tasks:l}}function sq(t){return{command:t.command,exitCode:t.exitCode,expect:t.expect,name:t.name,ok:t.ok,outputTail:t.outputTail,timedOut:t.timedOut}}async function iq(t,e){let n=[];for(let r of e.contract.checks){let[o]=await Je([cq(r)],aq(e,r),t);if(o!==void 0)n.push(sq(o))}return n}function aq(t,e){return(t.record.evidence.at(-1)?.gates.flatMap((r)=>r.checks)??[]).findLast((r)=>r.name===e.name)?.expect??oq[e.expect]}function cq(t){return{name:t.name,run:t.run,timeoutSeconds:t.timeoutSeconds}}var lq=1,fx=E({name:"replay",description:"Re-run the checks of done tasks whose scope changed since a reference",args:j({since:{default:lm,description:"Reference to compare with",type:"string"}}),json:!0,examples:["ari replay","ari replay --since origin/develop --json"],run:async(t)=>{let e=await mx(await _(),{since:t.args.since});return t.output.result(e,uq),e.regressed.length===0?void 0:lq}});function uq(t){let e=`Replayed ${t.tasks.length} done tasks against ${t.since} (${t.changed} changed files)`,n=t.tasks.flatMap((r)=>{if(r.ok)return[`ok ${r.task}`];let o=r.checks.filter((i)=>!i.ok),s=r.knowledge.length===0?[]:[` cited by: ${r.knowledge.join(", ")}`];return[`REGRESSED ${r.task}`,...o.flatMap((i)=>[` ${i.name} should ${i.expect}: ${i.command}`,dq(i.outputTail)]),...s]});return[e,...n].join(`
274
+ `)}function dq(t){return t.trimEnd().split(`
245
275
  `).map((e)=>` ${e}`).join(`
246
- `)}import{resolve as GB}from"path";import{existsSync as RB,readFileSync as IB}from"fs";var qs="Fix the proposal file, then run 'ari sleep --apply <file>' again",OB=["merges","promotions","archive","reason"],_B=["replace","entry"],PB=["task","notes","entry"],NB=["kind","scope","text"],DB=1;function rb(t,e){if(!RB(t))throw new g(`The proposal file ${t} does not exist`,qs);let n=IB(t),r;try{r=JSON.parse(n.toString("utf8"))}catch(s){let i=s instanceof Error?s.message:String(s);throw new g(`The proposal file ${t} is not valid JSON (${i})`,qs)}return{proposal:Tt("sleep proposal",qs,()=>LB(r,e.knowledge.maxEntryBytes)),sha256:tt(n)}}function ob(t,e,n,r){let o=[],s=new Map,i=(c,l)=>{let u=e.get(c),d=s.get(c);if(u===void 0)o.push(`${l} names the unknown entry "${c}"`);else if(u.status!=="active")o.push(`${l} names the archived entry "${c}"`);else if(Mn(u)&&!r)o.push(`${l} retires the ${u.kind} "${c}"; pass --force to retire ${u.kind} entries`);if(d!==void 0)o.push(`${l} names "${c}", which ${d} already retires`);s.set(c,l)};t.merges.forEach((c,l)=>{if(c.replace.length<DB)o.push(`merges[${l}].replace is empty`);c.replace.forEach((u,d)=>{i(u,`merges[${l}].replace[${d}]`)})}),t.archive.forEach((c,l)=>{i(c,`archive[${l}]`)});let a=new Map;return t.promotions.forEach((c,l)=>{let u=`promotions[${l}]`,d=n.get(c.task);if(d===void 0){o.push(`${u}.task names the unknown or unreadable task "${c.task}"`);return}if(c.notes.length===0)o.push(`${u}.notes is empty`);let p=a.get(c.task)??new Set;for(let m of c.notes){let f=d.notes[m];if(f===void 0)o.push(`${u}.notes names note ${m}, but "${c.task}" has none`);else if(f.promoted)o.push(`${u}.notes names note ${m}, which is already promoted`);if(p.has(m))o.push(`${u}.notes names note ${m} of "${c.task}" twice`);p.add(m)}a.set(c.task,p)}),o}function LB(t,e){let n=C(t,"proposal",OB);return{archive:F(n.archive,[],(r)=>D(r,"archive",x)),merges:F(n.merges,[],(r)=>D(r,"merges",(o,s)=>{let i=C(o,s,_B);return{entry:nb(i.entry,`${s}.entry`,e),replace:Et(i.replace,`${s}.replace`,(a,c)=>D(a,c,x))}})),promotions:F(n.promotions,[],(r)=>D(r,"promotions",(o,s)=>{let i=C(o,s,PB);return{entry:nb(i.entry,`${s}.entry`,e),notes:Et(i.notes,`${s}.notes`,(a,c)=>D(a,c,$t)),task:Et(i.task,`${s}.task`,x)}})),reason:F(n.reason,null,(r)=>ot(r,"reason").trim())}}function nb(t,e,n){let r=Et(t,e,(o,s)=>C(o,s,NB));return Cd({kind:r.kind,scope:r.scope??[],text:r.text},e,n)}var MB="(merged entry ";function ib(t,e,n,r){let o=qd(e),s=qd(jB(t,e)),i=new Map;for(let a of hr(n).slice(0,r))for(let c of a.record.knowledgeUsed){if(o(c)===null||s(c)!==null)continue;i.set(c,[...i.get(c)??[],a.contract.id])}return[...i.entries()].map(([a,c])=>({entry:a,tasks:c})).sort((a,c)=>I(a.entry,c.entry))}function ab(t){let e=t.tasks.map((r)=>`"${r}"`).join(", "),n=t.tasks.length===1?"task":"tasks";return`"${t.entry}" would no longer be active or replaced by an active entry, but ${n} ${e} used it`}function jB(t,e){let n=new Map(e);t.merges.forEach((r,o)=>{let s=`${MB}${o})`;n.set(s,vs(r.entry,{created:"",id:s,sources:[],supersedes:r.replace}));for(let i of r.replace)sb(n,i,s)});for(let r of t.archive)sb(n,r,null);return n}function sb(t,e,n){let r=t.get(e);if(r!==void 0)t.set(e,Xe(r,n))}var cb=()=>new Date().toISOString();async function lb(t,e,n={}){let r=L(t),o=await M(t),s=(n.clock??cb)(),i=n.force===!0;return fr(o,()=>{let{entries:a,proposal:c,sha256:l}=db(t,e,r,i),u=new Set(Ve(t)),d=pb(c,a,so(s),(f,y)=>Id(t,f,y,u)),p=qa(t,d.retirements);for(let{notes:f,task:y}of c.promotions)Ft(t,o,y,(S)=>yh(S,f));let m=lo(o,s,{archived:p,created:Aw(t,d.creations),forced:i,kind:"apply",promoted:gb(c),proposal:{sha256:l},pruned:[],reason:c.reason});return{...mb(d,c),ledger:m.id}})}function ub(t,e,n={}){let r=L(t),o=(n.clock??cb)(),{entries:s,proposal:i}=db(t,e,r,n.force===!0),a=new Set(Ve(t)),c=pb(i,s,so(o),(l,u)=>vs(l,{...u,id:Rd(l,a)}));return{...mb(c,i),changes:Ya(t,c.retirements,c.creations),dryRun:!0}}function db(t,e,n,r){let{proposal:o,sha256:s}=rb(e,n),i=new Map(Ne(t).map((p)=>[p.id,p])),{tasks:a}=It(t,n),c=new Map(a.map((p)=>[p.contract.id,p.record])),l=ob(o,i,c,r);if(l.length>0){let p=l.map((m)=>` - ${m}`).join(`
247
- `);throw new g(`The sleep proposal has ${l.length} problem(s):
248
- ${p}`,qs)}let u=n.knowledge.rehearsalTasks,d=r?[]:ib(o,i,a,u);if(d.length>0)throw FB(d,Math.min(u,hr(a).length));return{entries:i,proposal:o,sha256:s}}function FB(t,e){let n=t.map((r)=>` - ${ab(r)}`).join(`
249
- `);return new g(`The sleep proposal fails the rehearsal against the last ${e} done task(s):
250
- ${n}`,"Keep those entries out of the proposal, merge them into a successor, or run 'ari sleep --apply <file> --force' to apply it anyway")}function pb(t,e,n,r){let o=[],s=[];for(let i of t.merges){let a=i.replace.map((u)=>e.get(u)).filter((u)=>u!==void 0),c=[...new Set(a.flatMap((u)=>u.sources))].sort(I),l=r(i.entry,{created:n,sources:c,supersedes:[...i.replace]});o.push({entry:l,notes:[],origin:"merge",replaces:[...i.replace],task:null}),s.push(...a.map((u)=>({after:Xe(u,l.id),reason:"merge"})))}for(let i of t.promotions){let a=r(i.entry,{created:n,sources:[i.task],supersedes:[]});o.push({entry:a,notes:[...i.notes],origin:"promotion",replaces:[],task:i.task})}for(let i of t.archive){let a=e.get(i);if(a!==void 0)s.push({after:Xe(a,null),reason:"proposal"})}return{creations:o,retirements:s}}function gb(t){return t.promotions.map((e)=>({notes:[...e.notes],task:e.task}))}function mb(t,e){return{archived:t.retirements.map(({after:n})=>({id:n.id,supersededBy:n.supersededBy})),created:t.creations.map(({entry:n,origin:r})=>({id:n.id,kind:n.kind,origin:r})),promoted:gb(e)}}function og(t){let e=t.archived.map((s)=>` ${s.id} (${s.reason}${s.supersededBy===null?"":` of ${s.supersededBy}`})`),{clusters:n,decisions:r,notes:o}=t.candidates;return[..."dryRun"in t?["Dry run: nothing was written"]:[],`Pruned journals: ${t.pruned.length===0?"none":t.pruned.map((s)=>s.task).join(", ")}`,`Archived entries: ${e.length===0?"none":""}`.trimEnd(),...e,`Active knowledge: ${t.activeBytes} of ${t.maxBytes} bytes`,`Candidates: ${n.length} merge clusters, ${o.length} unpromoted notes, ${r.length} overlapping decision pairs`,...n.map((s)=>` merge? ${s.ids.join(", ")} (similarity ${s.similarity})`),...o.map((s)=>` promote? ${s.task} note ${s.note}: ${s.text.split(`
251
- `)[0]??""}`),...r.map((s)=>` reconcile? ${s.ids.join(" and ")}`),..."changes"in t?kb(t.changes):[],..."ledger"in t?[`Ledger entry: ${t.ledger}`]:[]].join(`
252
- `)}function fb(t){return[..."dryRun"in t?["Dry run: nothing was written"]:[],`Created: ${t.created.length===0?"none":t.created.map((e)=>e.id).join(", ")}`,`Archived: ${t.archived.length===0?"none":t.archived.map((e)=>e.id).join(", ")}`,`Promoted notes: ${t.promoted.length===0?"none":t.promoted.map((e)=>`${e.task} ${e.notes.join(", ")}`).join("; ")}`,..."changes"in t?kb(t.changes):[],..."ledger"in t?[`Ledger entry: ${t.ledger}`]:[]].join(`
253
- `)}function hb(t){let e=(r)=>r.length===0?"none":r.map((o)=>o.id).join(", "),n=t.unpromoted.map((r)=>`${r.task} ${r.notes.join(", ")}`).join("; ");return[..."dryRun"in t?["Dry run: nothing was written"]:[],`Undoing sleep entry ${t.undoes}`,`Restored: ${e(t.restored)}`,`Removed: ${e(t.removed)}`,`Reopened notes: ${n===""?"none":n}`,...t.journalsNotRestored.length===0?[]:[`Pruned journals are not restored: ${t.journalsNotRestored.join(", ")}`],..."ledger"in t?[`Ledger entry: ${t.ledger}`]:[]].join(`
254
- `)}function yb(t){let{due:e,sleep:n}=t;if(n===null)return`Sleep is not due: no journals of done tasks, ${e.activeBytes} of ${e.maxBytes} bytes of active knowledge, no candidates`;return[`Sleep is due: ${e.reasons.join(", ")}`,og(n)].join(`
255
- `)}function kb(t){return t.flatMap((e)=>{let n=e.supersededBy===null?"":` by ${e.supersededBy}`;return[`${e.change} ${e.id} (${e.reason}${n})`,...e.diff.map((r)=>` ${r}`)]})}var Sb=E({name:"sleep",description:"Consolidate memory: prune journals, archive duplicates, decay and enforce the budget",args:j({apply:{description:"Apply a validated JSON proposal of merges, promotions and archives",type:"string"},dryRun:{default:!1,description:"Show what would change, with a diff of each entry, and write nothing",type:"boolean"},force:{default:!1,description:"With --apply, allow retiring constraint and decision entries and entries that recent tasks used",type:"boolean"},ifDue:{default:!1,description:"Run the pass only when sleep is due, otherwise say that nothing is due",type:"boolean"},undo:{default:!1,description:"Undo a sleep ledger entry (the id is the argument; default: the latest that changed knowledge)",type:"boolean"}}),positionals:at({id:{description:"With --undo, the sleep ledger entry to undo"}}),json:!0,examples:["ari sleep","ari sleep --json","ari sleep --if-due","ari sleep --dry-run","ari sleep --apply proposal.json --dry-run","ari sleep --apply proposal.json","ari sleep --undo"],run:async(t)=>{let{apply:e,dryRun:n,force:r,ifDue:o,undo:s}=t.args,{id:i}=t.positionals;HB({apply:e,dryRun:n,force:r,ifDue:o,undo:s},i);let a=await O();if(s){t.output.result(n?await mE(a,i):await gE(a,i),hb);return}if(e!==void 0){let c=GB(process.cwd(),e),l=n?ub(a,c,{force:r}):await lb(a,c,{force:r});t.output.result(l,fb);return}if(o){let c=Fn(await kr(a)),l=c.due?await wb(a,n):null,u={due:c,sleep:l};t.output.result(u,yb);return}t.output.result(await wb(a,n),og)}});function wb(t,e){return e?Cw(t):yr(t)}function HB(t,e){let{apply:n,force:r,ifDue:o,undo:s}=t;if(e!==void 0&&!s)throw new T("A ledger id needs --undo",`Run 'ari sleep --undo ${e}'`);if(s){let i=[n===void 0?"":"--apply",r?"--force":"",o?"--if-due":""].filter((a)=>a.length>0);if(i.length>0)throw new T(`--undo cannot be combined with ${i.join(" or ")}`,"Run 'ari sleep --undo [<id>]'");return}if(n!==void 0&&o)throw new T("--if-due cannot be combined with --apply","Run one of them");if(r&&n===void 0)throw new T("--force applies only with --apply","Run 'ari sleep --apply <file> --force'")}import{existsSync as Mb}from"fs";import{basename as l2,extname as u2,join as jb}from"path";import{readFileSync as UB}from"fs";import{join as KB}from"path";var Eb=["checks","invariants","scope","locked"];function $b(t,e,{exact:n,pack:r}){if(r===null)return[`the pack "${e.contract.pack}" is not a built-in or project pack`];let o=e.record.status==="done",s=o?[...XB(t,e),...VB(e)]:[],i=e.record.evidence.flatMap(YB);if(!n)return[...s,...BB(e,r),...i];let a=o?zB(e,r):[];return[...s,...JB(e,r),...i,...a]}function bb(t,{exact:e}){let{evidence:n}=t.record;if(e)return n.at(-1)?.gates??[];return Eb.flatMap((r)=>{let o=ul(t,r),s=o.at(-1);return s===void 0?[]:[{...s,checks:vb(o)}]})}function BB(t,e){let n=e.stages.flatMap((u)=>u.gates),o=Eb.filter((u)=>n.some((d)=>d.kind===u)).filter((u)=>ul(t,u).length===0).map((u)=>`the record holds no ${u} evidence, but pack "${e.name}" runs that gate`),s=new Set(n.flatMap((u)=>WB(t.contract,u))),i=vb(ul(t,"checks")),a=[...s].filter((u)=>!i.some((d)=>d.name===u.name&&d.command===u.run)).map((u)=>`the record holds no evidence that ${u.name} (${JSON.stringify(u.run)}) passed`),c=ul(t,"invariants").at(-1)?.checks.map((u)=>u.command),l=c===void 0||ig(c,t.contract.invariants)?[]:[`the invariants evidence ran ${JSON.stringify(c)}, but the contract asks for ${JSON.stringify(t.contract.invariants)}`];return[...o,...a,...l]}function WB(t,e){return e.kind==="checks"&&e.expect==="pass"?Wr(t,e.select):[]}function ul(t,e){return t.record.evidence.flatMap((n)=>n.gates.filter((r)=>r.gate===e))}function vb(t){let e=t.flatMap((n)=>n.checks).filter((n)=>n.expect==="pass");return[...new Map(e.map((n)=>[sg(n),n])).values()]}function VB(t){return t.record.gatesHash===null?["the record has no frozen gates hash"]:[]}function JB(t,e){let{record:n}=t,r=n.status==="done"?e.stages.length:n.stage,o=n.evidence.length;return[...o===r?[]:[`the record holds evidence for ${o} ${kt(o,"stage","stages")}, but pack "${e.name}" expects ${r} at this point`],...n.evidence.flatMap((i,a)=>qB(i,e,a))]}function qB(t,e,n){let r=e.stages[n];if(r===void 0)return[];if(t.stage!==r.name)return[`evidence ${n+1} is for stage "${t.stage}", but stage ${n+1} of pack "${e.name}" is "${r.name}"`];let o=t.gates.map((i)=>i.gate),s=r.gates.map((i)=>i.kind);if(ig(o,s))return[];return[`the evidence of stage "${r.name}" records the gates [${o.join(", ")}], but the pack runs [${s.join(", ")}]`]}function YB(t){return t.gates.filter((e)=>!e.ok||e.checks.some((n)=>!n.ok)).map((e)=>`the evidence of stage "${t.stage}" records a failing ${e.gate} gate`)}function XB(t,e){let n=e.record.contractHash;if(n===null)return["the record has no frozen contract hash"];let r=UB(KB(t,bt(e.contract.id)),"utf8");if(un(r)===n)return[];return["the contract changed after 'ari start' or the last 'ari amend' froze it; a done contract must not change"]}function zB(t,e){let n=t.record.evidence.length-1,r=t.record.evidence[n],o=e.stages[n];if(r===void 0||o===void 0||r.stage!==o.name)return[];return r.gates.flatMap((s,i)=>ZB(t.contract,o,s,i))}function ZB(t,e,n,r){let o=e.gates[r];if(o===void 0||o.kind!==n.gate)return[];let s=QB(t,o);if(s===null)return[];let i=n.checks.map(t2);if(ig(i.map(sg),s.map(sg)))return[];return[`the ${n.gate} evidence of stage "${e.name}" ran ${Tb(i)}, but the contract asks for ${Tb(s)}`]}function QB(t,e){switch(e.kind){case"checks":return Wr(t,e.select).map((n)=>({command:n.run,expect:e.expect,name:n.name}));case"invariants":return t.invariants.map((n,r)=>({command:n,expect:"pass",name:`invariants[${r}]`}));default:return null}}function t2(t){return{command:t.command,expect:t.expect,name:t.name}}function sg(t){return JSON.stringify([t.name,t.command,t.expect])}function Tb(t){if(t.length===0)return"nothing";return t.map((e)=>`${e.name} (${JSON.stringify(e.command)}, expect ${e.expect})`).join(", ")}function ig(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Vn=0,cg=1,e2=128,n2=`
256
- `;async function xb(t,e){let n=e.evidence.at(-1);if(e.status!=="done"||n===void 0)return null;let r=fn(e.id),o=await P(t,["log","--reverse","--format=%H","HEAD","--",r]),s=null;for(let i of o.stdout.split(n2).filter((a)=>a.length>0)){let a=_b(await Ys(t,i,r));if(a===null||a.created!==e.history[0]?.at)continue;if(a.base!==null)s??=i;if(r2(a,n))return{finished:i,started:s??i}}return null}async function Ab(t,e,n){return _b(await Ys(t,e,fn(n)))?.status??null}async function Ys(t,e,n){let r=await P(t,["show",`${e}:${n}`],{allowedExitCodes:[Vn,e2]});return r.exitCode===Vn?r.stdout:null}async function Cb(t,e){return await Ob(t,e)!==null}async function Rb(t,e){return Ob(t,`${e}^`)}async function Xs(t,e,n){return(await P(t,["merge-base","--is-ancestor",e,n],{allowedExitCodes:[Vn,cg]})).exitCode===Vn}async function lg(t,e,n){let r=await P(t,["merge-base",e,n],{allowedExitCodes:[Vn,cg]});return r.exitCode===Vn?r.stdout.trim():null}async function ug(t,e,n){return Number((await P(t,["rev-list","--count",`${e}..${n}`])).stdout.trim())}async function Ib(t){return(await P(t,["rev-parse","--is-shallow-repository"])).stdout.trim()==="true"}async function Ob(t,e){let n=["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],r=await P(t,n,{allowedExitCodes:[Vn,cg]});return r.exitCode===Vn?r.stdout.trim():null}function _b(t){let e=o2(t);if(!ag(e))return null;let n=Array.isArray(e.evidence)?e.evidence.at(-1):null,r=Array.isArray(e.history)?e.history[0]:null;return{base:e.base??null,created:ag(r)?r.at:null,evidence:ag(n)?n:null,status:e.status}}function r2(t,{at:e,stage:n,treeHash:r}){let o=t.evidence;return o!==null&&o.at===e&&o.stage===n&&o.treeHash===r}function o2(t){if(t===null)return null;try{return JSON.parse(t)}catch(e){if(e instanceof SyntaxError)return null;throw e}}function ag(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function dg({packs:t},e){return{exact:!0,pack:pg(t,e.contract.pack)}}async function Pb(t,e,n,r){let{gatesHash:o}=e.record,s=r===null?null:await s2(t,r,e.contract.pack),i=[n,s].find((a)=>a!==null&&i2(a,e)===o);if(i)return dg(i,e);return{exact:!1,pack:pg((s??n).packs,e.contract.pack)}}async function s2(t,e,n){let r=Pu(n),o=await Ys(t,e,r),s=await Ys(t,e,Q);try{return{config:rr(s===null?{}:JSON.parse(s)),packs:pn(o===null?[]:[sa(o,r)])}}catch(i){if(i instanceof g||i instanceof SyntaxError)return null;throw i}}function i2({config:t,packs:e},n){let r=pg(e,n.contract.pack);return r===null?null:ia(r,t)}function pg(t,e){return t.find((n)=>n.name===e)??null}async function Db(t){let{commits:e,record:n,root:r,target:o}=t,{base:s}=n;if(s===null)return Lb("the record has no base commit");let i=await Cb(r,s);if(e===null){if(!i)return gg(s);return dl(await pe(r,await Nb(r,s,o,"HEAD")))}let{finished:a}=e,c=i&&await Xs(r,s,a),l=o===null?null:await lg(r,o,a);if(l===null||l===a)return c2(t,e,c?s:null);let u=c?await Nb(r,s,o,a):await a2(r,l,t.otherFinishes,a);return dl(await Xi(r,u,a))}async function Nb(t,e,n,r){let o=n===null?null:await lg(t,n,r);return o!==null&&await Xs(t,e,o)?o:e}async function a2(t,e,n,r){let o={commit:e,distance:await ug(t,e,r)};for(let s of n){if(s===r||!await Xs(t,e,s)||!await Xs(t,s,r))continue;let i=await ug(t,s,r);if(i<o.distance)o={commit:s,distance:i}}return o.commit}async function c2(t,e,n){let{record:r,root:o}=t,{finished:s,started:i}=e;if(n===null&&await Ib(o))return gg(r.base);let a=await Rb(o,i),c=a===null?null:await Xi(o,a,s);if(n===null)return c===null?gg(r.base):dl(c);let l=await Xi(o,n,s);return dl(c===null?l:l.filter((u)=>c.includes(u)))}function dl(t){return{files:t,problem:null}}function Lb(t){return{files:[],problem:t}}function gg(t){return Lb(`the base commit ${t} is not in this clone; fetch the full history`)}var d2="\x00",mg="HEAD",kg="done",fg=[ir,Ah],p2="invalid";async function Fb(t,e){let n=L(t);await Yi(t);let r=It(t,n),o=pn(me(t)),s=e.kind==="base"?await Hr(t,e.ref):null,i=new Map(r.tasks.map((p)=>[p.contract.id,p])),a=new Map(r.invalid.map((p)=>[p.id,p])),c=await g2(t,e,s,i),l=new Map;for(let p of c){let m=i.get(p);if(m!==void 0)l.set(p,await xb(t,m.record))}let u={commits:l,config:n,mode:e.kind,packs:o,root:t,target:s},d=[];for(let p of c){let m=i.get(p);if(m!==void 0){d.push(await h2(u,m));continue}let f=a.get(p)?.problem??f2(t,p);if(f===null)continue;d.push({gates:[],ok:!1,problems:[f],stage:null,status:p2,task:p})}return{failed:d.filter((p)=>!p.ok).map((p)=>p.task),mode:e.kind,ref:e.kind==="base"?e.ref:null,tasks:d}}async function g2(t,e,n,r){let o=n??mg,s=async(i)=>(r.get(i)?.record.status??await m2(t,i,o))===kg;switch(e.kind){case"all":return yg(hn(t),s);case"base":{let i=["diff","--name-only","--no-renames","-z",o,mg,"--",...fg],a=(await P(t,i)).stdout.split(d2),c=new Set(hg(a,ir));return yg(hg(a,...fg),async(l)=>c.has(l)||s(l))}case"local":{let i=ut(await M(t))?.task,a=await yg(hg(await pe(t,mg),...fg),s);return[...new Set([...i===void 0?[]:[i],...a])]}}}async function m2(t,e,n){if(!Mb(jb(t,fn(e))))return Ab(t,n,e);try{return yn(t,e).status}catch(r){if(r instanceof g)return kg;throw r}}function f2(t,e){let n=fn(e);return Mb(jb(t,n))?`${n} has a record but no contract`:null}function hg(t,...e){let n=t.filter((r)=>Z(r,e)).map((r)=>l2(r,u2(r)));return[...new Set(n)].filter(_u).sort(I)}async function yg(t,e){let n=[];for(let r of t)if(await e(r))n.push(r);return n}async function h2(t,e){let{record:n}=e,r=n.evidence.at(-1),o={status:n.status,task:e.contract.id};if(r===void 0){let u=n.status===kg?["the task is done but has no stage evidence"]:[];return{...o,gates:[],ok:u.length===0,problems:u,stage:null}}let{root:s}=t,i=t.mode==="all"?await Pb(s,e,t,Gb(t,e)?.finished??null):dg(t,e),a=$b(s,e,i),c=[];for(let u of bb(e,i)){let d=await y2(t,e,u);if(d===null)continue;let p=d.current===u.ok&&d.details.length===0;c.push({current:d.current,details:d.details,gate:u.gate,ok:p,recorded:u.ok})}let l=a.length===0&&c.every((u)=>u.ok);return{...o,gates:c,ok:l,problems:a,stage:r.stage}}function Gb(t,e){return t.commits.get(e.contract.id)??null}async function y2(t,e,n){switch(n.gate){case"checks":case"invariants":{let r=k2(e,n.checks);return r.length===0?null:w2(t,e,r)}case"locked":return T2(t,e);case"scope":return E2(t,e);default:return null}}function k2(t,e){if(t.record.status==="done")return[...e];return e.filter((n)=>n.expect==="pass")}async function w2(t,e,n){let r=[],o=!0;for(let s of n){let i={name:s.name,run:s.command,timeoutSeconds:S2(t,e,s.name)},[a]=await Le([i],s.expect,t.root);if(a===void 0)continue;if(o&&=a.ok,a.ok===s.ok)continue;r.push(a.ok?`${s.name} now meets its expectation (${s.expect})`:fd(a))}return{current:o,details:r}}function S2(t,e,n){return e.contract.checks.find((o)=>o.name===n)?.timeoutSeconds??t.config.checkTimeoutSeconds}async function T2(t,e){let n=await ln(t.root,e.contract.lock),r=Es(e.record.lockHashes,n);return{current:r.length===0,details:r}}async function E2(t,e){let{commits:n,root:r,target:o}=t,s=[...n].flatMap(([c,l])=>l===null||c===e.contract.id?[]:[l.finished]),i=await Db({commits:Gb(t,e),otherFinishes:s,record:e.record,root:r,target:o});if(i.problem!==null)return{current:!1,details:[i.problem]};let a=Wt(i.files).filter((c)=>!Z(c,e.contract.scope));return{current:a.length===0,details:a.map((c)=>`outside the scope: ${c}`)}}var $2=1,Ub=E({name:"verify",description:"Re-evaluate the reproducible gates of done tasks against their evidence",args:j({all:{default:!1,description:"Verify every done task",type:"boolean"},base:{description:"Verify tasks whose record changed between this reference and HEAD (CI mode)",type:"string"}}),json:!0,examples:["ari verify","ari verify --base origin/develop","ari verify --all --json"],run:async(t)=>{let{all:e,base:n}=t.args;if(e&&n!==void 0)throw new T("--all and --base exclude each other","Pass one of them");let r=n!==void 0?{kind:"base",ref:n}:e?{kind:"all"}:{kind:"local"},o=await Fb(await O(),r);return t.output.result(o,b2),o.failed.length===0?void 0:$2}});function b2(t){if(t.tasks.length===0)return"No task to verify";return t.tasks.flatMap((e)=>{let n=e.stage===null?"":` (${e.stage})`,r=e.gates.filter((i)=>!i.ok).flatMap((i)=>[` ${i.gate}: recorded ${Hb(i.recorded)}, now ${Hb(i.current)}`,...i.details.map((a)=>` ${a}`)]),o=e.problems.map((i)=>` ${i}`),s=e.ok&&e.gates.length===0?" (no evidence to reproduce yet)":"";return[`${e.ok?"ok":"FAILED"} ${e.task}${n}${s}`,...o,...r]}).join(`
257
- `)}function Hb(t){return t?"passed":"failed"}var Kb=[X$,Q$,z$,Sb,eb,Ub];var A2=".ari",C2="cli-state.json",R2=Bl({bin:"ari",commands:[rE,VE,Y$,bT,O$,_$,P$,qE,YE,XT,zT,ZT,XE,zE,ZE,QE,QT,...Kb,eE,nE,R$,C$,v$,I$,fy,D$],config:new Zl(x2(v2(),A2,C2),{}),description:"Task contracts, CLI-evaluated gates and tiered memory for coding agents",name:"Ariadne",version:ji});R2.main();
276
+ `)}import{resolve as Eq}from"path";import{existsSync as pq,readFileSync as gq}from"fs";var Ai="Fix the proposal file, then run 'ari sleep --apply <file>' again",mq=["merges","promotions","archive","reason"],fq=["replace","entry"],hq=["task","notes","entry"],yq=["kind","scope","text"],kq=1;function yx(t,e){if(!pq(t))throw new m(`The proposal file ${t} does not exist`,Ai);let n=gq(t),r;try{r=JSON.parse(n.toString("utf8"))}catch(s){let i=s instanceof Error?s.message:String(s);throw new m(`The proposal file ${t} is not valid JSON (${i})`,Ai)}return{proposal:At("sleep proposal",Ai,()=>wq(r,e.knowledge.maxEntryBytes)),sha256:Z(n)}}function kx(t,e,n,r){let o=[],s=new Map,i=(c,l)=>{let u=e.get(c),d=s.get(c);if(u===void 0)o.push(`${l} names the unknown entry "${c}"`);else if(u.status!=="active")o.push(`${l} names the archived entry "${c}"`);else if(pn(u)&&!r)o.push(`${l} retires the ${u.kind} "${c}"; pass --force to retire ${u.kind} entries`);if(d!==void 0)o.push(`${l} names "${c}", which ${d} already retires`);s.set(c,l)};t.merges.forEach((c,l)=>{if(c.replace.length<kq)o.push(`merges[${l}].replace is empty`);c.replace.forEach((u,d)=>{i(u,`merges[${l}].replace[${d}]`)})}),t.archive.forEach((c,l)=>{i(c,`archive[${l}]`)});let a=new Map;return t.promotions.forEach((c,l)=>{let u=`promotions[${l}]`,d=n.get(c.task);if(d===void 0){o.push(`${u}.task names the unknown or unreadable task "${c.task}"`);return}if(c.notes.length===0)o.push(`${u}.notes is empty`);let p=a.get(c.task)??new Set;for(let g of c.notes){let f=d.notes[g];if(f===void 0)o.push(`${u}.notes names note ${g}, but "${c.task}" has none`);else if(f.promoted)o.push(`${u}.notes names note ${g}, which is already promoted`);if(p.has(g))o.push(`${u}.notes names note ${g} of "${c.task}" twice`);p.add(g)}a.set(c.task,p)}),o}function wq(t,e){let n=T(t,"proposal",mq);return{archive:D(n.archive,[],(r)=>L(r,"archive",x)),merges:D(n.merges,[],(r)=>L(r,"merges",(o,s)=>{let i=T(o,s,fq);return{entry:hx(i.entry,`${s}.entry`,e),replace:ft(i.replace,`${s}.replace`,(a,c)=>L(a,c,x))}})),promotions:D(n.promotions,[],(r)=>L(r,"promotions",(o,s)=>{let i=T(o,s,hq);return{entry:hx(i.entry,`${s}.entry`,e),notes:ft(i.notes,`${s}.notes`,(a,c)=>L(a,c,ht)),task:ft(i.task,`${s}.task`,x)}})),reason:D(n.reason,null,(r)=>nt(r,"reason").trim())}}function hx(t,e,n){let r=ft(t,e,(o,s)=>T(o,s,yq));return bp({kind:r.kind,scope:r.scope??[],text:r.text},e,n)}var Sq="(merged entry ";function Sx(t,e,n,r){let o=Fp(e),s=Fp(vq(t,e)),i=new Map;for(let a of Lr(n).slice(0,r))for(let c of a.record.knowledgeUsed){if(o(c)===null||s(c)!==null)continue;i.set(c,[...i.get(c)??[],a.contract.id])}return[...i.entries()].map(([a,c])=>({entry:a,tasks:c})).sort((a,c)=>O(a.entry,c.entry))}function vx(t){let e=t.tasks.map((r)=>`"${r}"`).join(", "),n=t.tasks.length===1?"task":"tasks";return`"${t.entry}" would no longer be active or replaced by an active entry, but ${n} ${e} used it`}function vq(t,e){let n=new Map(e);t.merges.forEach((r,o)=>{let s=`${Sq}${o})`;n.set(s,Qs(r.entry,{created:"",id:s,sources:[],supersedes:r.replace}));for(let i of r.replace)wx(n,i,s)});for(let r of t.archive)wx(n,r,null);return n}function wx(t,e,n){let r=t.get(e);if(r!==void 0)t.set(e,dn(r,n))}var bx=()=>new Date().toISOString();async function Ex(t,e,n={}){let r=M(t),o=await P(t),s=(n.clock??bx)(),i=n.force===!0;return Nr(o,()=>{let{entries:a,proposal:c,sha256:l}=Tx(t,e,r,i),u=new Set(an(t)),d=xx(c,a,Io(s),(f,y)=>$p(t,f,y,u)),p=_c(t,d.retirements);for(let{notes:f,task:y}of c.promotions)Vt(t,o,y,(S)=>hy(S,f));let g=No(o,s,{archived:p,created:VS(t,d.creations),forced:i,kind:"apply",promoted:Ax(c),proposal:{sha256:l},pruned:[],reason:c.reason});return{...Cx(d,c),ledger:g.id}})}function $x(t,e,n={}){let r=M(t),o=(n.clock??bx)(),{entries:s,proposal:i}=Tx(t,e,r,n.force===!0),a=new Set(an(t)),c=xx(i,s,Io(o),(l,u)=>Qs(l,{...u,id:Ep(l,a)}));return{...Cx(c,i),changes:Pc(t,c.retirements,c.creations),dryRun:!0}}function Tx(t,e,n,r){let{proposal:o,sha256:s}=yx(e,n),i=new Map(pe(t).map((p)=>[p.id,p])),{tasks:a}=Pt(t,n),c=new Map(a.map((p)=>[p.contract.id,p.record])),l=kx(o,i,c,r);if(l.length>0){let p=l.map((g)=>` - ${g}`).join(`
277
+ `);throw new m(`The sleep proposal has ${l.length} problem(s):
278
+ ${p}`,Ai)}let u=n.knowledge.rehearsalTasks,d=r?[]:Sx(o,i,a,u);if(d.length>0)throw bq(d,Math.min(u,Lr(a).length));return{entries:i,proposal:o,sha256:s}}function bq(t,e){let n=t.map((r)=>` - ${vx(r)}`).join(`
279
+ `);return new m(`The sleep proposal fails the rehearsal against the last ${e} done task(s):
280
+ ${n}`,"Keep those entries out of the proposal, merge them into a successor, or run 'ari sleep --apply <file> --force' to apply it anyway")}function xx(t,e,n,r){let o=[],s=[];for(let i of t.merges){let a=i.replace.map((u)=>e.get(u)).filter((u)=>u!==void 0),c=[...new Set(a.flatMap((u)=>u.sources))].sort(O),l=r(i.entry,{created:n,sources:c,supersedes:[...i.replace]});o.push({entry:l,notes:[],origin:"merge",replaces:[...i.replace],task:null}),s.push(...a.map((u)=>({after:dn(u,l.id),reason:"merge"})))}for(let i of t.promotions){let a=r(i.entry,{created:n,sources:[i.task],supersedes:[]});o.push({entry:a,notes:[...i.notes],origin:"promotion",replaces:[],task:i.task})}for(let i of t.archive){let a=e.get(i);if(a!==void 0)s.push({after:dn(a,null),reason:"proposal"})}return{creations:o,retirements:s}}function Ax(t){return t.promotions.map((e)=>({notes:[...e.notes],task:e.task}))}function Cx(t,e){return{archived:t.retirements.map(({after:n})=>({id:n.id,supersededBy:n.supersededBy})),created:t.creations.map(({entry:n,origin:r})=>({id:n.id,kind:n.kind,origin:r})),promoted:Ax(e)}}function um(t){let e=t.archived.map((s)=>` ${s.id} (${s.reason}${s.supersededBy===null?"":` of ${s.supersededBy}`})`),{clusters:n,decisions:r,notes:o}=t.candidates;return[..."dryRun"in t?["Dry run: nothing was written"]:[],`Pruned journals: ${t.pruned.length===0?"none":t.pruned.map((s)=>s.task).join(", ")}`,`Archived entries: ${e.length===0?"none":""}`.trimEnd(),...e,`Active knowledge: ${t.activeBytes} of ${t.maxBytes} bytes`,`Candidates: ${n.length} merge clusters, ${o.length} unpromoted notes, ${r.length} overlapping decision pairs`,...n.map((s)=>` merge? ${s.ids.join(", ")} (similarity ${s.similarity})`),...o.map((s)=>` promote? ${s.task} note ${s.note}: ${s.text.split(`
281
+ `)[0]??""}`),...r.map((s)=>` reconcile? ${s.ids.join(" and ")}`),..."changes"in t?_x(t.changes):[],..."ledger"in t?[`Ledger entry: ${t.ledger}`]:[]].join(`
282
+ `)}function Rx(t){return[..."dryRun"in t?["Dry run: nothing was written"]:[],`Created: ${t.created.length===0?"none":t.created.map((e)=>e.id).join(", ")}`,`Archived: ${t.archived.length===0?"none":t.archived.map((e)=>e.id).join(", ")}`,`Promoted notes: ${t.promoted.length===0?"none":t.promoted.map((e)=>`${e.task} ${e.notes.join(", ")}`).join("; ")}`,..."changes"in t?_x(t.changes):[],..."ledger"in t?[`Ledger entry: ${t.ledger}`]:[]].join(`
283
+ `)}function Ix(t){let e=(r)=>r.length===0?"none":r.map((o)=>o.id).join(", "),n=t.unpromoted.map((r)=>`${r.task} ${r.notes.join(", ")}`).join("; ");return[..."dryRun"in t?["Dry run: nothing was written"]:[],`Undoing sleep entry ${t.undoes}`,`Restored: ${e(t.restored)}`,`Removed: ${e(t.removed)}`,`Reopened notes: ${n===""?"none":n}`,...t.journalsNotRestored.length===0?[]:[`Pruned journals are not restored: ${t.journalsNotRestored.join(", ")}`],..."ledger"in t?[`Ledger entry: ${t.ledger}`]:[]].join(`
284
+ `)}function Ox(t){let{due:e,sleep:n}=t;if(n===null)return`Sleep is not due: no journals of done tasks, ${e.activeBytes} of ${e.maxBytes} bytes of active knowledge, no candidates`;return[`Sleep is due: ${e.reasons.join(", ")}`,um(n)].join(`
285
+ `)}function _x(t){return t.flatMap((e)=>{let n=e.supersededBy===null?"":` by ${e.supersededBy}`;return[`${e.change} ${e.id} (${e.reason}${n})`,...e.diff.map((r)=>` ${r}`)]})}var Nx=E({name:"sleep",description:"Consolidate memory: prune journals, archive duplicates, decay and enforce the budget",args:j({apply:{description:"Apply a validated JSON proposal of merges, promotions and archives",type:"string"},dryRun:{default:!1,description:"Show what would change, with a diff of each entry, and write nothing",type:"boolean"},force:{default:!1,description:"With --apply, allow retiring constraint and decision entries and entries that recent tasks used",type:"boolean"},ifDue:{default:!1,description:"Run the pass only when sleep is due, otherwise say that nothing is due",type:"boolean"},undo:{default:!1,description:"Undo a sleep ledger entry (the id is the argument; default: the latest that changed knowledge)",type:"boolean"}}),positionals:st({id:{description:"With --undo, the sleep ledger entry to undo"}}),json:!0,examples:["ari sleep","ari sleep --json","ari sleep --if-due","ari sleep --dry-run","ari sleep --apply proposal.json --dry-run","ari sleep --apply proposal.json","ari sleep --undo"],run:async(t)=>{let{apply:e,dryRun:n,force:r,ifDue:o,undo:s}=t.args,{id:i}=t.positionals;$q({apply:e,dryRun:n,force:r,ifDue:o,undo:s},i);let a=await _();if(s){t.output.result(n?await f$(a,i):await m$(a,i),Ix);return}if(e!==void 0){let c=Eq(process.cwd(),e),l=n?$x(a,c,{force:r}):await Ex(a,c,{force:r});t.output.result(l,Rx);return}if(o){let c=er(await jr(a)),l=c.due?await Px(a,n):null,u={due:c,sleep:l};t.output.result(u,Ox);return}t.output.result(await Px(a,n),um)}});function Px(t,e){return e?WS(t):Mr(t)}function $q(t,e){let{apply:n,force:r,ifDue:o,undo:s}=t;if(e!==void 0&&!s)throw new v("A ledger id needs --undo",`Run 'ari sleep --undo ${e}'`);if(s){let i=[n===void 0?"":"--apply",r?"--force":"",o?"--if-due":""].filter((a)=>a.length>0);if(i.length>0)throw new v(`--undo cannot be combined with ${i.join(" or ")}`,"Run 'ari sleep --undo [<id>]'");return}if(n!==void 0&&o)throw new v("--if-due cannot be combined with --apply","Run one of them");if(r&&n===void 0)throw new v("--force applies only with --apply","Run 'ari sleep --apply <file> --force'")}import{existsSync as zx}from"fs";import{basename as Wq,extname as Jq,join as Zx}from"path";import{readFileSync as Tq}from"fs";import{join as xq}from"path";var Lx=["checks","invariants","scope","locked"];function Mx(t,e,{exact:n,pack:r}){if(r===null)return[`the pack "${e.contract.pack}" is not a built-in or project pack`];let o=e.record.status==="done",s=o?[...Pq(t,e),...Rq(e)]:[],i=e.record.evidence.flatMap(_q);if(!n)return[...s,...Aq(e,r),...i];let a=o?Nq(e,r):[];return[...s,...Iq(e,r),...i,...a]}function jx(t,{exact:e}){let{evidence:n}=t.record;if(e)return n.at(-1)?.gates??[];return Lx.flatMap((r)=>{let o=eu(t,r),s=o.at(-1);return s===void 0?[]:[{...s,checks:Fx(o)}]})}function Aq(t,e){let n=e.stages.flatMap((u)=>u.gates),o=Lx.filter((u)=>n.some((d)=>d.kind===u)).filter((u)=>eu(t,u).length===0).map((u)=>`the record holds no ${u} evidence, but pack "${e.name}" runs that gate`),s=new Set(n.flatMap((u)=>Cq(t.contract,u))),i=Fx(eu(t,"checks")),a=[...s].filter((u)=>!i.some((d)=>d.name===u.name&&d.command===u.run)).map((u)=>`the record holds no evidence that ${u.name} (${JSON.stringify(u.run)}) passed`),c=eu(t,"invariants").at(-1)?.checks.map((u)=>u.command),l=c===void 0||pm(c,t.contract.invariants)?[]:[`the invariants evidence ran ${JSON.stringify(c)}, but the contract asks for ${JSON.stringify(t.contract.invariants)}`];return[...o,...a,...l]}function Cq(t,e){return e.kind==="checks"&&e.expect==="pass"?po(t,e.select):[]}function eu(t,e){return t.record.evidence.flatMap((n)=>n.gates.filter((r)=>r.gate===e))}function Fx(t){let e=t.flatMap((n)=>n.checks).filter((n)=>n.expect==="pass");return[...new Map(e.map((n)=>[dm(n),n])).values()]}function Rq(t){return t.record.gatesHash===null?["the record has no frozen gates hash"]:[]}function Iq(t,e){let{record:n}=t,r=n.status==="done"?e.stages.length:n.stage,o=n.evidence.length;return[...o===r?[]:[`the record holds evidence for ${o} ${wt(o,"stage","stages")}, but pack "${e.name}" expects ${r} at this point`],...n.evidence.flatMap((i,a)=>Oq(i,e,a))]}function Oq(t,e,n){let r=e.stages[n];if(r===void 0)return[];if(t.stage!==r.name)return[`evidence ${n+1} is for stage "${t.stage}", but stage ${n+1} of pack "${e.name}" is "${r.name}"`];let o=t.gates.map((i)=>i.gate),s=r.gates.map((i)=>i.kind);if(pm(o,s))return[];return[`the evidence of stage "${r.name}" records the gates [${o.join(", ")}], but the pack runs [${s.join(", ")}]`]}function _q(t){return t.gates.filter((e)=>!e.ok||e.checks.some((n)=>!n.ok)).map((e)=>`the evidence of stage "${t.stage}" records a failing ${e.gate} gate`)}function Pq(t,e){let n=e.record.contractHash;if(n===null)return["the record has no frozen contract hash"];let r=Tq(xq(t,It(e.contract.id)),"utf8");if(Bt(r)===n)return[];return["the contract changed after 'ari start' or the last 'ari amend' froze it; a done contract must not change"]}function Nq(t,e){let n=t.record.evidence.length-1,r=t.record.evidence[n],o=e.stages[n];if(r===void 0||o===void 0||r.stage!==o.name)return[];return r.gates.flatMap((s,i)=>Dq(t.contract,o,s,i))}function Dq(t,e,n,r){let o=e.gates[r];if(o===void 0||o.kind!==n.gate)return[];let s=Lq(t,o);if(s===null)return[];let i=n.checks.map(Mq);if(pm(i.map(dm),s.map(dm)))return[];return[`the ${n.gate} evidence of stage "${e.name}" ran ${Dx(i)}, but the contract asks for ${Dx(s)}`]}function Lq(t,e){switch(e.kind){case"checks":return po(t,e.select).map((n)=>({command:n.run,expect:e.expect,name:n.name}));case"invariants":return t.invariants.map((n,r)=>({command:n,expect:"pass",name:`invariants[${r}]`}));default:return null}}function Mq(t){return{command:t.command,expect:t.expect,name:t.name}}function dm(t){return JSON.stringify([t.name,t.command,t.expect])}function Dx(t){if(t.length===0)return"nothing";return t.map((e)=>`${e.name} (${JSON.stringify(e.command)}, expect ${e.expect})`).join(", ")}function pm(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var lr=0,mm=1,jq=128,Fq=`
286
+ `;async function Gx(t,e){let n=e.evidence.at(-1);if(e.status!=="done"||n===void 0)return null;let r=Rn(e.id),o=await F(t,["log","--reverse","--format=%H","HEAD","--",r]),s=null;for(let i of o.stdout.split(Fq).filter((a)=>a.length>0)){let a=Wx(await Ci(t,i,r));if(a===null||a.created!==e.history[0]?.at)continue;if(a.base!==null)s??=i;if(Gq(a,n))return{finished:i,started:s??i}}return null}async function Hx(t,e,n){return Wx(await Ci(t,e,Rn(n)))?.status??null}async function Ci(t,e,n){let r=await F(t,["show",`${e}:${n}`],{allowedExitCodes:[lr,jq]});return r.exitCode===lr?r.stdout:null}async function Ux(t,e){return await Vx(t,e)!==null}async function Kx(t,e){return Vx(t,`${e}^`)}async function Ri(t,e,n){return(await F(t,["merge-base","--is-ancestor",e,n],{allowedExitCodes:[lr,mm]})).exitCode===lr}async function fm(t,e,n){let r=await F(t,["merge-base",e,n],{allowedExitCodes:[lr,mm]});return r.exitCode===lr?r.stdout.trim():null}async function hm(t,e,n){return Number((await F(t,["rev-list","--count",`${e}..${n}`])).stdout.trim())}async function Bx(t){return(await F(t,["rev-parse","--is-shallow-repository"])).stdout.trim()==="true"}async function Vx(t,e){let n=["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],r=await F(t,n,{allowedExitCodes:[lr,mm]});return r.exitCode===lr?r.stdout.trim():null}function Wx(t){let e=Hq(t);if(!gm(e))return null;let n=Array.isArray(e.evidence)?e.evidence.at(-1):null,r=Array.isArray(e.history)?e.history[0]:null;return{base:e.base??null,created:gm(r)?r.at:null,evidence:gm(n)?n:null,status:e.status}}function Gq(t,{at:e,stage:n,treeHash:r}){let o=t.evidence;return o!==null&&o.at===e&&o.stage===n&&o.treeHash===r}function Hq(t){if(t===null)return null;try{return JSON.parse(t)}catch(e){if(e instanceof SyntaxError)return null;throw e}}function gm(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function ym({packs:t},e){return{exact:!0,pack:km(t,e.contract.pack)}}async function Jx(t,e,n,r){let{gatesHash:o}=e.record,s=r===null?null:await Uq(t,r,e.contract.pack),i=[n,s].find((a)=>a!==null&&Kq(a,e)===o);if(i)return ym(i,e);return{exact:!1,pack:km((s??n).packs,e.contract.pack)}}async function Uq(t,e,n){let r=Ad(n),o=await Ci(t,e,r),s=await Ci(t,e,rt);try{return{config:vr(s===null?{}:JSON.parse(s)),packs:Tn(o===null?[]:[Ia(o,r)])}}catch(i){if(i instanceof m||i instanceof SyntaxError)return null;throw i}}function Kq({config:t,packs:e},n){let r=km(e,n.contract.pack);return r===null?null:Oa(r,t)}function km(t,e){return t.find((n)=>n.name===e)??null}async function Yx(t){let{commits:e,record:n,root:r,target:o}=t,{base:s}=n;if(s===null)return Xx("the record has no base commit");let i=await Ux(r,s);if(e===null){if(!i)return wm(s);return nu(await xe(r,await qx(r,s,o,"HEAD")))}let{finished:a}=e,c=i&&await Ri(r,s,a),l=o===null?null:await fm(r,o,a);if(l===null||l===a)return Vq(t,e,c?s:null);let u=c?await qx(r,s,o,a):await Bq(r,l,t.otherFinishes,a);return nu(await Ga(r,u,a))}async function qx(t,e,n,r){let o=n===null?null:await fm(t,n,r);return o!==null&&await Ri(t,e,o)?o:e}async function Bq(t,e,n,r){let o={commit:e,distance:await hm(t,e,r)};for(let s of n){if(s===r||!await Ri(t,e,s)||!await Ri(t,s,r))continue;let i=await hm(t,s,r);if(i<o.distance)o={commit:s,distance:i}}return o.commit}async function Vq(t,e,n){let{record:r,root:o}=t,{finished:s,started:i}=e;if(n===null&&await Bx(o))return wm(r.base);let a=await Kx(o,i),c=a===null?null:await Ga(o,a,s);if(n===null)return c===null?wm(r.base):nu(c);let l=await Ga(o,n,s);return nu(c===null?l:l.filter((u)=>c.includes(u)))}function nu(t){return{files:t,problem:null}}function Xx(t){return{files:[],problem:t}}function wm(t){return Xx(`the base commit ${t} is not in this clone; fetch the full history`)}var qq="\x00",Sm="HEAD",$m="done",vm=[Er,Gy],Yq="invalid";async function Qx(t,e){let n=M(t);await Fa(t);let r=Pt(t,n),o=Tn(Gt(t)),s=e.kind==="base"?await fo(t,e.ref):null,i=new Map(r.tasks.map((p)=>[p.contract.id,p])),a=new Map(r.invalid.map((p)=>[p.id,p])),c=await Xq(t,e,s,i),l=new Map;for(let p of c){let g=i.get(p);if(g!==void 0)l.set(p,await Gx(t,g.record))}let u={commits:l,config:n,mode:e.kind,packs:o,root:t,target:s},d=[];for(let p of c){let g=i.get(p);if(g!==void 0){d.push(await Qq(u,g));continue}let f=a.get(p)?.problem??Zq(t,p);if(f===null)continue;d.push({gates:[],ok:!1,problems:[f],stage:null,status:Yq,task:p})}return{failed:d.filter((p)=>!p.ok).map((p)=>p.task),mode:e.kind,ref:e.kind==="base"?e.ref:null,tasks:d}}async function Xq(t,e,n,r){let o=n??Sm,s=async(i)=>(r.get(i)?.record.status??await zq(t,i,o))===$m;switch(e.kind){case"all":return Em(In(t),s);case"base":{let i=["diff","--name-only","--no-renames","-z",o,Sm,"--",...vm],a=(await F(t,i)).stdout.split(qq),c=new Set(bm(a,Er));return Em(bm(a,...vm),async(l)=>c.has(l)||s(l))}case"local":{let i=gt(await P(t))?.task,a=await Em(bm(await xe(t,Sm),...vm),s);return[...new Set([...i===void 0?[]:[i],...a])]}}}async function zq(t,e,n){if(!zx(Zx(t,Rn(e))))return Hx(t,n,e);try{return On(t,e).status}catch(r){if(r instanceof m)return $m;throw r}}function Zq(t,e){let n=Rn(e);return zx(Zx(t,n))?`${n} has a record but no contract`:null}function bm(t,...e){let n=t.filter((r)=>et(r,e)).map((r)=>Wq(r,Jq(r)));return[...new Set(n)].filter(xd).sort(O)}async function Em(t,e){let n=[];for(let r of t)if(await e(r))n.push(r);return n}async function Qq(t,e){let{record:n}=e,r=n.evidence.at(-1),o={status:n.status,task:e.contract.id};if(r===void 0){let u=n.status===$m?["the task is done but has no stage evidence"]:[];return{...o,gates:[],ok:u.length===0,problems:u,stage:null}}let{root:s}=t,i=t.mode==="all"?await Jx(s,e,t,tA(t,e)?.finished??null):ym(t,e),a=Mx(s,e,i),c=[];for(let u of jx(e,i)){let d=await t5(t,e,u);if(d===null)continue;let p=d.current===u.ok&&d.details.length===0;c.push({current:d.current,details:d.details,gate:u.gate,ok:p,recorded:u.ok})}let l=a.length===0&&c.every((u)=>u.ok);return{...o,gates:c,ok:l,problems:a,stage:r.stage}}function tA(t,e){return t.commits.get(e.contract.id)??null}async function t5(t,e,n){switch(n.gate){case"checks":case"invariants":{let r=e5(e,n.checks);return r.length===0?null:n5(t,e,r)}case"locked":return o5(t,e);case"scope":return s5(t,e);default:return null}}function e5(t,e){if(t.record.status==="done")return[...e];return e.filter((n)=>n.expect==="pass")}async function n5(t,e,n){let r=[],o=!0;for(let s of n){let i={name:s.name,run:s.command,timeoutSeconds:r5(t,e,s.name)},[a]=await Je([i],s.expect,t.root);if(a===void 0)continue;if(o&&=a.ok,a.ok===s.ok)continue;r.push(a.ok?`${s.name} now meets its expectation (${s.expect})`:dp(a))}return{current:o,details:r}}function r5(t,e,n){return e.contract.checks.find((o)=>o.name===n)?.timeoutSeconds??t.config.checkTimeoutSeconds}async function o5(t,e){let n=await An(t.root,e.contract.lock),r=Xs(e.record.lockHashes,n);return{current:r.length===0,details:r}}async function s5(t,e){let{commits:n,root:r,target:o}=t,s=[...n].flatMap(([c,l])=>l===null||c===e.contract.id?[]:[l.finished]),i=await Yx({commits:tA(t,e),otherFinishes:s,record:e.record,root:r,target:o});if(i.problem!==null)return{current:!1,details:[i.problem]};let a=ne(i.files).filter((c)=>!et(c,e.contract.scope));return{current:a.length===0,details:a.map((c)=>`outside the scope: ${c}`)}}var i5=1,nA=E({name:"verify",description:"Re-evaluate the reproducible gates of done tasks against their evidence",args:j({all:{default:!1,description:"Verify every done task",type:"boolean"},base:{description:"Verify tasks whose record changed between this reference and HEAD (CI mode)",type:"string"}}),json:!0,examples:["ari verify","ari verify --base origin/develop","ari verify --all --json"],run:async(t)=>{let{all:e,base:n}=t.args;if(e&&n!==void 0)throw new v("--all and --base exclude each other","Pass one of them");let r=n!==void 0?{kind:"base",ref:n}:e?{kind:"all"}:{kind:"local"},o=await Qx(await _(),r);return t.output.result(o,a5),o.failed.length===0?void 0:i5}});function a5(t){if(t.tasks.length===0)return"No task to verify";return t.tasks.flatMap((e)=>{let n=e.stage===null?"":` (${e.stage})`,r=e.gates.filter((i)=>!i.ok).flatMap((i)=>[` ${i.gate}: recorded ${eA(i.recorded)}, now ${eA(i.current)}`,...i.details.map((a)=>` ${a}`)]),o=e.problems.map((i)=>` ${i}`),s=e.ok&&e.gates.length===0?" (no evidence to reproduce yet)":"";return[`${e.ok?"ok":"FAILED"} ${e.task}${n}${s}`,...o,...r]}).join(`
287
+ `)}function eA(t){return t?"passed":"failed"}var rA=[ux,gx,dx,Nx,fx,nA];var u5=".ari",d5="cli-state.json",p5=Du({bin:"ari",commands:[s$,J$,lx,bE,VT,WT,JT,Y$,X$,ZE,QE,t$,z$,Z$,Q$,tT,BT,e$,...rA,r$,o$,NT,PT,IT,LT,Ck,YT],config:new Ku(l5(c5(),u5,d5),{}),description:"Task contracts, CLI-evaluated gates and tiered memory for coding agents",name:"Ariadne",version:ya});p5.main();