@r5n/ariadne 0.5.0 → 0.6.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 (2) hide show
  1. package/dist/cli.js +205 -205
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,287 +1,287 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
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(`
3
+ import{homedir as n5}from"os";import{join as r5}from"path";class vt extends Error{_tag="Cancel";constructor(t="Operation cancelled"){super(t)}}function j(t){return t}function su(t){return t==null?[]:Array.isArray(t)?t:[t]}function eA(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 iu(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=su(e.string),e.boolean=su(e.boolean),p)for(n in e.alias){r=e.alias[n]=su(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);eA(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,Qr=1,Rm=2,Im=255;function Pi(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 _m=1,nA=2,Di="--",Pm="-",Hn="no-",rA=new Set(["false","true"]),ds=/^--([^=]+)(?:=(.*))?$/s,ps=/^-([^-=][^=]*)(?:=(.*))?$/s,lu=/^(?:---|-no-|-_|-[^-=][^=]*_)/,oA="_",ls="\x00";function je(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function eo(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=je(n);if(o!==n)e.alias[o]=n;if(r.default!==void 0)e.default[n]=r.default}return e}function Ni(t,e){let n={};for(let[i,a]of Object.entries(e.alias))n[a]=[...n[a]??[],i];let{_:r,...o}=iu(Fi(t,sA),{alias:n,boolean:[...e.boolean],default:{...e.default},string:[...e.string]}),s=Object.entries(o).map(([i,a])=>[au(i),au(a)]);return{...Object.fromEntries(s),_:r.map(au)}}function sA(t){if(t===Pm)return`${ls}${t}`;let e=ds.exec(t);if(lu.test(t)||iA(e?.[1]))return`--${ls}${t}`;return(e?e[2]:ps.exec(t)?.[2])===""?`${t}${ls}`:t}function iA(t){if(t===void 0)return!1;let e=t.startsWith(Hn)?t.slice(Hn.length):t;return e===oA||e in Object.prototype}function au(t){return typeof t==="string"&&t.startsWith(ls)?t.slice(ls.length):t}function us(t,e){return Object.hasOwn(e.alias,t)?e.alias[t]??t:t}function to(t,e){if(Object.hasOwn(e,t))return`--${je(t)}`;let n=Object.entries(e).find(([,r])=>r.alias===t)?.[0];if(n)return`--${je(n)}`;return t.length===_m?`-${t}`:`--${t}`}function Li(t,e,n,r){let{alias:o}=eo(e),s=Object.keys(t).find((i)=>!Object.hasOwn(e,i)&&!Object.hasOwn(o,i));if(s!==void 0)throw new v(`Unknown option: ${aA(s,r)}`,n)}function aA(t,e){if(t.startsWith("-"))return t;let n=e.indexOf(Di);for(let r of n<0?e:e.slice(0,n)){let o=ds.exec(r)?.[1];if(o===t||r===`--${Hn}${t}`)return`--${o}`;if(o===void 0&&ps.exec(r)?.[1]?.includes(t))return`-${t}`}return to(t,{})}function Nm(t,e){for(let[r,o]of Object.entries(t))if(Array.isArray(o))throw new v(`${to(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 Dm(to(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=to(r,e);throw new v(`Invalid number for ${a}: "${s}"`,`Use ${a}=<number> with a finite numeric value`)}n[r]=i}return n}function Dm(t){return new v(`${t} needs a value`,`Use ${t}=<value>`)}function Mi(t,e){let n=eo(e),r=du([...t],n),o=Ni(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 Lm(t,e){let n=eo(e);for(let r=0;r<t.length;r+=1){let o=t[r]??"";if(o===Di)return-1;if(o===Pm||!o.startsWith("-"))return r;if(cA(o,n,e))r+=1}return-1}function cA(t,e,n){if(t.startsWith(`--${Hn}`))return!1;let r=ds.exec(t),o=r??ps.exec(t);if(!o||o[2]!==void 0)return!1;let s=r?o[1]??"":o[1]?.at(-1)??"",i=n[us(s,e)]?.type;return i==="string"||i==="number"}function uu(t,e,n=e){let r=eo(e),{before:o,command:s,restArgs:i}=Mi(t,e),a=eo(n);cu(o,r,e,!0),cu(t,a,n,!0);let{_:c,...l}=Ni(Mm(o,r,e),r);Li(l,e,"Place command options after the command name",o);let{_:u,...d}=Ni(du(i,a),a),p=Nm({...Om(l,e,r),...Om(d,n,a)},e);return{command:s,flags:p,restArgs:i}}function Om(t,e,n){return Object.fromEntries(Object.entries(t).filter(([r])=>Object.hasOwn(e,r)||Object.hasOwn(n.alias,r)))}function ji(t,e){return Object.fromEntries(Object.keys(e).flatMap((n)=>{let r=t[n];return r===void 0?[]:[[n,r]]}))}function gs(t,e={}){let n=eo(e),r=lA(t,n);cu(r,n,e);let o=Ni(Mm(r,n,e),n),{_:s,...i}=o;return{args:Nm(i,e),rawPositionals:s.map(String)}}function cu(t,e,n,r=!1){let o=new Set;for(let s of t){if(s===Di)break;let i=s.match(/^-+/)?.[0];if(!i||lu.test(s))continue;let a=s.slice(i.length),c=a.split("=",_m)[0]??"",l=a.startsWith(Hn)?[a.slice(Hn.length)]:i.length===nA?[c]:[...c];for(let u of l){let d=us(u,e);if(r&&!Object.hasOwn(n,d))continue;if(o.has(d))throw new v(`${to(d,n)} can only be provided once`);o.add(d)}}}function Fi(t,e){let n=t.indexOf(Di);return t.map((r,o)=>n>=0&&o>=n?r:e(r,t[o+1]))}function du(t,e){return Fi(t,(n)=>{let r=ds.exec(n)??ps.exec(n);if(!r||r[2]!==void 0||n.startsWith(`--${Hn}`))return n;let o=n.startsWith("--")?r[1]??"":r[1]?.at(-1)??"";return e.boolean.includes(us(o,e))?`${n}=true`:n})}function Mm(t,e,n){let r=(i)=>n[us(i,e)]?.type,o=(i)=>i!==void 0&&!i.startsWith("-"),s=Fi(t,(i,a)=>{let c=ds.exec(i),l=c?null:ps.exec(i);if(i.startsWith(`--${Hn}`)||lu.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=to(us(g,e),n),I=!y||d===void 0&&!o(a);if(f==="string"&&(I||d===""))throw Dm(S);if(f==="number"&&I)throw new v(`${S} needs a value`,`Use ${S}=<number>`);if(f==="boolean"&&y&&d!==void 0&&!rA.has(d))throw new v(`Invalid value for ${S}: "${d}"`,`Use ${S}=true or ${S}=false`)}return i});return du(s,e)}function lA(t,e){return Fi(t,(n)=>n.replace(/^--(no-[^=]+)(=.*)?$/,(r,o,s)=>{let i=e.alias[o];return i&&e.boolean.includes(i)?`--${i}${s??""}`:r}))}function Gi(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 Hi(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 jm(t,e){let n=Object.values(e);if(n.some((r)=>r.variadic))return;return t[n.length]}var uA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,dA=new Set(["help","json"]),pA=/^[a-zA-Z0-9]$/,gA=new Set(["h","j"]);function Ui(){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 mA(e),Object.freeze(e)}}function Ki(t,e){let n=pu(e.map((r)=>r.name));if(n!==void 0)throw Error(`${t} has more than one command named "${n}"`)}function mA(t){let e=`Command "${t.name}"`;if(!uA.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(dA.has(je(u)))throw Error(`${e} cannot define the option "${u}": --${je(u)} is a global flag`);if(d.alias!==void 0&&gA.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(je),r=pu(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)=>!pA.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=pu(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`);Ki(e,t.subcommands)}function pu(t){return t.find((e,n)=>t.indexOf(e)!==n)}function st(t){return t}import{Console as TA}from"console";import{Writable as $A}from"stream";import{format as xA,stripVTControlCharacters as AA}from"util";var Un={active:!1};var fA=new Set(["0","false"]);function ms(t){if(process.env.NO_COLOR)return!1;let e=process.env.FORCE_COLOR;if(e!==void 0)return!fA.has(e);return t?.isTTY===!0}var hA=ms(process.stdout),Hm=["black","blue","cyan","gray","green","magenta","red","white","yellow"],yA=["bold","dim","italic","underline","reset"],Um={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},kA={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"},wA={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"},Fm={"\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 Bi(t){return(e)=>hA&&!Un.active?`${t}${e}${Um.reset}`:e}function SA(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<32&&n!==27)return!1}return!0}function Gm({bright:t=!1,color:e}){let n=Bun.color(e,"ansi"),r=typeof n==="string"&&n.length>0&&SA(n)?n:kA[e];if(!r)return"";return t&&r in Fm?Fm[r]:r}var vA=Hm.reduce((t,e)=>{let n=Gm({color:e});if(n)t[e]=Bi(n);let r=Gm({bright:!0,color:e});if(r)t[`${e}Bright`]=Bi(r);return t},{}),bA=yA.reduce((t,e)=>(t[e]=Bi(Um[e]),t),{}),EA=Hm.reduce((t,e)=>{let n=wA[e];if(n){let r=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[r]=Bi(n)}return t},{}),w={...vA,...bA,...EA};var CA=2,Vm=["clear","count","countReset","debug","dir","dirxml","group","groupCollapsed","groupEnd","info","log","table"],RA=[...Vm,"trace","write"],IA=1,OA="EPIPE",_A="EIO",dt={closedStreams:new Set,documentWritten:!1,jsonRuns:0,outputGuarded:!1,restoreStdout:void 0,sealed:!1,stdoutClosed:!1,stdoutWrite:void 0};function fs(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function gr(t){return fs()&&!Un.active&&t?.json!==!0}function Wm(){return Un.active}function Kn(t){let e=JSON.stringify(t??null,null,CA);if(e===void 0)throw TypeError("JSON cannot represent the value");return`${e}
4
+ `}function qm(){return dt.documentWritten}function Jm(){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(!Vi(n,process.stdout))throw n;dt.stdoutClosed=!0}}function Ym(){if(dt.outputGuarded)return;dt.outputGuarded=!0,process.stdout.write=Km(process.stdout.write,!0),console.write=Km(console.write,0),process.stdout.on("error",(t)=>{if(!Vi(t,process.stdout))throw t;dt.stdoutClosed=!0}),process.stderr.on("error",(t)=>{if(!Vi(t,process.stderr))throw t});for(let t of[process.stdout,process.stderr])t.once("close",()=>dt.closedStreams.add(t))}function Km(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(!Vi(s,process.stdout))throw s;return dt.stdoutClosed=!0,n(o)}}}function Vi(t,e){if(!(t instanceof Error))return!1;let n=Reflect.get(t,"code");return n===OA||n===_A&&e.isTTY===!0}function Wi(){let t=ms(process.stderr);return new $A({decodeStrings:!1,write(e,n,r){process.stderr.write(t?e:AA(e)),r()}})}async function Xm(t,e){if(!t)return e();dt.jsonRuns+=1,dt.restoreStdout??=PA(),Un.active=!0;try{return await e()}finally{if(dt.jsonRuns-=1,Un.active=dt.jsonRuns>0,!Un.active&&!dt.outputGuarded)dt.restoreStdout?.(),dt.restoreStdout=void 0}}async function zm(t){let e=Promise.all([dt.stdoutClosed?void 0:Bm(process.stdout),Bm(process.stderr)]);await(t===void 0?e:Promise.race([e,Bun.sleep(t)]))}function Bm(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 PA(){let t=process.stdout.write,e=new TA({stderr:process.stderr,stdout:process.stderr}),n=Object.fromEntries(RA.map((o)=>[o,console[o]])),r=Object.fromEntries(Vm.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:NA(e),write:DA}),()=>{process.stdout.write=t,Object.assign(console,n),dt.stdoutWrite=void 0}}function NA(t){let e=(...n)=>{let r={};Error.captureStackTrace(r,e);let o=r.stack?.split(`
5
+ `).slice(IA)??[];t.error([`Trace: ${xA(...n)}`,...o].join(`
6
+ `))};return e}function DA(...t){let e=Buffer.concat(t.map(LA));return process.stderr.write(e),e.byteLength}function LA(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 ve={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"}},no={help:ve.help,json:ve.json},mr="help",qi={[Zt]:"success",[Qr]:"failure",[Rm]:"usage error"};import{stripVTControlCharacters as Cu}from"util";import{styleText as XA}from"util";import{stdout as gf,stdin as zA}from"process";import ZA from"readline";var Zm=(()=>{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}})(),Qm=(t)=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,tf=(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 MA=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,jA=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ef=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,FA=/\t{1,1000}/y,nf=/[\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,GA=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,HA=/\p{M}+/gu,UA={limit:1/0,ellipsis:""},rf=(t,e={},n={})=>{let r=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?rf(o,UA,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=[[GA,d],[MA,0],[jA,a],[FA,c],[nf,l],[ef,p]],f=0,y=0,S=t.length,I=0,C=!1,J=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 Pt of B.replaceAll(HA,"")){let Q=Pt.codePointAt(0)||0;if(Qm(Q))R=2;else if(tf(Q))R=p;else R=d;if(A+R>G)J=Math.min(J,Math.max(N,f)+I);if(A+R>r){C=!0;break t}I+=Pt.length,A+=R}N=H=0}if(y>=S)break t;for(let B=0,Pt=g.length;B<Pt;B++){let[Q,Zr]=g[B];if(Q.lastIndex=y,Q.test(t)){if(I=Q===ef?Zm(t.slice(y,Q.lastIndex)):Q===nf?1:Q.lastIndex-y,R=I*Zr,A+R>G)J=Math.min(J,y+Math.floor((G-A)/Zr));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?J:S,truncated:C,ellipsed:C&&r>=s}},of=rf;var KA={limit:1/0,ellipsis:"",ellipsisWidth:0},BA=(t,e={})=>of(t,KA,e).width,Mt=BA;var Ji="\x1B",uf="\x9B",VA=39,mu="\x07",df="[",WA="]",pf="m",fu=`${WA}8;;`,sf=new RegExp(`(?:\\${df}(?<code>\\d+)m|\\${fu}(?<uri>.*)${mu})`,"y"),af=(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},cf=(t)=>`${Ji}${df}${t}${pf}`,lf=(t)=>`${Ji}${fu}${t}${mu}`,gu=(t,e,n)=>{let r=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:Mt(i),c=r.next(),l=r.next(),u=0;while(!c.done){let d=c.value,p=Mt(d);if(a+p<=n)t[t.length-1]+=d;else t.push(d),a=0;if(d===Ji||d===uf)o=!0,s=e.startsWith(fu,u+1);if(o){if(s){if(d===mu)o=!1,s=!1}else if(d===pf)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()},qA=(t)=>{let e=t.split(" "),n=e.length;while(n){if(Mt(e[n-1]))break;n--}if(n===e.length)return t;return e.slice(0,n).join(" ")+e.slice(n).join("")},JA=(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=Mt(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=Mt(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("");gu(a,p,e),c=Mt(a.at(-1)??"");continue}if(c+g>e&&c&&g){if(n.wordWrap===!1&&c<e){gu(a,p,e),c=Mt(a.at(-1)??"");continue}a.push(""),c=0}if(c+g>e&&n.wordWrap===!1){gu(a,p,e),c=Mt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=g}if(n.trim!==!1)a=a.map((d)=>qA(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===Ji||p===uf){sf.lastIndex=d+1;let f=sf.exec(l)?.groups;if(f?.code!==void 0){let y=Number.parseFloat(f.code);o=y===VA?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+=lf("");let g=o?af(o):void 0;if(o&&g)r+=cf(g)}else if(p===`
9
+ `){if(o&&af(o))r+=cf(o);if(s)r+=lf(s)}}return r},YA=/\r?\n/;function Bn(t,e,n){return String(t).normalize().split(YA).map((r)=>JA(r,e,n)).join(`
10
+ `)}var be={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 hs={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?be.up():"");if(t)e+=be.left;return e}};function fr(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?fr(s,e<0?-1:1,n):s}var QA=["up","down","left","right","space","enter","cancel"],tC=["January","February","March","April","May","June","July","August","September","October","November","December"],jt={actions:new Set(QA),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:[...tC],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 mf(t){if(t!==void 0)return t;if(jt.accessible!==void 0)return jt.accessible;let e=process.env.ACCESSIBLE;return e!==void 0&&e!==""&&e!=="0"&&e!=="false"}function ff(t,e){if(typeof t=="string")return jt.aliases.get(t)===e;for(let n of t)if(n!==void 0&&ff(n,e))return!0;return!1}function eC(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 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(`
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 W5=globalThis.process.platform.startsWith("win"),Xi=Symbol("clack:cancel");function zi(t){return t===Xi}function Yi(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var ro=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,hu=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function Sn(t,e,n,r=n,o=n,s){let i=ro(t??gf),a=Mt(n);return Bn(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 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(`
14
+ `)}function hf(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 Zi=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return mf(this.opts.accessible)}constructor(e,n=!0){let{input:r=zA,output:o=gf,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(Xi);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=ZA.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),Yi(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(be.show),this.output.off("resize",this.render),Yi(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(be.show),this.output.off("resize",this.render),Yi(this.input,!1),e(Xi)})})}_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&&jt.aliases.has(n.name)&&this.emit("cursor",jt.aliases.get(n.name)),jt.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=hf(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")}ff([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
+ `),Yi(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Bn(this._prevFrame,ro(this.output),{hard:!0,trim:!1}).split(`
16
+ `).length-1;this.output.write(be.move(-999,e*-1))}render(){let e=Bn(this._render(this)??"",ro(this.output),{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(be.hide);else{let n=eC(this._prevFrame,e),r=hu(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(be.move(0,i-s)),this.output.write(hs.lines(1));let a=e.split(`
17
+ `);this.output.write(a[i]),this._prevFrame=e,this.output.write(be.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(be.move(0,c))}this.output.write(hs.down());let a=e.split(`
18
18
  `).slice(i);this.output.write(a.join(`
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)}
19
+ `)),this._prevFrame=e;return}}this.output.write(hs.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};class yu extends Zi{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(be.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class ku extends Zi{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?fr(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=fr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=fr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var yf=class extends Zi{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?fr(r,1,this.options):r,this.changeValue(),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=fr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=fr(this.cursor,1,this.options);break}this.changeValue()})}};class wu extends Zi{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}${XA("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 oY}from"util";import Ee from"process";function nC(){if(Ee.platform!=="win32")return Ee.env.TERM!=="linux";return Boolean(Ee.env.CI)||Boolean(Ee.env.WT_SESSION)||Boolean(Ee.env.TERMINUS_SUBLIME)||Ee.env.ConEmuTask==="{cmd::Cmder}"||Ee.env.TERM_PROGRAM==="Terminus-Sublime"||Ee.env.TERM_PROGRAM==="vscode"||Ee.env.TERM==="xterm-256color"||Ee.env.TERM==="alacritty"||Ee.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var bu=nC(),Ef=()=>process.env.CI==="true";var tt=(t,e)=>bu?t:e,kf=tt("\u25C6","*"),Eu=tt("\u25A0","x"),Tu=tt("\u25B2","x"),ks=tt("\u25C7","o"),rC=tt("\u250C","T"),U=tt("\u2502","|"),Qe=tt("\u2514","\u2014"),lY=tt("\u2510","T"),uY=tt("\u2518","\u2014"),Su=tt("\u25CF",">"),ta=tt("\u25CB"," "),oC=tt("\u25FB","[\u2022]"),wf=tt("\u25FC","[+]"),Sf=tt("\u25FB","[ ]"),dY=tt("\u25AA","\u2022"),vf=tt("\u2500","-"),sC=tt("\u256E","+"),iC=tt("\u251C","+"),aC=tt("\u256F","+"),cC=tt("\u2570","+"),pY=tt("\u256D","+"),lC=tt("\u25CF","\u2022"),uC=tt("\u25C6","*"),dC=tt("\u25B2","!"),pC=tt("\u25A0","x"),ea=(t)=>{switch(t){case"initial":case"active":return h("cyan",kf);case"cancel":return h("red",Eu);case"error":return h("yellow",Tu);case"submit":return h("green",ks);case"validating":return h("dim",kf)}},Tf=(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 $f(t,e,n){let r=n?`${h("cyan",U)} `:"",o=Sn(t,e.join(" \u2022 "),r).split(`
20
+ `);return n&&o.push(h("cyan",Qe)),o}var bf=(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}},vu=({cursor:t,options:e,style:n,output:r=process.stdout,maxItems:o=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:i=4})=>{let a=ro(r)-s,c=hu(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),J=y-(f?1:0);for(let N=C;N<J;N++){let H=e[N],A=H!==void 0?n(H,N===t):"",R=Bn(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,Pt=()=>bf(S,A,0,R,B),Q=()=>bf(S,A,R+1,S.length,B,!0);g?({lineCount:A,removals:N}=Pt(),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}=Pt())),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 xf=(t)=>{let e=t.active??"Yes",n=t.inactive??"No";return new yu({active:e,inactive:n,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let r=t.withGuide??jt.withGuide,o=`${ea(this.state)} `,s=r?`${h("gray",U)} `:"",i=Sn(t.output,t.message,s,o),a=`${r?`${h("gray",U)}
22
22
  `:""}${i}
23
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?`
24
+ ${h("gray",U)}`:""}`}default:{let l=r?`${h("cyan",U)} `:"",u=r?h("cyan",Qe):"";return`${a}${l}${this.value?`${h("green",Su)} ${e}`:`${h("dim",ta)} ${h("dim",e)}`}${t.vertical?r?`
25
25
  ${h("cyan",U)} `:`
26
- `:` ${h("dim","/")} `}${this.value?`${h("dim",zi)} ${h("dim",n)}`:`${h("green",ku)} ${n}`}
26
+ `:` ${h("dim","/")} `}${this.value?`${h("dim",ta)} ${h("dim",n)}`:`${h("green",Su)} ${n}`}
27
27
  ${u}
28
- `}}}}).prompt()};var hC=[`${h("dim","\u2191/\u2193")} to navigate`,`${h("dim","Space:")} select`,`${h("dim","Enter:")} confirm`],ms=(t,e)=>t.split(`
28
+ `}}}}).prompt()};var gC=[`${h("dim","\u2191/\u2193")} to navigate`,`${h("dim","Space:")} select`,`${h("dim","Enter:")} confirm`],ys=(t,e)=>t.split(`
29
29
  `).map((n)=>e(n)).join(`
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)}
30
+ `),Af=(t)=>{let e=(o,s)=>{let i=o.label??String(o.value);return s==="disabled"?`${h("gray",Sf)} ${ys(i,(a)=>h(["strikethrough","gray"],a))}${o.hint?` ${h("dim",`(${o.hint??"disabled"})`)}`:""}`:s==="active"?`${h("cyan",oC)} ${i}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="selected"?`${h("green",wf)} ${ys(i,(a)=>h("dim",a))}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="cancelled"?`${ys(i,(a)=>h(["strikethrough","dim"],a))}`:s==="active-selected"?`${h("green",wf)} ${i}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="submitted"?`${ys(i,(a)=>h("dim",a))}`:`${h("dim",Sf)} ${ys(i,(a)=>h("dim",a))}`},n=t.required??!0,r=t.showInstructions??!0;return new ku({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??jt.withGuide,s=Sn(t.output,t.message,o?`${Tf(this.state)} `:"",`${ea(this.state)} `),i=`${o?`${h("gray",U)}
32
32
  `:""}${s}
33
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
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(`
35
+ `).map((g,f)=>f===0?`${o?`${h("yellow",Qe)} `:""}${h("yellow",g)}`:` ${g}`).join(`
36
36
  `),d=i.split(`
37
37
  `).length,p=u.split(`
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(`
38
+ `).length+1;return`${i}${l}${vu({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
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(`
42
+ `).length,d=r?$f(t.output,gC,o):o?[h("cyan",Qe)]:[],p=d.join(`
43
+ `),g=d.length+1;return`${i}${l}${vu({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 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(`
46
+ `}}}}).prompt()};var Kt={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??jt.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
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)=>{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)}
49
+ `)},info:(t,e)=>{Kt.message(t,{...e,symbol:h("blue",lC)})},success:(t,e)=>{Kt.message(t,{...e,symbol:h("green",uC)})},step:(t,e)=>{Kt.message(t,{...e,symbol:h("green",ks)})},warn:(t,e)=>{Kt.message(t,{...e,symbol:h("yellow",dC)})},warning:(t,e)=>{Kt.warn(t,e)},error:(t,e)=>{Kt.message(t,{...e,symbol:h("red",pC)})}},Cf=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??jt.withGuide?`${h("gray",Qe)} `:"";n.write(`${r}${h("red",t)}
50
50
 
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}
51
+ `)},Rf=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??jt.withGuide?`${h("gray",rC)} `:"";n.write(`${r}${t}
52
+ `)},If=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??jt.withGuide?`${h("gray",U)}
53
+ ${h("gray",Qe)} `:"";n.write(`${r}${t}
54
54
 
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(`
55
+ `)};var mC=(t)=>t,fC=(t,e,n)=>{let r={hard:!0,trim:!1},o=Bn(t,e,r).split(`
56
+ `),s=o.reduce((c,l)=>Math.max(Mt(l),c),0),i=o.map(n).reduce((c,l)=>Math.max(Mt(l),c),0),a=e-(i-s);return Bn(t,a,r)},Of=(t="",e="",n)=>{let r=n?.output??Ee.stdout,o=n?.withGuide??jt.withGuide,s=n?.format??mC,i=["",...fC(t,ro(r)-6,s).split(`
57
+ `).map(s),""],a=Mt(e),c=Math.max(i.reduce((p,g)=>{let f=Mt(g);return f>p?f:p},0),a)+2,l=i.map((p)=>`${h("gray",U)} ${p}${" ".repeat(c-Mt(p))}${h("gray",U)}`).join(`
58
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)}
59
+ `:"",d=o?iC:cC;r.write(`${u}${h("green",ks)} ${h("reset",e)} ${h("gray",vf.repeat(Math.max(c-a-1,1))+sC)}
60
60
  ${l}
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(`
61
+ ${h("gray",d+vf.repeat(c+2)+aC)}
62
+ `)};var gY={light:tt("\u2500","-"),heavy:tt("\u2501","="),block:tt("\u2588","#")};var hC=[`${h("dim","\u2191/\u2193")} to navigate`,`${h("dim","Enter:")} confirm`],Qi=(t,e)=>t.includes(`
63
63
  `)?t.split(`
64
64
  `).map((n)=>e(n)).join(`
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)}
65
+ `):e(t),_f=(t)=>{let e=(r,o)=>{if(r===void 0)return"";let s=r.label??String(r.value);switch(o){case"disabled":return`${h("gray",ta)} ${Qi(s,(i)=>h("gray",i))}${r.hint?` ${h("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${Qi(s,(i)=>h("dim",i))}`;case"active":return`${h("green",Su)} ${s}${r.hint?` ${h("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${Qi(s,(i)=>h(["strikethrough","dim"],i))}`;default:return`${h("dim",ta)} ${Qi(s,(i)=>h("dim",i))}`}},n=t.showInstructions??!0;return new yf({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let r=t.withGuide??jt.withGuide,o=`${ea(this.state)} `,s=`${Tf(this.state)} `,i=Sn(t.output,t.message,s,o),a=`${r?`${h("gray",U)}
66
66
  `:""}${i}
67
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
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(`
69
+ `).length,u=n?$f(t.output,hC,r):r?[h("cyan",Qe)]:[],d=u.join(`
70
+ `),p=u.length+1;return`${a}${c}${vu({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 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}
73
+ `}}}}).prompt()};var mY=`${h("gray",U)} `;var Pf=(t)=>new wu({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??jt.withGuide,n=`${`${e?`${h("gray",U)}
74
+ `:""}${ea(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",Qe):"",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",U)} `:"",c=e?h("yellow",Ze):"";return`${n.trim()}
77
+ `}case"error":{let i=this.error?` ${h("yellow",this.error)}`:"",a=e?`${h("yellow",U)} `:"",c=e?h("yellow",Qe):"";return`${n.trim()}
78
78
  ${a}${o}
79
79
  ${c}${i}
80
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}
81
+ ${a}`:""}`}default:{let i=e?`${h("cyan",U)} `:"",a=e?h("cyan",Qe):"";return`${n}${i}${o}
82
82
  ${a}
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(`
83
+ `}}}}).prompt();function Nf(t=process.stdin){return t.readableEnded||t.destroyed}async function Df({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 kC}from"util";var $u=bu?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],wC=80,SC=8,vC=3,bC="...",xu="\r\x1B[K",EC=80,TC=/\s*\n\s*/g,ws=new Set;function Mf(){for(let t of[...ws])t.error()}function jf({output:t=process.stdout}={}){let e=t.isTTY===!0&&!Ef(),n=ms(t),r="",o=0,s=!1,i,a=(g)=>{t.write(e||n?g:kC(g))},c=()=>{let g=w.magenta($u[o%$u.length]??""),f=".".repeat(Math.floor(o/SC)%(vC+1)),y=`${g} ${r.replace(TC," ")}${f}`;a(`${xu}${Bun.sliceAnsi(y,0,(t.columns||EC)-1)}`),o+=1},l=()=>e?c():a(`${w.magenta($u[0]??"")} ${r}${bC}
84
+ `),u=()=>(clearInterval(i),ws.delete(p)),d=(g,f)=>{if(u())a(`${e?xu:""}${g} ${f}
85
+ `)},p={cancel(g=r){s=ws.has(p)||s,d(w.red(Eu),g)},clear(){if(u()&&e)a(xu)},error(g=r){d(w.red(Tu),g)},get isCancelled(){return s},message(g=r){let f=Lf(g);if(f===r)return;if(r=f,ws.has(p)&&!e)l()},start(g=""){if(p.clear(),s=!1,r=Lf(g),o=0,ws.add(p),a(`${w.gray(U)}
86
+ `),l(),!e)return;i=setInterval(c,wC),i.unref()},stop(g=r){d(w.green(ks),g)}};return p}function Lf(t){return t.replace(/\.+$/,"")}var xC="Pass the value as an argument or option instead";function AC(t){if(zi(t))throw new vt;return t}function CC(t){if(gr())return;throw new v(`Cannot prompt for ${t} without a terminal`,xC)}async function na(t,e,{edits:n=!1,hint:r}){if(CC(e.message),Nf(e.input))throw new vt;return IC(r),AC(await Df({...e,edits:n},(o)=>t({...e,signal:o})))}function RC(t){return t.map((e)=>e.key?`${w.bold(e.key)} ${w.dim(e.text)}`:w.dim(e.text)).join(w.dim(" \xB7 "))}function IC(t){Kt.info(RC(t))}var ra={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 Te(t){return na(xf,t,{hint:ra.confirm})}async function Au(t){return na(Pf,t,{edits:!0,hint:ra.text})}async function hr(t){return na(_f,{showInstructions:!1,...t},{hint:ra.select})}async function oa(t){return na(Af,{showInstructions:!1,...t},{hint:ra.multiselect})}function yr(t){return Wm()&&t.output===void 0?{...t,output:process.stderr}:t}function oo(t){return(e,n={})=>t(e,yr(n))}var bt={error:oo(Kt.error),info:oo(Kt.info),message:(t,e={})=>Kt.message(t,yr(e)),step:oo(Kt.step),success:oo(Kt.success),warn:oo(Kt.warn),warning:oo(Kt.warning)};function kr(t,e={}){Rf(t,yr(e))}function le(t,e={}){If(t,yr(e))}function Ss(t,e={}){Cf(t,yr(e))}function Dt(t,e,n={}){Of(t,e,yr(n))}function sa(t={}){return jf(yr(t))}import{inspect as OC}from"util";var _C=4;function ia(t,e=[]){if(e.length>=_C)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:ca(s),message:aa(s)},...s instanceof Error?ia(s,r):[]])}function aa(t){return la(t instanceof Error?t.message||t.name:t)}function ca(t){return t instanceof m&&t.hint!==void 0?la(t.hint):void 0}function la(t){return typeof t==="string"?t:OC(t,{breakLength:Number.POSITIVE_INFINITY})}var PC="Error",NC=27,DC=new RegExp(`${String.fromCharCode(NC)}\\[[\\d;]*m`,"g"),LC=9,MC=10,jC=31,FC=127,GC=159,HC=16,UC=4;function Vn(t,{json:e}){if(Mf(),VC(t),e)wn(Kn({error:KC(t)}));return Ff(t)}function KC(t){let e=Ff(t),n=Cu(aa(t));if(!(t instanceof Error))return{_tag:PC,message:n,exitCode:e,causes:[]};let r=ca(t);return{_tag:BC(t),message:n,hint:r===void 0?void 0:Cu(r),exitCode:e,causes:ia(t).map((o)=>Cu(o.message))}}function Ff(t){if(t instanceof vt)return Zt;if(t instanceof m)return Pi(t.exitCode)?t.exitCode:Qr;return Qr}function BC(t){let e=Reflect.get(t,"_tag");return typeof e==="string"?e:la(t.name)}function VC(t){if(t instanceof vt)return;let e=Wi(),n=ua(aa(t));if(t instanceof m){let r=ca(t);if(bt.warn(w.yellow(n),{output:e}),r)bt.info(w.dim(ua(r)),{output:e})}else bt.error(w.red(n),{output:e});if(!(t instanceof Error))return;for(let r of ia(t))if(bt.info(w.dim(`caused by: ${ua(r.message)}`),{output:e}),r.hint)bt.info(w.dim(` ${ua(r.hint)}`),{output:e})}function ua(t){return Array.from(t.replace(DC,""),(e)=>{let n=e.charCodeAt(0);return n<=jC&&n!==LC&&n!==MC||n>=FC&&n<=GC?`\\u${n.toString(HC).padStart(UC,"0")}`:e}).join("")}var WC=500,qC="The command stopped before it finished because nothing was left for it to wait for";function Gf({json:t}){let e={ending:void 0,failed:!1,settled:!1},n=(o,s)=>(e.ending??=JC(o,s),e.ending),r=(o)=>{if(e.failed||e.ending)return;e.failed=!0;let s=Vn(o,{json:t&&!qm()});Jm(),n(s,e.settled?void 0:WC)};return process.on("uncaughtException",r),process.on("unhandledRejection",r),process.on("beforeExit",()=>{if(!e.settled)r(Error(qC))}),{exit:(o)=>n(o),settle(){e.settled=!0}}}async function JC(t,e){process.exitCode=t,await zm(e),process.exit(t)}var vn=new Uint32Array(65536),YC=(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},XC=(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 J=vn[e.charCodeAt(C)],G=s[C/32|0]>>>C&1,N=o[C/32|0]>>>C&1,H=J|f,A=((J|N)&y)+y^y|J|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,J=((y|I)&u)+u^u|y|I,G=l|~(J|u),N=u&J;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},Ru=(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 YC(t,e);return XC(t,e)},Hf=(t,e)=>{let n=1/0,r=0;for(let o=0;o<e.length;o++){let s=Ru(t,e[o]);if(s<n)n=s,r=o}return e[r]};function da(t,e,n){let r=e.length>0?Hf(t,[...e]):void 0,o=`Run "${n} --help" for usage.`;return new v(`Unknown command: ${t}`,r?`Did you mean "${r}"? ${o}`:o)}function vs(t,e){if(Array.isArray(e))return[...e];if(!Uf(t)||!Uf(e))return e;return Object.fromEntries([...Object.entries(t),...Object.entries(e).map(([n,r])=>[n,vs(Object.hasOwn(t,n)?t[n]:void 0,r)])])}function Uf(t){if(t===null||typeof t!=="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Kf(t,e){return{name:t.name,bin:t.bin,version:t.version,description:t.description,exitCodes:{...qi},options:Bf(ve),commands:e.map((n)=>pa(n,`${t.bin} ${n.name}`))}}function pa(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:Bf(t.args),examples:[...t.examples],commands:t.subcommands.map((n)=>pa(n,`${e} ${n.name}`))}}function Bf(t){return Object.entries(t).map(([e,n])=>({name:e,flag:`--${je(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 Vf}from"util";var zC=2,ZC="0.0.0",QC=(t)=>t,V={arg:w.magenta,cmd:w.cyan,default:w.bold,desc:QC,flag:w.green,header:(t)=>w.bold(w.yellow(t)),hint:w.dim,name:(t)=>w.bold(w.cyan(t)),placeholder:w.magenta};function Wf(t){return`${V.name(t.name)} ${V.hint(t.version??ZC)}`}function qf(t,e){let n=`${V.name(t.name)}${t.version?` ${V.hint(`v${t.version}`)}`:""}`;return Yf([[n,...t.description?[V.desc(t.description)]:[]],tn("Usage:",[` ${V.cmd(t.bin)} ${V.placeholder("[command]")} ${V.placeholder("[options]")}`]),tn("Commands:",Xf(e)),tn("Options:",Zf(ve)),tn("Exit codes:",zf()),[`${V.hint("Run")} ${V.cmd(`${t.bin} <command> --help`)} ${V.hint("for command details.")}`]])}function Jf(t,e){let n=t.json?{...t.args,json:ve.json}:t.args,r=[...t.subcommands.length>0?[` ${V.cmd(e)} ${V.placeholder("<command>")} ${V.placeholder("[options]")}`]:[],...t.run?[` ${tR(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 Yf([[V.name(e),V.desc(t.description)],tn("Usage:",r),tn("Commands:",Xf(t.subcommands)),tn("Arguments:",nR(t.positionals)),tn("Options:",Zf(n)),tn("Examples:",t.examples.map((o)=>` ${V.cmd(o)}`)),tn("Exit codes:",zf())])}function tR(t,e){let n=eR(t.positionals);return t.passthrough?[V.cmd(e),V.placeholder("[options]"),V.placeholder("[--]"),...n]:[V.cmd(e),...n,V.placeholder("[options]")]}function tn(t,e){return e.length>0?[V.header(t),...e]:[]}function Yf(t){return t.filter((e)=>e.length>0).map((e)=>e.join(`
87
87
  `)).join(`
88
88
 
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
89
+ `)}function Xf(t){return ga(t.map((e)=>[` ${V.cmd(e.name)}`,V.desc(e.description)]))}function zf(){return ga(Object.entries(qi).map(([t,e])=>[` ${t}`,e]))}function Iu(t,e){return e.variadic?`${t}...`:t}function eR(t){return Object.entries(t).map(([e,n])=>n.required?V.arg(`<${Iu(e,n)}>`):V.arg(`[${Iu(e,n)}]`))}function nR(t){return ga(Object.entries(t).map(([e,n])=>[` ${V.arg(Iu(e,n))}`,`${V.desc(n.description??"")}${n.required?"":V.hint(" (optional)")}`]))}function Zf(t){return ga(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=rR(n),i=s===void 0?"":` (default: ${V.default(s)})`;return[` ${r}${V.flag(`--${je(e)}`)}${o}`,`${V.desc(n.description??"")}${i}`]}))}function rR(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 ga(t){let e=Math.max(0,...t.map(([n])=>Vf(n).length));return t.map(([n,r])=>`${n}${" ".repeat(e-Vf(n).length+zC)}${r}`)}function ma(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=oR(t,n,r);if(e=!0,o!==void 0)wn(o)}}}function oR(t,e,n){if(t)return Kn(e);return n?`${n(e)}
90
+ `:void 0}function fa(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 ha(t,e,n,r){let o=await Xm(n.json,async()=>{let s=await t.run?.(n);return typeof s==="number"?sR(e,s):Zt});if(n.json&&!r.emitted())throw Error(`${e} finished in JSON mode without calling ctx.output.result`);return o}function sR(t,e){if(Pi(e))return e;throw Error(`${t} returned ${e}, which is not an exit code from ${Zt} to ${Im}`)}var Ou="__exit__",Qf="__run__",iR="Back",aR="Return to previous menu";async function th(t,e){if(e)throw new v("Interactive mode cannot be combined with --json","Pass a command and its arguments instead");if(!fs())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}`:"";kr(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 eh(t,new Map,r),le(t.interactive.goodbyeMessage),Zt}async function eh(t,e,n){while(!0){let r=await cR(t,e,n);if(r===void 0)return;if(e.set(n.path,r),r===Qf&&n.owner){await nh(t,n.owner,n.path);continue}let o=n.commands.find((s)=>s.name===r);if(o)await lR(t,e,o,`${n.path} ${r}`)}}async function cR(t,e,n){let r=n.root?{hint:t.interactive.exitHint,label:t.interactive.exitLabel,value:Ou}:{hint:aR,label:iR,value:Ou};try{let o=await hr({initialValue:e.get(n.path),message:n.message,options:[...n.owner?[{hint:n.owner.description,label:n.owner.name,value:Qf}]:[],...n.commands.map((s)=>({hint:s.description,label:s.name,value:s.name})),r]});return o===Ou?void 0:o}catch(o){if(o instanceof vt)return;throw o}}async function lR(t,e,n,r){if(n.subcommands.length===0)return nh(t,n,r);return eh(t,e,{commands:n.subcommands,message:`${n.name}:`,path:r,root:!1,...n.run?{owner:n}:{}})}async function nh(t,e,n){try{await uR(t,e,n)}catch(r){if(r instanceof vt)return;if(!(r instanceof m))throw r;Vn(r,{json:!1})}}async function uR(t,e,n){let{args:r}=gs([],e.args),o=Gi([],e.positionals),s=e.prompts?null:Hi(o,e.positionals);if(s)throw new v(s,`Run "${n} --help" for usage.`);let i=ma(!1),a={args:ji(r,e.args),interactive:e.prompts,json:!1,positionals:o};await ha(e,n,fa(t,a,i),i)}var dR="--",pR=/^(?:--json(?:=true)?|-[^-=]*j[^-=]*(?:=true)?)$/,gR=/^(?:--no-(?:help|json)|(?:--(?:help|json)|-[hj]+)(?:=(?:true|false))?)$/;async function _u(t,e){try{return await mR(t,e)}catch(n){return{code:Vn(n,{json:Nu(e)}),menu:!1}}}function Pu(t,e){let{command:n,restArgs:r}=Mi(e,ve),o=n===void 0||n===mr?void 0:sh(t,n,r);if(!o||o instanceof v||!o.command.passthrough)return{operands:[],options:[...e]};let s=Lm(o.tokens,{...o.command.args,...no}),i=s<0?[]:o.tokens.slice(s);return{operands:i,options:e.slice(0,e.length-i.length)}}async function mR(t,{options:e,operands:n}){let{command:r,flags:o,restArgs:s}=uu(e,ve,no),i=o.json===!0,a={code:Zt,menu:!1};if(r===void 0){if(o.interactive&&!o.help&&!o.version)return{code:await th(t,i),menu:!0};return wn(o.version&&!o.help?hR(t,i):rh(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===mr)return wn(yR(t,s,i)),a;let l=kR(t,r,s);if(o.help)return wn(Du(l.command,l.path,i)),a;return{code:await wR(t,l,n,i),menu:!1}}function Nu({options:t}){let{before:e,restArgs:n}=Mi(t,ve);return[e,n].some((r)=>fR(r).some((o)=>pR.test(o)))}function fR(t){let e=t.indexOf(dR);return e<0?t:t.slice(0,e)}function hR({info:t},e){return e?Kn({name:t.name,bin:t.bin,version:t.version}):`${Wf(t)}
91
+ `}function rh(t,e){return e?Kn(Kf(t.info,t.commands)):`${qf(t.info,t.commands)}
92
+ `}function Du(t,e,n){return n?Kn(pa(t,e)):`${Jf(t,e)}
93
+ `}function yR(t,e,n){let{args:r,rawPositionals:o}=gs(e,no);if(Li(r,no,`Run "${t.info.bin} ${mr} [command]" for usage.`,e),o.length===0)return rh(t,n);let{command:s,path:i}=oh(t.commands,o,t.info.bin);return Du(s,i,n)}function oh(t,e,n){let[r="",...o]=e,s=t.find((a)=>a.name===r);if(!s)throw da(r,Lu(t),n);let i=`${n} ${r}`;return o.length===0?{command:s,path:i}:oh(s.subcommands,o,i)}function Lu(t){return t.map((e)=>e.name)}function kR(t,e,n){let r=sh(t,e,n);if(r instanceof v)throw r;return r}function sh(t,e,n){let r=t.commands.find((o)=>o.name===e);if(!r)return da(e,Lu(t.commands),t.info.bin);return ih({command:r,path:`${t.info.bin} ${e}`,tokens:n})}function ih(t){let{command:e,path:n,tokens:r}=t;if(e.subcommands.length===0)return t;let o=r.findIndex((a)=>!gR.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 ih({command:i,path:`${n} ${s}`,tokens:r.toSpliced(o,1)});if(e.run&&Object.keys(e.positionals).length>0)return t;return da(s,Lu(e.subcommands),n)}async function wR(t,{command:e,path:n,tokens:r},o,s){let i=`Run "${n} --help" for usage.`,a={...e.args,...no},c=gs(r,a),{args:l}=c,u=[...c.rawPositionals,...o];if(e.strict)Li(l,a,i,r);if(s&&!e.json)throw new v(`${n} does not support --json`,i);let d=e.strict?jm(u,e.positionals):void 0;if(d!==void 0)throw new v(`Unexpected argument: ${d}`,i);if(!e.run)return wn(Du(e,n,s)),Zt;let p=Gi(u,e.positionals),g=Hi(p,e.positionals);if(g)throw new v(g,i);let f=e.prompts&&u.length===0&&fs()&&!s,y={args:ji(l,e.args),interactive:f,json:s,positionals:p},S=ma(s);try{return await ha(e,n,fa(t,y,S),S)}catch(I){return Vn(I,{json:s&&!S.emitted()})}}var SR={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",promptMessage:"What would you like to do?"};function Mu(t){let e=`CLI "${t.name}"`;if(Ki(e,t.commands),t.commands.some((r)=>r.name===mr))throw Error(`${e} cannot define a command named "${mr}": 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:{...SR,...t.interactive}};return{async main(r=process.argv.slice(2)){Ym();let o=Pu(n,r),s=Gf({json:Nu(o)}),i=await _u(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 _u(n,Pu(n,r))).code}}}import ao from"fs";import Bu from"path";var wr=(t)=>(t.map=(e)=>wr((n)=>e(t(n))),t.or=(e)=>wr((n)=>{try{return t(n)}catch(r){return e(n)}}),t),ya=()=>"bad banditype"();var ah=()=>wr((t)=>t),ch=(t)=>wr((e)=>t.includes(e)?e:ya()),ka=(t)=>wr((e)=>typeof e===typeof t?e:ya()),X=()=>ka(""),Sr=()=>ka(0),wa=()=>ka(!0);var ju=()=>ka(),Wn=()=>wr((t)=>t===null?t:ya()),bs=(t)=>wr((e)=>e instanceof t?e:ya()),lh=(t)=>bs(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)=>bs(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 so=(t)=>bs(Array).map((e)=>e.map(t));import{randomUUID as vR}from"crypto";import{closeSync as uh,fchmodSync as bR,fsyncSync as dh,openSync as ph,renameSync as ER,rmSync as TR,writeFileSync as $R}from"fs";import{dirname as xR,join as AR}from"path";function bn(t,e,{durable:n=!1,mode:r}={}){let o=xR(t),s=AR(o,`.${process.pid}.${vR()}.tmp`);try{let i=ph(s,"wx",r);try{if(typeof e==="function")e(i);else $R(i,e);if(r!==void 0)bR(i,r);if(n)dh(i)}finally{uh(i)}if(ER(s,t),n)CR(o)}finally{TR(s,{force:!0})}}function CR(t){let e=ph(t,"r");try{dh(e)}finally{uh(e)}}function qn(t){return t instanceof Error?t.message:String(t)}function Tt(t){if(typeof t!=="object"||t===null)return;let e=Reflect.get(t,"code");return typeof e==="string"?e:void 0}function Fu(t,e){return Tt(t)===e}import io from"fs";var RR=".lock",IR=".break",gh=10,OR=1e4,_R=5000;function mh(t,e){let n=`${t}${RR}`,r=crypto.randomUUID();PR(n,r);try{return e()}finally{fh(n,r)}}function PR(t,e){let n=Date.now()+OR;while(!hh(t,e)){if(Date.now()>n)throw Error(`timed out waiting for ${t}, which another process holds`);if(Gu(t))NR(t,e);else Bun.sleepSync(gh)}}function fh(t,e){if(DR(t)===e)io.rmSync(t,{force:!0})}function NR(t,e){let n=`${t}${IR}`;if(!hh(n,e)){if(Gu(n))io.rmSync(n,{force:!0});else Bun.sleepSync(gh);return}try{if(Gu(t))io.rmSync(t,{force:!0})}finally{fh(n,e)}}function hh(t,e){try{return io.writeFileSync(t,e,{flag:"wx"}),!0}catch(n){if(Tt(n)==="EEXIST")return!1;throw n}}function Gu(t){let e=io.statSync(t,{throwIfNoEntry:!1})?.mtimeMs;return e!==void 0&&Date.now()-e>_R}function DR(t){try{return io.readFileSync(t,"utf8")}catch(e){if(Tt(e)==="ENOENT")return;throw e}}import Hu from"fs";import vr from"path";var LR="..",MR=40;function kh(t){let{root:e}=vr.parse(vr.resolve(t)),n=yh(vr.resolve(t)),r=e,o=0;for(let s=n.shift();s!==void 0;s=n.shift()){if(s===LR){r=vr.dirname(Hu.realpathSync(r));continue}let i=vr.join(r,s);if(!Hu.lstatSync(i,{throwIfNoEntry:!1})?.isSymbolicLink()){r=i;continue}if(o+=1,o>MR)throw Error(`too many symbolic links in ${t}`);let a=Hu.readlinkSync(i);if(vr.isAbsolute(a))r=e;n.unshift(...yh(a))}return r}function yh(t){return t.split(vr.sep).filter((e)=>e!==""&&e!==".")}function Ku(t,e){JSON.parse(t);let n=JSON.parse(JSON.stringify(e)),r=jR(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
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(`
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 Pt of l.entries)B+=t.slice(R,Pt.node.start)+a(Pt.node,S(Pt.key)),R=Pt.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),J=l.entries[1],G=J?t.slice(f.node.end,J.start):`,${I.includes(`
99
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(`
100
+ `))});return`${p?"[":"{"}${I}${A.join(G)}${C}${p?"]":"}"}`}function c(l,u,d){if(!d)return Uu(l,i);let p=t.lastIndexOf(`
101
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.0";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}
102
+ `,s+g)}return t.slice(0,r.start)+a(r,n)+t.slice(r.end)}function Uu(t,e){if(Array.isArray(t))return`[${t.map((o)=>Uu(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}${Uu(s,e)}`);return`{${e}${r.join(`,${e}`)}${e}}`}function jR(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 FR=2,Vu="ConfigError",GR=bs(Object);class Wu{loaded;configPath;defaultConfig;options;constructor(t,e,n={}){this.configPath=Bu.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 ao.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:Vu})}readStored(){try{let t=this.readConfigFile();if(t===void 0)return structuredClone(this.defaultConfig);return vs(structuredClone(this.defaultConfig),wh(t))}catch(t){throw this.unreadable(t)}}update(t){try{let e=this.savePath();mh(e,()=>this.write(e,t(this.readStored())))}catch(e){throw e instanceof m?e:this.saveFailure(e)}}savePath(){let t=this.exists()?ao.realpathSync(this.configPath):kh(this.configPath);return ao.mkdirSync(Bu.dirname(t),{recursive:!0}),t}write(t,e){let n=this.exists()?ao.statSync(this.configPath).mode:void 0,r=this.exists()?Ku(ao.readFileSync(this.configPath,"utf-8"),e):`${JSON.stringify(e,null,FR)}
103
+ `;bn(t,r,{mode:n})}saveFailure(t){return new m(`Cannot save config at ${this.configPath}: ${qn(t)}`,`Check that ${Bu.dirname(this.configPath)} is writable and that no other process is saving the file`,void 0,{cause:t,tag:Vu})}load(){let{parse:t,strict:e}=this.options;try{let n=this.readConfigFile();if(n===void 0)return{config:structuredClone(this.defaultConfig)};let r=vs(structuredClone(this.defaultConfig),wh(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:Wi()}),{config:structuredClone(this.defaultConfig),error:n}}}loadFailure(t){return new m(`Cannot read config at ${this.configPath}: ${qn(t)}`,"Repair the file and try again",void 0,{cause:t,tag:Vu})}readConfigFile(){try{return ao.readFileSync(this.configPath,"utf-8")}catch(t){if(Fu(t,"ENOENT"))return;throw t}}}function wh(t){let e=JSON.parse(t);if(Array.isArray(e))throw Error("Config must be an object");return GR(e)}var Sa="0.6.1";var E=Ui();var Sh=new Map;function et(t,e){return e.some((n)=>KR(n).match(t))}function qu(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 UR(t)}function br(t){let e=qu(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 UR(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 KR(t){let e=Sh.get(t);if(e)return e;let n=new Bun.Glob(t);return Sh.set(t,n),n}class b extends Error{_tag="ValidationError"}var BR=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,VR=/^[A-Za-z_$][A-Za-z0-9_$]*$/,WR="must be lower-case letters and digits separated by single hyphens",qR=new Set(Object.getOwnPropertyNames(Object.prototype)),JR=X(),YR=wa(),va=Sr(),XR=so(ah()),zR=X().or(Wn());function Ct(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(!VR.test(e))return`${t}[${JSON.stringify(e)}]`;return t.length===0?e:`${t}.${e}`}function T(t,e,n){let r=Eh(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 En(t,e,n){return Object.entries(Eh(t,e)).map(([r,o])=>{if(qR.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 Tn(JR,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 Rt(t,e){return Tn(zR,t,e,"must be a string or null")}function Fe(t,e){let n=x(t,e);if(!BR.test(n))throw new b(`${e} ${WR}, got ${JSON.stringify(n)}`);return n}function $t(t,e){return Tn(YR,t,e,"must be true or false")}function Bt(t,e){let n=Tn(va,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=Tn(va,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 Jn(t,e){let n=Tn(va,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 Ju(t,e){let n=Tn(va,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 Tn(ch(t),e,n,`must be one of ${t.join(", ")}`)}function L(t,e,n){return Tn(XR,t,e,"must be a list").map((o,s)=>n(o,k(e,s)))}function Lt(t,e){return L(t,e,x)}function ba(t,e){return L(t,e,(n,r)=>bh(n,r,qu))}function vh(t,e){return L(t,e,(n,r)=>bh(n,r,br))}function bh(t,e,n){let r=x(t,e),o=n(r);if(o!==null)throw new b(`${e} ${o}`);return r}function Eh(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw new b(`${e} must be an object`);return t}function Tn(t,e,n,r){try{return t(e)}catch{throw new b(`${n} ${r}`)}}var ZR=["task","review"],Yu=["task"],Qt="{prompt}",Ts="{model}",QR=["command","reviewCommand","model","modelFlag","env","inheritEnv","timeoutSeconds","roles"],tI=["default","stages","review"],eI=["agent","model"],nI=/^[A-Za-z_][A-Za-z0-9_]*$/,rI=":",oI="-",Ea={default:null,review:null,stages:{}};function Er(t){return t.roles??Yu}function $h(t){let e=En(t,"agents",sI);for(let[n]of e)Fe(n,"agent name");return Object.fromEntries(e)}function sI(t,e){let n=T(t,e,QR),r={command:Th(n.command,k(e,"command"))};if(n.reviewCommand!==void 0)r.reviewCommand=Th(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=cI(n.modelFlag,k(e,"modelFlag"));if(n.env!==void 0)r.env=lI(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=Jn(n.timeoutSeconds,k(e,"timeoutSeconds"));if(n.roles!==void 0)r.roles=uI(n.roles,k(e,"roles"));return r}function xh(t){let e=T(t,"routing",tI);return{default:D(e.default,Ea.default,(n)=>Es(n,"routing.default")),review:D(e.review,Ea.review,(n)=>Es(n,"routing.review")),stages:Object.fromEntries(D(e.stages,[],(n)=>En(n,"routing.stages",iI)))}}function Es(t,e){if(t===null)return null;if(typeof t==="string")return aI(t,e);let n=T(t,e,eI),r=Fe(n.agent,k(e,"agent")),o=D(n.model,null,(s)=>nt(s,k(e,"model")));return{agent:r,model:o}}function iI(t,e){let n=Es(t,e);if(n!==null)return n;throw new b(`${e} must name an agent; leave the stage out to use routing.default`)}function aI(t,e){let n=t.indexOf(rI);if(n===-1)return{agent:Fe(t,e),model:null};let r=Fe(t.slice(0,n),`${e} (agent)`),o=nt(t.slice(n+1),`${e} (model)`);return{agent:r,model:o}}function Ah(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(!Er(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 Th(t,e){let n=L(t,e,nt);if(n.length===0)throw new b(`${e} must not be empty`);return n}function cI(t,e){let n=x(t,e);if(n.startsWith(oI)&&n.trim()===n&&n.length>1)return n;throw new b(`${e} must be an option such as "--model"`)}function lI(t,e){let n=L(t,e,(r,o)=>{let s=x(r,o);if(nI.test(s))return s;throw new b(`${o} must be an environment variable name, not a value`)});return Ch(n,e)}function uI(t,e){let n=Ch(L(t,e,(r,o)=>K(ZR,r,o)),e);if(n.length===0)throw new b(`${e} must name at least one role`);return n}function Ch(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 dI=["GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_PREFIX","GIT_WORK_TREE"],Ge=Object.fromEntries(dI.map((t)=>[t,void 0]));var _h={SIGHUP:129,SIGINT:130,SIGTERM:143},Rh=Object.keys(_h),Ih={SIGHUP:()=>Xu("SIGHUP"),SIGINT:()=>Xu("SIGINT"),SIGTERM:()=>Xu("SIGTERM")},co=[],zu={interrupted:!1};function te(t){if(co.length===0)for(let e of Rh)process.on(e,Ih[e]);return co.push(t),()=>{let e=co.indexOf(t);if(e===-1)return;if(co.splice(e,1),co.length===0)for(let n of Rh)process.off(n,Ih[n])}}function Ph(){return zu.interrupted}function Xu(t){if(zu.interrupted)return;zu.interrupted=!0;let e=_h[t],n=co.toReversed().flatMap((r)=>pI(r)??[]);if(n.length===0)process.exit(e);Promise.all(n).finally(()=>process.exit(e))}function pI(t){try{let e=t();return e instanceof Promise?e.catch(Oh):null}catch(e){return Oh(e),null}}function Oh(t){let e=t instanceof Error?t.message:String(t);process.stderr.write(`ari could not clean up after an interrupt: ${e}
104
+ `)}var gI=["ESRCH","EPERM"];function He(t,e){try{process.kill(-t,e)}catch(n){if(!gI.includes(Tt(n)))throw n}}import{existsSync as mI,mkdirSync as fI,readFileSync as hI,realpathSync as yI,rmSync as kI}from"fs";import{homedir as wI}from"os";import{join as Nh}from"path";function Z(t){return new Bun.CryptoHasher("sha256").update(t).digest("hex")}var SI=".ari",vI="trust",bI=".json",EI=384,TI=Et({root:X(),sha256:X(),trustedAt:X()});function Dh(){let t=process.env.HOME;return Nh(t===void 0||t===""?wI():t,SI,vI)}function $s(t){try{return yI(t)}catch{return t}}function Lh(t){let e=$s(t);try{let n=TI(JSON.parse(hI(Zu(e),"utf8")));return n.root===e?n:null}catch{return null}}function Mh(t,e,n=new Date){let r=$s(t),o={root:r,sha256:e,trustedAt:n.toISOString()};return fI(Dh(),{recursive:!0}),bn(Zu(r),`${JSON.stringify(o,null,2)}
105
+ `,{mode:EI}),o}function jh(t){let e=Zu($s(t));if(!mI(e))return!1;return kI(e,{force:!0}),!0}function Zu(t){return Nh(Dh(),`${Z(t)}${bI}`)}import{existsSync as mN}from"fs";import{join as fN}from"path";function O(t,e){if(t<e)return-1;if(t>e)return 1;return 0}var $I=2;function pt(t){return`${JSON.stringify(t,xI,$I)}
106
+ `}function xI(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 AI=["cached","run"],Fh="TYPESAFE_API_URL",CI=["TYPESAFE_API_KEY","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_TOKEN","CLOUDFLARE_AUTH_TOKEN"],RI=["argus"],II="cached",OI=25,_I=6000,PI=1000,NI=20000,DI=["config","command","mode","limit","maxBytes","timeoutSeconds","verdicts"];function Hh(t){let e=T(t,"review.argus",DI),n=D(e.timeoutSeconds,null,(o)=>Jn(o,"review.argus.timeoutSeconds")),r=D(e.verdicts,!1,(o)=>$t(o,"review.argus.verdicts"));return{command:D(e.command,[...RI],MI),config:ft(e.config,"review.argus.config",nt),limit:D(e.limit,OI,(o)=>Gh(o,"limit",PI)),maxBytes:D(e.maxBytes,_I,(o)=>Gh(o,"maxBytes",NI)),mode:D(e.mode,II,(o)=>K(AI,o,"review.argus.mode")),...n===null?{}:{timeoutSeconds:n},...r?{verdicts:r}:{}}}function LI(t){return t==="run"?[Fh,...CI]:[Fh]}function Ta(t){let e=t.mode==="run";if(t.verdicts!==!0)return[e?"run":"check"];return e?["run","snapshot","import"]:["snapshot","import"]}function $a(t){return LI(t==="run"?"run":"cached")}function lo(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 MI(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 Gh(t,e,n){let r=`review.argus.${e}`,o=Bt(t,r);if(o>n)throw new b(`${r} must be at most ${n}`);return o}import{randomUUID as qP}from"crypto";import{appendFileSync as JP,existsSync as Rn,linkSync as YP,mkdirSync as xd,readdirSync as XP,readFileSync as _s,renameSync as zP,rmSync as Ad,writeFileSync as ZP}from"fs";import{basename as QP,dirname as Cd,join as It}from"path";function xs(t){if(typeof t!=="object"||t===null||Object.isFrozen(t))return t;for(let e of Object.values(t))xs(e);return Object.freeze(t)}var jI="basic",FI=300,GI=6000,HI=20,UI=2000,KI=!0,BI=1200,VI=60000,WI=25,qI=0.95,JI=0.75,YI=10,XI=!1,zI=!0,ZI=25,QI=["**/*.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__/**"],tO="Fix the reported value in .ari/config.json",eO=["$schema","pack","requireTask","checkTimeoutSeconds","testGlobs","regression","review","context","knowledge","snapshots","hooks","agents","routing"],nO=["maxEntryBytes","maxBytes","decayAfterTasks","duplicateSimilarity","mergeSimilarity","rehearsalTasks","sleepOnStop"],xt=xs({agents:{},checkTimeoutSeconds:FI,context:{briefBytes:UI,budget:GI,journalTail:HI},hooks:{brief:KI},knowledge:{decayAfterTasks:WI,duplicateSimilarity:qI,maxBytes:VI,maxEntryBytes:BI,mergeSimilarity:JI,rehearsalTasks:YI,sleepOnStop:XI},pack:jI,regression:{setup:[]},requireTask:!1,review:{command:null},routing:Ea,snapshots:{auto:zI,keep:ZI},testGlobs:QI});function Tr(t){return structuredClone(Ct("config",tO,()=>Uh(t)))}function xa(t){try{return Uh(t),null}catch(e){if(e instanceof b)return e.message;throw e}}function Uh(t){let e=T(t,"config",eO);if(e.$schema!==void 0)x(e.$schema,"$schema");let n={agents:D(e.agents,xt.agents,$h),checkTimeoutSeconds:D(e.checkTimeoutSeconds,xt.checkTimeoutSeconds,(r)=>Jn(r,"checkTimeoutSeconds")),context:D(e.context,xt.context,rO),hooks:D(e.hooks,xt.hooks,oO),knowledge:D(e.knowledge,xt.knowledge,sO),pack:D(e.pack,xt.pack,(r)=>Fe(r,"pack")),regression:D(e.regression,xt.regression,aO),requireTask:D(e.requireTask,xt.requireTask,(r)=>$t(r,"requireTask")),review:D(e.review,xt.review,cO),routing:D(e.routing,xt.routing,xh),snapshots:D(e.snapshots,xt.snapshots,iO),testGlobs:D(e.testGlobs,xt.testGlobs,(r)=>vh(r,"testGlobs"))};return Ah(n),n}function rO(t){let e=T(t,"context",["budget","journalTail","briefBytes"]),n=xt.context;return{briefBytes:D(e.briefBytes,n.briefBytes,(r)=>Bt(r,"context.briefBytes")),budget:D(e.budget,n.budget,(r)=>Bt(r,"context.budget")),journalTail:D(e.journalTail,n.journalTail,(r)=>ht(r,"context.journalTail"))}}function oO(t){let e=T(t,"hooks",["brief"]);return{brief:D(e.brief,xt.hooks.brief,(n)=>$t(n,"hooks.brief"))}}function sO(t){let e=T(t,"knowledge",nO),n={decayAfterTasks:uo(e,"decayAfterTasks",Bt),duplicateSimilarity:uo(e,"duplicateSimilarity",Ju),maxBytes:uo(e,"maxBytes",Bt),maxEntryBytes:uo(e,"maxEntryBytes",Bt),mergeSimilarity:uo(e,"mergeSimilarity",Ju),rehearsalTasks:uo(e,"rehearsalTasks",ht),sleepOnStop:D(e.sleepOnStop,xt.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 iO(t){let e=T(t,"snapshots",["auto","keep"]),n=xt.snapshots;return{auto:D(e.auto,n.auto,(r)=>$t(r,"snapshots.auto")),keep:D(e.keep,n.keep,(r)=>Bt(r,"snapshots.keep"))}}function uo(t,e,n){return D(t[e],xt.knowledge[e],(r)=>n(r,`knowledge.${e}`))}function aO(t){let e=T(t,"regression",["setup"]);return{setup:D(e.setup,xt.regression.setup,(n)=>L(n,"regression.setup",nt))}}function cO(t){let e=T(t,"review",["command","agent","model","argus"]),n=D(e.command,xt.review.command,(i)=>Rt(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:Fe(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:Hh(e.argus);return{command:n,...r===null?{}:{agent:r},...o===null?{}:{model:o},...s===null?{}:{argus:s}}}var As='writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys',lO=/"(?:[^"\\]|\\.)*"|'(?:[^']|'')*'/sy,uO=/(?:[^,[\]{}:#\n]|:(?![ \t\n,[\]{}]|$)|(?<![ \t\n])#)+/sy,dO=/(?:[ \t\n]|(?<=[ \t\n])#[^\n]*)+/sy,pO=/[&!*][^\s,[\]{}]*|\?(?=[ \t\n])/sy,gO=/[ \t\n,[\]{}]/;function td(t){return`defines "${t}" twice`}function ed(t,e){return Aa(lO,t,e)}function nd(t){return String(Bun.YAML.parse(t))}function Kh(t,e){let n=[],r=e,o=!1;while(r<t.length){let s=fO(t,r,o);if(r+=s.text.length,s.kind==="space")continue;let i=mO(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 mO(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?Qu(n):null;case"comma":{let o=r?Qu(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,Qu(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"?nd(t.text):t.text.trim();return null;case"space":return null}}function Qu(t){let{key:e,keys:n}=t;if(e===null||n===null)return null;if(n.has(e))return td(e);return n.add(e),null}function fO(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||gO.test(t[e+1]??" ")))return{kind:"colon",text:r};let o=Aa(dO,t,e);if(o!==null)return{kind:"space",text:o};let s=ed(t,e);if(s!==null)return{kind:"quoted",text:s};let i=Aa(pO,t,e);if(i!==null)return{kind:"special",text:i};return{kind:"plain",text:Aa(uO,t,e)??r}}function Aa(t,e,n){return t.lastIndex=n,t.exec(e)?.[0]??null}var hO=/^(?:---|\.\.\.)(?=[ \t]|$)/,yO=/^( *)((?:-(?: +|$))*)(.*)$/s,Bh=/^(?:[&!][^ \t]*(?:[ \t]+|$))+/,kO=/^#/,wO=/^[{[]/,SO=/^\?(?:[ \t]|$)/,vO=/^\*.*:(?:[ \t]|$)/s,Vh=/^[ \t]*:(?:[ \t]+|$)/,bO=/^([^\s|>%@`"'&*!#,[\]{}](?:(?![ \t]#).)*?)[ \t]*:(?:[ \t]+(.*))?$/s,Wh=-1;function qh(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(hO)?.[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(yO)??[];if(n!==null&&l.length>n)continue;if(u===""&&Jh(d))continue;let p=l.length+u.length;xO(e,u===""?p:l.length);let g=EO(d);if(g===As)return g;if(g!==null){let{keys:I}=AO(e,p);if(I.has(g.name))return td(g.name);I.add(g.name)}let f=$O(g===null?d:g.value),y=u===""?e.at(-1)?.column??Wh:c.lastIndexOf("-",p-1);if(n=f.kind==="text"?g===null?y:p:null,f.kind!=="flow")continue;let S=Kh(t,i+c.length-f.text.length);if(S.problem!==null)return S.problem;if(r=S.end,g===null&&Vh.test(t.slice(S.end,o).trimEnd()))return As}return null}function EO(t){if(SO.test(t)||vO.test(t))return As;let e=t.replace(Bh,""),n=TO(e);return n!==null&&e!==t?As:n}function TO(t){let e=ed(t,0);if(e===null){let[,r,o=""]=t.match(bO)??[];return r===void 0?null:{name:r,value:o}}let n=t.slice(e.length).match(Vh)?.[0];return n===void 0?null:{name:nd(e),value:t.slice(e.length+n.length)}}function $O(t){let e=t.replace(Bh,"");if(Jh(e))return{kind:"block",text:e};return{kind:wO.test(e)?"flow":"text",text:e}}function Jh(t){return t.trim()===""||kO.test(t)}function xO(t,e){while((t.at(-1)?.column??Wh)>e)t.pop()}function AO(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 po="---",CO=/^\uFEFF+/,RO=/\r\n?/g;function go(t){return t.replace(CO,"").replace(RO,`
108
+ `)}function Ca(t){let e=go(t).split(`
109
+ `);if(e[0]?.trimEnd()!==po)throw new b(`the file must start with a "${po}" line that opens the front matter`);let n=e.findIndex((r,o)=>o>0&&r.trimEnd()===po);if(n===-1)throw new b(`the front matter has no closing "${po}" line`);return{body:e.slice(n+1).join(`
110
+ `),data:rd(e.slice(1,n).join(`
111
+ `),"the front matter")}}function Ra(t,e){return`${po}
112
112
  ${t.join(`
113
113
  `)}
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()}
114
+ ${po}
115
+ ${e}`}function en(t){return JSON.stringify(t.toWellFormed())}function mo(t){return`[${t.map(en).join(", ")}]`}function rd(t,e){let n=go(t),r=IO(n,e),o=qh(n);if(o===null)return r;throw new b(`${e} ${o}`)}function IO(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 sd=3,Xh="spike",OO=/^[A-Za-z][A-Za-z0-9._-]*$/,_O=["pass","fail","regression"],PO={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"},NO=["title","pack","scope","lock","depends","criteria","checks","invariants","budget"],DO="AC-1",LO="Describe the change, its constraints and how a reviewer can verify it.";function Ia(t,e,n){return Ct(`contract "${t}"`,`Fix the front matter of .ari/tasks/${t}.md`,()=>MO(t,e,n))}function Vt(t){return Z(go(t))}function zh(t,e){let n=e===Xh?["criteria: []"]:["criteria:",` - id: ${en(DO)}`,' text: ""'," checks: []"],r=[`title: ${en(t)}`,`pack: ${en(e)}`,"scope: []","lock: []","depends: []",...n,"checks: {}","invariants: []","budget:",` attempts: ${sd}`];return Ra(r,`${LO}
116
+ `)}function fo(t,e){let n=e.find((o)=>o.name===t.pack),r=[...VO(t),...id(t)];return[...HO(t),...UO(t,n,e,r.length>0),...Yh("scope",t.scope,!0),...Yh("lock",t.lock,!1),...BO(t),...r,...WO(t),...qO(t)]}function ho(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 od(t,"pass");case"expect:fail":return od(t,"fail");case"expect:regression":return od(t,"regression")}}function od(t,e){return t.checks.filter((n)=>n.expect===e)}function id(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 MO(t,e,n){let{body:r,data:o}=Ca(e),s=T(o,"front matter",NO);return{body:r.trim(),budget:lt(s.budget,{attempts:sd},jO),checks:lt(s.checks,[],(i)=>GO(i,n.checkTimeoutSeconds)),criteria:lt(s.criteria,[],(i)=>L(i,"criteria",FO)),depends:lt(s.depends,[],(i)=>Lt(i,"depends")),id:t,invariants:lt(s.invariants,[],(i)=>Lt(i,"invariants")),lock:lt(s.lock,[],(i)=>Lt(i,"lock")),pack:lt(s.pack,n.pack,(i)=>x(i,"pack")),scope:ft(s.scope,"scope",Lt),title:ft(s.title,"title",x)}}function jO(t){let e=T(t,"budget",["attempts"]);return{attempts:lt(e.attempts,sd,(n)=>Bt(n,"budget.attempts"))}}function FO(t,e){let n=T(t,e,["id","text","checks"]);return{checks:lt(n.checks,[],(r)=>Lt(r,k(e,"checks"))),id:ft(n.id,k(e,"id"),x),text:ft(n.text,k(e,"text"),x)}}function GO(t,e){return En(t,"checks",(n,r,o)=>{if(!OO.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(_O,i,k(r,"expect"))),name:o,run:ft(s.run,k(r,"run"),x),timeoutSeconds:lt(s.timeout,e,(i)=>Jn(i,k(r,"timeout")))}}).map(([,n])=>n)}function HO(t){return t.title.trim().length===0?["title must not be empty"]:[]}function UO(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(KO)))].filter((s)=>!r||s!=="all"&&s!=="criteria").filter((s)=>ho(t,s).length===0).map((s)=>`pack "${e.name}" needs at least one ${PO[s]}`)}function KO(t){if(t.kind==="regression")return["expect:regression"];return t.kind==="checks"?[t.select]:[]}function Yh(t,e,n){let r=n&&e.length===0?[`${t} must list at least one glob`]:[],o=e.flatMap((s)=>{let i=br(s);return i===null?[]:[`${t} glob ${JSON.stringify(s)} ${i}`]});return[...r,...o]}function BO(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 VO(t){let n=t.pack!==Xh&&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 WO(t){return t.checks.filter((e)=>e.run.trim().length===0).map((e)=>`check ${e.name} must have a run command`)}function qO(t){return t.invariants.some((e)=>e.trim().length===0)?["invariants must not contain an empty command"]:[]}var ue=["fact","decision","constraint","pattern","gotcha"],JO=["active","archived"],YO=/^\d{4}-\d{2}-\d{2}$/,XO=/\s+/g,zO=["kind","scope","sources","status","supersedes","supersededBy","created"];function Oa(t,e){return Ct(`knowledge entry "${t}"`,`Restore .ari/knowledge/${t}.md from git`,()=>ZO(t,e))}function $r(t){let e=[`kind: ${en(t.kind)}`,`scope: ${mo(t.scope)}`,`sources: ${mo(t.sources)}`,`status: ${en(t.status)}`,`supersedes: ${mo(t.supersedes)}`,`supersededBy: ${t.supersededBy===null?"null":en(t.supersededBy)}`,`created: ${en(t.created)}`];return Ra(e,`${t.text.trim()}
117
+ `)}function ad(t){return t.normalize("NFC").toLowerCase().replace(XO," ").trim()}function ZO(t,e){let{body:n,data:r}=Ca(e),o=T(r,"front matter",zO),s=ft(o.created,"created",x);if(!YO.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(ue,a,c)),scope:lt(o.scope,[],(a)=>ba(a,"scope")),sources:lt(o.sources,[],(a)=>Lt(a,"sources")),status:lt(o.status,"active",(a)=>K(JO,a,"status")),supersededBy:lt(o.supersededBy,null,(a)=>Rt(a,"supersededBy")),supersedes:lt(o.supersedes,[],(a)=>Lt(a,"supersedes")),text:i}}var Zh="<!--",Qh="-->",yo="`",ty=2,QO=/^ {0,3}(`{3,}|~{3,})(.*)$/,t_=/^ {0,3}(`{3,}|~{3,})[ \t]*$/,e_=/^ {0,3}(#{1,6})(?:[ \t]+(.*))?$/,n_=/(?:^|[ \t]+)#+[ \t]*$/,r_=/\s+/g;function nn(t){return t.replace(r_," ").trim().toLowerCase()}function ny(t){let{unclosedComment:e,visible:n}=a_(go(t).split(`
118
+ `)),r=[],o=null;for(let s of n){let i=s.fenced?null:i_(s.text);if(i!==null&&i.level<=ty){if(o=i.level===ty?o_(i.text,s.line):null,o!==null)r.push(o);continue}o?.lines.push(s)}return{sections:r.map(s_),unclosedComment:e}}function o_(t,e){return{lines:[],section:{body:"",heading:t,key:nn(t),line:e,prose:[]}}}function s_({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 i_(t){let e=e_.exec(t);if(e===null)return null;return{level:(e[1]??"").length,text:(e[2]??"").replace(n_,"").trim()}}function a_(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=l_(s,n)?null:n;continue}let a=r===null?c_(s):null;if(a!==null){n=a,e.push({fenced:!0,line:i,text:s});continue}let c=u_(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 c_(t){let e=QO.exec(t),n=e?.[1];if(n===void 0)return null;let r=n.slice(0,1);if(r===yo&&(e?.[2]??"").includes(yo))return null;return{length:n.length,marker:r}}function l_(t,e){let n=t_.exec(t)?.[1];return n?.startsWith(e.marker)===!0&&n.length>=e.length}function u_(t,e){let n=e,r=!1,o="",s=0;while(s<t.length){if(n){let a=t.indexOf(Qh,s);if(a===-1)return{fresh:r,inside:!0,text:o};n=!1,r=!1,s=a+Qh.length;continue}if(t.startsWith(Zh,s)){n=!0,r=!0,s+=Zh.length;continue}let i=t[s]===yo?d_(t,s):s+1;o+=t.slice(s,i),s=i}return{fresh:r,inside:n,text:o}}function d_(t,e){let n=ey(t,e),r=t.indexOf(yo,e+n);while(r!==-1){let o=ey(t,r);if(o===n)return r+o;r=t.indexOf(yo,r+o)}return e+n}function ey(t,e){let n=e;while(t[n]===yo)n++;return n-e}var cd="TODO(ari): write this section",$n="Acceptance criteria",_a=["Problem","Context","Options","Decision",$n,"Scope","Risks and open questions"],p_={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."]},g_=["Fill this section."],m_=/\s+/g,f_=/<!--|-->/g,h_=/^[-*+][ \t]+([^\s:]+):(?=\s|$)/;function ry(t,e=[]){let n=new Set(_a.map(nn)),r=e.filter((i)=>!n.has(nn(i))),o=[..._a,...r].map(y_);return`# ${t.replace(f_,"").replace(m_," ").trim()}
120
120
 
121
121
  ${o.join(`
122
122
 
123
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(`
124
+ `}function oy(t){let{requirements:e}=t,{sections:n,unclosedComment:r}=ny(t.text),o=r===null?[]:[`Close the HTML comment that starts at line ${r} of ${t.path} with -->`],s=e.sections.flatMap((a)=>k_(a,n,t.path)),i=e.traceable?w_(n,t):{ids:0,problems:[]};return{filled:e.sections.length-s.length,problems:[...o,...s,...i.problems],traced:i.ids}}function y_(t){let e=(p_[t]??g_).join(`
125
125
  `);return`## ${t}
126
126
  <!--
127
127
  ${e}
128
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
129
+ ${cd}`}function k_(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(cd))return[`Fill the section '${t}' in ${n}: replace the placeholder '${cd}'`];return o.trim().length===0?[`Fill the section '${t}' in ${n}`]:[]}function w_(t,e){let n=nn($n),r=t.filter((g)=>g.key===n).flatMap((g)=>g.prose.flatMap(S_)),{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 S_(t){let e=h_.exec(t)?.[1];return e===void 0?[]:[e]}var ay=200,v_=".ari/designs/{id}.md",b_=/\{id\}/g,E_=/[\r\n]/,T_="Fix the pack file; see the packs section of the Ariadne design",$_=["all","criteria","expect:pass","expect:fail","expect:regression"],x_=["pass","fail"],A_=["kind","path","minBytes","sections","traceable"],C_="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.",Cs={kind:"criteria"},rn={kind:"invariants"},ee={kind:"scope"},Ue={kind:"locked"},ld={kind:"tests-unchanged"},R_={kind:"regression"},ud={kind:"approval"},sy={kind:"review"};function de(t,e){return{expect:e,kind:"checks",select:t}}function dd(t,e={}){return{kind:"artifact",minBytes:ay,path:t,...e}}var iy=xs([{description:"Implement the contract and prove it with its checks",name:"basic",stages:[{gates:[Cs,de("criteria","pass"),rn,ee,Ue],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:[dd(".ari/designs/{id}.md"),ud],instruction:"Write the design to .ari/designs/{id}.md, then ask a human to approve it.",name:"design"},{gates:[Cs,de("all","pass"),rn,ee,Ue],instruction:"Implement the approved design inside the scope until every check passes.",name:"implement"},{gates:[sy,de("all","pass"),rn,ee,Ue],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:[Cs,de("criteria","fail"),ee],instruction:"Write failing tests for every criterion. Do not implement the change yet.",name:"red"},{gates:[de("all","pass"),ld,rn,ee,Ue],instruction:"Make every check pass with the smallest change. Do not edit the tests.",name:"green"},{gates:[de("all","pass"),ld,rn,ee,Ue],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:[de("expect:regression","fail"),ee],instruction:"Write a regression check that fails because of the bug. Do not fix it yet.",name:"reproduce"},{gates:[R_,de("all","pass"),rn,ee,Ue],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:[Cs,ud],instruction:"Specify the criteria and their checks in the contract, run ari amend, then ask a human to approve.",name:"specify"},{gates:[de("all","pass"),rn,ee,Ue],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:[ld,de("all","pass"),rn,ee,Ue],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:[dd(".ari/designs/{id}.md"),ee,Ue],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:[dd(v_,{sections:[..._a],traceable:!0}),ud,ee],instruction:C_,name:"design"},{gates:[Cs,de("all","pass"),rn,ee,Ue],instruction:"Implement the approved design inside the scope until every check passes.",name:"implement"},{gates:[sy,de("all","pass"),rn,ee,Ue],instruction:"Get the change reviewed: run the review command or ask a human to approve it.",name:"review"}]}]),cy={approval:(t,e)=>Yn(t,e,"approval"),artifact:D_,checks:N_,command:(t,e)=>{let n=T(t,e,["kind","run"]);return{kind:"command",run:nt(n.run,k(e,"run"))}},criteria:(t,e)=>Yn(t,e,"criteria"),invariants:(t,e)=>Yn(t,e,"invariants"),locked:(t,e)=>Yn(t,e,"locked"),regression:(t,e)=>Yn(t,e,"regression"),review:(t,e)=>Yn(t,e,"review"),scope:(t,e)=>Yn(t,e,"scope"),"tests-unchanged":(t,e)=>Yn(t,e,"tests-unchanged")},I_=Object.keys(cy);function Pa(t,e="pack"){return Ct(e,T_,()=>O_(rd(t,"the pack file")))}function xn(t){let e=new Map(t.map((s)=>[s.name,s])),n=iy.map((s)=>e.get(s.name)??s),r=new Set(iy.map((s)=>s.name)),o=t.filter((s)=>!r.has(s.name)).sort((s,i)=>O(s.name,i.name));return[...n,...o]}function Ke(t,e){let n=xn(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 Na(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 ko(t,e){return t.instruction.replace(b_,e)}function O_(t){let e=T(t,"pack",["name","description","stages"]),n=L(e.stages,"stages",__);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:Fe(e.name,"name"),stages:n}}function __(t,e){let n=T(t,e,["name","instruction","gates"]),r=L(n.gates,k(e,"gates"),P_);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:Fe(n.name,k(e,"name"))}}function P_(t,e){let n=T(t,e,["kind","select","expect","path","minBytes","sections","traceable","run"]),r=K(I_,n.kind,k(e,"kind"));return cy[r](n,e)}function Yn(t,e,n){return T(t,e,["kind"]),{kind:n}}function N_(t,e){let n=T(t,e,["kind","select","expect"]);return de(lt(n.select,"all",(r)=>K($_,r,k(e,"select"))),lt(n.expect,"pass",(r)=>K(x_,r,k(e,"expect"))))}function D_(t,e){let n=T(t,e,A_),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)=>L_(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,ay,(a)=>ht(a,k(e,"minBytes"))),path:r,...s===void 0?{}:{sections:s},...i?{traceable:i}:{}}}function L_(t,e){let n=L(t,e,(o,s)=>{let i=nt(o,s).trim();if(E_.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 ly="attempt budget exhausted",uy="failedAttempts",M_={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 pd(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 py(t){let e=t.history[0]?.at??"";return pt(t)===pt(pd(t.id,e))}function gd(t,e){return An(t,["draft"],"mark ready"),{...t,history:[...t.history,on("ready",e)],status:"ready"}}function gy(t,e,n,r){return An(t,["ready"],"start"),{...t,attempts:0,...by(n),base:e,history:[...t.history,on("started",r,{detail:e})],stage:0,status:"active"}}function my(t,e,n,r){if(An(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 fy(t,e,n){if(An(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:ly,stage:e.stage});return{...t,attempts:r,history:i?[...t.history,s,a]:[...t.history,s],lastFailure:e,question:i?ly:t.question,status:i?"blocked":"active"}}function md(t,e,n){An(t,["draft","ready","active","blocked"],"amend");let r=Rs(e.reason,"Amending a task needs a reason","Pass --reason <text>"),o=e.base!==null&&e.base!==t.base;if(o)An(t,["active","blocked"],"move the base of");let s=o?e.base:t.base,i=`gates ${e.gatesHash}, locks ${dy(e.lockHashes)}, tests ${dy(e.stageTestHashes)}`,a=o?`, base ${t.base} -> ${s}`:"",c=`${r} (contract ${e.contractHash}, ${i}${a})`;return{...t,...by(e),approvals:t.approvals.filter((l)=>l.stage!==e.stage),base:s,history:[...t.history,on("amended",n,{detail:c})]}}function hy(t,e,n){An(t,["active"],"block");let r=Rs(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 fd(t,e,n){An(t,["blocked"],"resolve");let r=Rs(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 yy(t,e,n){An(t,["active"],"approve");let{artifactHashes:r,stage:o,treeHash:s}=e,i=Rs(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 ky(t,e,n){let r=Rs(e,"A note needs text","Pass the note text as an argument");return{...t,notes:[...t.notes,{at:n,promoted:!1,text:r}]}}function Da(t,e){let n=new Map(Object.entries(t.journalStats??{}).filter(([o])=>o!==uy));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),[uy]:r}}}function wy(t,e){let n=[...new Set([...t.knowledgeUsed,...e])].sort(O);return{...t,knowledgeUsed:n}}function Sy(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 vy(t,e){let n=new Set(e);return{...t,notes:t.notes.map((r,o)=>n.has(o)?{...r,promoted:!1}:r)}}function by({contractHash:t,gatesHash:e,lockHashes:n,stageTestHashes:r}){return{contractHash:t,gatesHash:e,lockHashes:{...n},stageTestHashes:{...r}}}function dy(t){return Z(pt(t))}function An(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 ")}`,M_[t.status](t.id))}function Rs(t,e,n){let r=t.trim();if(r.length===0)throw new m(e,n);return r}import{mkdirSync as j_,readFileSync as F_,rmSync as La,statSync as G_,writeFileSync as H_}from"fs";import{dirname as U_}from"path";var K_="EEXIST",B_="ENOENT",V_="ESRCH",W_=".break",q_=20,J_=1e4,Y_=1000,X_=10,z_=0;function yd(t,e,n){return Is(t,`task "${e}"`,n)}function Is(t,e,n){Z_(t,e);try{return n()}finally{La(t,{force:!0})}}function Z_(t,e){j_(U_(t),{recursive:!0});let n=Date.now()+J_;while(!Ey(t)){if(hd(t))Q_(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(q_)}}function Q_(t){let e=`${t}${W_}`;if(!Ey(e)){if(hd(e))La(e,{force:!0});return}try{if(hd(t))La(t,{force:!0})}finally{La(e,{force:!0})}}function Ey(t){try{return H_(t,`${process.pid}`,{flag:"wx"}),!0}catch(e){if(Tt(e)===K_)return!1;throw e}}function hd(t){let e=tP(t);if(e===null)return!1;if(Number.isNaN(e.pid))return Date.now()-e.modifiedMs>Y_;return!eP(e.pid)}function tP(t){try{return{modifiedMs:G_(t).mtimeMs,pid:Number.parseInt(F_(t,"utf8"),X_)}}catch(e){if(Tt(e)===B_)return null;throw e}}function eP(t){try{return process.kill(t,z_),!0}catch(e){return Tt(e)!==V_}}var kd=["draft","ready","active","blocked","done"],nP=["pass","fail"],rP=["criteria","checks","invariants","scope","locked","tests-unchanged","regression","artifact","approval","review","command"],oP=["created","ready","started","advanced","done","failed","amended","blocked","resolved","approved"],sP=["edit","shell","tool","check","done","context","note","stop","compact","session"],iP=["approvals","attempts","base","contractHash","evidence","gatesHash","history","id","journalStats","knowledgeUsed","lastFailure","lockHashes","notes","question","stage","stageTestHashes","status"],aP=["command","durationMs","exitCode","expect","name","ok","outputSha256","outputTail","timedOut"];function Ty(t,e){return Ct(`task record "${t}"`,`Restore .ari/tasks/${t}.json from git; only ari writes it`,()=>{let n=cP(e);if(n.id!==t)throw new b(`id is "${n.id}" but the file belongs to task "${t}"`);return n})}function ja(t){let e=T(t,"event",["at","detail","task","type"]);return{at:x(e.at,"at"),detail:Object.fromEntries(En(e.detail,"detail",fP)),task:x(e.task,"task"),type:K(sP,e.type,"type")}}function cP(t){let e=T(t,"record",iP);return{approvals:L(e.approvals,"approvals",lP),attempts:ht(e.attempts,"attempts"),base:Rt(e.base,"base"),contractHash:Rt(e.contractHash,"contractHash"),evidence:L(e.evidence,"evidence",dP),gatesHash:D(e.gatesHash,null,(n)=>Rt(n,"gatesHash")),history:L(e.history,"history",uP),id:x(e.id,"id"),journalStats:e.journalStats===null?null:mP(e.journalStats,"journalStats"),knowledgeUsed:Lt(e.knowledgeUsed,"knowledgeUsed"),lastFailure:e.lastFailure===null?null:pP(e.lastFailure,"lastFailure"),lockHashes:Ma(e.lockHashes,"lockHashes"),notes:L(e.notes,"notes",wd),question:Rt(e.question,"question"),stage:ht(e.stage,"stage"),stageTestHashes:Ma(e.stageTestHashes,"stageTestHashes"),status:K(kd,e.status,"status")}}function lP(t,e){let n=T(t,e,["artifactHashes","at","by","stage","treeHash"]);return{artifactHashes:D(n.artifactHashes,{},(r)=>Ma(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)=>Rt(r,k(e,"treeHash")))}}function wd(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 uP(t,e){let n=T(t,e,["at","by","detail","stage","type"]);return{at:x(n.at,k(e,"at")),by:Rt(n.by,k(e,"by")),detail:Rt(n.detail,k(e,"detail")),stage:Rt(n.stage,k(e,"stage")),type:K(oP,n.type,k(e,"type"))}}function dP(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"),$y),stage:x(n.stage,k(e,"stage")),testHashes:Ma(n.testHashes,k(e,"testHashes")),treeHash:x(n.treeHash,k(e,"treeHash"))}}function pP(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"),$y),stage:x(n.stage,k(e,"stage")),treeHash:x(n.treeHash,k(e,"treeHash"))}}function $y(t,e){let n=T(t,e,["checks","details","gate","ok","summary"]);return{checks:L(n.checks,k(e,"checks"),gP),details:Lt(n.details,k(e,"details")),gate:K(rP,n.gate,k(e,"gate")),ok:$t(n.ok,k(e,"ok")),summary:x(n.summary,k(e,"summary"))}}function gP(t,e){let n=T(t,e,aP),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(nP,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 Ma(t,e){return Object.fromEntries(En(t,e,x))}function mP(t,e){return Object.fromEntries(En(t,e,ht))}function fP(t,e){if(typeof t==="string"||typeof t==="boolean")return t;if(typeof t==="number"&&Number.isFinite(t))return t;return Lt(t,e)}import{copyFileSync as $P,existsSync as xP,mkdtempSync as AP,readFileSync as CP,readlinkSync as RP,rmSync as IP,utimesSync as OP}from"fs";import{tmpdir as _P}from"os";import{join as Ga,resolve as PP}from"path";import{lstatSync as hP,statSync as yP}from"fs";import{dirname as kP,join as wP}from"path";var SP=["ENOENT","ENOTDIR","ELOOP"];function $e(t){return xy(()=>hP(t))}function Sd(t){return xy(()=>yP(t))}function xe(t,e,n=new Map){let r=kP(e);if(r===".")return!1;let o=n.get(r);if(o!==void 0)return o;let s=$e(wP(t,r))?.isSymbolicLink()===!0||xe(t,r,n);return n.set(r,s),s}function xy(t){try{return t()}catch(e){if(SP.includes(Tt(e)))return null;throw e}}import{realpathSync as vP}from"fs";var Os="ari-base-",vd="ari-index-",Ay="ari-verdicts-",bP=12;function Fa(t){return`${vd}${EP(t)}-`}function EP(t){return Z(TP(t)).slice(0,bP)}function TP(t){try{return vP(t)}catch{return t}}var Ha="\x00",ne=0,NP=128,DP=128,Py=1,Ny=1,LP=1,bd=["diff","--name-only","--no-renames","--ignore-submodules=untracked","-z"],MP=["git","--no-optional-locks","--no-replace-objects",...["core.fsmonitor=false","core.untrackedCache=false","core.trustctime=true","core.checkStat=default"].flatMap((t)=>["-c",t])],Cy=1,jP=/^(?:[a-z]|S) /,Ry=/^s/i,FP=2,GP="symlink:",HP=["--no-assume-unchanged","--no-skip-worktree"],Iy="worktree ",UP="bare",KP="prunable",Oy=/^(?:error|fatal): /;async function F(t,e,n={}){let r=[...MP,...e],o=WP(r,t,n),[s,i,a]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if((n.allowedExitCodes??[ne]).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 Xn(t){let e=await F(t,["rev-parse","--show-toplevel"],{allowedExitCodes:[ne,NP]});if(e.exitCode!==ne)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 PP(t,n.stdout.trim())}async function Ua(t){let e=await F(t,["rev-parse","--verify","--quiet","HEAD^{commit}"],{allowedExitCodes:[ne,Py]});if(e.exitCode!==ne)throw new m("The repository has no commits yet","Make a first commit, then run the command again");return e.stdout.trim()}async function Dy(t){let e=await F(t,["config","user.name"],{allowedExitCodes:[ne,Ny]}),n=e.stdout.trim();return e.exitCode===ne&&n.length>0?n:null}async function Ae(t,e){let n=await Fy(t,async(s)=>(await jy(t,await Ba(t),s),F(t,[...bd,e,"--"],{env:s}))),r=await F(t,[...bd,"--cached",e,"--"]),o=await F(t,["ls-files","--others","--exclude-standard","-z"]);return Td([n,r,o].flatMap((s)=>Be(s.stdout)))}async function Ka(t,e,n){let r=await F(t,[...bd,e,n,"--"]);return Td(Be(r.stdout))}async function wo(t,e){let n=await F(t,["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],{allowedExitCodes:[ne,Py]});if(n.exitCode!==ne)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 Ly(t,e,n){let r=await F(t,["merge-base",e,n],{allowedExitCodes:[ne,LP]});if(r.exitCode!==ne)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 My(t){let e=await F(t,["worktree","list","--porcelain","-z"]),n=[],r=null;for(let o of[...e.stdout.split(Ha),""])if(o.startsWith(Iy))r=o.slice(Iy.length);else if(o===UP||o.startsWith(KP))r=null;else if(o===""&&r!==null)n.push(r),r=null;return n}async function Ce(t,e){return Fy(t,async(n)=>{await jy(t,await Ba(t),n);let r=await F(t,["add","--all","--sparse","--","."],{allowedExitCodes:[ne,DP],env:n});if(r.exitCode!==ne)throw new m(`git cannot hash the working tree: ${Ed(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 Cn(t,e){if(e.length===0)return{};let n=await F(t,["ls-files","--cached","--others","--exclude-standard","-z"]),r=new Map,o=Td(Be(n.stdout)).filter((s)=>et(s,e)&&!xe(t,s,r));return Object.fromEntries(o.flatMap((s)=>{let i=VP(Ga(t,s));return i===null?[]:[[s,i]]}))}function Ed(t){let e=t.split(`
130
+ `).map((r)=>r.trim()).filter((r)=>r.length>0),n=e.filter((r)=>Oy.test(r)).map((r)=>r.replace(Oy,""));return(n.length>0?n:e).join("; ")||"no output"}async function Ba(t){let e=await F(t,["ls-files","-v","-z"]),n=Be(e.stdout).filter((o)=>jP.test(o)),r=n.some((o)=>Ry.test(o))&&await BP(t);return n.filter((o)=>!(r&&Ry.test(o))||$e(Ga(t,_y(o)))!==null).map(_y)}async function BP(t){return(await F(t,["config","--type=bool","core.sparseCheckout"],{allowedExitCodes:[ne,Ny]})).stdout.trim()==="true"}function _y(t){return t.slice(FP)}async function jy(t,e,n){if(e.length===0)return;let r=`${e.join(Ha)}${Ha}`;for(let o of HP)await F(t,["update-index",o,"-z","--stdin"],{env:n,stdin:r})}async function Fy(t,e){let n=AP(Ga(_P(),Fa(t))),r=Ga(n,"index"),o=()=>IP(n,{force:!0,recursive:!0}),s=te(o);try{let i=await sn(t,"index");if(xP(i))$P(i,r),OP(r,Cy,Cy);return await e({GIT_INDEX_FILE:r})}finally{o(),s()}}function VP(t){let e=$e(t);if(e?.isSymbolicLink())return`${GP}${Z(RP(t))}`;return e?.isFile()?Z(CP(t)):null}function WP(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 Be(t){return t.split(Ha).filter((e)=>e.length>0)}function Td(t){return[...new Set(t)].sort(O)}var q=".ari",xr=".ari/tasks/*.json",Gy=".ari/tasks/*.md",rt=".ari/config.json",So="ids",tN=`${q}/`,Va="tasks",Hy="knowledge",Uy="packs",eN="ari",Rd="active.json",nN="journal",Ky=".md",By=".json",Vy=".md",$d=".yaml",rN=".jsonl",Id=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Wy=`
131
+ `,oN=".ari-",sN=".tmp",iN="ENOENT",qy="EEXIST",aN=new Set(["EPERM","ENOTSUP","ENOSYS","EXDEV"]),cN="locks",lN=".lock";function vo(t){return t===q||t.startsWith(tN)}function re(t){return t.filter((e)=>!vo(e))}function bo(t){if(Rn(It(t,q)))return;throw new m("Ariadne is not initialised in this repository","Run 'ari init'")}function Jy(){return pt(xt)}function M(t){bo(t);let e=It(t,rt);if(!Rn(e))return Tr({});return Tr(Dd(e,rt,"Fix the JSON syntax of .ari/config.json"))}function Od(t){return Id.test(t)}function zn(t){if(Od(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 Ot(t){return`${q}/${Va}/${zn(t)}${Ky}`}function In(t){return`${q}/${Va}/${zn(t)}${By}`}function _d(t){return`${q}/${Uy}/${t}${$d}`}function pe(t){return bo(t),Ja(It(t,q,Va),Ky)}function On(t){return bo(t),Ja(It(t,q,Va),By)}function it(t,e,n){bo(t);let r=It(t,Ot(e));if(!Rn(r))throw new m(`Task "${e}" does not exist`,"Run 'ari list' to see the tasks of this repository");let o=_s(r,"utf8");return{contractText:o,task:{contract:Ia(e,o,n),record:_n(t,e)}}}function Nt(t,e){let n={invalid:[],tasks:[]};for(let r of pe(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=Ot(o),i=()=>new m(`Task "${o}" already exists at ${s}`,"Run 'ari list'");yd(ek(e,o),o,()=>{if(Rn(It(t,s))||!tk(t,o))throw i();zy(t,n),Zn(It(t,s),r,i)})}function Xy(t){let e=pe(t);return[...e,...On(t).filter((n)=>!e.includes(n)&&!tk(t,n))]}function zy(t,e){Pn(It(t,In(e.id)),pt(e))}function Wt(t,e,n,r){return yd(ek(e,n),n,()=>{let o=r(_n(t,n));return zy(t,o),o})}function Ht(t){bo(t);let e=It(t,q,Uy);return Ja(e,$d).map((n)=>{let r=_d(n),o=Pa(_s(It(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}${$d} or fix its name`)})}function an(t){return bo(t),Ja(It(t,q,Hy),Vy)}function ge(t){return an(t).map((e)=>Oa(e,_s(nk(t,e),"utf8")))}function Wa(t,e){if(!Id.test(e.id))throw Error(`Knowledge entry id "${e.id}" is not a slug`);let n=nk(t,e.id);Zn(n,$r(e),()=>Error(`Knowledge entry ${n} already exists`))}async function P(t){return sn(t,eN)}function gt(t){let e=It(t,Rd);if(!Rn(e))return null;let n=`Delete ${e}, then run 'ari next', which offers to adopt the task again`,r=Dd(e,e,n);return Ct("active task pointer",n,()=>{let o=T(r,"pointer",["since","task"]);return{since:x(o.since,"since"),task:x(o.task,"task")}})}function Pd(t,e){Pn(It(t,Rd),pt(e))}function Zy(t){Ad(It(t,Rd),{force:!0})}function Ar(t,e){let n=Nd(t,e.task);xd(Cd(n),{recursive:!0});let r=JSON.stringify(JSON.parse(pt(e)));JP(n,`${r}${Wy}`)}function qa(t,e){Ad(Nd(t,e),{force:!0})}function Qy(t,e){let n=Nd(t,e);if(!Rn(n))return[];return _s(n,"utf8").split(Wy).flatMap((r)=>{if(r.trim().length===0)return[];let o=uN(r);return o===null||o.task!==e?[]:[o]})}function uN(t){try{return ja(JSON.parse(t))}catch(e){if(e instanceof SyntaxError||e instanceof b)return null;throw e}}function Nd(t,e){return It(t,nN,`${zn(e)}${rN}`)}function _n(t,e){let n=In(e),r=It(t,n);if(!Rn(r))throw new m(`Task "${e}" has a contract but no record at ${n}`,`Restore ${n} from git; only ari writes it`);return Ty(e,Dd(r,n,`Restore ${n} from git; only ari writes it`))}function tk(t,e){if(!Rn(It(t,In(e))))return!0;try{return py(_n(t,e))}catch(n){if(n instanceof m)return!1;throw n}}function ek(t,e){return It(t,cN,`${zn(e)}${lN}`)}function nk(t,e){return It(t,q,Hy,`${e}${Vy}`)}function Dd(t,e,n){let r=_s(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 Ja(t,e){return dN(t).filter((r)=>r.endsWith(e)).map((r)=>QP(r,e)).filter((r)=>Id.test(r)).sort(O)}function dN(t){try{return XP(t)}catch(e){if(Tt(e)===iN)return[];throw e}}function Pn(t,e){xd(Cd(t),{recursive:!0}),bn(t,e)}function Zn(t,e,n){let r=gN(t);try{ZP(r,e),pN(r,t)}catch(o){if(Tt(o)===qy)throw n();throw o}finally{Ad(r,{force:!0})}}function pN(t,e){try{YP(t,e)}catch(n){if(!aN.has(Tt(n)??""))throw n;if(Rn(e))throw Object.assign(Error(`${e} already exists`),{code:qy});zP(t,e)}}function gN(t){let e=Cd(t);return xd(e,{recursive:!0}),It(e,`${oN}${qP()}${sN}`)}var hN=1,yN=/^[\w@%+=:,./{}-]+$/,Ld="the base set of variables only",kN="the whole environment, with every token in it",wN="{base}",SN="{changed-files}",vN="{verdicts-file}",bN="argus sends the source of the changed files to the model endpoint";function rk(t,e){let n=EN(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:hN};return{commands:TN(e,n),sha256:Z(pt(r))}}function EN(t){if(!mN(fN(t,q)))return[];return Ht(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 TN(t,e){let n=Object.entries(t.agents).flatMap(([a,c])=>$N(a,c)),r=t.review.command===null?[]:[Eo("review.command",t.review.command)],o=xN(t.review.argus),s=t.regression.setup.map((a,c)=>Eo(`regression.setup[${c}]`,a)),i=e.map(({pack:a,run:c,stage:l})=>Eo(`.ari/packs/${a}: stage ${l}, command gate`,c));return[...n,...r,...o,...s,...i]}function $N(t,e){let n=AN(e),r=e.reviewCommand===void 0?[]:[Eo(`agents.${t}.reviewCommand`,Md(e.reviewCommand),n)];return[Eo(`agents.${t}.command`,Md(e.command),n),...r]}function xN(t){if(t===void 0)return[];let e={base:wN,configPath:t.config,file:vN,only:SN};return Ta(t).map((n)=>{let r=`${Ld} and ${$a(n).join(", ")}, when set`,o=n==="run"?`${r}; ${bN}`:r;return Eo("review.argus.command",Md(lo(t,n,e)),o)})}function AN(t){if(t.inheritEnv===!0)return kN;return t.env===void 0||t.env.length===0?Ld:`${Ld} and ${t.env.join(", ")}`}function Eo(t,e,n=null){return{command:e,environment:n,source:t}}function Md(t){return t.map((e)=>yN.test(e)?e:JSON.stringify(e)).join(" ")}var Cr="ARI_TRUST_CONFIG",CN="1";function To(){return process.env[Cr]===CN}function Ve(t,e){let n=rk(t,e),r=Lh(t),o=RN(n.commands.length,n.sha256,r?.sha256??null);return{commands:n.commands,root:$s(t),sha256:n.sha256,state:o,trustedAt:r?.trustedAt??null,trustedSha256:r?.sha256??null}}function Nn(t){return t.state==="untrusted"||t.state==="changed"}function $o(t,e){let n=Ve(t,e);if(n.state==="not-required")return n;let r=Mh(t,n.sha256);return{...n,state:"trusted",trustedAt:r.trustedAt,trustedSha256:r.sha256}}function ok(t){return jh(t)}function RN(t,e,n){if(t===0)return"not-required";if(n===null)return"untrusted";return n===e?"trusted":"changed"}var IN=1,ON="Commands that ari would run for this repository";async function Qn({config:t,root:e},n){if(To())return;let r=Ve(e,t);if(!Nn(r))return;if(gr()&&await Fd(r.root,r.commands)){$o(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 ${Cr}=1 where the repository is already trusted, such as in CI`,IN,{tag:"ConfigNotTrusted"})}function jd(t){return t.flatMap(({command:e,environment:n,source:r})=>[`${r}: ${e}`,...n===null?[]:[` environment: ${n}`]])}async function Fd(t,e){Dt(jd(e).join(`
132
+ `),ON);try{return await Te({initialValue:!1,message:`Trust these commands in ${t}?`})}catch(n){if(n instanceof vt)return!1;throw n}}var _N=2,Rr=1,PN=5000,NN=1000,DN=2147483647,LN=1048576,MN=["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 Ir(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",Rr,{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`,Rr,{tag:"AgentNotConfigured"});if(!Er(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`,Rr,{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 Ya(i,""),i}function Ya(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(Qt)))throw new m(`The command of agent "${o}" has no ${Qt} argument`,`Put ${Qt} where the agent takes its prompt in ${c}`,Rr,{tag:"AgentCommandInvalid"});let l=a.some((p)=>p.includes(Ts));if(l&&r===null)throw new m(`Agent "${o}" needs a model for ${Ts} in ${c}`,`Set agents.${o}.model, give a model in routing, or pass --model`,Rr,{tag:"AgentCommandInvalid"});if(!l&&r!==null&&n.modelFlag===void 0)throw new m(`Agent "${o}" has no way to take the model "${r}"`,`Put ${Ts} in ${c}, or set agents.${o}.modelFlag`,Rr,{tag:"AgentCommandInvalid"});let u=a.map((p)=>p.replaceAll(Qt,()=>e).replaceAll(Ts,()=>r??"")),d=!l&&r!==null&&n.modelFlag!==void 0?[n.modelFlag,r]:[];return[...u,...d]}function Xa(t){if(t.inheritEnv===!0)return{...process.env,...Ge};return Ps(t.env??[])}function Ps(t){let e=[...MN,...t].filter((n)=>!(n in Ge));return Object.fromEntries(e.flatMap((n)=>process.env[n]===void 0?[]:[[n,process.env[n]]]))}async function za(t,e,n){let r=Ya(t,e),{name:o}=t;return Gd(r,{...n,action:`start the agent "${o}"`,maxCaptureBytes:LN,reapGroup:t.role==="review",startFailure:(s,i)=>new m(`Agent "${o}" could not start: ${s}`,`Fix agents.${o}.command in .ari/config.json`,Rr,{cause:i,tag:"AgentStartFailed"}),timeoutSeconds:n.timeoutSeconds??t.config.timeoutSeconds})}async function Gd(t,e){await Qn(e.trust,e.action);let n=jN(t,e),r=te(()=>sk(n)),o={timedOut:!1},s=e.timeoutSeconds,i=s===void 0?void 0:setTimeout(()=>{o.timedOut=!0,sk(n)},Math.min(s*NN,DN)),a=e.stdout==="capture"?FN(n,e.maxCaptureBytes):Promise.resolve({overflowed:!1,text:""}),c=await n.exited;if(clearTimeout(i),Ph())await new Promise(()=>{return});if(e.reapGroup)He(n.pid,"SIGKILL");r();let{overflowed:l,text:u}=await a;return{exitCode:c,overflowed:l,stdout:u,timedOut:o.timedOut}}function jN(t,e){let n=e.stdout==="inherit"?"inherit":e.stdout==="capture"?"pipe":_N;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 FN(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,He(t.pid,"SIGKILL");break}r.push(i),o+=i.length}return{overflowed:s,text:new TextDecoder().decode(Buffer.concat(r))}}async function sk(t){He(t.pid,"SIGTERM"),await Promise.race([t.exited,Bun.sleep(PN)]),He(t.pid,"SIGKILL")}var xo=["task","review","both"],Hd="--model",We=[{binary:"claude",command:["claude","-p",Qt,"--permission-mode","acceptEdits"],label:"Claude Code",modelFlag:Hd,name:"claude",reviewCommand:["claude","-p",Qt,"--tools","Read,Grep,Glob","--permission-mode","dontAsk"]},{binary:"codex",command:["codex","exec","--sandbox","workspace-write",Qt],label:"Codex CLI",modelFlag:Hd,name:"codex",reviewCommand:["codex","exec","--sandbox","read-only",Qt]},{binary:"gemini",command:["gemini","--approval-mode","auto_edit","-p",Qt],label:"Gemini CLI",modelFlag:Hd,name:"gemini",reviewCommand:["gemini","--approval-mode","plan","-p",Qt]}];function ik(t){let e=We.find((n)=>n.name===t);if(e!==void 0)return e;throw new v(`ari has no agent preset "${t}"`,`Choose one of: ${We.map((n)=>n.name).join(", ")}, or add the agent to .ari/config.json yourself`)}function ak(t){let e=t??"task",n=xo.find((r)=>r===e);if(n!==void 0)return n;throw new v(`Unknown role "${e}"`,`Choose one of: ${xo.join(", ")}`)}function Ao(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 GN="--version",HN=5000,UN=200;async function ck(){return Promise.all(We.map(KN))}async function KN(t){return{...await Ns([t.binary]),label:t.label,preset:t.name}}async function Ns(t){for(let e of t){let n=Bun.which(e);if(n!==null)return{binary:e,path:n,version:await BN(n)}}return{binary:t[0]??"",path:null,version:null}}async function BN(t){let e;try{e=Bun.spawn([t,GN],{detached:!0,env:{...Ps([]),...Ge},stderr:"ignore",stdin:"ignore",stdout:"pipe"})}catch{return null}let n=()=>He(e.pid,"SIGKILL"),r=te(n),o=setTimeout(n,HN),[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,UN):null}import{isDeepStrictEqual as v0}from"util";import{existsSync as qd,mkdirSync as h0,readFileSync as wk,statSync as y0}from"fs";import{dirname as k0,join as Sk}from"path";import{isDeepStrictEqual as uk}from"util";var VN=/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g,WN=/"(?:[^"\\\n]|\\.)*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,qN=/[^\r\n]/g,JN=/(?:^|\n)([\t ]*)[^\n]*$/,YN=/^[\t ]*\r?\n/,XN=/^[\t ]+(?=\S)/m,zN=" ",Ds=",";function Ud(t){return t.replace(WN,(e)=>e.startsWith('"')?e:e.replace(qN," "))}function Za(t,e){let n=XN.exec(t)?.[0]??zN,r=t.includes(`\r
134
134
  `)?`\r
135
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(`
136
+ `,o=(i,a)=>{let c=t.slice(i.start,i.end);if(uk(i.value,a))return c;let l=r+(JN.exec(t.slice(0,i.start))?.[1]??""),u=(A,R)=>JSON.stringify(A,null,n).replaceAll(`
137
+ `,R);if(!lk(i.value)||!lk(a)||Array.isArray(i.value)!==Array.isArray(a))return u(a,l);let d=ZN(i,a),p=[],g="",f=i.start+1,y=(A)=>{let R=t.slice(f,A);return g+(g.length===0||YN.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 Pt=o(A.node,a[B]);p.push(R+t.slice(A.start,A.node.start)+Pt+t.slice(A.node.end,A.end))}else if(R.trim().length>0)g=R.trimEnd();f=t[A.end]===Ds?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)}),J=y(i.end-1),G=J.trimEnd(),N=C.length===0?J.slice(G.length):l,H=p.length>0&&C.length>0?Ds:"";return c[0]+p.join(Ds)+H+G+C.join(Ds)+N+c.at(-1)},s=QN(Ud(t));return t.slice(0,s.start)+o(s,JSON.parse(JSON.stringify(e)))+t.slice(s.end)}function ZN({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||uk(o.node.value,e[s]))&&Object.hasOwn(e,s))r.set(o,s)}return r}function lk(t){return typeof t==="object"&&t!==null}function QN(t){let e=[...t.matchAll(VN)],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]===Ds?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 pk,readlinkSync as n0,realpathSync as r0,statSync as o0}from"fs";import{basename as s0,dirname as Ls,isAbsolute as i0,join as tc,relative as a0,resolve as gk,sep as c0}from"path";async function Qa(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(!pe(t).includes(o)){if(On(t).includes(o)&&dk(_n(t,o)))throw t0(o);return r}let{contractText:s,task:i}=it(t,o,e);if(!dk(i.record))return r;return{...r,drift:e0(i,s),task:i}}function dk({status:t}){return t==="active"||t==="blocked"}function t0(t){return new m(`the contract of the active task "${t}" is missing`,`Restore ${Ot(t)}`)}function e0({contract:t,record:e},n){if(e.contractHash===null||Vt(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 ${Ot(t.id)}`}var mk=".git",l0="..",ec=0,u0=1,fk=128,d0=40,p0=["rev-parse","--show-toplevel","--absolute-git-dir","--git-common-dir"];function hk(){let t=new Map,e=new Map,n=new Map,r=[],o=(c)=>Kd(t,c,()=>g0(c)),s=(c)=>Kd(e,c.root,async()=>{let l=await f0(c);return r.push(l),l}),i=async(c)=>{let l=[],u=null;for(let d of yk(c).filter((p)=>pk(tc(p,mk)))){let p=await o(d);if(p===null)continue;if(u!==null&&await m0(u,p))break;if(u=p,pk(tc(d,q)))l.push(await s(p))}return l},a=(c)=>{let l=kk(Ut(c));return Kd(n,l,()=>i(l))};return{at:async(c)=>(await a(c))[0]??null,governing:a,opened:()=>r}}function Ut(t,e=d0){let n=Vd(()=>r0(t));if(n!==null)return n;let r=Ls(t);if(r===t)return t;let o=tc(Ut(r,e),s0(t)),s=e>0?Bd(o):null;return s===null?o:Ut(gk(Ls(o),s),e-1)}function Bd(t){return Vd(()=>n0(t))}function nc(t){return Vd(()=>o0(t).isDirectory())??!1}function cn(t,e){let n=a0(t,e),r=n.split(c0);return r[0]===l0||i0(n)?null:r.join("/")}function Vd(t){try{return t()}catch{return null}}function Kd(t,e,n){let r=t.get(e);if(r!==void 0)return r;let o=n();return t.set(e,o),o}function yk(t){let e=Ls(t);return e===t?[t]:[t,...yk(e)]}function kk(t){return nc(t)||Ls(t)===t?t:kk(Ls(t))}async function g0(t){let e=await F(t,p0,{allowedExitCodes:[ec,fk]});if(e.exitCode!==ec)return{fault:`git cannot read the repository at ${t}`,gitDirectories:[tc(t,mk)],root:t};let[n="",r="",o=""]=e.stdout.split(`
138
+ `);if(Ut(n)!==t)return null;let s=[r,gk(t,o)].map((i)=>Ut(i));return{fault:null,gitDirectories:[...new Set(s)],root:t}}async function m0(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:[ec,u0,fk]})).exitCode===ec}async function f0({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 Qa(n)}}catch(r){if(!(r instanceof m))throw r;return{fault:Wd(r),gitDirectories:e,root:n,workspace:null}}}function Wd({hint:t,message:e}){return t===void 0?e:`${e} (${t})`}var w0=2;function rc(t,e){let n=W(t,e);return n===null?null:oe(e,n)}function W(t,e){let n=Sk(t,e);return qd(n)?wk(n,"utf8"):null}function oe(t,e){let n;try{n=JSON.parse(Ud(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 oc(t,e,n){if(!qd(t))return n;try{return e(JSON.parse(wk(t,"utf8")))}catch{return n}}function Jd(t,e,n){return Re(t,e,tr(W(t,e),n))}function tr(t,e){return t===null?`${JSON.stringify(e,null,w0)}
139
+ `:Za(t,e)}function Re(t,e,n){let r=Sk(t,e),o=W(t,e),s=Ms(o,n);if(s!=="unchanged")Or(r,n,S0(r));return s}function Ms(t,e){if(t===e)return"unchanged";return t===null?"created":"updated"}function Or(t,e,n){let r=Ut(t);h0(k0(r),{recursive:!0}),bn(r,e,{mode:n})}function S0(t){return qd(t)?y0(t).mode:void 0}function z(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}var Yd="agents",vk=1;function bk(t,e){let n=ik(e.preset),r=e.name??n.name,o=Ao(n,e.role,e.model),{agents:s,settings:i}=$k(t),a=s[r];if(a!==void 0&&v0(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`,vk,{tag:"AgentExists"});let c={...i,[Yd]:{...s,[r]:o}};return xk(c,`ari cannot add agent "${r}"`,"Choose another name with --name"),{action:Jd(t,rt,c),entry:o,name:r,preset:n.name}}function Ek(t,e){let{agents:n,settings:r}=$k(t);if(n[e]===void 0)return{action:"unchanged",name:e};let{[e]:o,...s}=n,i={...r,[Yd]:s};return xk(i,`ari cannot remove agent "${e}"`,`Change the routing and review settings that name "${e}" in ${rt} first`),Jd(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:Er(o),timeoutSeconds:o.timeoutSeconds??null})),routing:e.routing}}function sc(t){if(t===null)return"none";return t.model===null?t.agent:`${t.agent} (${t.model})`}function $k(t){M(t);let e=rc(t,rt)??{},n=e[Yd]??{};return{agents:z(n)?n:{},settings:e}}function xk(t,e,n){let r=xa(t);if(r!==null)throw new m(`${e}: ${r}`,n,vk,{tag:"InvalidConfig"})}import{existsSync as b0}from"fs";import{join as E0}from"path";async function _r(t,e){let n=T0(t),r=await e();if(n)$0(t);return r}function T0(t){if(!b0(E0(t,q)))return!0;try{return!Nn(Ve(t,M(t)))}catch(e){if(e instanceof m)return!1;throw e}}function $0(t){try{let e=M(t);if(Nn(Ve(t,e)))$o(t,e)}catch(e){if(!(e instanceof m))throw e}}var x0=" ";async function _(){return Xn(process.cwd())}function qe(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 Ie(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 ic(t){return t.flatMap((e)=>A0(e)).join(`
140
+ `)}function A0(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)=>`${x0}${s}`)]);return[e,...n,...r]}var C0=We.map((t)=>t.name).join(", "),R0=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 _()),P0)}}),I0=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: ${xo.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: ${C0}`,required:!0}}),run:async(t)=>{let e=await _(),n=await _r(e,()=>bk(e,{model:Ie(t.args.model,"--model"),name:Ie(t.args.name,"--name"),preset:t.positionals.preset,role:ak(t.args.role)}));t.output.result(n,Ck)}}),O0=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 _r(e,()=>Ek(e,t.positionals.name)),Ck)}}),_0=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 ck()},({agents:e})=>e.map(N0).join(`
142
+ `))}}),Ak=E({description:"Configure the agents that 'ari run' and 'ari review' start",name:"agents",subcommands:[R0,I0,O0,_0]});function P0(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}: ${sc(c)}`),i=[`routing default: ${sc(n)}`,...s,`routing review: ${sc(r)}`];return[...e.length===0?["No agents are configured; run 'ari agents add <preset>'"]:e,...i].join(`
143
+ `)}function Ck(t){return`Agent "${t.name}" ${t.action} in .ari/config.json`}function N0(t){if(t.path===null)return`${t.preset} not found on PATH`;return`${t.preset} ${t.path} ${t.version??"version unknown"}`}import{existsSync as TH}from"fs";import{join as $H}from"path";import{resolve as M0}from"path";var D0=/^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)/,L0=/\r?\n/;function js(t,e){return typeof t==="object"&&t!==null?t[e]:void 0}function qt(t,e){let n=js(t,e);return typeof n==="string"?n:null}function ac(t,e){return qt(t,"cwd")??e}function Rk(t){return t.split(L0).flatMap((e)=>D0.exec(e.trim())?.[1]?.trim()??[])}function Fs(t,e,n){return{command:n.command??null,cwd:e,event:t,paths:n.paths??[],tool:n.tool??null}}var Xd=["before-edit","before-shell","after-tool","stop","pre-compact","session-start"],Dn=new Set(["before-edit","before-shell"]);function Ik(t){return Xd.includes(t)}var j0=30,F0=120,G0=new Set(["stop","pre-compact"]),H0=1000,U0="apply_patch",Ok="run_shell_command";function mt(t,e,n=null){let r=G0.has(t)?F0:j0;return{agentEvent:e,event:t,matcher:n,timeoutSeconds:r}}var _k=[mt("stop","Stop"),mt("pre-compact","PreCompact","manual|auto"),mt("session-start","SessionStart","startup|resume|clear|compact|fork")];function Zd(t){return{decision:"block",reason:t}}function zd(t){return(e)=>({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t,permissionDecisionReason:e}})}function Pk(t,e,n){let r=js(e,"tool_input"),o=qt(r,"file_path")??qt(r,"notebook_path"),s=qt(r,"command"),i=qt(e,"tool_name"),a=i===Ok?qt(r,"dir_path"):null;return Fs(t,M0(ac(e,n),a??""),{command:s,paths:o===null?[]:[o],tool:i})}function K0(t,e,n){let r=qt(e,"tool_name"),o=qt(js(e,"tool_input"),"command"),s=r===U0?{paths:Rk(o??"")}:{command:o};return Fs(t,ac(e,n),{...s,tool:r})}function B0(t,e,n){let r=qt(e,"cwd")??qt(js(e,"workspace_roots"),"0")??n,o=qt(e,"file_path");return Fs(t,r,{command:qt(e,"command"),paths:t==="after-tool"&&o!==null?[o]:[]})}function V0(t,e,n){return Fs(t,ac(e,n),{command:qt(W0(e),"command"),tool:qt(e,"toolName")})}function W0({toolArgs:t}){if(typeof t!=="string")return t;try{return JSON.parse(t)}catch{return null}}function Qd({answers:t},e,n){let r=q0(t,e,n);return typeof r==="string"?r:JSON.stringify(r)}function q0(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:zd("ask"),block:Zd,context:(t)=>t,deny:zd("deny")},file:".claude/settings.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,...Dn.has(e)?{onFailure:"block"}:{},timeout:n,type:"command"}),label:"Claude Code",layout:"grouped",name:"claude",parse:Pk,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"),..._k],support:"verified"},Y0={answers:{allow:(t)=>t==="stop"?{}:"",block:Zd,context:(t)=>t,deny:zd("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:K0,registrations:[mt("before-edit","PreToolUse","^apply_patch$"),mt("before-shell","PreToolUse","^Bash$"),mt("after-tool","PostToolUse","^(Bash|apply_patch)$"),..._k],support:"verified"},X0={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*H0,type:"command"}),label:"Gemini CLI",layout:"grouped",name:"gemini",parse:Pk,registrations:[mt("before-edit","BeforeTool","write_file|replace"),mt("before-shell","BeforeTool",Ok),mt("after-tool","AfterTool","write_file|replace|run_shell_command"),mt("stop","AfterAgent","*"),mt("pre-compact","PreCompress","*"),mt("session-start","SessionStart","*")],support:"verified"},z0={answers:{allow:(t)=>Dn.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,...Dn.has(e)?{failClosed:!0}:{},timeout:n}),label:"Cursor",layout:"flat",name:"cursor",parse:B0,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)=>Dn.has(t)?{permissionDecision:"allow"}:"",block:Zd,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:V0,registrations:[mt("before-shell","preToolUse","bash|powershell"),mt("stop","agentStop"),mt("pre-compact","preCompact"),mt("session-start","sessionStart")],support:"partial"},Oe=[J0,Y0,X0,z0,Z0];import{existsSync as Gs,readFileSync as Mk,rmSync as Q0,statSync as tD}from"fs";import{join as Hs,relative as ep}from"path";var jk="# ari:managed",eD=493,nD=64,rD=1,Nk=0,Co=[{command:"ari scope --staged",name:"pre-commit"},{command:"ari verify",name:"pre-push"}],oD=["","."].flatMap((t)=>["yml","yaml","json","toml"].map((e)=>`${t}lefthook.${e}`)),Dk=".husky",Lk=/\.ya?ml$/,Fk=Co.map((t)=>t.name);async function Ro(t){let e=await sn(t,"hooks");return Co.every(({name:n})=>{let r=Hs(e,n);return np(r)&&Hk(r)})}async function lc(t){let e=await Us(t);for(let n of e)if(n.action!=="unchanged")Or(n.target,n.script,eD);return{agent:"git",files:e.map(({action:n,hook:r,path:o})=>({action:n,hook:r,path:o}))}}async function Us(t){let e=await rp(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=Co.map((s)=>({hook:s,path:Hs(n,s.name),script:sD(s)})),o=r.filter(({path:s})=>Gs(s)&&!np(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: ${cc("").join("; ")}`)}return r.map(({hook:s,path:i,script:a})=>{let c=Gs(i);return{action:c&&Mk(i,"utf8")===a&&Hk(i)?"unchanged":c?"updated":"created",hook:s.name,path:ep(t,i),script:a,target:i}})}async function Gk(t){return ep(t,await sn(t,"hooks"))}async function Ks(t){let e=await sn(t,"hooks");return Co.map(({name:n})=>{let r=Hs(e,n);return{action:np(r)?"removed":"unchanged",hook:n,path:ep(t,r),target:r}})}async function uc(t){let e=await Ks(t);for(let n of e)if(n.action==="removed")Q0(n.target);return{agent:"git",files:e.map(({action:n,hook:r,path:o})=>({action:n,hook:r,path:o}))}}function np(t){return Gs(t)&&Mk(t,"utf8").includes(jk)}function Hk(t){return(tD(t).mode&nD)!==0}function sD(t){return["#!/bin/sh",jk,"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 rp(t){let e=await F(t,["config","--get","core.hooksPath"],{allowedExitCodes:[Nk,rD]}),n=e.stdout.trim();if(e.exitCode===Nk&&n.length>0)return tp(`core.hooksPath (${n})`,cc(`${n}/`),"Add the lines yourself: ");let r=oD.find((o)=>Gs(Hs(t,o)));if(r!==void 0){let o=Lk.test(r)?iD():cc("lefthook ");return tp(`lefthook (${r})`,o,Lk.test(r)?`Add to ${r}:
145
+ `:"Add the lines yourself: ")}if(Gs(Hs(t,Dk)))return tp("husky",cc(`${Dk}/`),"Add the lines yourself: ");return null}function cc(t){return Co.map((e)=>`${t}${e.name}: ${e.command}`)}function tp(t,e,n){let r=n.endsWith(`
146
146
  `)?`
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=`
147
+ `:"; ";return{hint:`${n}${e.join(r)}`,lines:e,name:t}}function iD(){return Co.flatMap((t)=>[`${t.name}:`," commands:",` ari-${t.name}:`,` run: ${t.command}`])}import{realpathSync as aD,rmSync as cD}from"fs";import{join as dc}from"path";var pc={read:W,remove:(t,e)=>{cD(aD(dc(t,e)))},write:(t,e,n)=>{Re(t,e,n)}};function op(){let t=new Map;return{read:(e,n)=>{let r=dc(e,n);return t.has(r)?t.get(r)??null:W(e,n)},remove:(e,n)=>{t.set(dc(e,n),null)},write:(e,n,r)=>{t.set(dc(e,n),r)}}}var Bs={kind:"none"},Vs={kind:"delete"};function Io(t,e){return{exact:e,kind:"write",text:t}}function gc(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=Ms(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 lD,readFileSync as uD}from"fs";import{join as sp}from"path";var ip="hooks.json",dD=384,Uk=lh(Et({installed:X(),original:X().or(Wn())}));function Kk(t,e=ip){let n=sp(t,e);if(!lD(n))return{state:"absent"};try{return{path:n,receipts:Uk(JSON.parse(uD(n,"utf8"))),state:"readable"}}catch{return{path:n,state:"unreadable"}}}function Oo(t,e,n=ip){return Bk(t,n)[e]??null}function _o(t,e,n,r=ip){let{[e]:o,...s}=Bk(t,r);if(n===null&&o===void 0)return;let i=n===null?s:{...s,[e]:n};Or(sp(t,r),`${JSON.stringify(i)}
148
+ `,dD)}function Bk(t,e){return oc(sp(t,e),Uk,{})}var pD="ari hook",gD=1;function ap(t,e){return`${pD} ${t} ${e}`}function qk(t,e,n){let{file:r,name:o}=e,s=W(t,r),i=s===null?{}:oe(r,s),a=Oo(n,r),c=lp(i,e)?void 0:s,l=a?.installed===s?a?.original:c,u=Re(t,r,Ws(e,s)),d=W(t,r)??"";return _o(n,r,l===void 0?null:{installed:d,original:l}),{action:u,agent:o,events:qs(e),file:r}}function Ws(t,e){let n=e===null?{}:oe(t.file,e);return tr(e,Jk(n,t,t.registrations))}function mc(t,e,n){let{action:r}=cp(t,e,{forget:!0,state:n,view:pc});return{action:r,agent:e.name,file:e.file}}function mD(t,e,n){if(e===null)return Bs;let r=oe(t.file,e);if(!lp(r,t))return Bs;if(n?.installed!==e)return Io(tr(e,Jk(r,t,[])),!1);return n.original===null?Vs:Io(n.original,!0)}function cp(t,e,n){let{file:r}=e,{forget:o,state:s,view:i}=n,a=Oo(s,r),c=gc(t,r,mD(e,i.read(t,r),a),i);if(o)_o(s,r,null);return c}function un(t,e){let n=rc(t,e.file);return n!==null&&lp(n,e)}function qs(t){return[...new Set(t.registrations.map((e)=>e.event))]}function lp({hooks:t},e){if(!z(t))return!1;return Object.values(t).flat().some((n)=>Yk(n,e).length>0)}function Jk({hooks:t={},...e},n,r){if(!z(t))throw Vk(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 Vk(n,`hooks.${a} that is not a list`);let l=fD(c,n,r.filter(({agentEvent:u})=>u===a));return l.length===0&&c.length>0?[]:[[a,l]]}),i=n.layout==="flat"?{version:e.version??gD}:{};return{...e,...i,...s.length===0?{}:{hooks:Object.fromEntries(s)}}}function Vk({file:t},e){return new m(`${t} has a ${e}`,`Fix ${t}`)}function fD(t,e,n){let r=new Set(n);return[...t.flatMap((s)=>{let i=Yk(s,e),a=[...r].filter(({event:c})=>i.includes(ap(e.name,c)));for(let c of a)r.delete(c);return[...hD(s,e),...a.map((c)=>Wk(e,c))]}),...[...r].map((s)=>Wk(e,s))]}function Wk(t,e){let n=t.handler(ap(t.name,e.event),e);if(t.layout==="flat")return n;return e.matcher===null?{hooks:[n]}:{hooks:[n],matcher:e.matcher}}function hD(t,e){let n=Xk(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 Yk(t,e){return Xk(t,e).flatMap((n)=>zk(n,e))}function Xk(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=ap(e,"");return n.filter((o)=>typeof o==="string"&&o.startsWith(r))}import{join as L1,resolve as Dv}from"path";var Zk=1.2,Qk=0.75,tw=0.5,yD=/[\p{Variation_Selector}\p{Me}]/gu,kD=/[\p{L}\p{N}][\p{L}\p{M}\p{N}]*/gu;function ew(t){return t.normalize("NFC").toLowerCase().replace(yD,"").match(kD)??[]}function fc(t,e){let n=[...new Set(ew(t))].sort(O),r=e.map(wD),o=r.reduce((a,c)=>a+c.length,0),s=r.length===0?0:o/r.length,i=new Map(n.map((a)=>[a,SD(a,r)]));return r.map((a)=>({id:a.id,score:vD(a,n,i,s)})).sort((a,c)=>c.score-a.score||O(a.id,c.id))}function wD(t){let e=ew(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 SD(t,e){let n=e.filter((r)=>r.frequencies.has(t)).length;return Math.log(1+(e.length-n+tw)/(n+tw))}function vD(t,e,n,r){let o=r===0?1:t.length/r,s=Zk*(1-Qk+Qk*o);return e.reduce((i,a)=>{let c=t.frequencies.get(a)??0,l=n.get(a)??0;return i+l*c*(Zk+1)/(c+s)},0)}function yt(t){return Buffer.byteLength(t,"utf8")}function up(t){return Math.ceil(yt(t)/4)}import{readFileSync as Qw}from"fs";import{join as tS}from"path";var bD=1000,ED=2147483647,TD=60,sw=8192,iw=sw*2,$D=1000,xD=`exec 2>&1
149
+ `,AD=192,CD=128,nw=`
150
+ `,RD=[126,127],rw=128,ID=31;async function aw(t,e){let n=performance.now(),r=Bun.spawn(["sh","-c",`${xD}${t}`],{cwd:e.cwd,detached:!0,env:{...process.env,...Ge},stderr:"pipe",stdin:"ignore",stdout:"pipe"}),o=te(()=>dp(r.pid));try{return await OD(r,t,e,n)}finally{o()}}async function OD(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)=>_D(u,o))),a={timedOut:!1},c=setTimeout(()=>{a.timedOut=!0,dp(t.pid)},Math.min(n.timeoutSeconds*bD,ED));await t.exited,clearTimeout(c);let l=await PD(i,$D);if(dp(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:dw(o.window),timedOut:a.timedOut}}function cw(t){return t.exitCode===0&&!t.timedOut}function lw(t){return t.exitCode!==0&&!t.timedOut&&!pp(t)&&!gp(t)}function pp(t){let{exitCode:e}=t;return e===null||e>rw&&e<=rw+ID}function gp(t){return t.exitCode!==null&&!t.timedOut&&RD.includes(t.exitCode)}async function _D(t,e){for(;;){let{done:n,value:r}=await t.read();if(n)return;e.hasher.update(r),e.window=mp(ND(e.window,r),iw)}}async function PD(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 dp(t){He(t,"SIGKILL")}function uw(t){return dw(mp(new TextEncoder().encode(t),iw))}function dw(t){let n=new TextDecoder().decode(ow(t)).split(nw);if(n.at(-1)==="")n.pop();let r=new TextEncoder().encode(n.slice(-TD).join(nw));return new TextDecoder().decode(ow(mp(r,sw)))}function ow(t){let e=0;while(e<t.length&&((t[e]??0)&AD)===CD)e++;return t.subarray(e)}function mp(t,e){return t.length<=e?t:t.subarray(t.length-e)}function ND(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 aw(o.run,{cwd:n,timeoutSeconds:o.timeoutSeconds});r.push(DD(o.name,e,s))}return r}async function Js(t,e,n,r,o){return await Qn(t,e),Je(n,r,o)}function DD(t,e,n){let r=e==="pass"?cw(n):lw(n);return{...n,expect:e,name:t,ok:r}}function fp(t){return`${t.name} should ${t.expect} but ${LD(t)}`}function Pr(t){return t.filter((e)=>!e.ok).map(fp)}function wt(t,e,n){return t===1?e:n}function LD(t){if(t.timedOut)return`timed out after ${t.durationMs} ms`;if(gp(t))return`could not run (exit code ${t.exitCode})`;if(!pp(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 WD,mkdirSync as qD,readlinkSync as JD,rmSync as yp,symlinkSync as YD}from"fs";import{dirname as XD,join as yc}from"path";import{existsSync as MD,mkdtempSync as jD,readFileSync as FD,realpathSync as GD,rmSync as pw}from"fs";import{tmpdir as HD}from"os";import{join as hp}from"path";var Ys=0,gw=128,UD="gitdir",KD=".git",BD=["-c","core.hooksPath=/dev/null"];async function hc(t,e,n){let r=GD(jD(hp(HD(),Os))),o={admin:null,directory:r},s=te(()=>mw(t,o));try{return await VD(t,e,o),await n(r)}finally{mw(t,o),s()}}async function VD(t,e,n){let{directory:r}=n,o=await F(t,[...BD,"worktree","add","--detach",r,e],{allowedExitCodes:[Ys,gw],env:{GIT_INDEX_FILE:void 0}});if(o.exitCode!==Ys)throw Error(`git worktree add ${r} ${e} failed in ${t}: ${Ed(o.stderr)}`);let s=await F(r,["rev-parse","--absolute-git-dir"],{allowedExitCodes:[Ys,gw],env:Ge}),i=s.stdout.trim();if(s.exitCode===Ys&&fw(i,r))n.admin=i}function mw(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(pw(r,{force:!0,recursive:!0}),o.exitCode===Ys||n===null)return;if(fw(n,r))pw(n,{force:!0,recursive:!0})}function fw(t,e){let n=hp(t,UD);return MD(n)&&FD(n,"utf8").trim()===hp(e,KD)}var zD="@base",ZD=12;async function hw(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=re(t.changedFiles).filter((p)=>et(p,t.config.testGlobs)),o=await hc(t.root,t.base,(p)=>QD(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=[...Pr(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 QD(t,e,n,r){for(let a of n)eL(t.root,r,a);let o=tL(t.config),s=o.length===0?[]:await Js({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}${zD}`}));return{checks:await Je(i,"fail",r),setup:s}}function tL(t){return t.regression.setup.map((e,n)=>({name:`setup[${n}]`,run:e,timeoutSeconds:t.checkTimeoutSeconds}))}function eL(t,e,n){let r=yc(t,n),o=yc(e,n),s=xe(t,n)?null:$e(r);if(s===null){nL(e,n);return}if(!s.isFile()&&!s.isSymbolicLink())return;if(yw(e,n),yp(o,{force:!0,recursive:!0}),s.isFile())WD(r,o);else YD(JD(r),o)}function nL(t,e){let n=yc(t,e);if(xe(t,e)||$e(n)?.isDirectory()!==!1)return;yp(n,{force:!0})}function yw(t,e){let n=XD(e);if(n===".")return;yw(t,n);let r=yc(t,n),o=$e(r);if(o?.isDirectory())return;if(o!==null)yp(r,{force:!0});qD(r)}import{readFileSync as xM}from"fs";import{join as AM}from"path";var er="candidates",rL=["confirmed","false_positive","deferred","uncertain"],oL=["id","verdict","rationale"],kp="argus verdicts: ";function kw(t,e){if(t===void 0)return{answers:[],warnings:[]};if(!Array.isArray(t))return iL(`${er} must be a list, so no answer was sent`);let n=[],r=[];for(let[i,a]of t.entries())try{r.push(sL(a,k(er,i),e))}catch(c){if(!(c instanceof b))throw c;n.push(`${kp}${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(`${kp}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 sL(t,e,n){let r=T(t,e,oL),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(rL,r.verdict,k(e,"verdict"))}}function iL(t){return{answers:[],warnings:[`${kp}${t}`]}}import{realpathSync as _w}from"fs";import{readFileSync as aL,realpathSync as cL}from"fs";import{join as lL,sep as uL}from"path";var dL="reviews",ww=8,pL=/^[a-f0-9]{64}$/,gL=Et({reviewer:Et({promptVersion:X()}),snapshotId:X(),verdicts:so(Et({reviewId:X()}))});function Sw(t,e,n){let r=lL(n.stateDirectory,dL),o;try{let l=cL(t.verdictFile);if(!l.startsWith(`${r}${uL}`))return`its verdict template ${t.verdictFile} is not in ${r}`;o=gL(JSON.parse(aL(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)=>pL.test(l))),a=e.filter((l)=>i.has(l.reviewId)),c=mL(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 mL(t){let e=Math.max(ww,...t.map((n)=>n.length));for(let n=ww;n<e;n+=1)if(new Set(t.map((r)=>r.slice(0,n))).size===t.length)return n;return e}function vw(t,e){return new Map(t.slice(0,e).flatMap((n)=>n.id===void 0?[]:[[n.id,n.reviewId]]))}var bw="ArgusStartFailed",wp=16777216,fL=1;async function kc(t,e,n,r){try{return await Gd(n,{action:e==="import"?"start argus to import review verdicts":"start argus to collect review evidence",cwd:t.root,environment:Ps($a(e)),maxCaptureBytes:wp,reapGroup:!0,startFailure:(o,s)=>new m(`argus could not start: ${o}`,"Install argus or fix review.argus.command",fL,{cause:s,tag:bw}),stdout:"capture",timeoutSeconds:r,trust:{config:t.config,root:t.root}})}catch(o){if(o instanceof m&&o._tag===bw)return o.message;throw o}}var hL=1,yL=300,Ew="...",kL=/\p{Cc}+/gu,wL=Et({choice:X(),confidence:Sr()}),SL=Et({evaluation:Et({answer:wL}).or(Wn()),flagged:wa(),line:Sr(),path:X(),question:X(),reviewId:X(),status:X(),target:X()}),vL=Et({results:so(SL),root:X(),snapshotId:X().or(Wn()).or(ju()),verdictFile:X().or(Wn()).or(ju())}),bL=Et({error:Et({message:X()})});function $w(t,e){let n;try{n=JSON.parse(t)}catch{return{kind:"invalid"}}let r=Tw(()=>vL(n));if(r!==null)return EL(r,e);let o=Tw(()=>bL(n));if(o===null)return{kind:"invalid"};return{kind:"failure",message:Xs(o.error.message,yL)}}function EL(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<hL)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:TL(t)}}function TL(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 Xs(t,e){let n=t.replace(kL," ").trim();return n.length>e?`${n.slice(0,e-Ew.length)}${Ew}`:n}function Tw(t){try{return t()}catch{return null}}import{existsSync as xL,realpathSync as Aw}from"fs";import{dirname as AL,join as CL,relative as RL,resolve as IL,sep as Cw}from"path";var OL=["cache","reports","reviews","verifications"],_L="ari-probe",Rw=1,xw=0,PL=1;function Iw(t,e){let n=IL(t,e);if(!xL(n))return{location:null,problem:`the argus config ${e} does not exist`};try{return{location:{configPath:n,stateDirectory:Aw(AL(n))},problem:null}}catch{return{location:null,problem:`the directory of the argus config ${e} cannot be read`}}}async function Ow(t,e){let n=Aw(t);for(let r of OL){let o=CL(e.stateDirectory,r);if(!NL(n,o))continue;let s=RL(n,o).split(Cw).join("/");if(await DL(t,`${s}/${_L}`))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`,Rw,{tag:"ArgusStateInRepository"})}}async function wc(t,e,n="collected evidence"){if(await Ce(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",Rw,{tag:"ArgusChangedTree"})}function NL(t,e){return e===t||e.startsWith(`${t}${Cw}`)}async function DL(t,e){try{return(await F(t,["check-ignore","--quiet","--",e],{allowedExitCodes:[xw,PL]})).exitCode===xw}catch{return!1}}var LL=1,ML=500,Pw={blocked:0,checked:0,pending:0},jL=/[\\*?[\]{}()!@+,#]/g,FL="argus (run) was allowed to send the source of the changed files to its model endpoint",GL=0,HL=1;async function Nw(t){let{argus:e,changedFiles:n,root:r}=t,o=e.mode==="run"||e.verdicts===!0,s=o?VL(n):{files:[],warnings:[]};if(o?s.files.length===0:n.length===0)return vc(e.mode,!0,[],Pw,[]);let a=Iw(r,e.config);if(a.location===null)return Sc(t,a.problem);await Ow(r,a.location);let c={base:t.base,configPath:a.location.configPath,only:s.files.map(WL).join(`
151
+ `)};if(e.mode==="run")t.notify?.(JL(e.limit));let l=await UL(t,c);if(typeof l==="string")return Sc(t,l);if(e.verdicts!==!0)return vc(e.mode,!0,l.candidates,l.counts,s.warnings);if(l.snapshot===null)return Sc(t,"argus report create saved no snapshot");let u=Sw(l.snapshot,l.candidates,a.location);if(typeof u==="string")return Sc(t,u);return{...vc(e.mode,!0,u.candidates,l.counts,s.warnings),offer:u.offer}}function Dw(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 UL(t,e){let n="argus was not asked anything";for(let r of Ta(t.argus).filter((o)=>o!=="import"))if(n=await KL(t,r,e),typeof n==="string")return n;return n}async function KL(t,e,n){let r=t.argus.timeoutSeconds??t.config.checkTimeoutSeconds,o=await kc(t,e,lo(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 ${wp} bytes`;let s=$w(o.stdout,new Set(t.changedFiles));if(s.kind==="failure")return`argus failed: ${s.message}`;if(s.kind==="invalid"||![GL,HL].includes(o.exitCode))return`argus exited with ${o.exitCode} and did not print its JSON report`;if(!qL(s.root,t.root))return`its project root ${s.root} is not the root of this repository`;return s}function bc(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?[FL]:[];return[`argus (${o}): ${e} candidates in the changed files, ${c}; ${l}`,...u,...t.verdicts===void 0?[]:[BL(t.verdicts)],...t.warnings]}function BL({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 Sc(t,e){if(!t.explicit&&t.verdictsExplicit!==!0)return vc(t.argus.mode,!1,[],Pw,[`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`,LL,{tag:"ArgusUnavailable"})}function vc(t,e,n,r,o){return{candidates:n,counts:r,mode:t,offer:null,used:e,warnings:o}}function VL(t){let e=t.filter((s)=>!s.includes(`
152
+ `)),n=e.slice(0,ML),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 WL(t){return t.replace(jL,"\\$&")}function qL(t,e){try{return _w(t)===_w(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 YL,rmSync as XL,writeFileSync as zL}from"fs";import{tmpdir as ZL}from"os";import{join as Lw}from"path";var QL="verdicts.json",tM=384,eM=2,nM=300,Mw="argus verdicts: ",rM=Et({imported:Sr()}).or(Et({error:Et({message:X()})}));async function jw(t){let{answers:e}=t;if(e.length===0)return{saved:0,sent:0,warnings:[]};let n=YL(Lw(ZL(),Ay)),r=()=>XL(n,{force:!0,recursive:!0}),o=te(r);try{let s=Lw(n,QL);return zL(s,`${JSON.stringify(sM(t),null,eM)}
153
+ `,{mode:tM}),await oM(t,s)}finally{r(),o()}}async function oM(t,e){let{answers:n,base:r,context:o,offer:s,seconds:i}=t,a=lo(o.argus,"import",{base:r,configPath:s.configPath,file:e,only:null}),c=n.length,l=await kc(o,"import",a,i);if(typeof l==="string")return Ec(c,l);if(l.timedOut)return Ec(c,`argus did not finish importing within ${i} seconds`);let u=iM(l.stdout);if(u===null)return Ec(c,`argus exited with ${l.exitCode} and did not print its JSON result`);if("error"in u)return Ec(c,`argus rejected the verdicts: ${Xs(u.error.message,nM)}`);let d=u.imported<c?[`${Mw}argus saved ${u.imported} of ${c} verdicts`]:[];return{saved:u.imported,sent:c,warnings:d}}function sM({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 iM(t){try{return rM(JSON.parse(t))}catch{return null}}function Ec(t,e){return{saved:0,sent:t,warnings:[`${Mw}${e}; nothing was saved, and the review is not affected`]}}var aM="argus verdicts: the review did not finish cleanly, so no answer was sent";async function Fw(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=kw(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?[]:[aM]]};let d=o.argus.timeoutSeconds??o.config.checkTimeoutSeconds,p=await jw({answers:l.answers,base:o.base,context:o,model:s,offer:c,seconds:d});if(p.sent>0)await wc(o.root,e,"imported the verdicts");return{verdicts:{...u,saved:p.saved,sent:p.sent},warnings:[...l.warnings,...p.warnings]}}var cM=120,lM=2,Nr=`
154
+ `,uM="## Candidates from a decision model (not verified defects)",Gw=["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(Nr),dM=[`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 "${er}" key:`,`"${er}":[{"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(Nr);function Uw(t,e){let r=t.some((a)=>a.id!==void 0)?`${Gw}${Nr}${dM}`:Gw,o=`${uM}${Nr}${Nr}${r}${Nr}`,s=[];for(let a of t){let c=[...s,pM(a)],l=Hw(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:Hw(o,s,i,e)}}function Hw(t,e,n,r){let o=n===0?[]:[gM(n,r)];return[t,...e,...o].join(Nr)}function pM(t){let e=`${Tc(t.path)}:${t.line}`,n=t.confidence.toFixed(lM);return`- ${t.id===void 0?"":`[${t.id}] `}${e} ${Tc(t.target)}: question "${Tc(t.question)}", answer "${Tc(t.answer)}", confidence ${n}`}function gM(t,e){return`(${t} more candidate${t===1?"":"s"} left out to stay within ${e} bytes)`}function Tc(t){return Xs(t.replaceAll('"',"'"),cM)}var Sp=["critical","major","minor","info"],mM=["critical","major"],fM=["pass","fail"],hM=["verdict","findings"],Kw=["severity","file","line","summary"],yM=/^```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```$/;function Bw(t,e=[]){let n=t.trim();if(n.length===0)return{extras:{},problem:"the review agent printed nothing",verdict:null};let r=yM.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",[...hM,...e]);return{extras:Object.fromEntries(e.filter((a)=>(a in s)).map((a)=>[a,s[a]])),problem:null,verdict:kM(s)}}catch(s){if(s instanceof b)return{extras:{},problem:`the review agent's answer: ${s.message}`,verdict:null};throw s}}function Vw(t){return t.findings.filter((e)=>mM.includes(e.severity))}function $c(t){let e=t.file===null?"":` ${t.file}${t.line===null?"":`:${t.line}`}`;return`${t.severity}${e}: ${t.summary}`}function kM(t){let e=K(fM,t.verdict,"verdict");return{findings:L(t.findings,"findings",wM),verdict:e}}function wM(t,e){let n=T(t,e,Kw);for(let r of Kw)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:Bt(n.line,k(e,"line")),severity:K(Sp,n.severity,k(e,"severity")),summary:nt(n.summary,k(e,"summary"))}}var qw=120000,SM=20000,vM=3,bM=12,zs=`
155
155
 
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(`
156
+ `,Ww="```",EM='{"verdict":"fail","findings":[{"severity":"major","file":"src/a.ts","line":12,"summary":"\u2026"}]}';function Jw(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:",EM,'- "verdict" is "pass" when the change meets the contract and has no critical or major problem, otherwise "fail".',`- "severity" is one of ${Sp.join(", ")}; "file" and "line" may be null; "findings" may be empty.`].join(`
158
158
  `),`## Contract (${t.contractPath})
159
159
 
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
160
+ ${t.contractText.trim()}`,[`## Files changed since ${t.base.slice(0,bM)}`,"",...t.changedFiles.length===0?["(none)"]:t.changedFiles.map((c)=>`- ${c}`)].join(`
161
+ `)].join(zs),o=TM(t,r),s=o===null?r:[r,o.text].join(zs),i=qw-Buffer.byteLength(s)-zs.length*2,a=[s,`## Diff
162
162
 
163
- ${Jw}diff
163
+ ${Ww}diff
164
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=`
165
+ ${Ww}`].join(zs);return{argus:o,prompt:a}}function TM(t,e){if(t.argus===void 0)return null;let n=qw-Buffer.byteLength(e)-zs.length*vM;return Uw(t.argus.candidates,Math.max(0,Math.min(t.argus.maxBytes,n-SM)))}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 CM={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"},Yw=["--no-color","--no-ext-diff","--no-textconv","--no-renames"],Xw=[":(glob,exclude).ari/tasks/*.json",":(glob,exclude).ari/knowledge/**"],RM="review:",IM=1;async function zw(t){let{config:e,root:n,task:r}=t,{agent:o,model:s}=e.review,i=Ir(e,{agent:o,model:s,role:"review",route:null}),a=xM(AM(n,Ot(r.contract.id)),"utf8"),{argus:c}=e.review,l=await vp({...t,contractText:a,...c===void 0?{}:{argus:{argus:c,explicit:!1}}},i),u=l.ok?"passed":"failed",d=[...l.problems,...l.findings.map($c),...l.argus===void 0?[]:bc(l.argus)],p=`the review agent ${l.agent} ${u} the change`;return kt("review",l.ok,p,d,[l.evidence])}async function vp(t,e){let{config:n,root:r,task:o}=t,s=_M(o);await Qn({config:n,root:r},`start the agent "${e.name}"`);let i=await Ce(r,[]),a=await OM(r,i,s,o.contract.id),c=Be((await F(r,["diff","--name-only","-z",...Yw,s,a,"--",".",...Xw])).stdout),l=t.argus===void 0?null:await Nw({...t.argus,base:s,changedFiles:c,config:n,root:r});if(l!==null)await wc(r,i);let u=(await F(r,["diff",...Yw,s,a,"--",".",...Xw])).stdout,{argus:d,prompt:p}=Jw({...l===null||t.argus===void 0?{}:{argus:{candidates:l.candidates,maxBytes:t.argus.argus.maxBytes}},base:s,changedFiles:c,contract:o.contract,contractPath:Ot(o.contract.id),contractText:t.contractText,diff:u,stage:t.stage}),g=e.config.timeoutSeconds??n.checkTimeoutSeconds,f=performance.now(),y=await hc(r,a,async(Q)=>{let Zr=await za(e,p,{cwd:Q,environment:Xa(e.config),stdout:"capture",timeoutSeconds:g,trust:{config:n,root:r}});return{copyChanged:await Ce(Q,[])!==i,ran:Zr}}),S=Math.round(performance.now()-f),I=await Ce(r,[])!==i,{ran:C}=y,J=d===null||l===null?new Map:vw(l.candidates,d.included),G=Bw(C.stdout,J.size===0?[]:[er]),N=G.verdict===null?[]:Vw(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:Ya(e,Qt).join(" "),durationMs:S,exitCode:C.timedOut?null:C.exitCode,expect:"pass",name:`${RM}${e.name}`,ok:R,outputSha256:Z(C.stdout),outputTail:uw(C.stdout),timedOut:C.timedOut},Pt=l===null||t.argus===void 0?null:await Fw({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:J,written:G.extras[er]});return{agent:e.name,...l===null?{}:{argus:Dw(l,d,Pt??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 OM(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:CM})).stdout.trim()}function _M(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`,IM,{tag:"TaskNotStarted"})}var PM="{id}",NM=[".ari/tasks/**",".ari/knowledge/**"];async function Ep(t){let e=Ln(t.task,t.pack),r={...t,changedFiles:()=>Ae(t.root,nS(t.task)),stage:e},o=[],s=[];for(let[i,a]of e.gates.entries()){let c=await DM(a,r);if(o.push(c),c.ok&&KM(a)&&i<e.gates.length-1)s.push({index:i,result:await BM(a.kind,c,r)})}for(let i of s)o[i.index]=await i.result();return o}function Ln(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 Zs(t,e,n){let r=await Cn(t,e.testGlobs);return Object.fromEntries(Object.entries(r).filter(([o])=>!vo(o)&&et(o,n.scope)))}async function Tp(t,e,n){let o=e.gates.flatMap((s)=>s.kind==="artifact"?[Po(s.path,n)]:[]).flatMap((s)=>{let i=tS(t,s);return Sd(i)?.isFile()?[[s,Z(Qw(i))]]:[]});return{artifactHashes:Object.fromEntries(o),treeHash:await Ce(t,NM)}}function Qs(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 DM(t,e){switch(t.kind){case"criteria":return LM(e.task.contract);case"checks":return MM(t.select,t.expect,e);case"invariants":return jM(e);case"scope":return FM(e);case"locked":return GM(e);case"tests-unchanged":return HM(e);case"regression":return hw({base:nS(e.task),changedFiles:await e.changedFiles(),config:e.config,contract:e.task.contract,root:e.root});case"artifact":return UM(t,e);case"approval":return $p("approval",e);case"review":return VM(e);case"command":return WM(t.run,e)}}function LM(t){let e=id(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 MM(t,e,n){let r=ho(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=Pr(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 jM(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=Pr(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 FM(t){let e=re(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 GM(t){let e=await Cn(t.root,t.task.contract.lock),n=Qs(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 HM(t){let e=await Zs(t.root,t.config,t.task.contract),n=Qs(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 UM(t,e){let{contract:n}=e.task,r=Po(t.path,n.id),o=tS(e.root,r),s=Sd(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=oy({contractPath:Ot(n.id),criteria:n.criteria.map((g)=>g.id),path:r,requirements:{sections:t.sections??[],traceable:t.traceable===!0},text:Qw(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 Po(t,e){return t.replaceAll(PM,e)}function KM(t){return t.kind==="approval"||t.kind==="review"}async function BM(t,e,n){let{agent:r,command:o}=n.config.review;if(t==="approval"||o===null&&r===void 0)return()=>$p(t,n);let s=await bp(n);return async()=>{if(eS(s,await bp(n)))return e;return kt(t,!1,"the working tree changed while the gates after the review ran",[],e.checks)}}function bp(t){return Tp(t.root,t.stage,t.task.contract.id)}function eS(t,e){return t.treeHash===e.treeHash&&Qs(t.artifactHashes,e.artifactHashes).length===0}async function $p(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 bp(e),i=o.filter((c)=>eS(c,s));if(i.length>0)return kt(t,!0,`stage ${n} approved by ${Zw(i)}`);let a=`the working tree changed after ${Zw(o)} approved stage ${n}`;return kt(t,!1,`${a}; ${r} again`)}function Zw(t){return[...new Set(t.map((e)=>e.by))].join(", ")}async function VM(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 $p("review",t);let r={name:"review",run:n,timeoutSeconds:t.config.checkTimeoutSeconds},o={config:t.config,root:t.root},s=await Js(o,"run review.command",[r],"pass",t.root),i=Pr(s),a=i.length===0?"the review command passed":"the review command failed";return kt("review",i.length===0,a,i,s)}async function WM(t,e){let n={name:"command",run:t,timeoutSeconds:e.config.checkTimeoutSeconds},r={config:e.config,root:e.root},o=await Js(r,"run a command gate of a project pack",[n],"pass",e.root),s=Pr(o),i=s.length===0?`${t} passed`:`${t} failed`;return kt("command",s.length===0,i,s,o)}function nS(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 qM,existsSync as JM,fstatSync as YM,openSync as XM,readSync as zM}from"fs";import{join as ZM}from"path";var QM="journal",tj=".jsonl",rS=65536,ej=1000,xc=10;function Ac(t,e,n){let r=[];if(n===0)return r;for(let o of rj(sS(t,e))){let s=iS(o,e);if(s!==null)r.push(s);if(r.length===n)break}return r.reverse()}function*oS(t,e){let n=[];for(let r of nj(sS(t,e))){let o=iS(r,e);if(o===null)continue;if(n.push(o),n.length<ej)continue;yield n,n=[]}if(n.length>0)yield n}function sS(t,e){return ZM(t,QM,`${zn(e)}${tj}`)}function iS(t,e){try{let n=ja(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*nj(t){let e=[];for(let n of aS(t,!1)){let r=0;for(let o=n.indexOf(xc);o!==-1;o=n.indexOf(xc,r))yield Buffer.concat([...e,n.subarray(r,o)]),e=[],r=o+1;e.push(n.subarray(r))}yield Buffer.concat(e)}function*rj(t){let e=[];for(let n of aS(t,!0)){let r=n.length;for(let o=n.lastIndexOf(xc);o!==-1;o=o===0?-1:n.lastIndexOf(xc,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*aS(t,e){if(!JM(t))return;let n=XM(t,"r");try{let{size:r}=YM(n);for(let o=0;o<r;o+=rS){let s=Math.min(rS,r-o),i=Buffer.alloc(s),a=zM(n,i,0,s,e?r-o-s:o);yield i.subarray(0,a)}}finally{qM(n)}}import{readFileSync as lj}from"fs";import{join as uj}from"path";var oj=/\p{M}+/gu,sj=/[\u00DF\u00E6\u0111\u00F0\u0127\u0131\u0142\u0153\u00F8\u00FE]/g,ij=/[^a-z0-9]+/,aj={\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 ti(t,e){if(!Number.isInteger(e)||e<=0)throw Error(`slugify needs a positive maxWords, got ${e}`);let r=t.toLowerCase().normalize("NFKD").replace(oj,"").replace(sj,(o)=>aj[o]??"").split(ij).filter((o)=>o.length>0).slice(0,e).join("-");return cj(r)}function cj(t){if(t.length<=64)return t;let e=t.lastIndexOf("-",64);return e>0?t.slice(0,e):t.slice(0,64)}function ei(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 dj=["constraint","decision"],pj=6,gj=10,mj="knowledge",fj=".md",hj=4,yj="\x00",kj=",",wj={"[":"]","{":"}"},Sj="\\",vj=()=>new Date().toISOString();function xp(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(ue,t.kind,`${e}.kind`),scope:ba(t.scope,`${e}.scope`),text:r}}function cS(t){return ue.includes(t)}function ni(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 Ap(t,e){let n=ti(t.text,pj),r=ei(n.length>0?n:t.kind,e);return e.add(r),r}function Cp(t,e,n,r){for(;;){let o=ni(e,{...n,id:Ap(e,r)});try{return Wa(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 dj.includes(t.kind)}function No(t){return t.slice(0,gj)}function ri(t,e){Pn(_e(t,e.id),$r(e))}function bj(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 Do(t){let e=await F(t,["ls-files","--cached","--others","--exclude-standard","-z"]);return re([...new Set(e.stdout.split(yj).filter((n)=>n.length>0))])}function Cc(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 lS(t){let e=[],n=[],r="";for(let o=0;o<t.length;o++){let s=t[o]??"";if(s===Sj){r+=t.slice(o,o+2),o++;continue}let i=wj[s];if(i!==void 0)n.push(i);else if(s===n.at(-1))n.pop();if(s===kj&&n.length===0){e.push(r.trim()),r="";continue}r+=s}return e.push(r.trim()),e.filter((o)=>o.length>0)}function Ej(t,e,n={}){let r=M(t),o=Ct("note","Shorten the text or fix the --kind and --scope values",()=>xp(e,"note",r.knowledge.maxEntryBytes)),i={created:No((n.clock??vj)()),sources:[...n.sources??[]],supersedes:[]};return Cp(t,o,i,new Set(an(t)))}async function uS(t,e,n={}){M(t);let r=gt(await P(t))?.task,o=r!==void 0&&pe(t).includes(r)?[r]:[];return Ej(t,e,{...n,sources:o})}function Rp(t,e={}){return M(t),{entries:ge(t).filter((r)=>e.all===!0||r.status==="active")}}function dS(t,e,n={}){let{entries:r}=Rp(t,n),o=new Map(r.map((a)=>[a.id,a]));return{matches:fc(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:Tj(c)}]}),query:e}}function pS(t,e,n){return{entry:oi(t,e),uses:bj(n).get(e)??0}}function gS(t,e,n={}){let r=oi(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 ri(t,o),o}function oi(t,e){if(M(t),an(t).includes(e))return Oa(e,lj(_e(t,e),"utf8"));throw new m(`Knowledge entry "${e}" does not exist`,"Run 'ari knowledge list --all' to see every entry")}function _e(t,e){return uj(t,q,mj,`${e}${fj}`)}function Tj(t){let e=10**hj;return Math.round(t*e)/e}var $j=4,Pe=`
167
167
 
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=`
168
+ `,wS=`
169
+ `,xj=3,Aj=/`+/g,Cj=/^ {0,3}(?:```|~~~)/,Rj=/\n+$/,Ij=/\n/g,SS=`
170
+ `,Pp="none",mS={constraint:0,decision:1},Np={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"}},Oj=["failure","rules","notes","knowledge","journal"],_j=/y$/,Pj=()=>new Date().toISOString();async function rr(t,e={}){let n=M(t),r=await P(t),o=e.id??Nj(r),s=e.budget??n.context.budget,{task:i}=it(t,o,n),a=ge(t).filter((g)=>g.status==="active"),c=(await Do(t)).filter((g)=>et(g,i.contract.scope)),l=Mj(t,i),u=jj(i),d=[...Fj(i.record.lastFailure,e.commandOutput!==!1),...Gj(i,a,c),...Hj(i.record.notes),...Uj(i,a,c),...Kj(Ac(r,o,n.context.journalTail))],p=Dj(o,s,l,u,d);if(i.record.status!=="done"&&e.journal!==!1){let g=(e.clock??Pj)(),f={[So]:p.knowledge,tokens:p.estimatedTokens};Ar(r,{at:g,detail:f,task:o,type:"context"})}return p}function Nj(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 Dj(t,e,n,r,o){let s=e*$j,i=[n,Rc(r.fields,r.body)],a=fS(o,yt(i.join(Pe)),Number.POSITIVE_INFINITY),c=yt(hS(i,a.sections,null))<=s,l=yt(`${Pe}${kS(e,yS(o))}`),u=c?i:[n,Lj(t,n,r,s-l)],d=u.join(Pe),p=c?a:fS(o,yt(d)+l,s),g=yS(p.omitted),f=hS(u,p.sections,g.length===0?null:kS(e,g)),y=[Ip("task",u[0]??"",1),Ip("contract",u[1]??"",1),...p.sections.map((S)=>Ip(S.name,vS(S),S.items.length))];return{budget:e,estimatedTokens:up(f),knowledge:p.sections.flatMap((S)=>S.knowledge),omitted:g,sections:y,sha256:Z(f),task:t,text:f}}function Lj(t,e,{body:n,fields:r},o){let s=Rc(r,n);if(yt([e,s].join(Pe))<=o)return s;let i=`_The contract body is shortened to fit the budget; read ${Ot(t)}._`,a=o-yt([e,Rc(r,i)].join(Pe))-Pe.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)=>Cj.test(d)?[p]:[]),u=l.length%2===0?c:c.slice(0,l.at(-1));return Rc(r,[u.join(`
172
+ `).trim(),i].filter((d)=>d.length>0).join(Pe))}function Rc(t,e){return e.length===0?t:`${t}${Pe}${e}`}function fS(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?wS:`${Pe}${Dp(i.section)}${Pe}`,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 hS(t,e,n){return[...[...t,...e.map(vS)],...n===null?[]:[n]].join(Pe)}function vS(t){return`${Dp(t.name)}${Pe}${t.items.join(wS)}`}function Dp(t){return`## ${Np[t].title}`}function Ip(t,e,n){return{estimatedTokens:up(e),items:n,name:t,text:e,title:Np[t].title}}function yS(t){return Oj.flatMap((e)=>{let n=t.filter((r)=>r.section===e).length;return n===0?[]:[{count:n,section:e}]})}function kS(t,e){let n=e.map(({count:r,section:o})=>{let{unit:s}=Np[o];return`${r} ${r===1?s:`${s.replace(_j,"ie")}s`}`});return`_Omitted to fit the budget of ${t} tokens: ${n.join(", ")}._`}function Mj(t,e){let{contract:n,record:r}=e,o=Ke(n.pack,Ht(t)),s=Ln(e,o);return[`# ${n.id}: ${n.title}`,"",`- Status: ${r.status}`,`- Pack: ${o.name}`,`- Stage: ${s.name} (${r.stage+1} of ${o.stages.length})`,`- Instruction: ${nr(ko(s,n.id))}`,...r.question===null?[]:[`- Question: ${nr(r.question)}`]].join(`
173
+ `)}function jj(t){let{contract:e}=t,n=e.criteria.map((i)=>{let a=i.checks.length===0?Pp:i.checks.join(", ");return`- ${i.id}: ${nr(i.text)} (checks: ${a})`}),r=e.checks.map((i)=>`- ${i.name} (expect ${i.expect}, timeout ${i.timeoutSeconds}s): ${Ic(i.run)}`),o=e.invariants.map((i)=>`- ${Ic(i)}`),s=[Dp("contract"),"",`Scope: ${_p(e.scope)}`,`Lock: ${_p(e.lock)}`,...Op("Criteria:",n),...Op("Checks:",r),...Op("Invariants:",o)];return{body:e.body.trim(),fields:s.join(`
174
+ `)}}function Op(t,e){return e.length===0?[`${t} ${Pp}`]:[t,...e]}function Fj(t,e){if(t===null)return[];let n=t.gates.filter((o)=>!o.ok).flatMap((o)=>[`- ${o.gate}: ${nr(o.summary)}`,...o.details.map((s)=>` - ${nr(s)}`),...o.checks.filter((s)=>e&&!s.ok&&s.outputTail.length>0).map((s)=>` ${s.name} output:${SS}${nr(Bj(s.outputTail))}`)]);return[{knowledgeId:null,section:"failure",text:[`Stage ${t.stage} at ${t.at}:`,...n].join(`
175
+ `)}]}function Gj(t,e,n){return bS(t,e,n).sort((r,o)=>(mS[r.kind]??0)-(mS[o.kind]??0)).map((r)=>ES("rules",r))}function bS(t,e,n){return e.filter((r)=>pn(r)&&Cc(r.scope,t.contract.scope,n))}function Hj(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}: ${nr(e.text)}`}))}function Uj(t,e,n){let r=new Set(bS(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 fc(a,o.map((l)=>({id:l.id,text:l.text}))).flatMap(({id:l})=>{let u=s.get(l);return u===void 0?[]:[ES("knowledge",u)]})}function ES(t,e){let n=e.scope.length===0?"":` (scope: ${_p(e.scope)})`;return{knowledgeId:e.id,section:t,text:`- ${e.kind} ${Ic(e.id)}${n}: ${nr(e.text)}`}}function Kj(t){return t.map((e)=>({knowledgeId:null,section:"journal",text:`- ${e.at} ${e.type} ${JSON.stringify(JSON.parse(pt(e.detail)))}`}))}function _p(t){return t.length===0?Pp:t.map(Ic).join(", ")}function Ic(t){let e="`".repeat(TS(t)+1),n=t.startsWith("`")||t.endsWith("`")?" ":"";return`${e}${n}${t}${n}${e}`}function Bj(t){let e="`".repeat(Math.max(xj,TS(t)+1));return`${e}
177
+ ${t.replace(Rj,"")}
178
+ ${e}`}function TS(t){return Math.max(0,...[...t.matchAll(Aj)].map((e)=>e[0].length))}function nr(t){return t.replace(Ij,SS)}function $S(t,e){let n=Math.max(t.length,e.length);return n===0?1:1-Ru(t,e)/n}var Vj=3;function Lp(t,e,n,r){return{clusters:Wj(t,r),decisions:Jj(t,n),notes:qj(e)}}function Mp(t,e,n){let r=ad(t),o=ad(e),s=Math.max(r.length,o.length);if(s>0&&Math.min(r.length,o.length)/s<n)return 0;return $S(r,o)}function Wj(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=Mp(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:Yj(r.get(i)??0)})).sort((i,a)=>O(i.ids[0]??"",a.ids[0]??""))}function qj(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 Jj(t,e){let n=t.filter((r)=>r.kind==="decision");return n.flatMap((r,o)=>n.slice(o+1).filter((s)=>Cc(r.scope,s.scope,e)).map((s)=>({ids:[r.id,s.id]})))}function Yj(t){let e=10**Vj;return Math.round(t*e)/e}import{existsSync as mF,readFileSync as HS}from"fs";function jp(t,e){let n=xS(t),r=xS(e),o=Xj(n,r),s=[],i=0,a=0;while(i<n.length&&a<r.length)if(n[i]===r[a])i++,a++;else if(si(o,i+1,a)>=si(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 xS(t){if(t.length===0)return[];let e=t.split(`
179
+ `);if(e.at(-1)==="")e.pop();return e}function Xj(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]?si(n,r+1,s+1)+1:Math.max(si(n,r+1,s),si(n,r,s+1))}return n}function si(t,e,n){return t[e]?.[n]??0}import{existsSync as FS,mkdirSync as lF,readFileSync as GS}from"fs";import{join as ci}from"path";import{existsSync as zj,readdirSync as Zj}from"fs";var gn=".json",IS=/^(\d{8}T\d{9}Z)(?:-(\d+))?$/,Qj=/[^0-9TZ]/g,AS=10,Oc=1;function ii(t){return IS.test(t)}function _c(t,e){let n=t.replace(Qj,""),r=Oc;while(e(CS(n,r)))r++;return CS(n,r)}function Lo(t){if(!zj(t))return[];return Zj(t).filter((e)=>e.endsWith(gn)&&ii(e.slice(0,-gn.length)))}function Dr(t,e){let[n="",r=`${Oc}`]=RS(t),[o="",s=`${Oc}`]=RS(e);return O(n,o)||Number.parseInt(r,AS)-Number.parseInt(s,AS)}function CS(t,e){return e===Oc?t:`${t}-${e}`}function RS(t){return IS.exec(t)?.slice(1).filter((e)=>e!==void 0)??[t]}var ai=1,OS=["pass","apply","undo"];var tF=/^[0-9a-f]{64}$/,LS=["version","id","at","kind"],_S=[...LS,"forced","reason","proposal","pruned","archived","created","promoted"],PS=[...LS,"undoes","restored","removed","unpromoted"],eF=["duplicate","decay","budget","merge","proposal"],nF=["merge","promotion"],rF=["utf8","base64"];function MS(t,e,n){return Ct(`sleep ledger entry ${e}`,n,()=>oF(t))}function oF(t){let e=T(t,"entry",PS.concat(_S)),n=K(OS,e.kind,"kind"),r=ht(e.version,"version");if(r!==ai)throw new b(`version ${r} is not supported`);let o={at:x(e.at,"at"),id:x(e.id,"id"),version:ai};if(n==="undo"){let i=T(t,"entry",PS);return{...o,kind:n,removed:L(i.removed,"removed",NS),restored:L(i.restored,"restored",NS),undoes:x(i.undoes,"undoes"),unpromoted:L(i.unpromoted,"unpromoted",DS)}}let s=T(t,"entry",_S);return{...o,archived:L(s.archived,"archived",sF),created:L(s.created,"created",iF),forced:$t(s.forced,"forced"),kind:n,promoted:L(s.promoted,"promoted",DS),proposal:s.proposal===null?null:cF(s.proposal),pruned:L(s.pruned,"pruned",aF),reason:Rt(s.reason,"reason")}}function sF(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`,Pc),reason:K(eF,n.reason,`${e}.reason`),sha256:Mn(n.sha256,`${e}.sha256`),supersededBy:Rt(n.supersededBy,`${e}.supersededBy`)}}function iF(t,e){let n=T(t,e,["id","kind","origin","replaces","task","notes","sha256"]);return{id:x(n.id,`${e}.id`),kind:K(ue,n.kind,`${e}.kind`),notes:L(n.notes,`${e}.notes`,ht),origin:K(nF,n.origin,`${e}.origin`),replaces:Lt(n.replaces,`${e}.replaces`),sha256:Mn(n.sha256,`${e}.sha256`),task:Rt(n.task,`${e}.task`)}}function Pc(t,e){let n=T(t,e,["sha256","encoding","content"]);return{content:x(n.content,`${e}.content`),encoding:K(rF,n.encoding,`${e}.encoding`),sha256:Mn(n.sha256,`${e}.sha256`)}}function NS(t,e){let n=T(t,e,["id","sha256"]);return{id:x(n.id,`${e}.id`),sha256:Mn(n.sha256,`${e}.sha256`)}}function DS(t,e){let n=T(t,e,["task","notes"]);return{notes:L(n.notes,`${e}.notes`,ht),task:x(n.task,`${e}.task`)}}function aF(t,e){let n=T(t,e,["task","events"]);return{events:ht(n.events,`${e}.events`),task:x(n.task,`${e}.task`)}}function cF(t){let e=T(t,"proposal",["sha256"]);return{sha256:Mn(e.sha256,"proposal.sha256")}}function Mn(t,e){let n=x(t,e);if(!tF.test(n))throw new b(`${e} must be a SHA-256 hex digest`);return n}var uF="sleep",dF=ci("locks","sleep.ledger.lock"),pF="the sleep ledger",Fp="Restore the file from a backup, or delete it to drop that entry from the sleep history";function Gp(t){return ci(t,uF)}function Lr(t,e){return Is(ci(t,dF),pF,e)}function Mo(t){return t.kind!=="undo"}function jo(t,e,n){let r=Gp(t);lF(r,{recursive:!0});let o=_c(e,(i)=>FS(jS(t,i))),s={...n,at:e,id:o,version:ai};return Zn(jS(t,o),pt(s),()=>Error(`The sleep ledger entry ${o} already exists`)),s}function li(t){let e=Gp(t);return Lo(e).map((n)=>gF(ci(e,n),n)).sort((n,r)=>Dr(n.id,r.id))}function ui(t){let e=new Map;for(let n of t)if(n.kind==="undo")e.set(n.undoes,n.id);return e}function Fo(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 Mr(t){return Buffer.from(t.content,t.encoding==="utf8"?"utf8":"base64")}function Go(t){return Z(GS(t))}function Hp(t){return FS(t)?Go(t):null}function jS(t,e){return ci(Gp(t),`${e}${gn}`)}function gF(t,e){let n;try{n=JSON.parse(GS(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})`,Fp)}let r=MS(n,t,Fp);if(`${r.id}${gn}`===e)return r;throw new m(`The sleep ledger entry ${t} declares the id "${r.id}"`,Fp)}function Nc(t,e){return e.map(({after:n,reason:r})=>{let o=_e(t,n.id),s=Fo(HS(o));return ri(t,n),{id:n.id,original:s,reason:r,sha256:Go(o),supersededBy:n.supersededBy}})}function US(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:Go(_e(t,n.id)),task:i}))}function Dc(t,e,n){let r=n.map(({entry:s,origin:i})=>({change:"created",diff:jp("",$r(s)),id:s.id,reason:i,supersededBy:null})),o=e.map(({after:s,reason:i})=>({change:i==="merge"?"replaced":"archived",diff:jp(fF(t,s.id),$r(s)),id:s.id,reason:i,supersededBy:s.supersededBy}));return[...r,...o]}function fF(t,e){let n=_e(t,e);return mF(n)?HS(n,"utf8"):""}function or(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 jr(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 Up(t,e){return[...new Set(t.record.knowledgeUsed.map((n)=>hF(n,e)))]}function Kp(t){let e=yF(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 hF(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 yF(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 kF=["fact","pattern","gotcha"],wF=()=>new Date().toISOString();async function Fr(t,e={}){let n=M(t),r=await P(t),o=await Do(t),s=(e.clock??wF)();return Lr(r,()=>{let{retirements:i,...a}=VS(t,r,n,o,!0),c=jo(r,s,{archived:Nc(t,i),created:[],forced:!1,kind:"pass",promoted:[],proposal:null,pruned:a.pruned,reason:null});return{...a,ledger:c.id}})}async function KS(t){let e=M(t),n=await P(t),r=await Do(t),{retirements:o,...s}=VS(t,n,e,r,!1);return{...s,changes:Dc(t,o,[]),dryRun:!0}}async function Gr(t,e={}){let n=M(t),r=await P(t),{tasks:o}=Nt(t,n),s=Ho(new Map(ge(t).map((a)=>[a.id,a]))),i=e.candidates===!1?{clusters:[],decisions:[],notes:[]}:Lp(s,o,await Do(t),n);return{activeBytes:Bp(s),clusters:i.clusters.length,decisions:i.decisions.length,journaled:o.filter((a)=>WS(r,a)).map((a)=>a.contract.id).sort(O),maxBytes:n.knowledge.maxBytes,notes:i.notes.length}}async function BS(t){return or(await Gr(t,{candidates:!1})).due?Fr(t):null}function VS(t,e,n,r,o){let{tasks:s}=Nt(t,n),{pruned:i,tasks:a}=SF(t,e,s,o),c=new Map(ge(t).map((p)=>[p.id,p])),l=[...EF(c,n),...TF(c,a,n),...$F(c,a,n)],u=l.flatMap(({id:p,reason:g})=>{let f=c.get(p);return f===void 0?[]:[{after:f,reason:g}]}),d=Ho(c);return{activeBytes:Bp(d),archived:l,candidates:Lp(d,a,r,n),maxBytes:n.knowledge.maxBytes,pruned:i,retirements:u}}function SF(t,e,n,r){let o=[],s=n.map((i)=>{let{id:a}=i.contract;if(!WS(e,i))return i;let c=0,l=(d)=>{let p=vF(d,e,a);return c=p.events,p.record},u=r?Wt(t,e,a,l):l(i.record);if(r)qa(e,a);return o.push({events:c,task:a}),{contract:i.contract,record:u}});return{pruned:o,tasks:s}}function WS(t,e){return e.record.status==="done"&&Ac(t,e.contract.id,1).length>0}function vF(t,e,n){let r=t,o=0;for(let s of oS(e,n))r=bF(r,s),o+=s.length;return{events:o,record:r}}function bF(t,e){let n=e.flatMap((r)=>{let o=r.detail[So];return r.type==="context"&&Array.isArray(o)?o:[]});return Da(wy(t,n),e)}function Ho(t){return[...t.values()].filter((e)=>e.status==="active").sort((e,n)=>O(e.id,n.id))}function Bp(t){return t.reduce((e,n)=>e+yt(n.text),0)}function qS(t,e){return O(t.created,e.created)||O(t.id,e.id)}function EF(t,e){let n=[],r=[];for(let o of Ho(t).filter((s)=>!pn(s)).sort(qS)){let s=n.find((i)=>i.kind===o.kind&&Mp(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 TF(t,e,n){let r=jr(e).slice(0,n.knowledge.decayAfterTasks);if(r.length<n.knowledge.decayAfterTasks)return[];let o=new Set(r.flatMap((i)=>Up(i,t))),s=r.map((i)=>No(i.record.history[0]?.at??"")).sort(O)[0]??"";return Ho(t).flatMap((i)=>{if(!kF.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 $F(t,e,n){let r=new Map;for(let a of jr(e).flatMap((c)=>Up(c,t)))r.set(a,(r.get(a)??0)+1);let o=Ho(t).filter((a)=>!pn(a)).sort((a,c)=>(r.get(a.id)??0)-(r.get(c.id)??0)||qS(a,c)),s=[],i=Bp(Ho(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 xF}from"fs";import{join as JS}from"path";var YS=1048576,AF=".ari/designs/";function Lc(t,e){let n=t.stages.flatMap((r)=>r.gates.flatMap((o)=>o.kind==="artifact"?[Po(o.path,e)]:[]));return[...new Set(n)].sort(O)}function Wp(t){return t.startsWith(AF)}function XS(t,e){let n=$e(JS(t,e));if(n===null)return{artifact:null,warning:null};if(n.isSymbolicLink()||xe(t,e))return Vp(e,"it is a symbolic link or lies behind one");if(!n.isFile())return Vp(e,"it is not a regular file");if(n.size>YS)return Vp(e,`it is larger than ${YS} bytes`);return{artifact:{file:Fo(xF(JS(t,e))),path:e},warning:null}}function Vp(t,e){return{artifact:null,warning:`${t} was not captured: ${e}`}}async function zS(t,e,n){let{contractText:r,task:o}=it(t,e,n),s=Ke(o.contract.pack,Ht(t)),i=Lc(s,e).map((u)=>XS(t,u)),a=await rr(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:Vt(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 qp(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 iv,mkdirSync as LF,readFileSync as MF,rmSync as jF}from"fs";import{join as Mc}from"path";var di=1,ZS=["manual","pre-compact","approve","stage"],QS=["save","restore"];var rv=["version","id","at","kind","task","pruned"],tv=[...rv,"trigger","reason","contract","record","artifacts","notes","context"],ev=[...rv,"restores","written"],nv="/",CF="..",RF=/[\\\0]/;function ov(t,e,n){return Ct(`snapshot entry ${e}`,n,()=>IF(t))}function IF(t){let e=T(t,"entry",tv.concat(ev)),n=K(QS,e.kind,"kind"),r=ht(e.version,"version");if(r!==di)throw new b(`version ${r} is not supported`);let o={at:x(e.at,"at"),id:x(e.id,"id"),pruned:Lt(e.pruned,"pruned"),task:x(e.task,"task"),version:di};if(n==="restore"){let i=T(t,"entry",ev);return{...o,kind:n,restores:x(i.restores,"restores"),written:L(i.written,"written",DF)}}let s=T(t,"entry",tv);return{...o,artifacts:L(s.artifacts,"artifacts",PF),context:ft(s.context,"context",NF),contract:ft(s.contract,"contract",OF),kind:n,notes:L(s.notes,"notes",wd),reason:Rt(s.reason,"reason"),record:ft(s.record,"record",_F),trigger:K(ZS,s.trigger,"trigger")}}function OF(t,e){let n=T(t,e,["sha256","text"]);return{sha256:Mn(n.sha256,k(e,"sha256")),text:x(n.text,k(e,"text"))}}function _F(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:Rt(n.stageName,k(e,"stageName")),status:K(kd,n.status,k(e,"status"))}}function PF(t,e){let n=T(t,e,["path","file"]);return{file:ft(n.file,k(e,"file"),Pc),path:sv(n.path,k(e,"path"))}}function NF(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:Lt(n.knowledge,k(e,"knowledge")),sha256:Mn(n.sha256,k(e,"sha256")),text:x(n.text,k(e,"text"))}}function DF(t,e){let n=T(t,e,["path","before","sha256"]);return{before:n.before===null?null:Pc(n.before,k(e,"before")),path:sv(n.path,k(e,"path")),sha256:Mn(n.sha256,k(e,"sha256"))}}function sv(t,e){let n=x(t,e);if(n.length===0||n.startsWith(nv)||n.split(nv).includes(CF)||RF.test(n))throw new b(`${e} must be a path inside the repository, got ${JSON.stringify(n)}`);return n}var FF="snapshots",GF=Mc("locks","snapshots.lock"),HF="the snapshots",Jp="Restore the file from a backup, or delete it to drop that entry from the snapshot history";function Hr(t){return Mc(t,FF)}function jc(t,e){return Is(Mc(t,GF),HF,e)}function Fc(t,e,n){LF(Hr(t),{recursive:!0});let r=_c(e,(s)=>iv(sr(t,s))),o={...n,at:e,id:r,version:di};return Zn(sr(t,r),pt(o),()=>Error(`The snapshot entry ${r} already exists`)),o}function jn(t){let e=[],n=[];for(let r of Lo(Hr(t))){let o=r.slice(0,-gn.length);try{e.push(av(t,o))}catch(s){n.push({id:o,problem:UF(s)})}}return{entries:e.sort((r,o)=>Dr(r.id,o.id)),unreadable:n.sort((r,o)=>Dr(r.id,o.id))}}function Uo(t,e){if(ii(e)&&iv(sr(t,e)))return av(t,e);let n=jn(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 Gc(t,e){for(let n of e)jF(sr(t,n),{force:!0})}function sr(t,e){return Mc(Hr(t),`${e}${gn}`)}function av(t,e){let n=sr(t,e),r;try{r=JSON.parse(MF(n,"utf8"))}catch(s){let i=s instanceof Error?s.message:String(s);throw new m(`The snapshot entry ${n} cannot be read (${i})`,Jp)}let o=ov(r,n,Jp);if(o.id===e)return o;throw new m(`The snapshot entry ${n} declares the id "${o.id}"`,Jp)}function UF(t){if(t instanceof m)return t.message;return t instanceof Error?t.message:String(t)}var KF=()=>new Date().toISOString(),BF={id:null,warning:null};async function Yp(t,e={}){let n=M(t),r=await P(t),o=e.task??VF(r),{plan:s,warnings:i}=await zS(t,o,n),a=(e.clock??KF)();return jc(r,()=>{let c=jn(r).entries.filter((p)=>p.task===o),l=c.findLast(Xp);if(l!==void 0&&qp(l)===qp(s))return cv(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=Fc(r,a,{...s,kind:"save",pruned:u,reason:e.reason??null,task:o,trigger:e.trigger??"manual"});return Gc(r,u),cv(d.id,o,s,u,i,!0)})}async function Ko(t,e,n,r={}){try{if(!M(t).snapshots.auto)return BF;let o=await Yp(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 Xp(t){return t.kind==="save"}function VF(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 cv(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 mv=`
180
180
 
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
181
+ `,lv=`
182
+ `,WF=/\s+/g,uv=60,qF=40,dv="...",fv=["tasks","snapshot","rules"],JF={rules:"Constraints and decisions:",snapshot:null,tasks:"Tasks:"},pv={active:0,ready:1},YF=`No Ariadne tasks yet. Create one with 'ari new "<title>"'.`,XF="Ariadne could not list the tasks of this repository. Run 'ari next' to see why.",zF="No task is active in this worktree and none is ready to start. Run 'ari next'.",ZF="No task is active in this worktree. Run 'ari next' for the next action.";function hv(t){let e=[],{root:n,state:r}=t,o=zp(e,"tasks",()=>Nt(n,t.config),null),s=zp(e,"knowledge",()=>ge(n),[]),i=o?.tasks??[],a=i.filter((g)=>g.record.status==="active"),c=tG(i,a).map(eG),l=zp(e,"snapshots",()=>sG(r,a),null),u=s.filter(nG).sort(rG).map(oG),d=QF(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:aG(d,p,t.config.context.briefBytes),warnings:e}}function QF(t,e){if(t===null)return XF;if(t===0)return YF;return e===0?zF:ZF}function zp(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 tG(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)=>(pv[o.record.status]??0)-(pv[s.record.status]??0)||O(o.contract.id,s.contract.id))}function eG({contract:t,record:e}){return`- ${t.id}: ${tg(t.title)} (${t.pack}, ${e.status})`}function nG(t){return t.status==="active"&&pn(t)&&t.scope.length===0}function rG(t,e){return O(t.id,e.id)}function oG(t){return`- ${t.kind} \`${t.id}\`: ${tg(t.text)}`}function sG(t,e){let n=new Set(e.map((s)=>s.contract.id));if(n.size===0)return null;let o=Lo(Hr(t)).map((s)=>s.slice(0,-gn.length)).sort((s,i)=>Dr(i,s));for(let s of o.slice(0,qF)){let i=iG(t,s);if(i===null||i.kind!=="save"||!n.has(i.task))continue;let a=tg(i.reason??i.trigger),c=a.length>uv?`${a.slice(0,uv-dv.length)}${dv}`:a;return`Latest snapshot of an active task: ${s} of "${i.task}" (${c}); 'ari snapshot show ${s}' prints what it saved.`}return null}function iG(t,e){try{return Uo(t,e)}catch{return null}}function aG(t,e,n){let r=Qp(t,Zp(e),null);if(yt(r)<=n)return r;let o=yt(`${mv}${gv(e.length)}`),s=[];for(let a of fv.flatMap((c)=>e.filter((l)=>l.part===c))){let c=[...s,a];if(yt(Qp(t,Zp(c),null))+o<=n)s.push(a)}let i=e.length-s.length;return cG(Qp(t,Zp(s),i===0?null:gv(i)),n)}function Zp(t){let e={rules:[],snapshot:[],tasks:[]};for(let{part:n,text:r}of t)e[n].push(r);return e}function Qp(t,e,n){let r=fv.flatMap((o)=>{let s=e[o];if(s.length===0)return[];let i=JF[o];return[i===null?s.join(lv):[i,...s].join(lv)]});return[t,...r,...n===null?[]:[n]].join(mv)}function gv(t){return`Left out to fit context.briefBytes: ${t} ${t===1?"item":"items"}. 'ari list' and 'ari knowledge list' show everything.`}function tg(t){return t.replace(WF," ").trim()}function cG(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 _v}from"path";var yv=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"),lG=/[ \t\r\n]/,uG=/\$\(cat <<-?[ \t]*(["'])(\w+)\1\n[\s\S]*?\n[ \t]*\2\n\s*\)/g,dG=/\\[\s\S]/g,pG=/\\([$`"\\\n])/g,gG=/[$`]/,mG=/[$*?[]|\{./;var fG=/['"\\]/g,hG=/^\t+/;var yG=/[(`]/,kG=new Set(["-C","-c","--config-env","--exec-path","--git-dir","--namespace","--work-tree"]);function eg(t){let e=[],n=[],r=kv(""),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&&=!yG.test(u),r.words.length+r.inputs.length+r.outputs.length>0)e.push(r);r=kv(u)};while(i<t.length){yv.lastIndex=i;let u=yv.exec(t);if(u===null)break;let{arithmetic:d,blank:p,delimiter:g,double:f,escaped:y,input:S,output:I,plain:C,separator:J,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(SG(f),wG(f));else if(d!==void 0)a(d,!1);else if(C!==void 0)a(C,!mG.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(fG,""),tabs:N!==""});else if(J!==void 0){if(J===`
183
+ `)for(let H of n.splice(0)){let{body:A,end:R}=vG(t,i,H);r.inputs.push(A),i=R}l(J)}}return l(""),e}function ng(t){return eg(t).flatMap((e)=>[e,...[...e.words,...e.inputs].filter((n)=>lG.test(n)).flatMap(ng)])}function Hc(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(kG.has(r))n+=1;if(r==="-C")e.push(t[n]??"")}return null}function Ur(t){return t.slice(t.lastIndexOf("/")+1)}function kv(t){return{before:t,inputs:[],literal:!0,outputs:[],words:[]}}function wG(t){return!gG.test(t.replace(uG,"").replace(dG,""))}function SG(t){return t.replace(pG,(e,n)=>n===`
184
+ `?"":n)}function vG(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(hG,""):a)===n)return{body:t.slice(e,o),end:i};o=i+1}return{body:t.slice(e),end:t.length}}import{basename as bG,isAbsolute as EG,join as TG,resolve as Kc}from"path";var $G=/^[A-Za-z_]\w*\+?=/,xG=new Set("! { builtin command do elif else env exec if nohup sudo then time until while".split(" ")),AG=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"]]]),CG=new Set("ari ariadne cat cd diff echo egrep file gh grep head jq ls popd printf pushd rg tail test wc".split(" ")),RG=new Set("add blame branch commit diff fetch grep log ls-files push show status tag".split(" ")),IG=new Set(["cd","popd","pushd"]),wv=new Set(["","&&",";",`
186
+ `]),OG="S suffix",_G=/^(?:-[a-z0-9E]*i|--in-place)/,PG=/^(?:-[a-zA-Z0-9]*[ef]|--expression|--file)/,NG="e f l expression file line-length",DG=/^-[a-zA-Z0-9]*[eE]/,LG="e E",MG=/^-\w+$/,jG=/^\.\w+$/,FG=/^(?:-[a-zA-Z]*t$|--target-directory)/,GG=/^(?:--staged|-[A-Za-z]*S)/,HG=/^(?:--worktree|-[A-Za-z]*W)/,Sv="of=",og="--",rg=".";function bv(t,e){let n=e,r=e,o=!0,s=t.map((i,a)=>{let c=KG(i,n),[l="",u="-",...d]=Bc(i);if(!IG.has(l))return o=!1,c;return o&&=l==="cd"&&i.literal&&!u.startsWith("-")&&d.length===0,o&&=wv.has(i.before)&&wv.has(t[a+1]?.before??""),r=o?Kc(r,u):r,n=o?r:null,c});return{directory:r,steps:s}}function Bc({words:t}){let e=t.findIndex((n)=>!$G.test(n)&&!xG.has(n));return e===-1?[]:[Ur(t[e]??""),...t.slice(e+1)]}function Vc(t,e=""){let n=new Set(e.split(" ")),r=t.indexOf(og),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(UG(a)))i+=1}return[...o,...r===-1?[]:t.slice(r+1)].filter((i)=>i.length>0)}function UG(t){if(t.startsWith("--"))return t.slice(2);return MG.test(t)?t.slice(-1):""}function KG(t,e){if(!t.literal)return{command:t,resolved:!1,targets:[]};let[n="",...r]=Bc(t),o=n==="git"?Hc(r):null,s=e===null?null:Kc(e,...o?.directories??[]),i=o===null?Ev(n,r,e):BG(o.subcommand,o.args,s),a=[...Uc(e,"file",t.outputs),...Uc(s,"file",i?.written),...Uc(s,"directory",i?.created),...Uc(s,"removed",i?.removed)],c=a.filter((l)=>l!==null);return{command:t,resolved:i!==null&&c.length===a.length,targets:c}}function Uc(t,e,n=[]){return n.flatMap((r)=>{if(t===null&&!EG(r))return null;let o=Kc(t??r,r),s=e!=="removed"&&nc(o);if(s&&e==="directory")return[];return{kind:s?"directory":e,path:o}})}function Ev(t,e,n){let[r,o]=AG.get(t)??[];if(r!==void 0)return{[r]:Vc(e,o)};switch(t){case"dd":return{written:e.filter((s)=>s.startsWith(Sv)).map((s)=>s.slice(Sv.length))};case"cp":case"ln":case"mv":return VG(t,e,n);case"sed":return{written:vv(e,NG,PG)??[]};case"perl":{let s=vv(e,LG,DG);return s===null?null:{written:s}}default:return CG.has(t)?{}:null}}function BG(t,e,n){switch(t){case"checkout":return e.includes(og)?{removed:e.slice(e.indexOf(og)+1)}:null;case"restore":return e.some((o)=>GG.test(o))&&!e.some((o)=>HG.test(o))?{}:{removed:Vc(e,"s source pathspec-from-file")};case"rm":case"mv":return Ev(t,e,n);default:return RG.has(t)?{}:null}}function VG(t,e,n){if(e.some((a)=>FG.test(a)))return null;let r=Vc(e,OG),[o=rg,s]=r.length<2?[rg,r]:[r.at(-1),r.slice(0,-1)],i=o.endsWith("/")||nc(Kc(n??rg,o));return{removed:t==="mv"?s:[],written:i?s.map((a)=>TG(o,bG(a))):[o]}}function vv(t,e,n){if(!t.some((s)=>_G.test(s)))return null;let r=Vc(t,e),o=r.length>1&&jG.test(r[0]??"")?r.slice(1):r;return t.some((s)=>n.test(s))?o:o.slice(1)}import{basename as Tv,dirname as WG,join as $v}from"path";var qG=[`${q}/tasks/*.md`,`${q}/designs/**`],JG="x",YG=/\*\*.*/,XG=".git",zG=[/^(?:ari|hooks|info)(?:\/|$)/,/^(?:HEAD|commondir|config(?:\.worktree)?|gitdir|objects|packed-refs|refs|worktrees)$/,/^(?:objects|refs|worktrees)\/(?!.*\.lock$)/],ZG="; pass the paths to change instead of their directory",QG="\x00",Wc=0,t1=1,xv=128;async function Av(t,e){let n=Ut(e),r=await t.governing(n),o=Iv(t.opened(),n);if(o!==null)return o;return r.flatMap((i)=>{let a=cn(i.root,n);return a===null||a.length===0?[]:pi(i,a)??[]})[0]??null}async function Cv(t,e){let n=[],r=new Map;for(let{kind:o,path:s}of e){let a=o==="removed"&&Bd(s)!==null?$v(Ut(WG(s)),Tv(s)):Ut(s),c=await t.governing(a),l=Iv(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 e1(o,s));return n}async function e1(t,e){let n=e.filter(({kind:a})=>a==="removed").map(({file:a})=>a),r=n.length===0?[]:await s1(t,n),o=n.flatMap((a)=>r.filter((u)=>a.length===0||u===a||u.startsWith(`${a}/`)).flatMap((u)=>{let d=pi(t,u);return d===null?[]:`${d}${u===a?"":ZG}`}).slice(0,1)),s=e.flatMap(({file:a,kind:c})=>{if(c==="removed"||a.length===0)return[];let l=c==="file"?pi(t,a):n1(t,a),u=c==="file"?a:`${a}/`;return l===null?[]:[{guarded:Rv(t,a)!==null,name:u,reason:l}]}),i=await i1(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 Rv(t,e){if(vo(e)&&!et(e,qG))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 pi(t,e,n=et){let r=Rv(t,e);if(r!==null||vo(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 n1(t,e){return pi(t,`${e}/${JG}`)===null?null:pi(t,e,r1)}function r1(t,e){let n=t.split("/").length,r=e.map((o)=>o.replace(YG,"**").split("/").slice(0,n).join("/"));return et(t,r)}function Iv(t,e){return t.some(({gitDirectories:r,root:o})=>cn($v(o,XG),e)===""||r.some((s)=>o1(s,e)))?`${Tv(e)} belongs to git and to ari's own state; use git and ari commands instead`:null}function o1(t,e){let n=cn(t,e);return n!==null&&zG.some((r)=>r.test(n))}async function s1({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:[Wc,xv]}),o=r.exitCode===Wc?Be(r.stdout):n;return[...Object.keys(e?.task?.record.lockHashes??{}),q,...o]}async function i1(t,e){if(e.length===0)return new Set;let n=await F(t,["check-ignore","-z","--stdin"],{allowedExitCodes:[Wc,t1,xv],stdin:[...new Set(e)].join(QG)});return new Set(n.exitCode===Wc?Be(n.stdout):[])}var a1="'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>'",c1="'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",l1="'ari uninstall' and 'ari hooks uninstall' remove the hooks that guard this repository; ask a person to run them",u1="'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",d1="run it as a plain command with literal paths, or ask a person to run it",p1=/(?:^|\/)(?:ari|ariadne)(?:@[^/]*)?$/,g1="approve",m1="trust",Ov="uninstall",f1="hooks",h1="git",y1="commit",k1="config",w1=/^core\.hookspath$/i,S1=/^(?:--config-env=)?core\.hookspath=|^GIT_CONFIG_KEY_\d+=core\.hookspath$/i,v1=/^(?:--)?unset/,b1=/^(?:--no-veri(?:f|fy)?|-[^-\smFcCtSu]*n\S*)$/,E1=/(?<![\w-])\.ari(?![\w.-])/,sg=/[\s'"`;&|()<>=,]+/,T1=[[/^(?: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)/]],$1=/^(?:ba|da|fi|k|z)?sh$/,x1=/^-[a-z]*c$/,A1=/^(?:bun|deno|node|perl|php|python|ruby)[\d.]*$/,C1=/^(?:-[a-zA-Z]*[ceEip]|--eval|--print)$/;async function Pv(t,e,n){let{directory:r,steps:o}=bv(eg(e),n),s=[...new Set([...await t.governing(n),...await t.governing(r)])],i=R1(ng(e));if(i!==null&&(s.length>0||await I1(t,e,n)))return{kind:"deny",reason:i};let a=await Cv(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)=>P1(d)??[])[0],l=s.filter(({fault:d,workspace:p})=>d!==null||p?.task!=null),u=c===void 0?null:D1(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; ${d1}`}}function R1(t){if(t.some((e)=>qc(e,g1)))return a1;if(t.some((e)=>qc(e,m1)))return c1;if(t.some((e)=>qc(e,Ov)||qc(e,f1,Ov)))return l1;return t.some(O1)?u1:null}async function I1(t,e,n){for(let r of new Set(e.split(sg)))if((await t.governing(_v(n,r))).length>0)return!0;return!1}function qc({words:t},e,n){return t.some((r,o)=>{if(!p1.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 O1({words:t}){if(t.some((e)=>S1.test(e)))return!0;return t.some((e,n)=>{let r=Ur(e)===h1?Hc(t.slice(n+1)):null;if(r?.subcommand===k1)return _1(r.args);return r?.subcommand===y1&&r.args.some((o)=>b1.test(o))})}function _1(t){let e=t.findIndex((n)=>w1.test(n));return e!==-1&&(e<t.length-1||t.some((n)=>v1.test(n)))}function P1({command:t}){let[e]=Bc(t),n=t.words.flatMap((o)=>o.split(sg)).filter((o)=>o.length>0);return n.map(Ur).find((o,s)=>N1(o,e,n,s+1))??(!t.literal&&t.outputs.length>0?">":null)}function N1(t,e,n,r){let o=T1.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=$1.test(t);if(!s&&!A1.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)=>x1.test(c)):i.slice(0,a===-1?i.length:a).some((c)=>C1.test(c))}function D1(t,e,n){if(t.length>0&&E1.test(e))return q;let r=new Set(e.split(sg));for(let{root:o,workspace:s}of t){let i=Object.keys(s?.task?.record.lockHashes??{}),a=new Set(i.map(Ur));for(let c of[...r].filter((l)=>a.has(Ur(l)))){let u=[o,...n].map((d)=>cn(o,Ut(_v(d,c)))).find((d)=>d!==null&&i.includes(d));if(u!==void 0)return u}}return null}var M1="stop.json",j1=500,F1=20000,me={kind:"allow"},G1={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"},H1=Et({task:X(),tree:X()});async function Lv(t){let e=hk();if(Dn.has(t.event))return U1(K1(e,t));let n=await e.at(t.cwd);if(n===null)return Jc(me);if(n.workspace===null)return Nv(t,n.fault??"");try{let r=[],o=await V1(t,n.workspace,r);return{...Jc(o),warning:r.length===0?null:r.join("; ")}}catch(r){if(!(r instanceof m))throw r;return Nv(t,Wd(r))}}function Nv({event:t},e){return{...Jc(me),warning:`ari hook skipped ${t}: ${e}`}}async function U1(t){let e=Promise.withResolvers(),n=setTimeout(e.resolve,F1,G1);try{return await Promise.race([e.promise,t.then(Jc)])}finally{clearTimeout(n)}}function Jc(t){return{decision:t,expired:!1,warning:null}}async function K1(t,e){let{command:n,cwd:r,event:o,paths:s}=e,i=await t.at(r);if(o==="before-shell"&&n!==null)return Pv(t,n,r);if(o==="before-edit"&&s.length>0)return B1(t,e);if(i===null)return me;return{kind:"ask",reason:`ari found no ${o==="before-edit"?"path":"command"} in the hook payload`}}async function B1(t,e){let n=[];for(let r of e.paths){let o=await Av(t,Dv(e.cwd,r));if(o!==null)n.push(o)}return n.length===0?me:{kind:"deny",reason:n.join("; ")}}async function V1(t,e,n){switch(t.event){case"before-edit":case"before-shell":return me;case"after-tool":return Yc(e,W1(t,e)),me;case"stop":{let r=await q1(e);if(r.kind==="allow"&&e.config.knowledge.sleepOnStop)await Y1(e.root);return r}case"pre-compact":{let r=await J1(e);if(r!==null)n.push(r);return Yc(e,{detail:{},type:"compact"}),await Fr(e.root),me}case"session-start":return z1(e,n)}}function W1(t,e){let n=Ut(e.root),r=t.paths.flatMap((o)=>cn(n,Ut(Dv(t.cwd,o)))??[]);if(r.length>0)return{detail:{paths:r},type:"edit"};if(t.command!==null)return{detail:{command:t.command.slice(0,j1)},type:"shell"};return{detail:t.tool===null?{}:{tool:t.tool},type:"tool"}}async function q1(t){let{task:e}=t;if(e===null||e.record.status!=="active")return me;let n=e.contract.id,r=await Ce(t.root,[xr]);if(e.record.evidence.at(-1)?.treeHash===r)return me;let o=L1(t.state,M1),s=oc(o,H1,null);if(s?.task===n&&s.tree===r)return me;return Or(o,`${JSON.stringify({task:n,tree:r})}
187
+ `),Yc(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 J1(t){if(t.task===null)return null;return(await Ko(t.root,t.task.contract.id,"pre-compact")).warning}async function Y1(t){try{await BS(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 X1(t,e){if(!t.config.hooks.brief)return me;try{let n=hv(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})`),me}}async function z1(t,e){if(t.task===null)return X1(t,e);Yc(t,{detail:{},type:"session"});let{text:n}=await rr(t.root,{id:t.task.contract.id});return n.trim().length===0?me:{kind:"context",text:n}}function Yc(t,e){if(t.task===null)return;Ar(t.state,{...e,at:new Date().toISOString(),task:t.task.contract.id})}var Bo="git",Z1={amp:"Amp",opencode:"OpenCode"},Q1=".git/hooks";function ig(){return[...Oe.map((t)=>t.name),Bo]}function Ne(t){let e=Oe.find((r)=>r.name===t);if(e!==void 0)return e;if(t===Bo)throw new v("git hooks run 'ari scope --staged' and 'ari verify' directly","Run 'ari hooks install --agent git'");let n=Z1[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: ${ig().join(", ")}`)}function Mv(t){if(t!==Bo)Ne(t)}async function Vo(t,e){if(e===Bo)return lc(t);return qk(t,Ne(e),await P(t))}async function jv(t,e){if(e===Bo)return uc(t);return mc(t,Ne(e),await P(t))}async function Fv(t){return[...Oe.map((n)=>({agent:n.name,events:qs(n),file:n.file,installed:un(t,n),label:n.label,support:n.support})),{agent:Bo,events:[...Fk],file:Q1,installed:await Ro(t),label:"git",support:"git"}]}async function Gv(t,e,n,r){let o=Ne(t),s=tH(o,e);try{let{decision:i,expired:a,warning:c}=await Lv(o.parse(s,eH(n),r));return{expired:a,stdout:Qd(o,s,i),warning:c}}catch(i){if(!Dn.has(s))throw i;let a=`ari could not check this ${s} event: ${i instanceof Error?i.message:String(i)}`;return{expired:!1,stdout:Qd(o,s,{kind:"deny",reason:a}),warning:a}}}function tH(t,e){if(!Ik(e))throw new v(`Unknown hook event "${e}"`,`Choose one of: ${Xd.join(", ")}`);if(qs(t).includes(e))return e;throw new v(`${t.label} has no ari adapter for "${e}"`,`Its adapter handles: ${qs(t).join(", ")}`)}function eH(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 Hv}from"os";import{join as nH}from"path";var Fn=["project","user"],rH=".ari",oH="receipts",sH="~/";function ir(t){let e=t??"project",n=Fn.find((r)=>r===e);if(n!==void 0)return n;throw new v(`Unknown scope "${e}"`,`Choose one of: ${Fn.join(", ")}`)}async function At(t,e){if(t==="user")return{base:Hv(),receipts:nH(Hv(),rH,oH),scope:t};let n=await Xn(e);return{base:n,receipts:await P(n),scope:t}}function se(t,e){return t==="user"?`${sH}${e}`:e}function gi(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 ag(t,e,n){return[...new Set(e)].map((r)=>gi(t,r,n))}import{isDeepStrictEqual as pH}from"util";function Xc(t){let{base:e,file:n,receipts:r}=t,o=W(e,n),s=t.install(o),i=Oo(r.directory,n,r.store),a=t.managed(o)?void 0:o,c=i?.installed===o?i.original:a,l=Re(e,n,s),u=W(e,n)??"";return _o(r.directory,n,c===void 0?null:{installed:u,original:c},r.store),l}function iH(t,e,n){if(e===null||!t.managed(e))return Bs;if(n?.installed!==e){let r=t.remove(e);return r===null?Vs:Io(r,!1)}return n.original===null?Vs:Io(n.original,!0)}function zc(t,e,n){let{base:r,file:o,receipts:s}=t,i=Oo(s.directory,o,s.store),a=gc(r,o,iH(t,e.read(r,o),i),e);if(n)_o(s.directory,o,null,s.store);return a}function Zc(t){return zc(t,pc,!0).action}function mn(t){return t.managed(W(t.base,t.file))}import{isDeepStrictEqual as aH}from"util";var Wo="# ari:begin",mi="# ari:end",fi=`\r
188
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(`
189
+ `,cH=1,lH=/^\r?\n/,uH=/\r$/;function Kv(t){return(t??"").split(fn).some((e)=>lg(e,Wo))}function Bv(t,e){let n=t??"";cg(e.file,n);let r=n.includes(fi)?fi:fn,o=[`${Wo} managed by 'ari mcp install'; 'ari mcp uninstall' removes it`,...e.lines,mi].join(r),s=Wv(e.file,n);if(s===null&&Uv(cg(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?dH(n,o,r):n.slice(0,s.start)+o+n.slice(s.end),a;try{a=cg(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)}`,cH,{cause:c})}if(aH(Uv(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 Vv(t,e){let n=Wv(t,e);if(n===null)return e;let r=e.slice(0,n.start),o=e.slice(n.end).replace(lH,""),i=(r.endsWith(`${fi}${fi}`)?r.slice(0,-fi.length):r.endsWith(`${fn}${fn}`)?r.slice(0,-fn.length):r)+o;return i.trim().length===0?null:i}function dH(t,e,n){if(t.length===0)return`${e}${n}`;return`${t.endsWith(fn)?t:`${t}${n}`}${n}${e}${n}`}function Wv(t,e){let n=[],r=0;for(let i of e.split(fn)){let a=r+i.replace(uH,"").length;if(lg(i,Wo))n.push({end:a,kind:Wo,start:r});else if(lg(i,mi))n.push({end:a,kind:mi,start:r});r+=i.length+fn.length}let[o,s]=n;if(o===void 0)return null;if(n.length!==2||o.kind!==Wo||s?.kind!==mi)throw new m(`${t} has a damaged ari block: expect one '${Wo}' line followed by one '${mi}' 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 lg(t,e){let n=t.trim();return n===e||n.startsWith(`${e} `)}function cg(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 Uv(t,e){return e.reduce((n,r)=>typeof n==="object"&&n!==null?n[r]:void 0,t)}var hn="ari",ug="ari",tl=["mcp","serve"],hi="mcpServers",gH="mcp.json",qv=900,mH=1000,fH=2,Qc={command:ug,args:tl},ie=[{agent:"claude",entry:Qc,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} -- ${ug} ${tl.join(" ")}'`},{agent:"codex",entry:{...Qc,tool_timeout_sec:qv},format:"toml",label:"Codex CLI",project:".codex/config.toml",user:".codex/config.toml",userHint:null},{agent:"gemini",entry:{...Qc,timeout:qv*mH},format:"json",label:"Gemini CLI",project:".gemini/settings.json",user:".gemini/settings.json",userHint:null},{agent:"cursor",entry:{type:"stdio",...Qc},format:"json",label:"Cursor",project:".cursor/mcp.json",user:".cursor/mcp.json",userHint:null}];function fe(t){return gi(ie,t,"MCP")}function De(t,e){return nl(t,e)}function qo(t,e){let n=nl(t,e);return{...Xv(t,e,n.file),action:Xc(n)}}function el(t,e){let n=nl(t,e);return{...Xv(t,e,n.file),action:Zc(n)}}function Yv(t,e){return ie.map((n)=>({agent:n.agent,files:[t,e].flatMap((r)=>{let o=n[r.scope];if(o===null)return[];let s=mn(nl(n,r));return[{file:se(r.scope,o),installed:s,scope:r.scope}]}),label:n.label}))}function Xv(t,e,n){return{agent:t.agent,file:se(e.scope,n),scope:e.scope,server:hn}}function nl(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:gH},o={base:e.base,file:n,receipts:r};return t.format==="toml"?{...o,...hH(t,n)}:{...o,...yH(t,n)}}function hH(t,e){let n={file:e,lines:[`[mcp_servers.${hn}]`,...kH(t.entry)],table:["mcp_servers",hn],value:t.entry};return{install:(r)=>Bv(r,n),managed:Kv,remove:(r)=>Vv(e,r)}}function yH(t,e){let n=(o)=>{let s=o[hi]??{};if(z(s))return s;throw new m(`${e} has a "${hi}" value that is not an object`,`Fix ${e}`)},r=(o,s)=>o===null?`${JSON.stringify(s,null,fH)}
192
+ `:Za(o,s);return{install:(o)=>{let s=o===null?{}:oe(e,o),i=n(s),a=i[hn];if(a!==void 0&&!Jv(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,[hi]:{...i,[hn]:c}})},managed:(o)=>o!==null&&Jv(n(oe(e,o))[hn]),remove:(o)=>{let{[hi]:s,...i}=oe(e,o),{[hn]:a,...c}=n(oe(e,o));return r(o,Object.keys(c).length===0?i:{...i,[hi]:c})}}}function kH(t){let{args:e,command:n,...r}=t;return Object.entries({command:n,args:e,...r}).map(([o,s])=>`${o} = ${zv(s)}`)}function zv(t){if(Array.isArray(t))return`[${t.map(zv).join(", ")}]`;return typeof t==="number"?String(t):JSON.stringify(t)}function Jv(t){if(!z(t)||t.command!==ug||!Array.isArray(t.args))return!1;return pH(t.args.slice(0,tl.length),tl)}import{existsSync as SH,readdirSync as vH,rmdirSync as bH}from"fs";import{dirname as ab,join as cb}from"path";var dg="```",wH=["`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","",...[...wH,...t].map((e)=>`- ${e}`)].join(`
193
+ `)}function Le(...t){return t.map((e)=>typeof e==="string"?e:e.join(`
194
194
  `)).join(`
195
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(`
196
+ `)}var Zv={body:Le(["# 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 Qv={body:Le(["# 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:","",`${dg}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]","---",dg],["- 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 tb={body:Le(["# 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 eb={body:Le(["# 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 nb={body:Le(["# 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 rb={body:Le(["# 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 ob="SKILL.md",rl="<!-- ari:managed by 'ari skills install'; 'ari skills uninstall' removes it -->";function sb({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
197
  `);return{description:e,name:n,text:`${r}
198
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(`---
199
+ `}}var ot=[Zv,tb,Qv,eb,rb,nb].map(sb);function ib(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 EH="skills.json",he=[{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 gi(he,t,"skill")}function yi(t,e,n){return cb(t[e],n,ob)}function ae(t,e,n){return mg(t,e,n)}function lb(t,e){for(let n of he){let r=ot.find((o)=>yi(n,t.scope,o.name)===e);if(r!==void 0)return{skill:r,target:n}}return null}function Jo(t,e,n=ot){return n.map((r)=>{let o=mg(t,e,r),s=W(o.base,o.file);if(s!==null&&!o.managed(s))return{...pg(t,e,r),action:"refused",reason:db(e,o.file)};return{...pg(t,e,r),action:Xc(o)}})}function ol(t,e,n=ot){return n.map((r)=>{let o=mg(t,e,r),s=Zc(o);if(s==="removed")pb(e.base,ab(o.file));return{...pg(t,e,r),action:s}})}function sl(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,il(n.length,e))}function il(t,e){return`Move or remove ${t===1?"that skill":"those skills"}, then run 'ari skills install --agent ${e}' again`}function gg(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 ub(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 pg(t,e,n){let r=se(e.scope,yi(t,e.scope,n.name));return{agent:t.agent,file:r,scope:e.scope,skill:n.name}}function db(t,e){return`${se(t.scope,e)} exists and ari did not write it`}function mg(t,e,n){let r=yi(t,e.scope,n.name),o=(s)=>(s??"").includes(rl);return{base:e.base,file:r,install:(s)=>{if(s===null||o(s))return n.text;throw new m(db(e,r),il(1,t.agent))},managed:o,receipts:{directory:e.receipts,store:EH},remove:()=>null}}function pb(t,e){let n=cb(t,e);if(e==="."||!SH(n)||vH(n).length>0)return;bH(n),pb(t,ab(e))}var Ft="AGENTS.md",fg="<!-- ari:begin -->",al="<!-- ari:end -->",xH=/^ {0,3}(<!-- ari:(?:begin|end) -->)\s*$/,AH=/^ {0,3}(`{3,}(?=[^`]*$)|~{3,})/,CH=/^ {0,3}(`{3,}|~{3,})[ \t]*\r?$/,hg=`${q}/config.json`,RH="git",gb=`\r
200
+ `,yg=`
201
+ `,IH=[fg,"## 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 your work is finished, remove the worktree and the branch you created for it, local branches included. Never remove a worktree you did not create, one with uncommitted changes or one that a process still uses.","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.",al];function kg(t){let e=ki(W(t,Ft));return{action:Re(t,Ft,e),path:Ft}}function wg(t,e){return Re(t,hg,Sg(W(t,hg),e))}function Sg(t,e){let n=t??Jy();if(e===null)return n;let r=oe(hg,n);if(Tr(r).pack===e)return n;return tr(n,{...r,pack:e})}async function mb(t,e={}){let n=[...e.agents??[],...e.gitHooks===!0?[RH]:[]],r=[...new Set(n)];for(let f of r)Mv(f);let o=ag(ie,e.mcp??[],"MCP"),s=ag(he,e.skills??[],"skill"),i=TH($H(t,q))?Ht(t):[],a=e.pack===void 0?null:Ke(e.pack,i).name,c=wg(t,a),l=kg(t),u=[];for(let f of r)u.push(await Vo(t,f));let d={base:t,receipts:await P(t),scope:"project"},p=o.map((f)=>qo(f,d)),g=s.flatMap((f)=>{let y=Jo(f,d);return sl(y,f.agent),y});return{agentsMd:l,config:c,hooks:u,mcp:p,pack:M(t).pack,root:t,skills:g}}function ki(t){let e=t??"",n=e.includes(gb)?gb:yg,r=IH.join(n),o=OH(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!==fg||i?.marker!==al)throw new m(`${Ft} has a damaged ari block: expect one ${fg} followed by one ${al}`,`Remove the ari markers and the lines between them from ${Ft}, then run 'ari init' again`);return`${e.slice(0,s.start)}${r}${e.slice(i.start+al.length)}`}function OH(t){let e=[],n=null,r=0;for(let o of t.split(yg)){let s=AH.exec(o)?.[1];if(n===null&&s!==void 0)n={mark:s,markers:e.length};else if(n!==null&&_H(o,n.mark))e.length=n.markers,n=null;let i=xH.exec(o)?.[1];if(i!==void 0)e.push({marker:i,start:r+o.indexOf(i)});r+=o.length+yg.length}return e}function _H(t,e){return CH.exec(t)?.[1]?.startsWith(e)===!0}function Kr(t){return t.kind==="config"?"ari init":yb("install",t)}function hb(t){return yb("uninstall",t)}function yb(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}${fb(r)}`;case"skill":return e===null?null:`ari skills ${t} --agent ${e}${fb(r)}`;case"config":case"routing":return null}}function fb(t){return t==="user"?" --scope user":""}var wb=5000,PH=new Set(["created","updated","unchanged"]),NH="2025-11-25",Sb=2,DH="ari_next",LH=new Set(["hooks","mcp","skill","git"]),MH="<!-- ari:begin -->",vb=".ari/config.json",jH=".git/hooks",bb="Install ari globally (bun add -g @r5n/ariadne), then run 'ari install' again";async function vg(t,e,n={}){let r=e.filter((a)=>PH.has(a.action)),o=await Promise.all(FH(r).map((a)=>GH(t,a)));if(!r.some((a)=>LH.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 Eg(s,t,n.timeoutMs??wb)]:[];return[bg(s),...i,...o]}function bg(t){return t===null?Yo("ari on PATH","ari is not on PATH, so agents cannot start it",bb):Tg("ari on PATH",t)}function Eg(t,e,n=wb){return BH(t,e,n)}function FH(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 GH(t,e){let n=cl(e),r=e.kind==="routing"?vb:e.kind==="git"?jH:e.file??"";try{let o=await UH(t,e);return o===null?Tg(n,KH(e,r)):Yo(n,`${r}: ${o}`,HH(e))}catch(o){if(!(o instanceof Error))throw o;let s=o instanceof m&&o.hint!==void 0?o.hint:`Fix ${r}`;return Yo(n,o.message,s)}}function HH(t){let e=Kr(t);return e===null?"Run 'ari install' again to repair it":`Run '${e}' to repair it`}function cl(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===Ft?"AGENTS.md block":"configuration";case"routing":return"configuration"}}async function UH(t,e){let n=e.agent??"";switch(e.kind){case"hooks":return un(t,Ne(n))?null:"has no ari hook entries";case"mcp":{let r=De(fe(n),await kb(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 kb(t,e.scope)],s=ot.filter((i)=>{let a=ae(r,o,i),c=W(a.base,a.file)??"";return!(c.startsWith(`---
202
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=`
203
+ `)&&c.includes(rl))}).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 Ro(t)?null:"pre-commit and pre-push do not both run ari";case"config":if(e.file===Ft)return(W(t,Ft)??"").includes(MH)?null:"has no ari block";return M(t),null;case"routing":return M(t),null}}function KH(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===Ft?"AGENTS.md has the ari block":`${vb} is valid`}}async function kb(t,e){return At(e,t)}async function BH(t,e,n){let o=Bun.spawn([t,"mcp","serve"],{cwd:e,detached:!0,env:{...process.env,...Ge},stderr:"pipe",stdin:"pipe",stdout:"pipe"}),s=()=>He(o.pid,"SIGKILL"),i=te(s),a=setTimeout(s,n);try{o.stdin.write(VH()),await o.stdin.flush();let c=await WH(o.stdout);return await o.stdin.end(),JH("ari mcp serve",c,n,await new Response(o.stderr).text())}catch(c){return Yo("ari mcp serve",`'ari mcp serve' failed: ${c instanceof Error?c.message:String(c)}`,bb)}finally{clearTimeout(a),s(),i()}}function VH(){return[{id:1,jsonrpc:"2.0",method:"initialize",params:{capabilities:{},clientInfo:{name:"ari-install",version:"1"},protocolVersion:NH}},{jsonrpc:"2.0",method:"notifications/initialized"},{id:Sb,jsonrpc:"2.0",method:"tools/list"}].map((e)=>`${JSON.stringify(e)}
204
+ `).join("")}async function WH(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=qH(s);if(i!==null&&i.id===Sb)return i}}return null}function qH(t){try{let e=JSON.parse(t);return z(e)?e:null}catch{return null}}function JH(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 Yo(t,i,"Run 'ari mcp serve' in this repository to see why")}let o=YH(e);if(!o.includes(DH))return Yo(t,"answered tools/list without ari's tools","Make sure 'ari' on PATH is @r5n/ariadne");return Tg(t,`answers, with ${o.length} tools`)}function YH(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 Tg(t,e){return{detail:e,hint:null,name:t,ok:!0}}function Yo(t,e,n){return{detail:e,hint:n,name:t,ok:!1}}import{existsSync as Pb}from"fs";import{join as Nb}from"path";function $g(t,e,n=ot){return n.map((r)=>{let o=ae(t,e,r),s=mn(o);return{current:s&&W(o.base,o.file)===r.text,file:se(e.scope,yi(t,e.scope,r.name)),installed:s,scope:e.scope,skill:r.name}})}function Eb(t,e){return he.map((n)=>({agent:n.agent,files:[t,e].flatMap((r)=>$g(n,r)),label:n.label}))}var at=["claude","codex","gemini","cursor","copilot"],ar=["hooks","mcp","skill"],Xe={hooks:"hooks",mcp:"MCP server",skill:"skill"},Cg="config",cr="agents-md",Ye="git",ul="claude mcp add --scope user ari -- ari mcp serve",xg=".ari/config.json",XH="AGENTS.md",Tb=".claude/settings.json",$b=["cursor","copilot"],xb={cursor:["claude","codex"],gemini:["codex"]},zH=["claude","codex","gemini"],ZH=":";function _t(t,e){return`${t}${ZH}${e}`}function dl(t){return at.includes(t)}function Gt(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 pl(t){let e=new Set(t.targets.filter(Og).map((n)=>n.agent));return at.filter((n)=>Gt(t,n).path!==null||e.has(n))}function Br(t,e,n,r){let o=t.initialised&&!r?[Ib(t,cr,"project")]:[],s=ar.flatMap((i)=>at.filter((a)=>e.includes(a)).map((a)=>aU(t,a,i,n)));return[...o,...s,cU(t)]}function QH(t,e,n,r){let s=Br(t,e,n,r).filter((a)=>a.skip===null&&a.problem===null).map((a)=>a.id),i=new Set(Xo(t,s).map(({id:a})=>a));return s.filter((a)=>!i.has(a))}function Ab(t,e,n,r){return Br(t,e,n,r).map((o)=>o.id)}function Cb(t,e,n,r){let o=Br(t,e,n,r),s=new Set(o.filter((i)=>i.status!=="current"&&i.elsewhere===null).map((i)=>i.id));return QH(t,e,n,r).filter((i)=>s.has(i))}function Rb(t,e){let n=t.configured.map((s)=>({...s,configured:!0})),r=new Set(n.map((s)=>s.name)),o=e.filter((s)=>Gt(t,s).preset&&!r.has(s)).map((s)=>({configured:!1,model:null,name:s,roles:[]}));return[...n,...o]}function Rg(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)iU(t,e.routing,e.init);let n=e.init,r=Br(t,e.agents,e.scope,n),o=new Set(e.targets),s=e.recommended?Xo(t,e.targets):[],i=new Map(s.map(({id:d,reason:p})=>[d,p])),a=n?[ll(Cg,null,"config","project",xg,null),ll(cr,null,"config","project",XH,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?lU(d.problem):null,f=d.skip??i.get(d.id)??g;return[ll(d.id,d.agent,d.kind,d.scope,d.file,f)]}),u=e.routing===null?[]:[ll("routing",null,"routing","project",xg,null)];return{init:n,pack:e.pack,routing:e.routing,scope:e.scope,targets:[...a,...l,...u],warnings:gl(t,{...e,targets:e.targets.filter((d)=>!i.has(d))})}}function gl(t,e){let n=Br(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=Ob(t),i=new Set([...[...r].filter((c)=>o.has(c)),...s]),a={answers:e,effective:i,installed:s,requested:r,state:t};return[...tU(a),...eU(a),...nU(a),...rU(a),...oU(a),...sU(a,n)]}function tU({answers:t,state:e}){return t.agents.flatMap((n)=>{let r=Gt(e,n);if(r.path!==null)return[];return[zo("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 eU({answers:t,requested:e}){if(t.scope!=="user"||!e.has(_t("mcp","claude")))return[];return[zo("claude-user-mcp","Claude Code keeps user-scope MCP servers in its own state file, which ari does not edit",`Run: ${ul}`)]}function nU({requested:t,state:e}){let n=e.hookManager;if(n===null||!t.has(Ye))return[];return[zo("git-hooks-managed",_b(n.name),n.hint)]}function rU({effective:t,installed:e,requested:n,state:r}){let o=_t("hooks","claude");if(!t.has(o))return[];return $b.flatMap((s)=>{let i=_t("hooks",s);if(!t.has(i)||!(n.has(i)||n.has(o)))return[];let a=Gt(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 ${Tb}, so every ari hook would run twice there`;return[zo("hooks-twice",u,l,c)]})}function oU({answers:t,effective:e,installed:n,requested:r,state:o}){return at.flatMap((s)=>{let i=xb[s];if(i===void 0||!t.agents.includes(s))return[];let a=[s,...i].filter((y)=>e.has(_t("skill",y)));if(a.length<2||!a.some((y)=>r.has(_t("skill",y))))return[];let c=Gt(o,s).label,l=_t("skill",s),u=r.has(l)&&!n.has(l)&&a.includes(s)?[l]:[],d=a.map((y)=>Ag(o,y)),p=a.filter((y)=>y!==s).map((y)=>Ag(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)=>Gt(o,y).label).join(" and ")} need them`,f=`${c} reads ${d.join(" and ")}, so it would load the ariadne skills ${uU(a.length)}`;return[zo("skill-twice",f,g,u)]})}function sU({requested:t},e){return e.flatMap((n)=>{if(n.problem===null||n.skip!==null||!t.has(n.id))return[];return[zo("target-blocked",n.problem.message,n.problem.hint)]})}function Xo(t,e){let n=new Set(e),r=Ob(t),o=new Set([...n,...r]),s=o.has(_t("hooks","claude")),i=$b.flatMap((c)=>{let l=_t("hooks",c);if(!s||!n.has(l)||r.has(l))return[];let u=`${Gt(t,c).label} runs Claude Code's hooks from ${Tb}`;return[{id:l,reason:u}]}),a=at.flatMap((c)=>{let l=_t("skill",c),u=(xb[c]??[]).find((g)=>o.has(_t("skill",g)));if(u===void 0||!n.has(l)||r.has(l))return[];let d=Ag(t,u),p=`${Gt(t,c).label} also reads ${d}, where ${Gt(t,u).label}'s copy is`;return[{id:l,reason:p}]});return[...i,...a]}function iU(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),...zH]);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 ${xg}, or leave the review agent out`,1,{tag:"ReviewCommandSet"})}function aU(t,e,n,r){let o=Gt(t,e),s=_t(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 ${Xe[n]} integration for ${o.label}`};if(i==="user"&&!o.userScope.includes(n))return{...a,skip:`${o.label} keeps user-scope MCP servers itself; run '${ul}'`};let c=Ig(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&&Og(u)?u.scope:null;return{...a,elsewhere:d,file:c.file,problem:c.problem,skip:null,status:c.status}}function cU(t){let e=t.hookManager,n={agent:null,elsewhere:null,id:Ye,kind:"git",scope:"project"};if(e!==null)return{...n,file:t.gitHooksDirectory,problem:null,skip:_b(e.name),status:null};return Ib(t,Ye,"project")}function Ib(t,e,n){let r=Ig(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 Ig(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 Ob(t){return new Set(t.targets.filter(Og).map((e)=>e.id))}function Og(t){return t.status!=="missing"&&t.agent!==null}function Ag(t,e){return Ig(t,_t("skill",e),"project").file}function _b(t){return`${t} manages this repository's git hooks, so ari leaves them alone`}function lU(t){return t.hint.length===0?t.message:`${t.message}. ${t.hint}`}function ll(t,e,n,r,o,s){return{agent:e,file:o,id:t,kind:n,scope:r,skip:s}}function zo(t,e,n,r=[]){return{code:t,drop:r,fix:n,message:e}}function uU(t){return t===2?"twice":`${t} times`}var dU={claude:["claude"],codex:["codex"],copilot:["copilot"],cursor:["cursor-agent","cursor"],gemini:["gemini"]},pU="<!-- ari:begin -->",gU=new Set(["EACCES","EISDIR","ELOOP","ENOTDIR","EPERM"]);async function Si(t,e){let n=Pb(Nb(t,rt)),r=e!==void 0?e:n?M(t):null,o=Pb(Nb(t,q))?Ht(t):[],s={project:await vU(t),user:await At("user",t)},[i,a,c]=await Promise.all([Promise.all(at.map(mU)),rp(t),Gk(t)]),l=[...n?[kU(t)]:[],...Oe.map((u)=>Pg(_t("hooks",_g(u.name)),_g(u.name),"hooks","project",u.file,()=>un(t,u),()=>Ws(u,W(t,u.file))===W(t,u.file))),...ml("mcp",s),...ml("skill",s),...a===null?[await wU(t,c)]:[]];return{agents:i,configured:SU(r),gitHooksDirectory:c,hookManager:a,initialised:n,pack:r?.pack??null,packs:xn(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 Db(t){let e={user:await At("user",t)};return[...ml("mcp",e),...ml("skill",e)]}async function mU(t){let e=Oe.find((c)=>c.name===t),n=ie.find((c)=>c.agent===t),r=he.find((c)=>c.agent===t),o=dU[t],s=await Ns(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:We.some((c)=>c.name===t),support:e?.support??"partial",userScope:a,version:s.version}}function ml(t,e){return(t==="mcp"?ie:he).flatMap((r)=>Fn.flatMap((o)=>{let s=e[o];if(r[o]===null||s===void 0)return[];let i=_g(r.agent);return[t==="mcp"?fU(i,o,s):hU(i,o,s)]}))}function fU(t,e,n){let r=ie.find((i)=>i.agent===t);if(r===void 0)throw Error(`ari has no mcp target for ${t}`);let o=De(r,n),s=()=>o.install(W(o.base,o.file))===W(o.base,o.file);return Pg(_t("mcp",t),t,"mcp",e,o.file,()=>mn(o),s)}function hU(t,e,n){let r=Jt(t),o=ot.map((c)=>ae(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{...Pg(_t("skill",t),t,"skill",e,r[e],s,i),parts:yU(t,n)}}function yU(t,e){return(wi(()=>$g(Jt(t),e),"").value??[]).map((r)=>({name:r.skill,status:fl(r.installed,r.current)}))}function Pg(t,e,n,r,o,s,i){let a={agent:e,file:se(r,o),id:t,kind:n,scope:r},c=wi(s,a.file);if(c.problem!==null)return{...a,problem:c.problem,status:"outdated"};let l=c.value===!0,u=wi(i,a.file);if(u.problem!==null)return{...a,problem:u.problem,status:l?"outdated":"missing"};return{...a,problem:null,status:fl(l,u.value===!0)}}function kU(t){let e={agent:null,file:Ft,id:cr,kind:"config",scope:"project"},n=wi(()=>W(t,Ft),Ft);if(n.problem!==null)return{...e,problem:n.problem,status:"outdated"};let r=n.value,o=(r??"").includes(pU),s=wi(()=>ki(r)===r,Ft);if(s.problem!==null)return{...e,problem:s.problem,status:"outdated"};return{...e,problem:null,status:fl(o,s.value===!0)}}async function wU(t,e){let n={agent:null,file:e,id:Ye,kind:"git",scope:"project"},r=await bU(()=>Ro(t),e);if(r.problem!==null)return{...n,problem:r.problem,status:"outdated"};let o=r.value===!0;try{let s=await Us(t);return{...n,problem:null,status:fl(o,s.every((i)=>i.action==="unchanged"))}}catch(s){return{...n,problem:Ng(s,e),status:o?"outdated":"missing"}}}function SU(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:Er(n)}))}async function vU(t){return{base:t,receipts:await P(t),scope:"project"}}function fl(t,e){if(!t)return"missing";return e?"current":"outdated"}function wi(t,e){try{return{problem:null,value:t()}}catch(n){return{problem:Ng(n,e),value:null}}}async function bU(t,e){try{return{problem:null,value:await t()}}catch(n){return{problem:Ng(n,e),value:null}}}function Ng(t,e){if(t instanceof m)return{hint:t.hint??"",message:t.message};let n=Tt(t);if(t instanceof Error&&n!==void 0&&gU.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 _g(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 Lb(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 ze(t){return`'${t.replaceAll("'","'\\''")}'`}function hl(t,e){return t.ok?Y(t.name,t.detail):St(t.name,t.detail,t.hint??e)}var EU="agent binaries",TU="ari agents detect";function Mb(t){let e=Object.keys(t.agents).sort(O);if(e.length===0)return[Y(EU,"none configured; 'ari agents add <preset>' adds one for ari run and ari review")];let n=xU(t);return e.map((r)=>$U(r,t.agents[r],n.has(r)))}function $U(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 '${TU}'`;return n?St(r,a,c):ct(r,a,c)}function xU(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 jb}from"fs";import{join as Fb}from"path";var yl="configuration",kl="trust",Gb="ari init",AU="ari doctor",CU=12;function Hb(t){if(!jb(Fb(t,q)))return{check:St(yl,"ari is not set up in this repository: .ari/ does not exist",Gb),config:null,skipReason:"ari is not set up in this repository"};try{let e=M(t);if(!jb(Fb(t,rt)))return{check:ct(yl,`${rt} is missing, so the defaults apply`,Gb),config:e,skipReason:null};return{check:Y(yl,`${rt} is valid (pack ${e.pack})`),config:e,skipReason:null}}catch(e){if(!(e instanceof m))throw e;return{check:St(yl,e.message,`Fix ${rt} by hand, then run '${AU}' again`),config:null,skipReason:"the configuration is not valid"}}}function Ub(t,e){let n=Ve(t,e),r=To();switch(n.state){case"not-required":return Y(kl,"the configuration starts no commands, so nothing needs trust");case"trusted":return Y(kl,`trusted since ${n.trustedAt} (configuration ${n.sha256.slice(0,CU)})`);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(kl,`${o}, but ${Cr}=1 lets ari run them`);return ct(kl,`${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 wl="ari on PATH",RU=/\d+(?:\.\d+)+[\w.+-]*/,Kb="bun add -g @r5n/ariadne";async function Bb(t){let e=bg(Bun.which("ari"));if(!e.ok)return St(wl,e.detail,Kb);let n=await Ns(["ari"]),r=n.path??e.detail;if(n.version===null)return ct(wl,`${r} did not report a version`,`${r} --version`);let o=RU.exec(n.version)?.[0]??n.version;if(o===t)return Y(wl,`${r} (Ariadne ${o})`);return ct(wl,`${r} is Ariadne ${o}, but this is Ariadne ${t}`,`${Kb}@${t}`)}var IU="ari doctor",Vb="git hooks",OU="agents",_U="ari hooks install --agent git",Dg="ari install";function Lg(t){return t.flatMap((e)=>{let n=DU(e);if(e.problem!==null)return[jU(n,e)];if(e.status==="missing")return e.kind==="config"?[FU(n,e)]:[];if(e.status==="current")return[Y(n,LU(e))];return[ct(n,MU(e),qb(e))]})}function Wb(t){let e=at.filter((r)=>t.targets.some((o)=>o.agent===r&&o.status!=="missing"));return[...e.length===0?[ct(OU,"no agent is set up here: no hooks, MCP server or skill is installed",Dg)]:e.flatMap((r)=>PU(t,r)),...NU(t)]}function PU(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=cl({agent:e,file:null,kind:r}),i=Xo(t,[_t(r,e)])[0];if(i!==void 0)return[Y(s,`not needed: ${i.reason}`)];let a=Kr({agent:e,kind:r,scope:"project"})??Dg;return[ct(s,`${n.label} has no ${Xe[r]} installed`,a)]})}function NU(t){if(t.hookManager!==null)return[Y(Vb,`${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(Vb,"not installed: commits and pushes are not checked against the task's scope",_U)]}function DU(t){let e=cl(t);return t.scope==="user"?`${e} (user)`:e}function LU(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 MU(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 jU(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 '${IU}' again`)}function FU(t,e){return ct(t,`${e.file} has no ari block, so agents are not told the loop`,qb(e))}function qb(t){return Kr(t)??Dg}import{existsSync as GU,readdirSync as HU,readFileSync as UU,realpathSync as KU,statSync as BU}from"fs";import{tmpdir as VU}from"os";import{join as Xb,resolve as WU,sep as qU}from"path";var JU=3600,YU=1000,zb=JU*YU,Jb="temporary files",XU=".git",Yb="gitdir:",zU="git worktree prune";async function Zb(t,e=Date.now()){let n=await ZU(t,e);if(n.length===0)return Y(Jb,"no leftover ari-base-* or ari-index-* directory older than one hour");let r=n.map((i)=>`${i.path} (${i.kind}, ${rK(i.ageMs)} old)`),o=n.map((i)=>i.kind==="base worktree"?`git worktree remove --force ${ze(i.path)}`:`rm -r ${ze(i.path)}`),s=n.some((i)=>i.kind==="base worktree")?[zU]:[];return ct(Jb,`${n.length} directory(ies) left behind by an interrupted run: ${r.join("; ")}`,[...o,...s].join(" && "))}async function ZU(t,e){let n=VU(),r=Fa(t),o=await QU(t);return eK(n).flatMap((s)=>{let i=Xb(n,s),a=nK(i,e);if(a===null||a<zb)return[];if(s.startsWith(r))return[{ageMs:a,kind:"temporary index",path:i}];return s.startsWith(Os)&&tK(i,o)?[{ageMs:a,kind:"base worktree",path:i}]:[]})}async function QU(t){try{return Qb(await sn(t,"worktrees"))}catch{return null}}function tK(t,e){if(e===null)return!1;try{let n=UU(Xb(t,XU),"utf8").trim();if(!n.startsWith(Yb))return!1;return Qb(WU(n.slice(Yb.length).trim())).startsWith(`${e}${qU}`)}catch{return!1}}function eK(t){try{return HU(t).filter((e)=>e.startsWith(Os)||e.startsWith(vd))}catch{return[]}}function nK(t,e){try{let n=BU(t);return n.isDirectory()?e-n.mtimeMs:null}catch{return null}}function Qb(t){return GU(t)?KU(t):t}function rK(t){let e=Math.floor(t/zb);return e<1?"under an hour":e===1?"1 hour":`${e} hours`}var tE="knowledge size",eE="sleep",nE="ari sleep",oK="ari doctor";async function rE(t){try{let e=or(await Gr(t));return[sK(e),iK(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 '${oK}' again`)]}}function sK({activeBytes:t,maxBytes:e}){let n=`${t} of ${e} bytes of active knowledge`;if(t<=e)return Y(tE,n);return ct(tE,`${n}: over the budget`,nE)}function iK(t){if(!t.due)return Y(eE,"nothing to consolidate");let e=t.reasons.map((n)=>aK(n,t));return ct(eE,`sleep is due: ${e.join("; ")}`,nE)}function aK(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 Mg="receipts",cK=[{kind:"hooks",name:"hooks.json"},{kind:"mcp",name:"mcp.json"},{kind:"skill",name:"skills.json"}],lK="ari install";function jg(t){let e={edited:0,fixes:[],matches:0,problems:[]};for(let o of t)for(let s of cK){if(s.kind==="hooks"&&o.scope==="user")continue;uK(o,s,e)}if(e.problems.length>0)return ct(Mg,`${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(Mg,"no receipts: nothing was installed through ari here");let r=e.edited===0?"":`; ${e.edited} edited since install, which uninstall keeps`;return Y(Mg,`${e.matches} of ${n} match their files${r}`)}function uK(t,e,n){let r=Kk(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 ${ze(r.path)}`);return}for(let[o,s]of Object.entries(r.receipts))dK(t,e.kind,o,s,n)}function dK(t,e,n,r,o){let s=pK(t,e,n);if(s===null)return;let i=gK(t,n);if(i===void 0)return;let a=mK(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(fK(e,s.agent,t.scope));return}if(i===r.installed)o.matches++;else o.edited++}function pK(t,e,n){if(e==="hooks"){let o=Oe.find((s)=>s.file===n);return o===void 0?null:{agent:o.name,hooks:o}}if(e==="mcp"){let o=ie.find((s)=>s[t.scope]===n);return o===void 0?null:{agent:o.agent,managed:De(o,t)}}let r=lb(t,n);return r===null?null:{agent:r.target.agent,managed:ae(r.target,t,r.skill)}}function gK(t,e){try{return W(t.base,e)}catch{return}}function mK(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 fK(t,e,n){return Kr({agent:e,kind:t,scope:n})??lK}import{accessSync as hK,constants as yK,existsSync as kK}from"fs";import{dirname as sE}from"path";function Zo(t){if(t.kind==="restore")return t.written.flatMap(({before:o,path:s})=>o===null?[]:oE(s,o));let{artifacts:e,context:n,contract:r}=t;return[...Vt(r.text)===r.sha256?[]:["the contract text does not match its SHA-256"],...e.flatMap(({file:o,path:s})=>oE(s,o)),...Z(n.text)===n.sha256?[]:["the context pack does not match its SHA-256"]]}function oE(t,e){return Z(Mr(e))===e.sha256?[]:[`${t} does not match its SHA-256`]}var iE="snapshots";async function aE(t){let e=await P(t),n=Hr(e),r=jn(e),o=r.unreadable.map(({id:c,problem:l})=>({detail:`${c} cannot be read (${l})`,fix:`rm ${ze(sr(e,c))}`})),s=r.entries.flatMap((c)=>{let l=Zo(c);if(l.length===0)return[];return[{detail:`${c.id} is not intact (${l.join("; ")})`,fix:`rm ${ze(sr(e,c.id))}`}]}),i=SK(n),a=[...o,...s,...i===null?[]:[{detail:`${i} is not writable, so automatic snapshots can only warn`,fix:`chmod u+w ${ze(i)}`}]];if(a.length===0)return Y(iE,wK(r.entries.length,new Set(r.entries.map((c)=>c.task)).size));return ct(iE,a.map((c)=>c.detail).join("; "),a.map((c)=>c.fix).join(" && "))}function wK(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 SK(t){let e=vK(t);try{return hK(e,yK.W_OK),null}catch{return e}}function vK(t){let e=t;while(!kK(e)&&sE(e)!==e)e=sE(e);return e}import{join as bK}from"path";var Qo="active task",cE="tasks",EK="active.json",TK=10,$K=new Set(["active","blocked"]),lE="ari list",xK="then run 'ari doctor' again";async function uE(t,e){let n=await P(t);return[AK(t,e,n),...IK(t,e)]}function AK(t,e,n){let r=`rm ${ze(bK(n,EK))}`,o=dE(()=>gt(n));if(o.failure!==null)return St(Qo,`the pointer of this worktree cannot be read: ${o.failure.message}`,r);if(o.value===null)return Y(Qo,"no task is active in this worktree");return CK(t,e,o.value,r)}function CK(t,e,n,r){let{task:o}=n;if(!pe(t).includes(o)){let i=On(t).includes(o)?"its contract is missing":"no such task exists";return ct(Qo,`the pointer of this worktree names "${o}", but ${i}`,r)}let s=dE(()=>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(Qo,`the pointer of this worktree names "${o}", which cannot be read: ${i.message}`,OK(i))}return RK(s.value,r)}function RK({contract:t,record:e},n){let r=t.id;if($K.has(e.status))return Y(Qo,`${r} (${e.status}, stage ${e.stage})`);return ct(Qo,`the pointer of this worktree names "${r}", which is ${e.status}`,n)}function IK(t,e){let{invalid:n,tasks:r}=Nt(t,e);if(n.length===0)return[Y(cE,`${r.length} task(s), every contract and record is readable`)];let o=n.slice(0,TK).map((i)=>St(`task ${i.id}`,i.problem,pE(i.hint))),s=n.length-o.length;return s>0?[...o,St(cE,`${s} more task(s) cannot be read`,lE)]:o}function dE(t){try{return{failure:null,value:t()}}catch(e){if(e instanceof m)return{failure:e,value:null};throw e}}function OK(t){return pE(t.hint??"")}function pE(t){return t.length===0?lE:`${t.replace(/\.$/,"")}, ${xK}`}var gE="git on PATH",_K="ari mcp serve",PK=5000,NK="ari doctor --json",DK="not inside a git working tree",LK="git is not on PATH",MK=["configuration","trust","project integrations","git hooks","agent binaries","tasks","temporary files","sleep and knowledge size","snapshots"],jK=["trust","agent binaries","tasks","sleep and knowledge size","snapshots"];async function mE({cwd:t,version:e}){let n=Bun.which("git"),r=n===null?null:await FK(t),o=[...await Ze("ari on PATH",async()=>[await Bb(e)]),n===null?St(gE,"git is not on PATH, so ari cannot read any repository","Install git"):Y(gE,n)],s=r===null?await GK(t,n===null?LK:DK):await HK(r),i=[...o,...s.checks],a=Lb(i);return{checks:i,ok:a.fail===0,root:r,skipped:s.skipped,summary:a,version:e}}async function FK(t){try{return await Xn(t)}catch(e){if(e instanceof m)return null;throw e}}async function GK(t,e){let n=await Db(t),r=await At("user",t);return{checks:[...Lg(n),...await Ze("ari mcp serve",()=>fE(t,n)),...await Ze("receipts",()=>[jg([r])])],skipped:MK.map((s)=>({name:s,reason:e}))}}async function HK(t){let e=Hb(t),{config:n}=e,r=await Ze("integrations",async()=>{let c=await Si(t,n);return[...Lg(c.targets),...Wb(c),...await fE(t,c.targets)]}),o=await Ze("receipts",async()=>[jg(await KK(t))]),s=await Ze("temporary files",async()=>[await Zb(t)]),i=n===null?{first:[],last:[]}:await UK(t,n),a=e.skipReason;return{checks:[e.check,...i.first,...r,...o,...i.last,...s],skipped:n===null&&a!==null?jK.map((c)=>({name:c,reason:a})):[]}}async function UK(t,e){let n=await Ze("trust",()=>[Ub(t,e)]),r=await Ze("agent binaries",()=>Mb(e)),o=await Ze("tasks",()=>uE(t,e)),s=await Ze("sleep",()=>rE(t)),i=await Ze("snapshots",async()=>[await aE(t)]);return{first:n,last:[...r,...o,...s,...i]}}async function KK(t){return[await At("project",t),await At("user",t)]}async function fE(t,e){let n=e.some((o)=>o.kind==="mcp"&&o.status!=="missing"),r=Bun.which("ari");if(!n||r===null)return[];return[hl(await Eg(r,t,PK),_K)]}async function Ze(t,e){try{return await e()}catch(n){return[BK(t,n)]}}function BK(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}`,NK)}var VK=26,yE=6,WK=" ".repeat(yE),qK={fail:"FAIL",ok:"ok",warn:"warn"};function Fg(t){return t.flatMap((e)=>{let n=`${JK(e.status,hE(qK[e.status],yE))}${hE(e.name,VK)}${e.detail}`;return e.hint===null||e.status==="ok"?[n]:[n,`${WK}fix: ${e.hint}`]})}function kE(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[...Fg(t.checks),...o,"",s].join(`
207
+ `)}function JK(t,e){switch(t){case"ok":return w.green(e);case"warn":return w.yellow(e);case"fail":return w.red(e)}}function hE(t,e){let n=Bun.stringWidth(t);return n>=e?`${t} `:`${t}${" ".repeat(e-n)}`}var YK=1,wE=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 mE({cwd:process.cwd(),version:t.cli.version??""});return t.output.result(e,kE),e.ok?void 0:YK}});function Sl(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 vl(t){return`depends forms a cycle: ${t.join(" -> ")}`}var XK=["ari check","ari done"],zK=["ari next"],ZK='ari new "<title>"',SE=["active","blocked"];function Gg(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 QK(n,t.packs);if(n?.record.status==="blocked")return tB(n,t.packs);let r=e.filter((u)=>!t.claimed.has(u.contract.id)),s=r.filter((u)=>SE.includes(u.record.status)).find((u)=>Ug(u,t.packs)===null);if(s)return eB(s,t.packs);let i=sB(r,t),a=aB(e,r.filter((u)=>!i.has(u.contract.id)));if(a)return rB(a,t.packs);let c=iB(e,r,t,i);if(c)return nB(c);let l=e.find((u)=>u.record.status==="draft");if(l)return oB(l);return{action:"new",commands:[ZK],instruction:"Create a task and write its contract: scope, criteria and checks.",stage:null,task:null}}function QK(t,e){let n=Hg(t,e);return{action:"continue",commands:[...XK],instruction:ko(n,t.contract.id),stage:n.name,task:t.contract.id}}function tB(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:Hg(t,e).name,task:t.contract.id}}function eB(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:Hg(t,e).name,task:t.contract.id}}function nB(t){return{action:"fix",commands:[...zK],instruction:t.instruction,stage:null,task:t.id}}function rB(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 oB(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 Hg(t,e){let n=Ug(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 Ug(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 sB(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,[...fo(s.contract,e),...a]]});return new Map(o.filter(([,s])=>s.length>0))}function iB(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=Sl(g,a);return y?[{id:g,instruction:`${vl(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)=>SE.includes(p.record.status)).flatMap((p)=>{let g=Ug(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 aB(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 cB}from"path";var vE=Error("the design already exists");function bE(t,e,n,r){let o=new Set;return lB(e).flatMap((s)=>{let i=Po(s.path,n);if(o.has(i))return[];return o.add(i),[{created:uB(t,i,ry(r,s.sections??[])),path:i}]})}function lB(t){return t.stages.flatMap((e)=>e.gates.flatMap((n)=>n.kind==="artifact"&&n.sections!==void 0?[n]:[]))}function uB(t,e,n){if(xe(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 Zn(cB(t,e),n,()=>vE),!0}catch(r){if(r===vE)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 dB}from"fs";import{resolve as pB}from"path";var gB="ENOENT";async function vi(t){let e=EE(t),n=new Map;for(let r of await My(t)){if(EE(r)===e)continue;let o=mB(await P(r));if(o!==null&&!n.has(o.task))n.set(o.task,r)}return n}function mB(t){try{return gt(t)}catch(e){if(e instanceof m)return null;throw e}}function EE(t){try{return dB(t)}catch(e){if(Tt(e)===gB)return pB(t);throw e}}var fB=8,hB=6,yB=10,TE=`
208
208
  scope: []
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(`
209
+ `,kB="decision",Kg=10,xE={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>'`},wB=()=>new Date().toISOString();async function AE(t,e,n={}){let r=await ye(t),o=e.trim(),s=ti(o,fB);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=Ke(n.pack??r.config.pack,r.projectPacks),a=[...n.scope??[]],c=a.find((f)=>br(f)!==null);if(c!==void 0)throw new m(`Scope glob ${JSON.stringify(c)} ${br(c)}`,"Pass globs relative to the root");let l=ei(s,Xy(t)),u=SB(zh(o,i.name),a),d=pd(l,kn(n)());Yy(t,r.state,d,u);let p=bE(t,i,l,o),g={contract:Ia(l,u,r.config),record:d};return{contractPath:Ot(l),designs:p,id:l,task:g}}async function CE(t,e,n={}){let r=await ye(t),{task:o}=it(t,e,r.config),s=kn(n)();gd(o.record,s);let i=[...fo(o.contract,r.packs),...AB(o.contract,t),...Wg(r,o.contract)];Bg(e,i,`Fix ${Ot(e)}, then run 'ari ready ${e}'`);let a=Wt(t,r.state,e,(c)=>gd(c,s));return{contract:o.contract,record:a}}async function ts(t,e,n={}){let r=await ye(t),{contractText:o,task:s}=it(t,e,r.config),{contract:i}=s,a=kn(n)();if(RB(r,e),await EB(r,e),Vg(s.record.status))return bB(r,s,a);let c=await Ua(t),l=await Cn(t,i.lock),u=await Zs(t,r.config,i),d={contractHash:Vt(o),gatesHash:Tl(r,i),lockHashes:l,stageTestHashes:u},p=(y)=>gy(y,c,d,a);p(s.record),Bg(e,fo(i,r.packs),`Fix ${Ot(e)}, then start it again`),CB(r,i),await TB(t,e),ME(i,l);let g=Wt(t,r.state,e,p);Pd(r.state,{since:a,task:e});let f={contract:i,record:g};return{...$l(f,lr(r,i)),task:f}}async function RE(t,e={}){let n=await ye(t),{contractText:r,task:o}=FE(n),s=lr(n,o.contract),i=Ln(o,s),a=await Ep({config:n.config,pack:s,root:t,task:o}),c=a.every((d)=>d.ok);Ar(n.state,HE("check",o,i,a,kn(e)()));let l=Vt(r)!==o.record.contractHash,u=Tl(n,o.contract)!==o.record.gatesHash;return{contractChanged:l,gates:a,gatesChanged:u,ok:c,stage:i.name,task:o}}async function IE(t,e={}){let n=await ye(t),r=FE(n),{task:o}=r,{contract:s}=o;GE(n,r);let i=lr(n,s),a=Ln(o,i),c=await Ce(t,[xr]),l=await Ep({config:n.config,pack:i,root:t,task:o}),u=kn(e)();Ar(n.state,HE("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)=>Wt(t,n.state,s.id,(H)=>(OB(o.record,H),N({...H,knowledgeUsed:_B(H.knowledgeUsed,g)})));if(!l.every((N)=>N.ok)){let N=f((A)=>fy(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 Zs(t,n.config,s),S={at:u,gates:l,stage:a.name,testHashes:y,treeHash:c},I=f((N)=>{let H=my(N,S,i.stages.length,y);return H.status==="done"?Da(H,g):H}),C=I.status==="done",J={contract:s,record:I};if(C)return Zy(n.state),qa(n.state,s.id),{...p,attempts:I.attempts,next:null,outcome:"done",task:J};let G=$l(J,i);return{...p,attempts:I.attempts,next:G,outcome:"advanced",task:J}}async function OE(t,e,n,r={}){let o=await ye(t),{contractText:s,task:i}=it(t,e,o.config),{contract:a,record:c}=i,l=Vg(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 Cn(t,a.lock),d=c.status!=="draft"&&c.status!=="done";if(d){let I=[...fo(a,o.packs),...Wg(o,a)];Bg(e,I,`Fix ${Ot(e)}, then run 'ari amend ${e}' again`)}if(l)$B(i,lr(o,a));let p=d?Ln(i,lr(o,a)).name:null;if(l)ME(a,u);let g=l?await Zs(t,o.config,a):{...c.stageTestHashes},y={base:r.onto===void 0?null:await Ly(t,"HEAD",await wo(t,r.onto)),contractHash:Vt(s),gatesHash:Tl(o,a),lockHashes:u,reason:n,stage:p,stageTestHashes:g},S=kn(r)();return md(c,y,S),{contract:a,record:Wt(t,o.state,e,(I)=>md(I,y,S))}}async function _E(t,e,n,r={}){let o=await ye(t),{task:s}=it(t,e,o.config),i=kn(r)(),a=Wt(t,o.state,e,(c)=>hy(c,n,i));return{contract:s.contract,record:a}}async function PE(t,e,n,r={}){let o=await ye(t),{task:s}=it(t,e,o.config),i=kn(r)();fd(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=ti(a,hB),d=ei(u.length>0?u:kB,an(t));Wa(t,{created:i.slice(0,yB),id:d,kind:"decision",scope:[...s.contract.scope],sources:[e],status:"active",supersededBy:null,supersedes:[],text:a});let p=Wt(t,o.state,e,(g)=>fd(g,n,i));return{knowledgeId:d,task:{contract:s.contract,record:p}}}async function NE(t,e,n,r={}){let o=await ye(t),s=it(t,e,o.config),{contract:i,record:a}=s.task,c=lr(o,i);if(a.status==="active")GE(o,s);let l=Ln(s.task,c),u=await Tp(t,l,e),d=kn(r)(),p=Wt(t,o.state,e,(g)=>(IB(a,g),yy(g,{...u,by:n,stage:l.name},d)));return{contract:i,record:p}}async function DE(t,e,n={}){let r=await ye(t),o=n.task??jE(r),{task:s}=it(t,o,r.config),i=kn(n)(),a=Wt(t,r.state,o,(c)=>ky(c,e,i));return{contract:s.contract,record:a}}async function bl(t){let e=await ye(t),n=gt(e.state),r=n===null?null:vB(e,n.task);if(r!==null&&Vg(r.record.status))return Gg({...{claimed:new Set,invalid:[],uncoveredLocks:new Map},active:n,packs:e.packs,tasks:[r]});let{invalid:o,tasks:s}=Nt(t,e.config),i=new Set((await vi(t)).keys()),a=await xB(t,s);return Gg({active:n,claimed:i,invalid:o,packs:e.packs,tasks:s,uncoveredLocks:a})}async function El(t,e={}){let n=await ye(t),r=Nt(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 Gn(t,e){let n=await ye(t),{task:r}=it(t,e,n.config),s=r.record.status==="active"||r.record.status==="blocked"?$l(r,lr(n,r.contract)):null;return{active:gt(n.state)?.task===e,instruction:s?.instruction??null,stage:s?.stage??null,task:r}}async function ye(t){let e=M(t),n=Ht(t);return{config:e,packs:xn(n),projectPacks:n,root:t,state:await P(t)}}function kn(t){return t.clock??wB}function Tl(t,e){let n=t.packs.find((r)=>r.name===e.pack);return n===void 0?null:Na(n,t.config)}function lr(t,e){return Ke(e.pack,t.projectPacks)}function $l(t,e){let n=Ln(t,e);return{instruction:ko(n,t.contract.id),stage:n.name}}function SB(t,e){if(e.length===0)return t;if(!t.includes(TE))throw Error("The contract template has no empty scope line");return t.replace(TE,()=>`
210
+ scope: ${mo(e)}
211
+ `)}function Bg(t,e,n){if(e.length===0)return;let r=e.map((o)=>` - ${o}`).join(`
212
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=`
213
+ ${r}`,n)}function Vg(t){return t==="active"||t==="blocked"}function vB(t,e){return pe(t.root).includes(e)?it(t.root,e,t.config).task:null}function bB(t,e,n){let r=e.contract.id;if(gt(t.state)?.task!==r)Pd(t.state,{since:n,task:r});return{...$l(e,lr(t,e.contract)),task:e}}async function EB(t,e){let n=(await vi(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 TB(t,e){let n=re(await Ae(t,"HEAD"));if(n.length===0)return;let r=n.length-Kg,o=r>0?` and ${r} more`:"",s=(await Ba(t)).filter((a)=>n.includes(a)),i=s.length===0?"":`; git hides ${s.slice(0,Kg).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,Kg).join(", ")}${o}`,`Commit, stash or ignore them, then run 'ari start ${e}'; the scope gate counts every change since the start commit${i}`)}function $B(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 xB(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 Cn(t,r));return new Map(n.flatMap((s)=>{let i=LE(s.contract,o);return i===void 0?[]:[[s.contract.id,i]]}))}function LE(t,e){return t.lock.find((n)=>!e.some((r)=>et(r,[n])))}function ME(t,e){let n=LE(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 ${Ot(t.id)}: escape [ ] { } * ? with a backslash, and lock only files that are not ignored`)}function Wg(t,e){let{tasks:n}=Nt(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=Sl(e.id,(s)=>r.get(s)??[]);return o===null?[]:[vl(o)]}function AB(t,e){let n=new Set(pe(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 CB(t,e){let n=new Set(pe(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=Wg(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 RB(t,e){let n=gt(t.state);if(n===null||n.task===e||!pe(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`,xE[r](n.task))}function jE(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 FE(t){let e=jE(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"}`,xE.blocked(e));throw new m(`Task "${e}" is ${o}, not active`,"Run 'ari next' to see what to do")}function GE(t,{contractText:e,task:n}){let{contract:r}=n;if(Vt(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(Tl(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 IB(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 OB(t,e){if(pt($E(t))===pt($E(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 $E(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 _B(t,e){let n=e.flatMap((r)=>{let o=r.detail[So];return r.type==="context"&&Array.isArray(o)?o:[]});return[...new Set([...t,...n])].sort(O)}function HE(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 PB=20,NB=`
214
214
 
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}
215
+ `,DB=["advanced","done","failed"];async function qg(t,e={}){let n=await IE(t,e),r=n.outcome==="done"?await Fr(t):null,o=n.outcome==="advanced"?await Ko(t,n.task.contract.id,"stage",e):{id:null,warning:null};return{...n,sleep:r,snapshot:o.id,snapshotWarning:o.warning}}async function UE(t,e){let n=M(t),r=(a)=>Ir(n,{agent:e.agent,model:e.model,role:"task",route:LB(n,a)});for(let a of MB(n,e))Ir(n,{agent:e.agent,model:e.model,role:"task",route:a});await Qn({config:n,root:t},"run an agent");let o=await GB(t,e),s=[],i=null;for(;;){let a=await Gn(t,o),c=r(a.stage??""),l=await UB(t,o,i),u=a.task.record.history.length,d=await za(c,l,{cwd:t,environment:Xa(c.config),stdout:e.output??"inherit",trust:{config:n,root:t}}),p=await jB(t,o,u)??await qg(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 LB(t,e){return t.routing.stages[e]??t.routing.default}function MB(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 jB(t,e,n){let r=await Gn(t,e),{contract:o,record:s}=r.task,i=s.history.slice(n).findLast((c)=>DB.includes(c.type)),a=FB(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 FB(t,e){if(t==="done"||t==="blocked")return t;if(e==="failed")return"failed";return e==="advanced"?"advanced":null}async function GB(t,e){if(e.task===void 0)return HB(t,e.clock);let n=await Gn(t,e.task),{question:r,status:o}=n.task.record,s=n.task.contract.id;switch(o){case"ready":return(await ts(t,s,{clock:e.clock})).task.contract.id;case"active":if(!n.active)await ts(t,s,{clock:e.clock});return s;case"blocked":throw new m(`Task "${s}" is blocked: ${r??"no question was recorded"}`,KE(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 HB(t,e){let n=await bl(t);if(n.task!==null&&n.action==="continue")return n.task;if(n.task!==null&&n.action==="start")return(await ts(t,n.task,{clock:e})).task.contract.id;if(n.task!==null&&n.action==="resolve")throw new m(`Task "${n.task}" is blocked`,KE(n.task));throw new m(`No task can run: ${n.instruction}`,`Run ${n.commands.map((r)=>`'${r}'`).join(", ")}`)}function KE(t){return`A human answers it with 'ari resolve ${t} --answer <text>'`}async function UB(t,e,n){let r=await Gn(t,e),o=(await rr(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?[]:[KB(n)];return[o,s,...a,i].join(NB)}function KB(t){let e=t.gates.filter((n)=>!n.ok).flatMap((n)=>BB(n));return[`'ari done' failed (attempt ${t.attempts} of ${t.budget}):`,...e].join(`
217
+ `)}function BB(t){let e=t.details.slice(0,PB).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 BE(t,e={}){let n=e.task===void 0?void 0:zn(e.task),r=jn(await P(t));return{entries:r.entries.filter((o)=>n===void 0||o.task===n).map(VB),unreadable:r.unreadable}}async function VE(t,e){let n=Uo(await P(t),e),r=Zo(n);return{entry:n,integrity:{ok:r.length===0,problems:r}}}function VB(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 Vr=["draft","ready","active","blocked","done"],WB="fact";function WE(t){return{id:t.contract.id,pack:t.contract.pack,status:t.record.status,title:t.contract.title}}async function xl(t){return bl(t)}async function Al(t,e){let n=await El(t,e.length===0?{}:{statuses:e});return{invalid:n.invalid,tasks:n.tasks.map(WE)}}async function Cl(t,e){return Gn(t,e)}async function Rl(t,e){let n=await AE(t,e.title,{pack:e.pack,scope:e.scope}),r=n.designs.length===0?{}:{designs:n.designs};return{contractPath:n.contractPath,...r,...WE(n.task)}}async function Il(t,e){let n=await CE(t,e);return{id:n.contract.id,status:n.record.status}}async function Ol(t,e){let n=await ts(t,e),{record:r}=n.task;return{base:r.base,id:r.id,instruction:n.instruction,stage:n.stage}}async function _l(t,e,n){let r=await _E(t,e,n);return{id:r.contract.id,question:r.record.question,status:r.record.status}}async function Pl(t){let e=await RE(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 Nl(t){let e=await qg(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 Dl(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??WB;if(!cS(i))throw new v(`--kind must be one of ${ue.join(", ")}, got "${i}"`,"Pass --kind fact");if(n)return{entry:await uS(t,{kind:i,scope:[...o??[]],text:s}),target:"knowledge"};let a=await DE(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 Ll(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 rr(t,{budget:n,id:e.id})}function Ml(t,e,n){return dS(t,e,{all:n})}async function jl(t,e){return Yp(t,e)}async function Fl(t,e){return BE(t,{task:e})}async function Gl(t,e){return VE(t,e)}function qE(t){return t.map((e)=>{let n=Vr.find((r)=>r===e);if(n!==void 0)return n;throw new v(`Unknown status "${e}"`,`Choose from ${Vr.join(", ")}`)})}async function JE(t,e={}){let n=e.staged??!1,{config:r,drift:o,task:s}=await Qa(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=re(n?await qB(t):await Ae(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 qB(t){let e=await F(t,["diff","--cached","--name-only","--no-renames","-z"]);return Be(e.stdout)}var Jg=1,YE=E({description:"Print the one next action",examples:["ari next","ari next --json"],json:!0,name:"next",run:async(t)=>{t.output.result(await xl(await _()),JB)}}),XE=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 Pl(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[ic(n.gates),`${r} for "${n.task}"`,...s].join(`
219
+ `)}),e.failed?Jg:void 0}}),zE=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 Nl(await _());for(let n of e.warnings??[])process.stderr.write(`${n}
220
+ `);return t.output.result(e.data,YB),e.failed?Jg:void 0}}),ZE=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 JE(await _(),{staged:t.args.staged});return t.output.result(e,zB),e.ok?void 0:Jg}});function JB(t){return[t.instruction,...t.commands.map((e)=>` ${e}`)].join(`
221
+ `)}function YB(t){let e=t.snapshot===void 0?[]:[`Snapshot ${t.snapshot} saved`];return[XB(t),...e].join(`
222
+ `)}function XB(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[ic(t.gates.filter((e)=>!e.ok)),`Stage ${t.stage} failed: attempt ${t.attempts} of ${t.budget}`].join(`
223
+ `);case"blocked":return[ic(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 zB(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 QE(t,e,n){let r=`ari hooks ${t} --agent`;return E({args:j({agent:{description:`Agent: ${ig().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),t2)}})}var ZB=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 Fv(await _());t.output.result({agents:e},({agents:n})=>n.map(e2).join(`
226
+ `))}}),tT=E({description:"Install, uninstall and list agent and git hook integrations",name:"hooks",subcommands:[QE("install","Install ari hooks into an agent's project settings or into git",Vo),QE("uninstall","Remove ari hooks from an agent's project settings or from git, and nothing else",jv),ZB]}),eT=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 Gv(t.positionals.agent,t.positionals.event,e,process.cwd());if(n.warning!==null)process.stderr.write(`${n.warning}
227
227
  `);if(n.stdout.length>0)process.stdout.write(`${n.stdout}
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(`
228
+ `);if(n.expired)await QB()}});async function QB(){return await new Promise((t)=>process.stdout.write("",()=>t())),process.exit()}function t2(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 e2(t){let e=t.installed?"installed":"not installed";return`${t.agent} ${t.support} ${e} ${t.file} ${t.events.join(", ")}`}var nT=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 _r(e,()=>mb(e,{agents:qe(t.args.agents),gitHooks:t.args.gitHooks,mcp:qe(t.args.mcp),pack:t.args.pack,skills:qe(t.args.skills)}));t.output.result(n,n2)}});function n2(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 r2="--hooks, --mcp, --skills or --git-hooks";function rT(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:s2(t.agent),init:t.init,kinds:e.size===0?void 0:e,pack:bi(t.pack,"--pack"),routing:i2(t),scope:t.scope===void 0?void 0:ir(t.scope)}}function oT(t){return Object.values(t).some((e)=>e!==void 0)}function Yg(t,e){return[...ar.filter((r)=>e.has(r)).flatMap((r)=>t.map((o)=>_t(r,o))),...e.has("git")?[Ye]:[]]}function Xg(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?[]:pl(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(r2);if(r.length>0)throw o2(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?Ab(t,i,c,o):Yg(i,e.kinds??new Set)}}function o2(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 s2(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(dl(n))return n;throw new v(`ari install has no agent "${n}"`,`Choose from: ${at.join(", ")}`)})}function i2(t){let e=bi(t.taskAgent,"--task-agent"),n=bi(t.reviewAgent,"--review-agent"),r=bi(t.taskModel,"--task-model"),o=bi(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 bi(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 cT}from"path";import{isDeepStrictEqual as Zg}from"util";var a2=1,c2=":",sT="routing.default",l2="review.agent";function aT(t,e){let n=oe(rt,t),r=zg(n,"agents"),o=zg(n,"routing"),s=zg(n,"review"),i=u2(r,e),a=i.flatMap(({entry:g,name:f})=>g===null?[]:[[f,g]]),c=m2(o.default,sT,e.task)?o.default:g2(e.task),l=f2(s,e.review)?s:h2(s,e.review),u={...n,agents:{...r,...Object.fromEntries(a)},review:l,routing:{...o,default:c}},d=xa(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:iT(o.default,c),agent:e.task.agent,detail:`tasks: ${Wr(e.task)}`,key:sT},{action:iT(s.agent===void 0?void 0:s,l),agent:e.review.agent,detail:`reviews: ${Wr(e.review)}`,key:l2}],next:tr(t,u)}}function u2(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])=>d2(r,o,t[r]))}function Wr(t){return t.model===null?`${t.agent} (CLI default model)`:`${t.agent} (${t.model})`}function d2(t,e,n){let r=We.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:Ao(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: ${We.map((l)=>l.name).join(", ")}`)}let s=p2(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&&xo.some((l)=>Zg(n,Ao(r,l,i)));if(r!==void 0&&a)return{action:"updated",entry:Ao(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`,a2,{tag:"AgentRoleMismatch"})}function p2(t){if(!z(t)||!Array.isArray(t.roles))return Yu;return t.roles.filter((e)=>typeof e==="string")}function zg(t,e){let n=t[e];return z(n)?n:{}}function g2(t){return t.model===null?t.agent:`${t.agent}${c2}${t.model}`}function m2(t,e,n){if(t===void 0||t===null)return!1;try{return Zg(Es(t,e),n)}catch{return!1}}function f2(t,e){return t.agent===e.agent&&(t.model??null)===e.model}function h2(t,e){let{model:n,...r}=t;return{...r,agent:e.agent,...e.model===null?{}:{model:e.model}}}function iT(t,e){if(t===void 0||t===null)return"created";return Zg(t,e)?"unchanged":"updated"}var y2=new Set(["created","updated","unchanged"]),k2="Fix the cause, then run 'ari install' again; it keeps what is already done";async function Hl(t,e,n,r={}){let o={mode:n,plan:e,root:t,scopes:await C2(t),view:A2(n)},s=[],i=!1;for(let a of e.targets){if(i||a.skip!==null){s.push(Ti(a,i?"pending":"skipped",i?null:a.skip));continue}r.start?.(a);try{let c=await w2(o,a);s.push(...c),r.done?.(a,c)}catch(c){let l={...Ti(a,"failed",qn(c)),hint:I2(c)};s.push(l),r.failed?.(a,l),i=!0}}return{failed:i,rows:s}}async function w2(t,e){if(e.id===Cg)return[Ei(e,S2(t))];if(e.id===cr)return[Ei(e,v2(t))];let{agent:n}=e;switch(e.kind){case"hooks":return[Ei(e,await b2(t,Qg(n)))];case"mcp":return[Ei(e,E2(t,Qg(n),e.scope))];case"skill":return[Ei(e,T2(t,Qg(n),e.scope))];case"git":return $2(t,e);case"routing":return x2(t,e);case"config":throw Error(`ari has no configuration target "${e.id}"`)}}function S2({mode:t,plan:e,root:n,view:r}){if(t==="apply")return wg(n,e.pack);return $i(r,n,rt,(o)=>Sg(o,e.pack))}function v2({mode:t,root:e,view:n}){if(t==="apply")return kg(e).action;return $i(n,e,Ft,ki)}async function b2({mode:t,root:e,view:n},r){let o=Ne(r);if(t==="preview")return $i(n,e,o.file,(i)=>Ws(o,i));let s=await Vo(e,r);return"action"in s?s.action:"unchanged"}function E2({mode:t,scopes:e,view:n},r,o){let s=e[o];if(t==="apply")return qo(fe(r),s).action;let i=De(fe(r),s);return $i(n,i.base,i.file,(a)=>i.install(a))}function T2({mode:t,scopes:e,view:n},r,o){let s=e[o],i=Jt(r);if(t==="apply"){let c=Jo(i,s);return sl(c,r),gg(c.flatMap((l)=>l.action==="refused"?[]:[l.action]))}let a=ot.map((c)=>{let l=ae(i,s,c);return $i(n,l.base,l.file,(u)=>l.install(u))});return gg(a)}async function $2({mode:t,root:e},n){return(t==="apply"?(await lc(e)).files:await Us(e)).map(({action:o,path:s})=>({...Ti(n,tm(o),null),file:s}))}function x2({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=aT(i,s);if(t==="apply")Re(n,rt,a.next);else r.write(n,rt,a.next);return a.changes.map((c)=>({...Ti(o,tm(c.action),null),agent:c.agent,detail:c.detail,key:c.key}))}function $i(t,e,n,r){let o=t.read(e,n),s=r(o);return t.write(e,n,s),Ms(o,s)}function A2(t){let e=new Map;return{read:(n,r)=>e.get(cT(n,r))??W(n,r),write:(n,r,o)=>{if(t==="preview")e.set(cT(n,r),o)}}}async function C2(t){return{project:{base:t,receipts:await P(t),scope:"project"},user:await At("user",t)}}function Ei(t,e){return Ti(t,tm(e),null)}function Ti(t,e,n){let r=t.file===null?null:t.file;return{action:e,agent:t.agent,detail:null,file:r===null?null:R2(t.scope,r),hint:null,key:null,kind:t.kind,reason:n,scope:t.scope,undo:y2.has(e)?hb(t):null}}function R2(t,e){return t==="user"&&!e.startsWith("~/")?se(t,e):e}function tm(t){return t==="removed"?"updated":t}function Qg(t){if(t!==null)return t;throw Error("This target needs an agent")}function I2(t){if(t instanceof m&&t.hint!==void 0&&t.hint.length>0)return t.hint;return k2}import{rmSync as O2}from"fs";var _2="knowledge",lT="Every 'ari sleep' pass and '--apply' writes an entry under <git-path>/ari/sleep/",P2=()=>new Date().toISOString();async function dT(t,e,n={}){let r=await P(t),o=(n.clock??P2)();return Lr(r,()=>{let s=mT(t,r,e);for(let c of s.restore)Pn(_e(t,c.id),Mr(c.original));for(let c of s.remove)O2(_e(t,c.id),{force:!0});for(let{notes:c,task:l}of s.unpromote)Wt(t,r,l,(u)=>vy(u,c));let i=fT(s),a=jo(r,o,{kind:"undo",removed:i.removed,restored:i.restored,undoes:s.target.id,unpromoted:i.unpromoted});return{...i,ledger:a.id}})}async function pT(t,e){let n=await P(t);return{...fT(mT(t,n,e)),dryRun:!0}}async function gT(t,e){let n=oi(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 Lr(r,()=>{let o=_e(t,e),s=Go(o),i=li(r),a=ui(i),c=i.filter(Mo).filter((l)=>!a.has(l.id)).reverse().flatMap((l)=>l.archived).find((l)=>l.id===e&&l.sha256===s)?.original;if(c===void 0)ri(t,{...n,status:"active",supersededBy:null});else Pn(o,Mr(c));return oi(t,e)})}function mT(t,e,n){let r=N2(li(e),n),o=[],s=r.archived.filter((a)=>{let c=Hp(_e(t,a.id));if(c===a.sha256)return!0;if(c!==a.original.sha256)o.push(`${uT(a.id)} ${c===null?"is missing":"changed after sleep archived it"}`);return!1}),i=r.created.filter((a)=>{let c=Hp(_e(t,a.id));if(c===null)return!1;if(c===a.sha256)return!0;return o.push(`${uT(a.id)} changed after sleep created it`),!1});if(o.length>0){let a=o.map((c)=>` - ${c}`).join(`
231
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}
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:D2(t,r.promoted)}}function N2(t,e){let n=ui(t);if(e===void 0){let s=t.filter(Mo).findLast((i)=>!n.has(i.id)&&Ul(i));if(s!==void 0)return s;throw new m("The sleep ledger has no entry that changed knowledge and is not undone yet",lT)}let r=ii(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(!Mo(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}`,lT);if(!Ul(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 Ul(t){return t.archived.length>0||t.created.length>0||t.promoted.length>0}function D2(t,e){let n=new Set(On(t));return e.flatMap(({notes:r,task:o})=>{if(!n.has(o))return[];let s=_n(t,o),i=r.filter((a)=>s.notes[a]?.promoted===!0);return i.length===0?[]:[{notes:i,task:o}]})}function fT(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 uT(t){return`${q}/${_2}/${t}.md`}var L2=3,hT=new Set(["active","blocked"]);async function yT(t){let e=Kl(()=>M(t));if(e===null)return[];let n=await P(t),r=Kl(()=>Nt(t,e)),o=r?.tasks??[],s=Kl(()=>gt(n))?.task??null,i=await M2(t,o,s),a=o.some((l)=>l.contract.id===s&&hT.has(l.record.status));return["ari next",...o.length+(r?.invalid.length??0)>0?["ari list"]:[],...i.slice(0,L2).map((l)=>`ari start ${l}`),...a?["ari context"]:[],...await F2(t,n)]}async function M2(t,e,n){let r=e.filter((s)=>hT.has(s.record.status)&&s.contract.id!==n);if(r.length===0)return[];let o=await j2(t);return r.map((s)=>s.contract.id).filter((s)=>!o.has(s))}async function j2(t){try{return await vi(t)}catch{return new Map}}async function F2(t,e){let n=await U2(()=>G2(t)),r=Kl(()=>H2(e));return[...n===!0?["ari sleep"]:[],...r===!0?["ari sleep --undo"]:[]]}async function G2(t){return or(await Gr(t,{candidates:!1})).due}function H2(t){let e=li(t),n=ui(e);return e.some((r)=>Mo(r)&&!n.has(r.id)&&Ul(r))}async function U2(t){try{return await t()}catch(e){if(e instanceof m)return null;throw e}}function Kl(t){try{return t()}catch(e){if(e instanceof m)return null;throw e}}import{homedir as K2}from"os";var xi=72,B2="ari install",V2="ari uninstall",kT=44,W2=28,wT=8,q2="Kept: .ari/ data, the AGENTS.md block, routing and trust",J2=[["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"]],bT=['ari new "Describe the first task"',"ari next"],nm=20,ST=26,em=13,ET=8,qr=11,TT=34,vT=12,Y2=/\d+(?:\.\d+)+[\w.+-]*/,$T="\u2026",X2="~",Bl=".ari/config.json",xT=new Set(["created","updated"]),Yt=" ",z2=`${w.green("\u2713")} installed ${w.yellow("\u2191")} update ${w.dim("\xB7")} not installed ${w.dim("\u2013")} not supported`,Z2={created:"create",failed:"fail",pending:"not run",skipped:"skip",unchanged:"unchanged",updated:"update"};function AT(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=[es("Repository",pV(t.root)),es("Ariadne",`${e} \xB7 ${n}`),...r===void 0?[]:[es("AGENTS.md",`${PT(r)} ari block`)],...lV(t),es("Git hooks",uV(t))],s=w.dim([ut("Agent",nm),ut("On PATH",em),...ar.map((a)=>ut(dV(a),ET))].join("")),i=at.map((a)=>aV(t,Gt(t,a)));return[...o,"",s,...i,"",z2].map(Me).join(`
233
+ `)}function CT(t,e,n){let r=new Map,o=[];for(let c of t){if(c.kind==="routing")continue;if(c.action==="skipped"){let u=Jr(c.reason??"",xi-Yt.length*2).map((d)=>`${Yt}${Yt}${w.dim(d)}`);o.push(`${Yt}${ur(e,c)}`,...u);continue}let l=iV(e,c);r.set(l,[...r.get(l)??[],rV(c)])}let s=[...r].flatMap(([c,l])=>[w.bold(c),...l]),i=n===null?[]:sV(t,n),a=o.length===0?[]:[w.bold("Skipped"),...o];return[...s,...i,...a].map(Me).join(`
234
+ `)}function RT(t,e){let[n]=e;if(n===void 0)return"";if(n.kind==="routing"){let o=e.filter((i)=>xT.has(i.action)).map((i)=>i.key??""),s=o.length===0?"unchanged":"updated";return Me(`${ut("Routing",ST)}${ns(s,!1)}${o.join(", ")||Bl}`)}let r=e.map((o)=>o.file??"").join(", ");return Me(`${ut(ur(t,n),ST)}${ns(n.action,!1)}${r}`)}function IT(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 Me(`${n} ${ut(e.name,nm)}${r}`)}).join(`
235
+ `)}function Yr(t,e){return[...Jr(t,xi),...Jr(e,xi).map((r)=>w.dim(r))].join(`
236
+ `)}function Jr(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 rm(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)=>`${Yt}${o}`)].map(Me).join(`
238
+ `)}function om(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,kT)}${Q2(o)}`]});if(n.length===0)return[];let r=n.length-wT;return[`${ut(V2,kT)}everything ari installed`,...n.slice(0,wT),...r>0?[`and ${r} more: see "undo" in --json`]:[],q2].map(Me)}function sm(t){return t.resume.map((e)=>Me(`${ut(e,W2)}${tV(e)}`))}function Q2(t){if(t.kind==="git")return"git hooks";let e=t.kind==="hooks"||t.kind==="mcp"||t.kind==="skill"?Xe[t.kind]:t.kind;return`${t.agent??""} ${e}`.trim()}function tV(t){return J2.find(([n])=>n.endsWith(" ")?t.startsWith(n):t===n)?.[1]??""}function eV(t){let e=om(t),n=sm(t);return[...e.length===0?[]:["","To undo",...e.map((r)=>`${Yt}${r}`)],...n.length===0?[]:["","To get back to your tasks",...n.map((r)=>`${Yt}${r}`)]]}function OT(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,qr)}${ut(a.file??"-",TT)} ${c}${l}${u}`}),n=t.warnings.flatMap((a)=>[`warning: ${a.message}`,` ${a.fix}`]),r=t.check?Fg(t.checks.map((a)=>hl(a,B2))):t.checks.map((a)=>`check ${a.ok?"ok":"FAILED"}: ${a.name}: ${a.detail}${a.hint===null?"":` (${a.hint})`}`),o=t.check?[nV(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?eV(t):[]].join(`
239
+ `)}function nV(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 ur(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?"":`${_T(t,e.agent)} `}${Xe[e.kind]}`}function ns(t,e){let n=ut(e?Z2[t]:t,qr);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 Me(t){if(Bun.stringWidth(t)<=xi)return t;return`${Bun.sliceAnsi(t,0,xi-1)}${$T}`}function Vl(t){if(t.path===null)return"not found";let e=Y2.exec(t.version??"")?.[0]??t.version??"found";return e.length>vT?`${e.slice(0,vT-1)}${$T}`:e}function rV(t){let e=t.kind==="config"&&t.file==="AGENTS.md"?"ari block":oV[t.kind],n=t.action==="failed"?w.red(t.reason??""):w.dim(e);return`${Yt}${ns(t.action,!0)}${ut(t.file??"",TT)} ${n}`}var oV={config:"configuration",git:"git hook",hooks:"hooks",mcp:"MCP server",routing:"routing",skill:`${ot.length} skills`};function sV(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)&&xT.has(u.action)).map((u)=>u.key??""),i=s("agents."),a=[...s("routing."),...s("review.")],c=r!==void 0?[`${Yt}${ns("failed",!0)}${w.red(r.reason??"")}`]:o?[`${Yt}${ns("pending",!0)}${Bl}`]:i.length+a.length===0?[`${Yt}${ns("unchanged",!0)}${Bl}`]:[...i.length===0?[]:[`${Yt}${w.green(ut("add",qr))}${i.join(", ")}`],...a.length===0?[]:[`${Yt}${w.yellow(ut("set",qr))}${a.join(", ")}`]];return[`${w.bold("Routing")} ${w.dim(Bl)}`,`${Yt}${ut("tasks",qr)}${Wr(e.task)}`,`${Yt}${ut("reviews",qr)}${Wr(e.review)}`,...c]}function iV(t,e){if(e.agent!==null)return _T(t,e.agent);return e.kind==="git"?"Git hooks":"Repository"}function _T(t,e){return t.agents.find((n)=>n.agent===e)?.label??e}function aV(t,e){let n=e.path===null?w.dim(ut("not found",em)):ut(Vl(e),em),r=ar.map((o)=>ut(cV(t,e.agent,o),ET));return[ut(e.label,nm),n,...r].join("")}function cV(t,e,n){if(!Gt(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 lV(t){let{review:e,task:n}=t.routing;if(n===null&&e===null)return[];let r=n===null?"tasks: not set":`tasks ${Wr(n)}`,o=e===null?"reviews: not set":`reviews ${Wr(e)}`;return[es("Routing",r),es("",o)]}function uV(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`${PT(e)} ${e.status==="missing"?"not installed":"pre-commit, pre-push"}`}function PT(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 dV(t){return t==="mcp"?"MCP":t==="hooks"?"Hooks":"Skill"}function es(t,e){return`${ut(t,qr+1)}${e}`}function pV(t){let e=K2();return t===e||t.startsWith(`${e}/`)?`${X2}${t.slice(e.length)}`:t}function ut(t,e){let n=Bun.stringWidth(t);return n>=e?`${t} `:`${t}${" ".repeat(e-n)}`}var gV="install plan",mV=new Set(["created","updated"]),fV=/^[\w@%+=:,./-]+$/,im=6;function NT(t,e,n){let r=e.filter((a)=>mV.has(a.action));if(r.length===0)return null;let o=[...new Set(r.map((a)=>ur(t,a)))],s=o.slice(0,im).join(", "),i=o.length>im?` and ${o.length-im} more`:"";return{detail:`${r.length} file(s) would change: ${s}${i}`,hint:hV(n),name:gV,ok:!1}}function hV(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} ${yV(o)}`]}),"--yes"].join(" ")}function yV(t){return fV.test(t)?t:`'${t.replaceAll("'","'\\''")}'`}var DT="basic",kV=2,wV="CLI default";async function FT(t,e){let{init:n,pack:r}=await SV(t,e),o=e.agents??await vV(t);OV(t,{agents:o,init:n,scope:"project",targets:[]},["agent-not-found"]);let s=e.scope??await bV(t,o);if(s==="user"&&o.includes("claude"))rs("Claude Code keeps user-scope MCP servers in its own state file, which ari does not edit",`Run: ${ul}`);let i=e.kinds===void 0?await EV(t,o,s,n):Yg(o,e.kinds),a=e.routing??await xV(t,o,t.initialised||n);return{agents:o,init:n,pack:r,recommended:!1,routing:a,scope:s,targets:i}}async function SV(t,e){let n=e.init===!0||e.pack!==void 0;if(t.initialised||n)return{init:n,pack:e.pack??null};if(rs(".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 Te({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 hr({initialValue:DT,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===DT?null:o}}async function vV(t){return oa({initialValues:pl(t),message:"Which agents do you use in this repository?",options:at.map((e)=>{let n=Gt(t,e),r=n.path===null?"not on PATH":Vl(n),o=n.support==="verified"?"hooks verified":"hooks in part",s=n.kinds.filter((i)=>i!=="hooks").map((i)=>Xe[i]);return{hint:`${r} \xB7 ${[o,...s].join(", ")}`,label:n.label,value:e}}),required:!1})}async function bV(t,e){if(!e.some((r)=>Gt(t,r).userScope.length>0))return"project";let n=e.includes("claude")?"; Claude Code's MCP server stays per repository":"";return hr({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 EV(t,e,n,r){await TV(t);let o=Br(t,e,n,r).filter((u)=>u.skip===null);for(let u of o.filter((d)=>d.problem!==null))rs(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?[]:[Ye];let i=s.map((u)=>u.id),a=new Map(Xo(t,i).map(({id:u,reason:d})=>[u,d])),c=await oa({initialValues:Cb(t,e,n,r),message:"What should ari install?",options:s.map((u)=>({hint:a.get(u.id)??CV(u),label:RV(t,u),value:u.id})),required:!1}),l=await $V(t,{agents:e,init:r,scope:n,targets:c});return t.hookManager===null?l:[...l,Ye]}async function TV(t){let e=t.hookManager;if(e===null)return;if(rs(`${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"),Dt(e.lines.join(`
240
+ `),"Git hook lines",{format:(r)=>r}),!await Te({initialValue:!0,message:"Continue without git hooks?"}))throw new vt}async function $V(t,e){let n=[...e.targets],r=gl(t,HT({...e,targets:n})).filter((o)=>o.code==="hooks-twice"||o.code==="skill-twice");for(let o of r){if(rs(o.message,o.fix),o.drop.length===0)continue;let s=o.drop.map((i)=>GT(t,i)).join(" and ");if(await Te({initialValue:!0,message:`Leave out the ${s}?`}))n=n.filter((i)=>!o.drop.includes(i))}return n}async function xV(t,e,n){let r=Rb(t,e);if(!n||r.length<kV)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(Dt(r.map((u)=>AV(t,u)).join(`
241
+ `),"Agents for 'ari run' and 'ari review'",{format:(u)=>u}),!await Te({initialValue:!1,message:"Run tasks and reviews on different agents or models?"}))return null;let s=await LT("Which agent implements tasks?",r,t.routing.task?.agent??null),i=await MT(`Model for ${s} on tasks`,jT(t.routing.task,s)),a=r.find((u)=>u.name!==s)?.name??null,c=await LT("Which agent reviews changes?",r,t.routing.review?.agent??a),l=await MT(`Model for ${c} on reviews`,jT(t.routing.review,c));return{review:{agent:c,model:l},task:{agent:s,model:i}}}async function LT(t,e,n){let r=e.some((o)=>o.name===n)?n:e[0]?.name;return hr({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 MT(t,e){let r=(await Au({initialValue:e??"",message:t,placeholder:wV})??"").trim();return r.length===0?null:r}function jT(t,e){return t!==null&&t.agent===e?t.model:null}function AV(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(` ${Vl(n)}`),o=e.configured?`configured: ${e.roles.join(", ")}`:"preset, not configured yet",s=e.model===null?"":w.dim(` model ${e.model}`);return Me(`${e.name.padEnd(10)}${o}${s}${r}`)}function CV(t){if(t.file===null)return;return t.kind==="skill"?`${t.file} \xB7 ${ot.length} skills`:t.file}function RV(t,e){return`${GT(t,e.id)}${IV(e)}`}function GT(t,e){if(e===Ye)return"Git hooks";if(e===cr)return"AGENTS.md block";let[n,r]=e.split(":"),o=at.find((a)=>a===r),s=ar.find((a)=>a===n);return`${o===void 0?r??"":Gt(t,o).label} ${s===void 0?n??"":Xe[s]}`}function IV(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 HT(t){return{...t,pack:null,recommended:!1,routing:null}}function OV(t,e,n){for(let r of gl(t,HT(e)))if(n.includes(r.code))rs(r.message,r.fix)}function rs(t,e){bt.warn(Yr(t,e))}var _V=1,Ai=new Set(["created","updated"]),Xr={format:(t)=>t},PV=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"}}),BT=E({args:PV,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)=>NV(t)});async function NV(t){let e=await _(),n=rT(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)kr(`${w.bold("ari install")} ${w.dim(`Ariadne ${c}`)}`);let l=i?await VT("Looking at this repository",()=>Si(e)):await Si(e);if(i)Dt(AT(l,c),"This repository",Xr);if(a&&!oT(n)){let S=await jV(l,e);if(S!==null)return Wl(t,l,S,{check:o,dryRun:s,upToDate:!0,visual:i})}let u=await KT(i,()=>a?FT(l,n):Xg(l,n,r)),d=Rg(l,u),p=await Hl(e,d,"preview");if(i)UV(l,d,p.rows,!a);let g=p.rows.some((S)=>Ai.has(S.action));if(p.failed||s){let S=p.rows.map(s?LV:MV),I=o&&!p.failed?await DV(i,l,p.rows,t.args):[],C=o&&!p.failed&&!g;return Wl(t,l,{checks:I,plan:d,rows:S},{check:o,dryRun:s,upToDate:C,visual:i})}if(!g){let S=await ql(i,e,p.rows);return Wl(t,l,{checks:S,plan:d,rows:p.rows},{check:o,dryRun:s,upToDate:!0,visual:i})}if(a)await KT(i,()=>KV());let f=await _r(e,()=>Hl(e,d,"apply",i?BV(l):{})),y=f.failed?[]:await ql(i,e,f.rows);return Wl(t,l,{checks:y,plan:d,rows:f.rows},{check:o,dryRun:s,upToDate:!1,visual:i})}async function DV(t,e,n,r){let o=await ql(t,e.root,n.filter((i)=>i.action==="unchanged")),s=NT(e,n,r);if(s===null)return o;if(t)bt.error(Yr(`${s.name}: ${s.detail}`,s.hint??""));return[s,...o]}function LV(t){return Ai.has(t.action)?{...t,undo:null}:t}function MV(t){return Ai.has(t.action)?{...t,action:"pending",undo:null}:t}async function jV(t,e){if(!t.initialised)return null;let n=FV(t);if(n===null||n.agents.length===0)return null;let r=Rg(t,n),o=await Hl(e,r,"preview");if(o.failed||o.rows.some((s)=>Ai.has(s.action)))return null;return{checks:await ql(!0,e,o.rows),plan:r,rows:o.rows}}function FV(t){try{return Xg(t,GV(),!0)}catch{return null}}function GV(){return{agents:void 0,init:void 0,kinds:void 0,pack:void 0,routing:void 0,scope:void 0}}async function Wl(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:bT,ok:!o,resume:r.dryRun||o?[]:await yT(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)HV(e,s);return t.output.result(s,r.visual?void 0:OT),o?_V:0}function HV(t,e){let n=e.targets.find((r)=>r.action==="failed");if(n!==void 0){bt.error(Yr(`${ur(t,n)}: ${n.reason??""}`,n.hint??"")),le(e.targets.some((r)=>Ai.has(r.action))&&!e.dryRun?"Stopped; run 'ari install' again to finish":"Nothing was written");return}if(e.check){le(e.ok?"Up to date: nothing would change and every check passed":"Not up to date, or a check failed");return}if(e.dryRun){le("Dry run: nothing was written");return}if(e.upToDate){Dt(rm(e),"Everything is up to date",Xr),UT(e),le(w.dim("To add an agent: ari install --agent <name>"));return}Dt(rm(e),e.ok?"Done":"Done, with problems",Xr),UT(e),le(e.ok?"ari is ready":"Fix the failed checks, then run 'ari install' again")}function UT(t){let e=om(t);if(e.length>0)Dt(e.join(`
242
+ `),"To undo",Xr);let n=sm(t);if(n.length>0)Dt(n.join(`
243
+ `),"To get back to your tasks",Xr)}function UV(t,e,n,r){if(r)for(let o of e.warnings)bt.warn(Yr(o.message,o.fix));Dt(CT(n,t,e.routing),"Plan",Xr)}async function KV(){if(await Te({initialValue:!0,message:"Write these changes?"}))return;throw new vt}async function KT(t,e){try{return await e()}catch(n){if(t&&n instanceof vt)Ss("Cancelled, nothing changed");throw n}}async function ql(t,e,n){if(!t)return vg(e,n);let r=await VT("Checking the installation",()=>vg(e,n));if(r.length===0)return r;let o=r.filter((s)=>!s.ok);Dt(IT(r),o.length===0?"Self-check passed":"Self-check found problems",Xr);for(let s of o)bt.error(Yr(`${s.name}: ${s.detail}`,s.hint??""));return r}function BV(t){let e=sa();return{done:(n,r)=>e.stop(RT(t,r)),failed:(n,r)=>e.error(`${ur(t,r)} failed${n.file===null?"":` (${n.file})`}`),start:(n)=>e.start(`Writing ${n.file??ur(t,{agent:n.agent,file:n.file,kind:n.kind})}`)}}async function VT(t,e){let n=sa();n.start(t);try{let r=await e();return n.clear(),r}catch(r){throw n.error(t),r}}var os=st({id:{description:"Task id",required:!0}}),WT=E({description:"Validate a draft contract and mark it ready",examples:["ari ready add-profile-inheritance"],json:!0,name:"ready",positionals:os,run:async(t)=>{let e=await Il(await _(),t.positionals.id);t.output.result(e,({id:n})=>`Task "${n}" is ready; run 'ari start ${n}'`)}}),qT=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:os,run:async(t)=>{let e=await Ol(await _(),t.positionals.id);t.output.result(e,({id:n,instruction:r,stage:o})=>`Task "${n}" is active at stage ${o}
244
244
  ${r}
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}
245
+ Then: ari check, ari done`)}}),JT=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:os,run:async(t)=>{let e=ln(t.args.reason,"--reason",`ari amend ${t.positionals.id} --reason <text>`),n=await OE(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`)}}),YT=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:os,run:async(t)=>{let e=ln(t.args.reason,"--reason",`ari block ${t.positionals.id} --reason <question>`),n=await _l(await _(),t.positionals.id,e);t.output.result(n,({id:r})=>`Task "${r}" is blocked; a human answers with 'ari resolve ${r} --answer <text>'`)}}),XT=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:os,run:async(t)=>{let e=ln(t.args.answer,"--answer",`ari resolve ${t.positionals.id} --answer <text>`),n=await PE(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`)}}),zT=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:os,run:async(t)=>{let e=await _(),n=await Dy(e);if(n===null)throw new m("git user.name is not set",`Run 'git config user.name "<your name>"'`);let r=await NE(e,t.positionals.id,n),o=r.record.approvals.at(-1),s=await Ko(e,r.contract.id,"approve");if(s.warning!==null)process.stderr.write(`${s.warning}
246
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(`
247
+ Snapshot ${c} saved`})}});import{stripVTControlCharacters as VV}from"util";var ZT=1,WV=2,qV=4,QT="Error",JV="Call the tool with the arguments its inputSchema describes";function t$(t){if(t instanceof b){let r=`Invalid arguments: ${t.message}`;return{error:{_tag:"UsageError",causes:[],exitCode:WV,hint:JV,message:r}}}if(!(t instanceof Error))return{error:{_tag:QT,causes:[],exitCode:ZT,message:Jl(String(t))}};let e=t instanceof m,n=e&&typeof t.hint==="string"?{hint:Jl(t.hint)}:{};return{error:{_tag:e?t._tag:t.name||QT,causes:YV(t),exitCode:e?t.exitCode:ZT,message:Jl(t.message),...n}}}function YV(t){let e=[],n=new Set([t]),r=t.cause;while(r!==void 0&&!n.has(r)&&e.length<qV)n.add(r),e.push(Jl(r instanceof Error?r.message:String(r))),r=r instanceof Error?r.cause:void 0;return e}function Jl(t){return VV(t)}var a$=["2026-07-28"],zl=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],tu="2.0",XV=-32700,Zl=-32600,zV=-32601,ss=-32602,ZV=-32603,QV=-32022,Ql="_meta",Xl="io.modelcontextprotocol/protocolVersion",e$="io.modelcontextprotocol/clientCapabilities",tW="io.modelcontextprotocol/serverInfo",eW="complete",n$=3600000,r$="public",nW="2025-06-18",o$={tools:{listChanged:!1}},c$=[...a$,...zl];function l$(t){let e={legacy:null},n=(c)=>{let l=rW(c);if("error"in l)return ke(l.error);let u=l.value,d=!("method"in u)&&(("result"in u)||("error"in u));if(!("id"in u)||d)return ke(null);let p=oW(u);if("error"in p)return ke(p.error);let{id:g,method:f,params:y}=p.value,S=!sW(y);if(S&&f==="initialize")return ke(r(g,y));if(S&&f==="ping")return ke(Yl(g,{}));let I=iW(g,y,e.legacy);if("error"in I)return ke(I.error);switch(f){case"server/discover":return I.value.kind==="modern"?ke(a(g,I.value,o())):ke(i$(g,f));case"tools/list":return ke(a(g,I.value,s(I.value)));case"tools/call":return i(g,I.value,y);default:return ke(i$(g,f))}},r=(c,l)=>{let u=l.protocolVersion,d=typeof u==="string"&&zl.includes(u)?u:zl[0]??"";e.legacy=d;let{info:p,instructions:g}=t;return Yl(c,{capabilities:o$,instructions:g,protocolVersion:d,serverInfo:p})},o=()=>({cacheScope:r$,capabilities:o$,instructions:t.instructions,supportedVersions:c$,ttlMs:n$}),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:r$,tools:l,ttlMs:n$}:{tools:l}},i=(c,l,u)=>{let{arguments:d={},name:p}=u;if(typeof p!=="string")return ke(we(c,ss,"tools/call needs a tool name"));let g=t.tools.find((y)=>y.name===p);if(g===void 0)return ke(we(c,ss,`Unknown tool: ${p}`));if(!z(d))return ke(we(c,ss,"tools/call arguments must be an object"));let f=async()=>{try{let y=await g.call(await t.root(),d);return a(c,l,s$(l,y.data,y.failed))}catch(y){return a(c,l,s$(l,t$(y),!0))}};return{kind:"queued",run:()=>f().catch((y)=>cW(c,y))}},a=(c,l,u)=>{if(l.kind==="legacy")return Yl(c,u);let d={[tW]:t.info};return Yl(c,{...u,[Ql]:d,resultType:eW})};return{receive:n}}function ke(t){return{kind:"now",message:t}}function s$(t,e,n){let r=[{text:JSON.stringify(e,null,2),type:"text"}],o=t.kind==="modern"||t.version>=nW;return{content:r,isError:n,...o?{structuredContent:e}:{}}}function rW(t){let e;try{e=JSON.parse(t)}catch{return{error:we(null,XV,"Parse error: each line must hold one JSON-RPC message")}}if(Array.isArray(e))return{error:we(null,Zl,"JSON-RPC batches are not supported")};if(!z(e))return{error:we(null,Zl,"A JSON-RPC message must be an object")};return{value:e}}function oW(t){let{id:e,jsonrpc:n,method:r,params:o={}}=t;if(!(typeof e==="string"||typeof e==="number"&&Number.isInteger(e)))return{error:we(null,Zl,"A request id must be a string or an integer")};if(n!==tu||typeof r!=="string")return{error:we(e,Zl,'A request needs "jsonrpc": "2.0" and a method name')};if(!z(o))return{error:we(e,ss,"params must be an object")};return{value:{id:e,method:r,params:o}}}function sW(t){return z(t[Ql])&&Xl in t[Ql]}function iW(t,e,n){let r=e[Ql];if(z(r)&&Xl in r){let s=r[Xl];if(typeof s!=="string"||!a$.includes(s))return{error:aW(t,s)};if(!z(r[e$]))return{error:we(t,ss,`_meta needs "${e$}"`)};return{value:{kind:"modern",version:s}}}if(n!==null)return{value:{kind:"legacy",version:n}};let o=`Missing _meta "${Xl}"; clients of protocol ${zl[0]} and earlier send initialize first`;return{error:we(t,ss,o)}}function aW(t,e){return{error:{code:QV,data:{requested:e,supported:c$},message:"Unsupported protocol version"},id:t,jsonrpc:tu}}function i$(t,e){return we(t,zV,`Method not found: ${e}`)}function cW(t,e){return we(t,ZV,`Internal error: ${e instanceof Error?e.message:String(e)}`)}function Yl(t,e){return{id:t,jsonrpc:tu,result:e}}function we(t,e,n){return{error:{code:e,message:n},id:t,jsonrpc:tu}}var dr="arguments",zr={destructiveHint:!1,readOnlyHint:!0},Ci={destructiveHint:!1,readOnlyHint:!1},lW={destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1},u$={readOnlyHint:!1},v$={description:"Task id",type:"string"},am={items:{type:"string"},type:"array"};function Xt(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 Se(t){return{data:t,failed:!1}}function zt(t,e){return T(t,dr,Object.keys(e))}function ce(t,e){return nt(t,`${dr}.${e}`)}function d$(t,e){return t===void 0?void 0:L(t,`${dr}.${e}`,x)}var is={},as={id:v$},p$={status:{...am,description:"Only tasks with these statuses",items:{enum:Vr}}},g$={pack:{description:"Methodology pack (defaults to config.pack)",type:"string"},scope:{...am,description:"Globs of the files the task may change"},title:{description:"Task title",type:"string"}},m$={global:{description:"Write a project knowledge entry instead of a task note",type:"boolean"},kind:{description:"Knowledge entry kind, with global",enum:ue},scope:{...am,description:"Globs the knowledge entry applies to, with global"},text:{description:"The note",type:"string"}},f$={budget:{description:"Token budget (default: context.budget)",minimum:1,type:"integer"},id:{description:"Task id (default: the active task)",type:"string"}},h$={reason:{description:"Why the snapshot is taken, for example 'design ready'",type:"string"},task:{description:"Task id (default: the active task)",type:"string"}},y$={task:{description:"Only the entries of this task",type:"string"}},k$={id:{description:"Snapshot id, as ari_snapshot_list shows it",type:"string"}},w$={id:v$,reason:{description:"The question for a human",type:"string"}},S$={all:{description:"Include archived entries",type:"boolean"},query:{description:"Words to search for",type:"string"}},b$=[Xt({annotations:zr,call:async(t,e)=>(zt(e,is),Se(await xl(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:is,title:"Next action"}),Xt({annotations:zr,call:async(t,e)=>{let n=zt(e,p$),r=D(n.status,[],(o)=>L(o,`${dr}.status`,(s,i)=>K(Vr,s,i)));return Se(await Al(t,r))},description:"List tasks (id, title, pack, status) and contracts or records that cannot be read.",name:"ari_list",properties:p$,title:"List tasks"}),Xt({annotations:zr,call:async(t,e)=>Se(await Cl(t,ce(zt(e,as).id,"id"))),description:"Show a task's contract, record, current stage and stage instruction.",name:"ari_show",properties:as,required:["id"],title:"Show task"}),Xt({annotations:Ci,call:async(t,e)=>{let n=zt(e,g$),r=n.pack===void 0?void 0:ce(n.pack,"pack"),o=d$(n.scope,"scope")??[];return Se(await Rl(t,{pack:r,scope:o,title:ce(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:g$,required:["title"],title:"New task"}),Xt({annotations:Ci,call:async(t,e)=>Se(await Il(t,ce(zt(e,as).id,"id"))),description:"Validate a draft contract, its pack and its dependencies, and mark it ready.",name:"ari_ready",properties:as,required:["id"],title:"Ready task"}),Xt({annotations:Ci,call:async(t,e)=>Se(await Ol(t,ce(zt(e,as).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:as,required:["id"],title:"Start task"}),Xt({annotations:u$,call:async(t,e)=>(zt(e,is),Pl(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:is,title:"Check stage"}),Xt({annotations:u$,call:async(t,e)=>(zt(e,is),Nl(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:is,title:"Finish stage"}),Xt({annotations:Ci,call:async(t,e)=>{let n=zt(e,m$),r=D(n.global,!1,(i)=>$t(i,`${dr}.global`)),o=n.kind===void 0?void 0:K(ue,n.kind,`${dr}.kind`),s=d$(n.scope,"scope");return Se(await Dl(t,{global:r,kind:o,scope:s,text:ce(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:m$,required:["text"],title:"Add note"}),Xt({annotations:zr,call:async(t,e)=>{let n=zt(e,f$),r=n.id===void 0?void 0:ce(n.id,"id"),o=n.budget===void 0?void 0:Bt(n.budget,`${dr}.budget`);return Se(await Ll(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:f$,title:"Task context"}),Xt({annotations:Ci,call:async(t,e)=>{let n=zt(e,w$);return Se(await _l(t,ce(n.id,"id"),ce(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:w$,required:["id","reason"],title:"Block task"}),Xt({annotations:zr,call:async(t,e)=>{let n=zt(e,S$),r=D(n.all,!1,(o)=>$t(o,`${dr}.all`));return Se(Ml(t,ce(n.query,"query"),r))},description:"Search the project's knowledge entries, ranked with BM25.",name:"ari_knowledge_search",properties:S$,required:["query"],title:"Search knowledge"}),Xt({annotations:lW,call:async(t,e)=>{let n=zt(e,h$),r=n.task===void 0?void 0:ce(n.task,"task"),o=n.reason===void 0?void 0:ce(n.reason,"reason");return Se(await jl(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:h$,title:"Save snapshot"}),Xt({annotations:zr,call:async(t,e)=>{let n=zt(e,y$),r=n.task===void 0?void 0:ce(n.task,"task");return Se(await Fl(t,r))},description:"List the saved snapshots and restores, oldest first, optionally of one task.",name:"ari_snapshot_list",properties:y$,title:"List snapshots"}),Xt({annotations:zr,call:async(t,e)=>Se(await Gl(t,ce(zt(e,k$).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:k$,required:["id"],title:"Show snapshot"})];var E$=`
248
+ `,uW=/\r$/,dW={name:"ari",title:"Ariadne",version:Sa},pW=["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 gW(t){return l$({info:dW,instructions:pW,root:()=>Xn(t),tools:b$})}async function $$(t){let e=gW(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)T$(e,l,o)}T$(e,i+s.decode(),o),await r}function T$(t,e,n){let r=e.replace(uW,"");if(r.trim().length>0)n(t.receive(r))}function x$(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: ${Fn.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 At(ir(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 At("project",l),await At("user",l));c.output.result({agents:u},({agents:d})=>d.map(mW).join(`
249
+ `))}});return[i("install",t.install),i("uninstall",t.uninstall),a]}function mW(t){let e=t.files.map((n)=>`${n.scope} ${n.installed?"installed":"not installed"} ${n.file}`);return`${t.agent} ${e.join("; ")}`}var fW=`ari mcp serve speaks the Model Context Protocol on stdin and stdout; an agent starts it. Press Ctrl-D to stop.
250
+ `,hW=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(fW);await $$({cwd:process.cwd(),input:Bun.stdin.stream(),write:(t)=>{process.stdout.write(t)}})}}),yW=x$({agents:ie.map((t)=>t.agent),example:{project:"claude",user:"codex"},group:"mcp",install:qo,noun:'MCP server "ari"',summaries:Yv,target:fe,uninstall:el},{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"}),A$=E({description:"Serve ari's task tools to agents over MCP, and register the server with them",name:"mcp",subcommands:[hW,...yW]});var C$=1;async function R$(t,e){let n=M(t),r=Ir(n,{...e,role:"review",route:wW(n)}),o=e.task??await SW(t),s=await Gn(t,o),i=s.stage??s.task.record.status,{contractText:a}=it(t,o,n),c=kW(n,e),l={config:n,contractText:a,root:t,stage:i,task:s.task,...c===null?{}:{argus:c}},{evidence:u,...d}=await vp(l,r);return{...d,stage:i,task:o}}function kW(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}`,C$,{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 wW(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 SW(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",C$,{tag:"NoActiveTask"})}var vW=1,I$=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 R$(await _(),{agent:Ie(t.args.agent,"--agent"),argus:t.args.argus,argusVerdicts:t.args.argusVerdicts,model:Ie(t.args.model,"--model"),notify:(n)=>bt.info(n),task:Ie(t.args.task,"--task")});return t.output.result(e,bW),e.ok?void 0:vW}});function bW(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)=>` - ${$c(i)}`),o=t.problems.map((i)=>` ! ${i}`),s=(t.argus===void 0?[]:bc(t.argus)).map((i)=>` ~ ${i}`);return[n,...o,...s,...r].join(`
251
+ `)}var EW=1,O$=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 UE(await _(),{agent:Ie(t.args.agent,"--agent"),model:Ie(t.args.model,"--model"),output:t.json?"stderr":"inherit",task:t.args.task});return t.output.result(e,TW),e.outcome==="done"?void 0:EW}});function TW(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 $W=1,xW=ot.map((t)=>t.name),AW=he.map((t)=>t.agent),CW=j({agent:{description:`Agent: ${AW.join(", ")}`,type:"string"},scope:{description:`Where to write: ${Fn.join(" or ")} (default: project)`,type:"string"},skill:{description:`Skills, comma-separated (default: all): ${xW.join(", ")}`,type:"string"}}),RW={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 _$(t){let e=`ari skills ${t} --agent`;return E({args:CW,description:RW[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 At(ir(n.args.scope),process.cwd()),s=ib(qe(n.args.skill)),i=t==="install"?Jo(r,o,s):ol(r,o,s);return n.output.result(i,(a)=>OW(a,r.agent)),i.some((a)=>a.action==="refused")?$W:void 0}})}var IW=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=Eb(await At("project",e),await At("user",e)),r=ot.map(({description:o,name:s})=>({description:o,name:s}));t.output.result({skills:r,agents:n},(o)=>_W(o.skills,o.agents))}}),P$=E({description:"Install ari's skills, which teach an agent the task loop, designs, contracts, review and memory",name:"skills",subcommands:[_$("install"),_$("uninstall"),IW]});function OW(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,il(r,e)].join(`
254
+ `)}function _W(t,e){let n=t.map((o)=>`${o.name} ${o.description}`),r=e.flatMap((o)=>Fn.map((s)=>`${o.agent} ${s} ${PW(o.files.filter((i)=>i.scope===s))}`));return[...n,"",...r].join(`
255
+ `)}function PW(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 NW}from"fs";import{join as N$}from"path";var DW=()=>new Date().toISOString(),Ri="Nothing was changed.",LW="it lies outside .ari/designs/, and a restore writes only designs";async function D$(t,e,n={}){let r=M(t),o=await P(t),s=Uo(o,e);if(!Xp(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=Zo(s);if(i.length>0)throw new m(`Snapshot ${e} is not intact: ${i.join("; ")}`,`${Ri} Restore another snapshot, or delete the entry file`);let{contractText:a,task:c}=it(t,s.task,r);MW(s,c.record.status,Vt(a));let l=Ke(c.contract.pack,Ht(t)),u=new Set(Lc(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}"`,`${Ri} The entry was edited or the pack changed; delete the entry file`);let p=s.artifacts.filter(({path:A})=>Wp(A)),g=s.artifacts.filter(({path:A})=>!Wp(A)).map(({path:A})=>({path:A,reason:LW})),f=jW(t,p),y=n.dryRun===!0,{estimatedTokens:S,knowledge:I,sha256:C,text:J}=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:J},dryRun:y,ledger:null,notRestored:g,notice:f.write.length===0?null:FW(s.task),snapshot:e,task:s.task,unchanged:f.unchanged,written:G};if(y||f.write.length===0)return N;let H=(n.clock??DW)();return jc(o,()=>{for(let{artifact:Q}of f.write)Pn(N$(t,Q.path),Mr(Q.file));let A=jn(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),Pt=Fc(o,H,{kind:"restore",pruned:B,restores:e,task:s.task,written:f.write.map(({artifact:Q,before:Zr})=>({before:Zr,path:Q.path,sha256:Q.file.sha256}))});return Gc(o,B),{...N,ledger:Pt.id}})}function MW(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`,`${Ri} '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`,`${Ri} 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 jW(t,e){let n=[],r={unchanged:[],write:[]};for(let o of e){let s=N$(t,o.path),i=$e(s);if(i?.isSymbolicLink()===!0||xe(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:Fo(NW(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("; ")}`,`${Ri} Replace it with a regular file or remove it, then restore again`)}function FW(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 M$(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}, ${cs(t.artifacts.length,"artifact")}, context of about ${t.context.estimatedTokens} tokens)`,...r,...e].join(`
257
+ `)}function j$(t){let e=t.entries.map(GW),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 F$({entry:t,integrity:e}){let n=e.ok?[]:[`Integrity: ${e.problems.join("; ")}`];if(t.kind==="restore")return[...L$(t),...HW(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[...L$(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 G$(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 ${cs(t.written.length,"file")}`:`Restored snapshot ${t.snapshot} of task "${t.task}": ${cs(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 GW(t){if(t.kind==="restore")return`${t.id} restore of ${t.restores??"?"} ${t.task} ${cs(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} ${cs(t.artifacts.length,"artifact")}${n}`}function L$(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 HW(t){let e=t.written.map((n)=>` ${n.path} now ${n.sha256}; before ${n.before?.sha256??"absent"}`);return[`Wrote ${cs(e.length,"file")}:`,...e,...t.pruned.length===0?[]:[`Pruned: ${t.pruned.join(", ")}`]]}function cs(t,e){return`${t} ${t===1?e:`${e}s`}`}var UW={description:"Task id (default: the active task)",type:"string"},KW=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 Fl(await _(),t.args.task),j$)}}),BW=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 Gl(await _(),t.positionals.id),F$)}}),VW=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 D$(await _(),t.positionals.id,{dryRun:t.args.dryRun});t.output.result(e,G$)}}),H$=E({args:j({reason:{description:"Why the snapshot is taken",type:"string"},task:UW}),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 jl(await _(),{reason:Ie(t.args.reason,"--reason"),task:t.args.task});t.output.result(e,M$)},subcommands:[KW,BW,VW]});var U$=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 Rl(await _(),{pack:t.args.pack,scope:qe(t.args.scope),title:t.positionals.title});t.output.result(e,({contractPath:n,designs:r,id:o})=>[`Created task "${o}" at ${n}`,...(r??[]).map(WW),`Complete its scope, criteria and checks, then run 'ari ready ${o}'`].join(`
262
+ `))}}),K$=E({args:j({status:{description:`Only these statuses, comma-separated (${Vr.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=qE(qe(t.args.status));t.output.result(await Al(await _(),e),qW)}}),B$=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 Cl(await _(),t.positionals.id),JW)}});function WW({created:t,path:e}){return t?`Wrote the design template to ${e}`:`Kept the existing design at ${e}`}function qW(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 JW(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 YW=1,XW=12,W$=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=To();if(t.args.revoke){let c=ok(e),l={...Ve(e,n),action:c?"revoked":"none",environment:r};t.output.result(l,V$);return}let o=Ve(e,n),s=Nn(o)&&(t.args.yes||await zW(t.json,o)),i=s?$o(e,n):o,a={...i,action:s?"trusted":"none",environment:r};return t.output.result(a,V$),Nn(i)&&!r?YW:void 0}});async function zW(t,e){if(!gr({json:t}))return!1;return Fd(e.root,e.commands)}function V$(t){let e=[`Trust for ${t.root}: ${ZW(t)}`,...jd(t.commands)],n=[...t.action==="trusted"?["Trusted the commands above"]:[],...t.action==="revoked"?["Revoked the trust record of this repository"]:[],...t.environment?[`${Cr}=1 is set, so ari runs these commands without a record`]:[],...Nn(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 ZW(t){switch(t.state){case"trusted":return`trusted since ${t.trustedAt} (configuration ${t.sha256.slice(0,XW)})`;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 QW="Fix the cause, then run 'ari uninstall' again; it keeps what is already done",tq="as it was before the install, byte for byte",eq="only ari's entries: the file changed after the install, so your edits stay";async function cm(t,e,n,r){let o={bases:n,mode:r,preview:op(),root:t},s=[];for(let i of e.targets){if(i.skip!==null){s.push(eu(i,"skipped",{reason:i.skip}));continue}try{s.push(...await nq(o,i))}catch(a){let c=eu(i,"failed",{hint:dq(a),reason:qn(a)});s.push({...c,file:iq(i)})}}return s}async function nq(t,e){if(e.kind==="git")return sq(t,e);let n=uq(e.agent),r=lq(t,e.scope),o=t.mode==="preview"?t.preview:op(),s=await rq(t,e,n,r,o);if(t.mode==="apply")await oq(t,e,n,r);return[aq(e,s,q$(e.kind,n,e.scope))]}async function rq(t,e,n,r,o){if(e.kind==="hooks"){let i=lm(t);return cp(i,Ne(n),{forget:!1,state:await P(i),view:o})}if(e.kind==="mcp")return zc(De(fe(n),r),o,!1);let s=Jt(n);return ub(ot.map((i)=>zc(ae(s,r,i),o,!1)))}async function oq(t,e,n,r){if(e.kind==="hooks"){let o=lm(t);mc(o,Ne(n),await P(o));return}if(e.kind==="mcp")el(fe(n),r);else ol(Jt(n),r)}async function sq(t,e){let n=lm(t),r=await Ks(n);if(t.mode==="apply")await uc(n);return r.map(({action:o,path:s})=>({...eu(e,o==="removed"?"removed":"unchanged",{}),file:s}))}function iq(t){return t.agent===null?null:q$(t.kind,t.agent,t.scope)}function q$(t,e,n){if(t==="hooks")return Ne(e).file;let r=t==="mcp"?fe(e)[n]:Jt(e)[n];return se(n,r??"")}function aq(t,e,n){let r=cq(e),o=e.restored===null?null:e.restored==="original"?tq:eq;return{...eu(t,r,{detail:o}),file:n}}function cq({action:t}){return t==="removed"?"removed":t==="unchanged"?"unchanged":"restored"}function eu(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 lq(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 lm({root:t}){if(t!==null)return t;throw Error("This uninstall target needs a repository")}function uq(t){if(t!==null)return t;throw Error("This uninstall target needs an agent")}function dq(t){return t instanceof m&&t.hint!==void 0&&t.hint.length>0?t.hint:QW}var pq=[{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"}],gq=[{how:"Delete the directory yourself: rm -r ~/.ari",what:"~/.ari: the trust records and the receipts of anything still installed"}];function J$(t){return t==="project"?pq:gq}var mq=["git","skill","mcp","hooks"],fq=["skill","mcp"],hq=new Set(["hooks","git"]),yq=[...at].reverse(),Y$="ari does not write this",kq={claude:"Claude Code keeps user-scope MCP servers itself; run 'claude mcp remove --scope user ari'"};async function X$(t,e){if(e==="user")return{user:await At("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 z$(t){if(t.scope!=="user"||t.kinds===void 0)return;if(![...t.kinds].some((e)=>hq.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 Z$(t,e,n){let{scope:r}=e,o=r==="user"?fq:mq,s=[];for(let i of o.filter((a)=>e.kinds?.has(a)??!0))s.push(...i==="git"?await Sq(t,e):wq(i,t,e,n));return{scope:r,targets:s}}function wq(t,e,n,r){let{agents:o,scope:s}=n,i=r[s];if(i===void 0)return[];return yq.filter((a)=>o?.includes(a)??!0).flatMap((a)=>{let c=vq(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:bq(t,a,s)}];return Tq(()=>Eq(t,a,e,i),!0)||o!==void 0?[{...l,skip:null}]:[]})}async function Sq(t,e){let n=e.kinds?.has("git")===!0;if(t===null||e.agents!==void 0&&!n)return[];return(await Ks(t)).some(({action:o})=>o==="removed")||n?[{agent:null,kind:"git",scope:"project",skip:null}]:[]}function vq(t,e,n){if(t==="hooks"){let o=Oe.find((s)=>s.name===e);return o===void 0?void 0:n==="project"?o.file:null}return(t==="mcp"?ie:he).find((o)=>o.agent===e)?.[n]}function bq(t,e,n){if(t==="mcp")return kq[e]??`${Y$} ${e}'s ${n}-scope MCP configuration`;return`${Y$} ${e}'s ${n}-scope ${t}`}function Eq(t,e,n,r){if(t==="mcp")return mn(De(fe(e),r));if(t==="skill"){let s=Jt(e);return ot.some((i)=>mn(ae(s,r,i)))}let o=Oe.find((s)=>s.name===e);return n!==null&&o!==void 0&&un(n,o)}function Tq(t,e){try{return t()}catch{return e}}var nu=" ",Q$=11,$q=34,xq=66,tx=72,Aq=["removed","restored","unchanged","skipped","failed"],Cq={failed:"failed",removed:"remove",restored:"restore",skipped:"skip",unchanged:"unchanged"};function ex(t){return t.targets.length===0}function Rq(t){if(t.kind==="git")return"git hook";return`${t.agent??""} ${Xe[t.kind]}`.trim()}function nx(t){return t.flatMap((e)=>ox(e,!0)).join(`
266
+ `)}function Iq(t){return t.targets.flatMap((e)=>ox(e,t.dryRun)).join(`
267
+ `)}function um(t){return t.flatMap((e)=>[...Jr(e.what,tx),...Jr(e.how,tx-nu.length).map((n)=>w.dim(`${nu}${n}`))]).join(`
268
+ `)}function dm(t){let e=Aq.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 rx(t){let e=t.dryRun?"Dry run: nothing was written":dm(t.targets),n=ex(t)?[]:[Iq(t),""],r=ex(t)?[]:["","Kept",um(t.kept)];return[...n,e,...r].join(`
269
+ `)}function ox(t,e){let n=ut(e?Cq[t.action]:t.action,Q$),r=ut(t.file??"",$q),o=`${nu}${Oq(t.action,n)}${r}${w.dim(Rq(t))}`,s=[t.detail,t.reason,t.hint].flatMap((i)=>i===null?[]:Jr(i,xq).map((a)=>`${nu}${" ".repeat(Q$)}${w.dim(a)}`));return[Me(o),...s]}function Oq(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 _q=1,pm={format:(t)=>t},Pq=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"}}),ix=E({args:Pq,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)=>Nq(t)});async function Nq(t){let e=jq(t.args),n=t.args.dryRun===!0,r=t.args.yes===!0;if(!t.interactive&&!r&&!n)throw Gq();let o=t.interactive,s=e.scope==="project"?await _():null,i=await X$(s,e.scope);if(o)kr(`${w.bold("ari uninstall")} ${w.dim(`Ariadne ${t.cli.version??""}`)}`);let a=await Z$(s,e,i),c=await cm(s,a,i,"preview");if(o&&c.length>0)Dt(nx(c),"Plan",pm);let l=c.some((d)=>d.action==="removed"||d.action==="restored");if(n)return sx(t,s,e,c,{dryRun:n,visual:o});if(l&&o&&!r)await Mq(()=>Lq());let u=await cm(s,a,i,"apply");return sx(t,s,e,u,{dryRun:!1,visual:o})}function sx(t,e,n,r,o){let s=r.some((a)=>a.action==="failed"),i={dryRun:o.dryRun,kept:[...J$(n.scope)],ok:!s,root:e,scope:n.scope,targets:r};if(o.visual)Dq(i);return t.output.result(i,o.visual?void 0:rx),s?_q:0}function Dq(t){if(t.targets.length===0){le("Nothing to remove");return}if(t.dryRun){le("Dry run: nothing was written");return}Dt(dm(t.targets),t.ok?"Done":"Done, with problems",pm),Dt(um(t.kept),"Kept",pm),le(t.ok?"ari is out of this setup":"Fix the failed rows, then run 'ari uninstall' again")}async function Lq(){if(await Te({initialValue:!0,message:"Remove these?"}))return;throw new vt}async function Mq(t){try{await t()}catch(e){if(e instanceof vt)Ss("Cancelled, nothing changed");throw e}}function jq(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:Fq(t.agent),kinds:e.size===0?void 0:e,scope:ir(t.scope)};return z$(n),n}function Fq(t){let e=[...new Set(qe(t))];if(e.length===0)throw new v("--agent needs at least one agent",`Choose from: ${at.join(", ")}`);return e.map((n)=>{if(dl(n))return n;throw new v(`ari uninstall has no agent "${n}"`,`Choose from: ${at.join(", ")}`)})}function Gq(){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 ax=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 Ll(await _(),{budget:t.args.budget,id:t.positionals.id});t.output.result(e,({text:n})=>n)}});var Hq=" ",Uq=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=Rp(await _(),{all:t.args.all});t.output.result(e,qq)}}),Kq=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(Hq),n=Ml(await _(),e,t.args.all);t.output.result(n,Jq)}}),Bq=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 El(e);t.output.result(pS(e,t.positionals.id,n),Yq)}}),Vq=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=gS(e,t.positionals.id,{force:t.args.force});t.output.result(n,(r)=>`Archived ${r.kind} ${r.id}`)}}),Wq=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 gT(await _(),t.positionals.id);t.output.result(e,(n)=>`Restored ${n.kind} ${n.id}`)}}),cx=E({name:"knowledge",description:"List, search, show, archive and restore project knowledge",subcommands:[Uq,Kq,Bq,Vq,Wq]});function lx(t){let e=t.status==="active"?"":` [${t.status}]`,n=t.text.split(`
270
+ `)[0]??"";return`${t.id} (${t.kind})${e}: ${n}`}function qq(t){return t.entries.length===0?"No knowledge entries":t.entries.map(lx).join(`
271
+ `)}function Jq(t){if(t.matches.length===0)return`No knowledge entry matches "${t.query}"`;return t.matches.map((e)=>`${e.score.toFixed(2)} ${lx(e.entry)}`).join(`
272
+ `)}function Yq(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 Xq=" ",ux=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: ${ue.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:lS(r),text:t.positionals.text.join(Xq)};t.output.result(await Dl(await _(),o),zq)}});function zq(t){return t.target==="task"?`Added note ${t.index} to ${t.task}`:`Added ${t.entry.kind} ${t.entry.id} to .ari/knowledge`}var gm="HEAD~1",Zq={fail:"fail",pass:"pass",regression:"pass"};async function dx(t,e={}){let n=M(t),r=e.since??gm,o=await wo(t,r),s=re(await Ae(t,o)),{tasks:i}=Nt(t,n),a=i.filter((u)=>u.record.status==="done"&&s.some((d)=>et(d,u.contract.scope))),c=ge(t),l=[];for(let u of a){let d=await tJ(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 Qq(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 tJ(t,e){let n=[];for(let r of e.contract.checks){let[o]=await Je([nJ(r)],eJ(e,r),t);if(o!==void 0)n.push(Qq(o))}return n}function eJ(t,e){return(t.record.evidence.at(-1)?.gates.flatMap((r)=>r.checks)??[]).findLast((r)=>r.name===e.name)?.expect??Zq[e.expect]}function nJ(t){return{name:t.name,run:t.run,timeoutSeconds:t.timeoutSeconds}}var rJ=1,px=E({name:"replay",description:"Re-run the checks of done tasks whose scope changed since a reference",args:j({since:{default:gm,description:"Reference to compare with",type:"string"}}),json:!0,examples:["ari replay","ari replay --since origin/develop --json"],run:async(t)=>{let e=await dx(await _(),{since:t.args.since});return t.output.result(e,oJ),e.regressed.length===0?void 0:rJ}});function oJ(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}`,sJ(i.outputTail)]),...s]});return[e,...n].join(`
274
+ `)}function sJ(t){return t.trimEnd().split(`
275
275
  `).map((e)=>` ${e}`).join(`
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(`
276
+ `)}import{resolve as yJ}from"path";import{existsSync as iJ,readFileSync as aJ}from"fs";var Ii="Fix the proposal file, then run 'ari sleep --apply <file>' again",cJ=["merges","promotions","archive","reason"],lJ=["replace","entry"],uJ=["task","notes","entry"],dJ=["kind","scope","text"],pJ=1;function mx(t,e){if(!iJ(t))throw new m(`The proposal file ${t} does not exist`,Ii);let n=aJ(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})`,Ii)}return{proposal:Ct("sleep proposal",Ii,()=>gJ(r,e.knowledge.maxEntryBytes)),sha256:Z(n)}}function fx(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<pJ)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 gJ(t,e){let n=T(t,"proposal",cJ);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,lJ);return{entry:gx(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,uJ);return{entry:gx(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 gx(t,e,n){let r=ft(t,e,(o,s)=>T(o,s,dJ));return xp({kind:r.kind,scope:r.scope??[],text:r.text},e,n)}var mJ="(merged entry ";function yx(t,e,n,r){let o=Kp(e),s=Kp(fJ(t,e)),i=new Map;for(let a of jr(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 kx(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 fJ(t,e){let n=new Map(e);t.merges.forEach((r,o)=>{let s=`${mJ}${o})`;n.set(s,ni(r.entry,{created:"",id:s,sources:[],supersedes:r.replace}));for(let i of r.replace)hx(n,i,s)});for(let r of t.archive)hx(n,r,null);return n}function hx(t,e,n){let r=t.get(e);if(r!==void 0)t.set(e,dn(r,n))}var wx=()=>new Date().toISOString();async function Sx(t,e,n={}){let r=M(t),o=await P(t),s=(n.clock??wx)(),i=n.force===!0;return Lr(o,()=>{let{entries:a,proposal:c,sha256:l}=bx(t,e,r,i),u=new Set(an(t)),d=Ex(c,a,No(s),(f,y)=>Cp(t,f,y,u)),p=Nc(t,d.retirements);for(let{notes:f,task:y}of c.promotions)Wt(t,o,y,(S)=>Sy(S,f));let g=jo(o,s,{archived:p,created:US(t,d.creations),forced:i,kind:"apply",promoted:Tx(c),proposal:{sha256:l},pruned:[],reason:c.reason});return{...$x(d,c),ledger:g.id}})}function vx(t,e,n={}){let r=M(t),o=(n.clock??wx)(),{entries:s,proposal:i}=bx(t,e,r,n.force===!0),a=new Set(an(t)),c=Ex(i,s,No(o),(l,u)=>ni(l,{...u,id:Ap(l,a)}));return{...$x(c,i),changes:Dc(t,c.retirements,c.creations),dryRun:!0}}function bx(t,e,n,r){let{proposal:o,sha256:s}=mx(e,n),i=new Map(ge(t).map((p)=>[p.id,p])),{tasks:a}=Nt(t,n),c=new Map(a.map((p)=>[p.contract.id,p.record])),l=fx(o,i,c,r);if(l.length>0){let p=l.map((g)=>` - ${g}`).join(`
277
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(`
278
+ ${p}`,Ii)}let u=n.knowledge.rehearsalTasks,d=r?[]:yx(o,i,a,u);if(d.length>0)throw hJ(d,Math.min(u,jr(a).length));return{entries:i,proposal:o,sha256:s}}function hJ(t,e){let n=t.map((r)=>` - ${kx(r)}`).join(`
279
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();
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 Ex(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 Tx(t){return t.promotions.map((e)=>({notes:[...e.notes],task:e.task}))}function $x(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:Tx(e)}}function mm(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?Rx(t.changes):[],..."ledger"in t?[`Ledger entry: ${t.ledger}`]:[]].join(`
282
+ `)}function xx(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?Rx(t.changes):[],..."ledger"in t?[`Ledger entry: ${t.ledger}`]:[]].join(`
283
+ `)}function Ax(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 Cx(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(", ")}`,mm(n)].join(`
285
+ `)}function Rx(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 Ox=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;kJ({apply:e,dryRun:n,force:r,ifDue:o,undo:s},i);let a=await _();if(s){t.output.result(n?await pT(a,i):await dT(a,i),Ax);return}if(e!==void 0){let c=yJ(process.cwd(),e),l=n?vx(a,c,{force:r}):await Sx(a,c,{force:r});t.output.result(l,xx);return}if(o){let c=or(await Gr(a)),l=c.due?await Ix(a,n):null,u={due:c,sleep:l};t.output.result(u,Cx);return}t.output.result(await Ix(a,n),mm)}});function Ix(t,e){return e?KS(t):Fr(t)}function kJ(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 Jx}from"fs";import{basename as GJ,extname as HJ,join as Yx}from"path";import{readFileSync as wJ}from"fs";import{join as SJ}from"path";var Px=["checks","invariants","scope","locked"];function Nx(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?[...AJ(t,e),...EJ(e)]:[],i=e.record.evidence.flatMap(xJ);if(!n)return[...s,...vJ(e,r),...i];let a=o?CJ(e,r):[];return[...s,...TJ(e,r),...i,...a]}function Dx(t,{exact:e}){let{evidence:n}=t.record;if(e)return n.at(-1)?.gates??[];return Px.flatMap((r)=>{let o=ru(t,r),s=o.at(-1);return s===void 0?[]:[{...s,checks:Lx(o)}]})}function vJ(t,e){let n=e.stages.flatMap((u)=>u.gates),o=Px.filter((u)=>n.some((d)=>d.kind===u)).filter((u)=>ru(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)=>bJ(t.contract,u))),i=Lx(ru(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=ru(t,"invariants").at(-1)?.checks.map((u)=>u.command),l=c===void 0||hm(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 bJ(t,e){return e.kind==="checks"&&e.expect==="pass"?ho(t,e.select):[]}function ru(t,e){return t.record.evidence.flatMap((n)=>n.gates.filter((r)=>r.gate===e))}function Lx(t){let e=t.flatMap((n)=>n.checks).filter((n)=>n.expect==="pass");return[...new Map(e.map((n)=>[fm(n),n])).values()]}function EJ(t){return t.record.gatesHash===null?["the record has no frozen gates hash"]:[]}function TJ(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)=>$J(i,e,a))]}function $J(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(hm(o,s))return[];return[`the evidence of stage "${r.name}" records the gates [${o.join(", ")}], but the pack runs [${s.join(", ")}]`]}function xJ(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 AJ(t,e){let n=e.record.contractHash;if(n===null)return["the record has no frozen contract hash"];let r=wJ(SJ(t,Ot(e.contract.id)),"utf8");if(Vt(r)===n)return[];return["the contract changed after 'ari start' or the last 'ari amend' froze it; a done contract must not change"]}function CJ(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)=>RJ(t.contract,o,s,i))}function RJ(t,e,n,r){let o=e.gates[r];if(o===void 0||o.kind!==n.gate)return[];let s=IJ(t,o);if(s===null)return[];let i=n.checks.map(OJ);if(hm(i.map(fm),s.map(fm)))return[];return[`the ${n.gate} evidence of stage "${e.name}" ran ${_x(i)}, but the contract asks for ${_x(s)}`]}function IJ(t,e){switch(e.kind){case"checks":return ho(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 OJ(t){return{command:t.command,expect:t.expect,name:t.name}}function fm(t){return JSON.stringify([t.name,t.command,t.expect])}function _x(t){if(t.length===0)return"nothing";return t.map((e)=>`${e.name} (${JSON.stringify(e.command)}, expect ${e.expect})`).join(", ")}function hm(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var pr=0,km=1,_J=128,PJ=`
286
+ `;async function Mx(t,e){let n=e.evidence.at(-1);if(e.status!=="done"||n===void 0)return null;let r=In(e.id),o=await F(t,["log","--reverse","--format=%H","HEAD","--",r]),s=null;for(let i of o.stdout.split(PJ).filter((a)=>a.length>0)){let a=Kx(await Oi(t,i,r));if(a===null||a.created!==e.history[0]?.at)continue;if(a.base!==null)s??=i;if(NJ(a,n))return{finished:i,started:s??i}}return null}async function jx(t,e,n){return Kx(await Oi(t,e,In(n)))?.status??null}async function Oi(t,e,n){let r=await F(t,["show",`${e}:${n}`],{allowedExitCodes:[pr,_J]});return r.exitCode===pr?r.stdout:null}async function Fx(t,e){return await Ux(t,e)!==null}async function Gx(t,e){return Ux(t,`${e}^`)}async function _i(t,e,n){return(await F(t,["merge-base","--is-ancestor",e,n],{allowedExitCodes:[pr,km]})).exitCode===pr}async function wm(t,e,n){let r=await F(t,["merge-base",e,n],{allowedExitCodes:[pr,km]});return r.exitCode===pr?r.stdout.trim():null}async function Sm(t,e,n){return Number((await F(t,["rev-list","--count",`${e}..${n}`])).stdout.trim())}async function Hx(t){return(await F(t,["rev-parse","--is-shallow-repository"])).stdout.trim()==="true"}async function Ux(t,e){let n=["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],r=await F(t,n,{allowedExitCodes:[pr,km]});return r.exitCode===pr?r.stdout.trim():null}function Kx(t){let e=DJ(t);if(!ym(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:ym(r)?r.at:null,evidence:ym(n)?n:null,status:e.status}}function NJ(t,{at:e,stage:n,treeHash:r}){let o=t.evidence;return o!==null&&o.at===e&&o.stage===n&&o.treeHash===r}function DJ(t){if(t===null)return null;try{return JSON.parse(t)}catch(e){if(e instanceof SyntaxError)return null;throw e}}function ym(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function vm({packs:t},e){return{exact:!0,pack:bm(t,e.contract.pack)}}async function Bx(t,e,n,r){let{gatesHash:o}=e.record,s=r===null?null:await LJ(t,r,e.contract.pack),i=[n,s].find((a)=>a!==null&&MJ(a,e)===o);if(i)return vm(i,e);return{exact:!1,pack:bm((s??n).packs,e.contract.pack)}}async function LJ(t,e,n){let r=_d(n),o=await Oi(t,e,r),s=await Oi(t,e,rt);try{return{config:Tr(s===null?{}:JSON.parse(s)),packs:xn(o===null?[]:[Pa(o,r)])}}catch(i){if(i instanceof m||i instanceof SyntaxError)return null;throw i}}function MJ({config:t,packs:e},n){let r=bm(e,n.contract.pack);return r===null?null:Na(r,t)}function bm(t,e){return t.find((n)=>n.name===e)??null}async function Wx(t){let{commits:e,record:n,root:r,target:o}=t,{base:s}=n;if(s===null)return qx("the record has no base commit");let i=await Fx(r,s);if(e===null){if(!i)return Em(s);return ou(await Ae(r,await Vx(r,s,o,"HEAD")))}let{finished:a}=e,c=i&&await _i(r,s,a),l=o===null?null:await wm(r,o,a);if(l===null||l===a)return FJ(t,e,c?s:null);let u=c?await Vx(r,s,o,a):await jJ(r,l,t.otherFinishes,a);return ou(await Ka(r,u,a))}async function Vx(t,e,n,r){let o=n===null?null:await wm(t,n,r);return o!==null&&await _i(t,e,o)?o:e}async function jJ(t,e,n,r){let o={commit:e,distance:await Sm(t,e,r)};for(let s of n){if(s===r||!await _i(t,e,s)||!await _i(t,s,r))continue;let i=await Sm(t,s,r);if(i<o.distance)o={commit:s,distance:i}}return o.commit}async function FJ(t,e,n){let{record:r,root:o}=t,{finished:s,started:i}=e;if(n===null&&await Hx(o))return Em(r.base);let a=await Gx(o,i),c=a===null?null:await Ka(o,a,s);if(n===null)return c===null?Em(r.base):ou(c);let l=await Ka(o,n,s);return ou(c===null?l:l.filter((u)=>c.includes(u)))}function ou(t){return{files:t,problem:null}}function qx(t){return{files:[],problem:t}}function Em(t){return qx(`the base commit ${t} is not in this clone; fetch the full history`)}var UJ="\x00",Tm="HEAD",Cm="done",$m=[xr,Gy],KJ="invalid";async function Xx(t,e){let n=M(t);await Ua(t);let r=Nt(t,n),o=xn(Ht(t)),s=e.kind==="base"?await wo(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 BJ(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 Mx(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 qJ(u,g));continue}let f=a.get(p)?.problem??WJ(t,p);if(f===null)continue;d.push({gates:[],ok:!1,problems:[f],stage:null,status:KJ,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 BJ(t,e,n,r){let o=n??Tm,s=async(i)=>(r.get(i)?.record.status??await VJ(t,i,o))===Cm;switch(e.kind){case"all":return Am(On(t),s);case"base":{let i=["diff","--name-only","--no-renames","-z",o,Tm,"--",...$m],a=(await F(t,i)).stdout.split(UJ),c=new Set(xm(a,xr));return Am(xm(a,...$m),async(l)=>c.has(l)||s(l))}case"local":{let i=gt(await P(t))?.task,a=await Am(xm(await Ae(t,Tm),...$m),s);return[...new Set([...i===void 0?[]:[i],...a])]}}}async function VJ(t,e,n){if(!Jx(Yx(t,In(e))))return jx(t,n,e);try{return _n(t,e).status}catch(r){if(r instanceof m)return Cm;throw r}}function WJ(t,e){let n=In(e);return Jx(Yx(t,n))?`${n} has a record but no contract`:null}function xm(t,...e){let n=t.filter((r)=>et(r,e)).map((r)=>GJ(r,HJ(r)));return[...new Set(n)].filter(Od).sort(O)}async function Am(t,e){let n=[];for(let r of t)if(await e(r))n.push(r);return n}async function qJ(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===Cm?["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 Bx(s,e,t,zx(t,e)?.finished??null):vm(t,e),a=Nx(s,e,i),c=[];for(let u of Dx(e,i)){let d=await JJ(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 zx(t,e){return t.commits.get(e.contract.id)??null}async function JJ(t,e,n){switch(n.gate){case"checks":case"invariants":{let r=YJ(e,n.checks);return r.length===0?null:XJ(t,e,r)}case"locked":return ZJ(t,e);case"scope":return QJ(t,e);default:return null}}function YJ(t,e){if(t.record.status==="done")return[...e];return e.filter((n)=>n.expect==="pass")}async function XJ(t,e,n){let r=[],o=!0;for(let s of n){let i={name:s.name,run:s.command,timeoutSeconds:zJ(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})`:fp(a))}return{current:o,details:r}}function zJ(t,e,n){return e.contract.checks.find((o)=>o.name===n)?.timeoutSeconds??t.config.checkTimeoutSeconds}async function ZJ(t,e){let n=await Cn(t.root,e.contract.lock),r=Qs(e.record.lockHashes,n);return{current:r.length===0,details:r}}async function QJ(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 Wx({commits:zx(t,e),otherFinishes:s,record:e.record,root:r,target:o});if(i.problem!==null)return{current:!1,details:[i.problem]};let a=re(i.files).filter((c)=>!et(c,e.contract.scope));return{current:a.length===0,details:a.map((c)=>`outside the scope: ${c}`)}}var t5=1,Qx=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 Xx(await _(),r);return t.output.result(o,e5),o.failed.length===0?void 0:t5}});function e5(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 ${Zx(i.recorded)}, now ${Zx(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 Zx(t){return t?"passed":"failed"}var tA=[ax,ux,cx,Ox,px,Qx];var o5=".ari",s5="cli-state.json",i5=Mu({bin:"ari",commands:[nT,BT,ix,wE,U$,K$,B$,WT,qT,YE,XE,zE,JT,YT,XT,zT,H$,ZE,...tA,tT,eT,O$,I$,A$,P$,Ak,W$],config:new Wu(r5(n5(),o5,s5),{}),description:"Task contracts, CLI-evaluated gates and tiered memory for coding agents",name:"Ariadne",version:Sa});i5.main();