@r5n/ariadne 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -4
- package/dist/cli.js +214 -125
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,148 +1,237 @@
|
|
|
1
1
|
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
2
|
// @bun
|
|
3
|
-
import{homedir as wA}from"os";import{join as $A}from"path";class _t extends Error{_tag="Cancel";constructor(t="Operation cancelled"){super(t)}}function L(t){return t}function so(t){return t==null?[]:Array.isArray(t)?t:[t]}function Tf(t,e,n,r){var s,o=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((s=+n,s*0===0)?s:n),!!n):(s=+n,s*0===0)?s:n;t[e]=o==null?i:Array.isArray(o)?o.concat(i):[o,i]}function oo(t,e){t=t||[],e=e||{};var n,r,s,o,i,a={_:[]},c=0,l=0,u=0,d=t.length;let p=e.alias!==void 0,f=e.unknown!==void 0,m=e.default!==void 0;if(e.alias=e.alias||{},e.string=so(e.string),e.boolean=so(e.boolean),p)for(n in e.alias){r=e.alias[n]=so(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(m){for(n in e.default)if(o=typeof e.default[n],r=e.alias[n]=e.alias[n]||[],e[o]!==void 0){e[o].push(n);for(c=0;c<r.length;c++)e[o].push(r[c])}}let h=f?Object.keys(e.alias):[];for(c=0;c<d;c++){if(s=t[c],s==="--"){a._=a._.concat(t.slice(++c));break}for(l=0;l<s.length;l++)if(s.charCodeAt(l)!==45)break;if(l===0)a._.push(s);else if(s.substring(l,l+3)==="no-"){if(o=s.substring(l+3),f&&!~h.indexOf(o))return e.unknown(s);a[o]=!1}else{for(u=l+1;u<s.length;u++)if(s.charCodeAt(u)===61)break;o=s.substring(l,u),i=s.substring(++u)||(c+1===d||(""+t[c+1]).charCodeAt(0)===45||t[++c]),r=l===2?[o]:o;for(u=0;u<r.length;u++){if(o=r[u],f&&!~h.indexOf(o))return e.unknown("-".repeat(l)+o);Tf(a,o,u+1<r.length||i,e)}}}if(m){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 ft=0,kn=1,Ma=2,Ga=255;function ir(t){return Number.isInteger(t)&&t>=0&&t<=255}class g extends Error{hint;exitCode;_tag;constructor(t,e,n=1,r={}){super(t,"cause"in r?{cause:r.cause}:void 0);this.hint=e;this.exitCode=n;this._tag=r.tag??"Exit"}}class v extends g{constructor(t,e,n={}){super(t,e,2,{...n,tag:n.tag??"UsageError"})}}var Fa=1,vf=2,cr="--",Ka="-",de="no-",Cf=new Set(["false","true"]),bn=/^--([^=]+)(?:=(.*))?$/s,xn=/^-([^-=][^=]*)(?:=(.*))?$/s,co=/^(?:---|-no-|-_|-[^-=][^=]*_)/,Af="_",wn="\x00";function Pt(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function We(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 s=Pt(n);if(s!==n)e.alias[s]=n;if(r.default!==void 0)e.default[n]=r.default}return e}function ar(t,e){let n={};for(let[i,a]of Object.entries(e.alias))n[a]=[...n[a]??[],i];let{_:r,...s}=oo(pr(t,Of),{alias:n,boolean:[...e.boolean],default:{...e.default},string:[...e.string]}),o=Object.entries(s).map(([i,a])=>[io(i),io(a)]);return{...Object.fromEntries(o),_:r.map(io)}}function Of(t){if(t===Ka)return`${wn}${t}`;let e=bn.exec(t);if(co.test(t)||Rf(e?.[1]))return`--${wn}${t}`;return(e?e[2]:xn.exec(t)?.[2])===""?`${t}${wn}`:t}function Rf(t){if(t===void 0)return!1;let e=t.startsWith(de)?t.slice(de.length):t;return e===Af||e in Object.prototype}function io(t){return typeof t==="string"&&t.startsWith(wn)?t.slice(wn.length):t}function $n(t,e){return Object.hasOwn(e.alias,t)?e.alias[t]??t:t}function Be(t,e){if(Object.hasOwn(e,t))return`--${Pt(t)}`;let n=Object.entries(e).find(([,r])=>r.alias===t)?.[0];if(n)return`--${Pt(n)}`;return t.length===Fa?`-${t}`:`--${t}`}function lr(t,e,n,r){let{alias:s}=We(e),o=Object.keys(t).find((i)=>!Object.hasOwn(e,i)&&!Object.hasOwn(s,i));if(o!==void 0)throw new v(`Unknown option: ${If(o,r)}`,n)}function If(t,e){if(t.startsWith("-"))return t;let n=e.indexOf(cr);for(let r of n<0?e:e.slice(0,n)){let s=bn.exec(r)?.[1];if(s===t||r===`--${de}${t}`)return`--${s}`;if(s===void 0&&xn.exec(r)?.[1]?.includes(t))return`-${t}`}return Be(t,{})}function Ua(t,e){for(let[r,s]of Object.entries(t))if(Array.isArray(s))throw new v(`${Be(r,e)} can only be provided once`);let n={...t};for(let[r,s]of Object.entries(e)){let o=t[r];if(o===void 0)continue;if(s.type==="string"&&typeof o==="boolean")throw Ba(Be(r,e));if(s.type!=="number")continue;let i=Number(o);if(typeof o==="boolean"||typeof o==="string"&&o.trim().length===0||!Number.isFinite(i)){let a=Be(r,e);throw new v(`Invalid number for ${a}: "${o}"`,`Use ${a}=<number> with a finite numeric value`)}n[r]=i}return n}function Ba(t){return new v(`${t} needs a value`,`Use ${t}=<value>`)}function ur(t,e){let n=We(e),r=uo([...t],n),s=ar(r,n)._[0],o=s===void 0?-1:r.indexOf(s);return{before:o>=0?t.slice(0,o):[...t],command:s,restArgs:o>=0?t.slice(o+1):[]}}function Wa(t,e){let n=We(e);for(let r=0;r<t.length;r+=1){let s=t[r]??"";if(s===cr)return-1;if(s===Ka||!s.startsWith("-"))return r;if(_f(s,n,e))r+=1}return-1}function _f(t,e,n){if(t.startsWith(`--${de}`))return!1;let r=bn.exec(t),s=r??xn.exec(t);if(!s||s[2]!==void 0)return!1;let o=r?s[1]??"":s[1]?.at(-1)??"",i=n[$n(o,e)]?.type;return i==="string"||i==="number"}function lo(t,e,n=e){let r=We(e),{before:s,command:o,restArgs:i}=ur(t,e),a=We(n);ao(s,r,e,!0),ao(t,a,n,!0);let{_:c,...l}=ar(Va(s,r,e),r);lr(l,e,"Place command options after the command name",s);let{_:u,...d}=ar(uo(i,a),a),p=Ua({...Ha(l,e,r),...Ha(d,n,a)},e);return{command:o,flags:p,restArgs:i}}function Ha(t,e,n){return Object.fromEntries(Object.entries(t).filter(([r])=>Object.hasOwn(e,r)||Object.hasOwn(n.alias,r)))}function dr(t,e){return Object.fromEntries(Object.keys(e).flatMap((n)=>{let r=t[n];return r===void 0?[]:[[n,r]]}))}function Sn(t,e={}){let n=We(e),r=Pf(t,n);ao(r,n,e);let s=ar(Va(r,n,e),n),{_:o,...i}=s;return{args:Ua(i,e),rawPositionals:o.map(String)}}function ao(t,e,n,r=!1){let s=new Set;for(let o of t){if(o===cr)break;let i=o.match(/^-+/)?.[0];if(!i||co.test(o))continue;let a=o.slice(i.length),c=a.split("=",Fa)[0]??"",l=a.startsWith(de)?[a.slice(de.length)]:i.length===vf?[c]:[...c];for(let u of l){let d=$n(u,e);if(r&&!Object.hasOwn(n,d))continue;if(s.has(d))throw new v(`${Be(d,n)} can only be provided once`);s.add(d)}}}function pr(t,e){let n=t.indexOf(cr);return t.map((r,s)=>n>=0&&s>=n?r:e(r,t[s+1]))}function uo(t,e){return pr(t,(n)=>{let r=bn.exec(n)??xn.exec(n);if(!r||r[2]!==void 0||n.startsWith(`--${de}`))return n;let s=n.startsWith("--")?r[1]??"":r[1]?.at(-1)??"";return e.boolean.includes($n(s,e))?`${n}=true`:n})}function Va(t,e,n){let r=(i)=>n[$n(i,e)]?.type,s=(i)=>i!==void 0&&!i.startsWith("-"),o=pr(t,(i,a)=>{let c=bn.exec(i),l=c?null:xn.exec(i);if(i.startsWith(`--${de}`)||co.test(i))return i;let u=c?[c[1]??""]:[...l?.[1]??""],d=c?c[2]:l?.[2];for(let[p,f]of u.entries()){let m=r(f),h=p===u.length-1,y=Be($n(f,e),n),x=!h||d===void 0&&!s(a);if(m==="string"&&(x||d===""))throw Ba(y);if(m==="number"&&x)throw new v(`${y} needs a value`,`Use ${y}=<number>`);if(m==="boolean"&&h&&d!==void 0&&!Cf.has(d))throw new v(`Invalid value for ${y}: "${d}"`,`Use ${y}=true or ${y}=false`)}return i});return uo(o,e)}function Pf(t,e){return pr(t,(n)=>n.replace(/^--(no-[^=]+)(=.*)?$/,(r,s,o)=>{let i=e.alias[s];return i&&e.boolean.includes(i)?`--${i}${o??""}`:r}))}function mr(t,e){let n={},r=Object.entries(e);for(let[s,[o,i]]of r.entries())n[o]=i.variadic?t.slice(s):t[s];return n}function fr(t,e){for(let[n,r]of Object.entries(e)){if(!r.required)continue;let s=t[n];if(Array.isArray(s)?s.length===0:!s)return`Missing required argument: <${n}${r.variadic?"...":""}>`}return null}function Ja(t,e){let n=Object.values(e);if(n.some((r)=>r.variadic))return;return t[n.length]}var Nf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Df=new Set(["help","json"]),jf=/^[a-zA-Z0-9]$/,Lf=new Set(["h","j"]);function gr(){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 Mf(e),Object.freeze(e)}}function hr(t,e){let n=po(e.map((r)=>r.name));if(n!==void 0)throw Error(`${t} has more than one command named "${n}"`)}function Mf(t){let e=`Command "${t.name}"`;if(!Nf.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(Df.has(Pt(u)))throw Error(`${e} cannot define the option "${u}": --${Pt(u)} is a global flag`);if(d.alias!==void 0&&Lf.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(Pt),r=po(n);if(r!==void 0)throw Error(`${e} has more than one option named --${r}`);let s=Object.values(t.args).flatMap((u)=>u.alias??[]),o=s.find((u)=>!jf.test(u));if(o!==void 0)throw Error(`${e} uses the alias "${o}": an alias is one letter or digit`);let i=s.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=po(s);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`);hr(e,t.subcommands)}function po(t){return t.find((e,n)=>t.indexOf(e)!==n)}function nt(t){return t}import{Console as qf}from"console";import{Writable as Yf}from"stream";import{format as Xf,stripVTControlCharacters as zf}from"util";var pe={active:!1};var Gf=new Set(["0","false"]);function kr(t){if(process.env.NO_COLOR)return!1;let e=process.env.FORCE_COLOR;if(e!==void 0)return!Gf.has(e);return t?.isTTY===!0}var Hf=kr(process.stdout),Xa=["black","blue","cyan","gray","green","magenta","red","white","yellow"],Ff=["bold","dim","italic","underline","reset"],za={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},Kf={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"},Uf={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"},qa={"\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 yr(t){return(e)=>Hf&&!pe.active?`${t}${e}${za.reset}`:e}function Bf(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<32&&n!==27)return!1}return!0}function Ya({bright:t=!1,color:e}){let n=Bun.color(e,"ansi"),r=typeof n==="string"&&n.length>0&&Bf(n)?n:Kf[e];if(!r)return"";return t&&r in qa?qa[r]:r}var Wf=Xa.reduce((t,e)=>{let n=Ya({color:e});if(n)t[e]=yr(n);let r=Ya({bright:!0,color:e});if(r)t[`${e}Bright`]=yr(r);return t},{}),Vf=Ff.reduce((t,e)=>(t[e]=yr(za[e]),t),{}),Jf=Xa.reduce((t,e)=>{let n=Uf[e];if(n){let r=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[r]=yr(n)}return t},{}),G={...Wf,...Vf,...Jf};var Zf=2,tc=["clear","count","countReset","debug","dir","dirxml","group","groupCollapsed","groupEnd","info","log","table"],Qf=[...tc,"trace","write"],tg=1,eg="EPIPE",ng="EIO",B={closedStreams:new Set,documentWritten:!1,jsonRuns:0,outputGuarded:!1,restoreStdout:void 0,sealed:!1,stdoutClosed:!1,stdoutWrite:void 0};function En(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function mo(t){return En()&&!pe.active&&t?.json!==!0}function ec(){return pe.active}function me(t){let e=JSON.stringify(t??null,null,Zf);if(e===void 0)throw TypeError("JSON cannot represent the value");return`${e}
|
|
4
|
-
`}function
|
|
5
|
-
`).slice(
|
|
6
|
-
`))};return e}function
|
|
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===
|
|
8
|
-
`){if(
|
|
9
|
-
`){if(
|
|
10
|
-
`)}var
|
|
3
|
+
import{homedir as pD}from"os";import{join as gD}from"path";class kt extends Error{_tag="Cancel";constructor(t="Operation cancelled"){super(t)}}function N(t){return t}function Ba(t){return t==null?[]:Array.isArray(t)?t:[t]}function bS(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 Wa(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,m=e.default!==void 0;if(e.alias=e.alias||{},e.string=Ba(e.string),e.boolean=Ba(e.boolean),p)for(n in e.alias){r=e.alias[n]=Ba(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(m){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 h=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&&!~h.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&&!~h.indexOf(s))return e.unknown("-".repeat(l)+s);bS(a,s,u+1<r.length||i,e)}}}if(m){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 At=0,Kr=1,pd=2,gd=255;function Wo(t){return Number.isInteger(t)&&t>=0&&t<=255}class f extends Error{hint;exitCode;_tag;constructor(t,e,n=1,r={}){super(t,"cause"in r?{cause:r.cause}:void 0);this.hint=e;this.exitCode=n;this._tag=r.tag??"Exit"}}class T extends f{constructor(t,e,n={}){super(t,e,2,{...n,tag:n.tag??"UsageError"})}}var fd=1,TS=2,Jo="--",hd="-",Ze="no-",ES=new Set(["false","true"]),Wr=/^--([^=]+)(?:=(.*))?$/s,Vr=/^-([^-=][^=]*)(?:=(.*))?$/s,qa=/^(?:---|-no-|-_|-[^-=][^=]*_)/,xS="_",Ur="\x00";function ee(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Xn(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=ee(n);if(o!==n)e.alias[o]=n;if(r.default!==void 0)e.default[n]=r.default}return e}function Vo(t,e){let n={};for(let[i,a]of Object.entries(e.alias))n[a]=[...n[a]??[],i];let{_:r,...o}=Wa(zo(t,vS),{alias:n,boolean:[...e.boolean],default:{...e.default},string:[...e.string]}),s=Object.entries(o).map(([i,a])=>[Va(i),Va(a)]);return{...Object.fromEntries(s),_:r.map(Va)}}function vS(t){if(t===hd)return`${Ur}${t}`;let e=Wr.exec(t);if(qa.test(t)||CS(e?.[1]))return`--${Ur}${t}`;return(e?e[2]:Vr.exec(t)?.[2])===""?`${t}${Ur}`:t}function CS(t){if(t===void 0)return!1;let e=t.startsWith(Ze)?t.slice(Ze.length):t;return e===xS||e in Object.prototype}function Va(t){return typeof t==="string"&&t.startsWith(Ur)?t.slice(Ur.length):t}function Br(t,e){return Object.hasOwn(e.alias,t)?e.alias[t]??t:t}function Yn(t,e){if(Object.hasOwn(e,t))return`--${ee(t)}`;let n=Object.entries(e).find(([,r])=>r.alias===t)?.[0];if(n)return`--${ee(n)}`;return t.length===fd?`-${t}`:`--${t}`}function qo(t,e,n,r){let{alias:o}=Xn(e),s=Object.keys(t).find((i)=>!Object.hasOwn(e,i)&&!Object.hasOwn(o,i));if(s!==void 0)throw new T(`Unknown option: ${AS(s,r)}`,n)}function AS(t,e){if(t.startsWith("-"))return t;let n=e.indexOf(Jo);for(let r of n<0?e:e.slice(0,n)){let o=Wr.exec(r)?.[1];if(o===t||r===`--${Ze}${t}`)return`--${o}`;if(o===void 0&&Vr.exec(r)?.[1]?.includes(t))return`-${t}`}return Yn(t,{})}function yd(t,e){for(let[r,o]of Object.entries(t))if(Array.isArray(o))throw new T(`${Yn(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 kd(Yn(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=Yn(r,e);throw new T(`Invalid number for ${a}: "${s}"`,`Use ${a}=<number> with a finite numeric value`)}n[r]=i}return n}function kd(t){return new T(`${t} needs a value`,`Use ${t}=<value>`)}function Yo(t,e){let n=Xn(e),r=Xa([...t],n),o=Vo(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 wd(t,e){let n=Xn(e);for(let r=0;r<t.length;r+=1){let o=t[r]??"";if(o===Jo)return-1;if(o===hd||!o.startsWith("-"))return r;if(IS(o,n,e))r+=1}return-1}function IS(t,e,n){if(t.startsWith(`--${Ze}`))return!1;let r=Wr.exec(t),o=r??Vr.exec(t);if(!o||o[2]!==void 0)return!1;let s=r?o[1]??"":o[1]?.at(-1)??"",i=n[Br(s,e)]?.type;return i==="string"||i==="number"}function Ya(t,e,n=e){let r=Xn(e),{before:o,command:s,restArgs:i}=Yo(t,e),a=Xn(n);Ja(o,r,e,!0),Ja(t,a,n,!0);let{_:c,...l}=Vo(Sd(o,r,e),r);qo(l,e,"Place command options after the command name",o);let{_:u,...d}=Vo(Xa(i,a),a),p=yd({...md(l,e,r),...md(d,n,a)},e);return{command:s,flags:p,restArgs:i}}function md(t,e,n){return Object.fromEntries(Object.entries(t).filter(([r])=>Object.hasOwn(e,r)||Object.hasOwn(n.alias,r)))}function Xo(t,e){return Object.fromEntries(Object.keys(e).flatMap((n)=>{let r=t[n];return r===void 0?[]:[[n,r]]}))}function Jr(t,e={}){let n=Xn(e),r=RS(t,n);Ja(r,n,e);let o=Vo(Sd(r,n,e),n),{_:s,...i}=o;return{args:yd(i,e),rawPositionals:s.map(String)}}function Ja(t,e,n,r=!1){let o=new Set;for(let s of t){if(s===Jo)break;let i=s.match(/^-+/)?.[0];if(!i||qa.test(s))continue;let a=s.slice(i.length),c=a.split("=",fd)[0]??"",l=a.startsWith(Ze)?[a.slice(Ze.length)]:i.length===TS?[c]:[...c];for(let u of l){let d=Br(u,e);if(r&&!Object.hasOwn(n,d))continue;if(o.has(d))throw new T(`${Yn(d,n)} can only be provided once`);o.add(d)}}}function zo(t,e){let n=t.indexOf(Jo);return t.map((r,o)=>n>=0&&o>=n?r:e(r,t[o+1]))}function Xa(t,e){return zo(t,(n)=>{let r=Wr.exec(n)??Vr.exec(n);if(!r||r[2]!==void 0||n.startsWith(`--${Ze}`))return n;let o=n.startsWith("--")?r[1]??"":r[1]?.at(-1)??"";return e.boolean.includes(Br(o,e))?`${n}=true`:n})}function Sd(t,e,n){let r=(i)=>n[Br(i,e)]?.type,o=(i)=>i!==void 0&&!i.startsWith("-"),s=zo(t,(i,a)=>{let c=Wr.exec(i),l=c?null:Vr.exec(i);if(i.startsWith(`--${Ze}`)||qa.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 m=r(g),h=p===u.length-1,w=Yn(Br(g,e),n),b=!h||d===void 0&&!o(a);if(m==="string"&&(b||d===""))throw kd(w);if(m==="number"&&b)throw new T(`${w} needs a value`,`Use ${w}=<number>`);if(m==="boolean"&&h&&d!==void 0&&!ES.has(d))throw new T(`Invalid value for ${w}: "${d}"`,`Use ${w}=true or ${w}=false`)}return i});return Xa(s,e)}function RS(t,e){return zo(t,(n)=>n.replace(/^--(no-[^=]+)(=.*)?$/,(r,o,s)=>{let i=e.alias[o];return i&&e.boolean.includes(i)?`--${i}${s??""}`:r}))}function Zo(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 Qo(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 $d(t,e){let n=Object.values(e);if(n.some((r)=>r.variadic))return;return t[n.length]}var OS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,_S=new Set(["help","json"]),PS=/^[a-zA-Z0-9]$/,NS=new Set(["h","j"]);function ts(){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 jS(e),Object.freeze(e)}}function es(t,e){let n=za(e.map((r)=>r.name));if(n!==void 0)throw Error(`${t} has more than one command named "${n}"`)}function jS(t){let e=`Command "${t.name}"`;if(!OS.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(_S.has(ee(u)))throw Error(`${e} cannot define the option "${u}": --${ee(u)} is a global flag`);if(d.alias!==void 0&&NS.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(ee),r=za(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)=>!PS.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=za(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`);es(e,t.subcommands)}function za(t){return t.find((e,n)=>t.indexOf(e)!==n)}function rt(t){return t}import{Console as WS}from"console";import{Writable as VS}from"stream";import{format as JS,stripVTControlCharacters as qS}from"util";var Qe={active:!1};var MS=new Set(["0","false"]);function qr(t){if(process.env.NO_COLOR)return!1;let e=process.env.FORCE_COLOR;if(e!==void 0)return!MS.has(e);return t?.isTTY===!0}var DS=qr(process.stdout),Ed=["black","blue","cyan","gray","green","magenta","red","white","yellow"],LS=["bold","dim","italic","underline","reset"],xd={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},FS={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"},GS={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"},bd={"\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 ns(t){return(e)=>DS&&!Qe.active?`${t}${e}${xd.reset}`:e}function HS(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<32&&n!==27)return!1}return!0}function Td({bright:t=!1,color:e}){let n=Bun.color(e,"ansi"),r=typeof n==="string"&&n.length>0&&HS(n)?n:FS[e];if(!r)return"";return t&&r in bd?bd[r]:r}var KS=Ed.reduce((t,e)=>{let n=Td({color:e});if(n)t[e]=ns(n);let r=Td({bright:!0,color:e});if(r)t[`${e}Bright`]=ns(r);return t},{}),US=LS.reduce((t,e)=>(t[e]=ns(xd[e]),t),{}),BS=Ed.reduce((t,e)=>{let n=GS[e];if(n){let r=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[r]=ns(n)}return t},{}),k={...KS,...US,...BS};var YS=2,Ad=["clear","count","countReset","debug","dir","dirxml","group","groupCollapsed","groupEnd","info","log","table"],XS=[...Ad,"trace","write"],zS=1,ZS="EPIPE",QS="EIO",Z={closedStreams:new Set,documentWritten:!1,jsonRuns:0,outputGuarded:!1,restoreStdout:void 0,sealed:!1,stdoutClosed:!1,stdoutWrite:void 0};function Yr(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Za(t){return Yr()&&!Qe.active&&t?.json!==!0}function Id(){return Qe.active}function tn(t){let e=JSON.stringify(t??null,null,YS);if(e===void 0)throw TypeError("JSON cannot represent the value");return`${e}
|
|
4
|
+
`}function Rd(){return Z.documentWritten}function Od(){Z.sealed=!0}function _e(t){if(Z.documentWritten=!0,Z.sealed||Z.stdoutClosed)return;let e=Z.stdoutWrite??process.stdout.write;try{e.call(process.stdout,t)}catch(n){if(!rs(n,process.stdout))throw n;Z.stdoutClosed=!0}}function _d(){if(Z.outputGuarded)return;Z.outputGuarded=!0,process.stdout.write=vd(process.stdout.write,!0),console.write=vd(console.write,0),process.stdout.on("error",(t)=>{if(!rs(t,process.stdout))throw t;Z.stdoutClosed=!0}),process.stderr.on("error",(t)=>{if(!rs(t,process.stderr))throw t});for(let t of[process.stdout,process.stderr])t.once("close",()=>Z.closedStreams.add(t))}function vd(t,e){let n=(r)=>{let o=r.at(-1);if(typeof o==="function")queueMicrotask(()=>o());return e};return function(...o){if(Z.stdoutClosed)return n(o);try{return t.apply(this,o)}catch(s){if(!rs(s,process.stdout))throw s;return Z.stdoutClosed=!0,n(o)}}}function rs(t,e){if(!(t instanceof Error))return!1;let n=Reflect.get(t,"code");return n===ZS||n===QS&&e.isTTY===!0}function os(){let t=qr(process.stderr);return new VS({decodeStrings:!1,write(e,n,r){process.stderr.write(t?e:qS(e)),r()}})}async function Pd(t,e){if(!t)return e();Z.jsonRuns+=1,Z.restoreStdout??=t$(),Qe.active=!0;try{return await e()}finally{if(Z.jsonRuns-=1,Qe.active=Z.jsonRuns>0,!Qe.active&&!Z.outputGuarded)Z.restoreStdout?.(),Z.restoreStdout=void 0}}async function Nd(t){let e=Promise.all([Z.stdoutClosed?void 0:Cd(process.stdout),Cd(process.stderr)]);await(t===void 0?e:Promise.race([e,Bun.sleep(t)]))}function Cd(t){if(t.writableFinished||Z.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 t$(){let t=process.stdout.write,e=new WS({stderr:process.stderr,stdout:process.stderr}),n=Object.fromEntries(XS.map((o)=>[o,console[o]])),r=Object.fromEntries(Ad.map((o)=>[o,e[o].bind(e)]));return Z.stdoutWrite=t,process.stdout.write=process.stderr.write.bind(process.stderr),Object.assign(console,r,{trace:e$(e),write:n$}),()=>{process.stdout.write=t,Object.assign(console,n),Z.stdoutWrite=void 0}}function e$(t){let e=(...n)=>{let r={};Error.captureStackTrace(r,e);let o=r.stack?.split(`
|
|
5
|
+
`).slice(zS)??[];t.error([`Trace: ${JS(...n)}`,...o].join(`
|
|
6
|
+
`))};return e}function n$(...t){let e=Buffer.concat(t.map(r$));return process.stderr.write(e),e.byteLength}function r$(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 Kt={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"}},zn={help:Kt.help,json:Kt.json},Sn="help",ss={[At]:"success",[Kr]:"failure",[pd]:"usage error"};import{stripVTControlCharacters as fc}from"util";import{styleText as y$}from"util";import{stdout as Yd,stdin as k$}from"process";import w$ from"readline";var jd=(()=>{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}})(),Md=(t)=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Dd=(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 o$=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,s$=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ld=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,i$=/\t{1,1000}/y,Fd=/[\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,a$=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,c$=/\p{M}+/gu,l$={limit:1/0,ellipsis:""},Gd=(t,e={},n={})=>{let r=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?Gd(o,l$,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=[[a$,d],[o$,0],[s$,a],[i$,c],[Fd,l],[Ld,p]],m=0,h=0,w=t.length,b=0,v=!1,B=w,K=Math.max(0,r-s),_=0,M=0,A=0,C=0;t:while(!0){if(M>_||h>=w&&h>m){let G=t.slice(_,M)||t.slice(m,h);b=0;for(let Tt of G.replaceAll(c$,"")){let Pt=Tt.codePointAt(0)||0;if(Md(Pt))C=2;else if(Dd(Pt))C=p;else C=d;if(A+C>K)B=Math.min(B,Math.max(_,m)+b);if(A+C>r){v=!0;break t}b+=Tt.length,A+=C}_=M=0}if(h>=w)break t;for(let G=0,Tt=g.length;G<Tt;G++){let[Pt,dd]=g[G];if(Pt.lastIndex=h,Pt.test(t)){if(b=Pt===Ld?jd(t.slice(h,Pt.lastIndex)):Pt===Fd?1:Pt.lastIndex-h,C=b*dd,A+C>K)B=Math.min(B,h+Math.floor((K-A)/dd));if(A+C>r){v=!0;break t}A+=C,_=m,M=h,h=m=Pt.lastIndex;continue t}}h+=1}return{width:v?K:A,index:v?B:w,truncated:v,ellipsed:v&&r>=s}},Hd=Gd;var u$={limit:1/0,ellipsis:"",ellipsisWidth:0},d$=(t,e={})=>Hd(t,u$,e).width,mt=d$;var is="\x1B",Vd="\x9B",p$=39,tc="\x07",Jd="[",g$="]",qd="m",ec=`${g$}8;;`,Kd=new RegExp(`(?:\\${Jd}(?<code>\\d+)m|\\${ec}(?<uri>.*)${tc})`,"y"),Ud=(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},Bd=(t)=>`${is}${Jd}${t}${qd}`,Wd=(t)=>`${is}${ec}${t}${tc}`,Qa=(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===is||d===Vd)o=!0,s=e.startsWith(ec,u+1);if(o){if(s){if(d===tc)o=!1,s=!1}else if(d===qd)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()},m$=(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("")},f$=(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 m=a.at(-1)??"",h=m.trimStart();if(m.length!==h.length)a[a.length-1]=h,c=mt(h)}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 m=e-c,h=1+Math.floor((g-m-1)/e);if(Math.floor((g-1)/e)<h)a.push("");Qa(a,p,e),c=mt(a.at(-1)??"");continue}if(c+g>e&&c&&g){if(n.wordWrap===!1&&c<e){Qa(a,p,e),c=mt(a.at(-1)??"");continue}a.push(""),c=0}if(c+g>e&&n.wordWrap===!1){Qa(a,p,e),c=mt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=g}if(n.trim!==!1)a=a.map((d)=>m$(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===is||p===Vd){Kd.lastIndex=d+1;let m=Kd.exec(l)?.groups;if(m?.code!==void 0){let h=Number.parseFloat(m.code);o=h===p$?void 0:h}else if(m?.uri!==void 0)s=m.uri.length===0?void 0:m.uri}if(l[d+1]===`
|
|
8
|
+
`){if(s)r+=Wd("");let g=o?Ud(o):void 0;if(o&&g)r+=Bd(g)}else if(p===`
|
|
9
|
+
`){if(o&&Ud(o))r+=Bd(o);if(s)r+=Wd(s)}}return r},h$=/\r?\n/;function en(t,e,n){return String(t).normalize().split(h$).map((r)=>f$(r,e,n)).join(`
|
|
10
|
+
`)}var Ut={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 Xr={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?Ut.up():"");if(t)e+=Ut.left;return e}};function $n(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?$n(s,e<0?-1:1,n):s}var S$=["up","down","left","right","space","enter","cancel"],$$=["January","February","March","April","May","June","July","August","September","October","November","December"],ft={actions:new Set(S$),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:[...$$],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 Xd(t){if(t!==void 0)return t;if(ft.accessible!==void 0)return ft.accessible;let e=process.env.ACCESSIBLE;return e!==void 0&&e!==""&&e!=="0"&&e!=="false"}function zd(t,e){if(typeof t=="string")return ft.aliases.get(t)===e;for(let n of t)if(n!==void 0&&zd(n,e))return!0;return!1}function b$(t,e){if(t===e)return;let n=t.split(`
|
|
11
11
|
`),r=e.split(`
|
|
12
|
-
`),
|
|
13
|
-
`).map((c,l,u)=>{let d=
|
|
14
|
-
`)}function
|
|
15
|
-
`),
|
|
16
|
-
`).length-1;this.output.write(
|
|
17
|
-
`);this.output.write(a[i]),this._prevFrame=e,this.output.write(
|
|
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 nL=globalThis.process.platform.startsWith("win"),cs=Symbol("clack:cancel");function ls(t){return t===cs}function as(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var Zn=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,nc=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function Pe(t,e,n,r=n,o=n,s){let i=Zn(t??Yd),a=mt(n);return en(e,i-a,{hard:!0,trim:!1}).split(`
|
|
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 Zd(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 us=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return Xd(this.opts.accessible)}constructor(e,n=!0){let{input:r=k$,output:o=Yd,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(cs);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=w$.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),as(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Ut.show),this.output.off("resize",this.render),as(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(Ut.show),this.output.off("resize",this.render),as(this.input,!1),e(cs)})})}_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&&ft.aliases.has(n.name)&&this.emit("cursor",ft.aliases.get(n.name)),ft.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=Zd(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")}zd([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
|
+
`),as(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=en(this._prevFrame,Zn(this.output),{hard:!0,trim:!1}).split(`
|
|
16
|
+
`).length-1;this.output.write(Ut.move(-999,e*-1))}render(){let e=en(this._render(this)??"",Zn(this.output),{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(Ut.hide);else{let n=b$(this._prevFrame,e),r=nc(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(Ut.move(0,i-s)),this.output.write(Xr.lines(1));let a=e.split(`
|
|
17
|
+
`);this.output.write(a[i]),this._prevFrame=e,this.output.write(Ut.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(Ut.move(0,c))}this.output.write(Xr.down());let a=e.split(`
|
|
18
18
|
`).slice(i);this.output.write(a.join(`
|
|
19
|
-
`)),this._prevFrame=e;return}}this.output.write(
|
|
20
|
-
`);return n&&
|
|
21
|
-
`);
|
|
22
|
-
|
|
19
|
+
`)),this._prevFrame=e;return}}this.output.write(Xr.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};class rc extends us{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(Ut.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class oc extends us{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?$n(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=$n(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=$n(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var Qd=class extends us{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?$n(r,1,this.options):r,this.changeValue(),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=$n(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=$n(this.cursor,1,this.options);break}this.changeValue()})}};class sc extends us{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}${y$("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 y,stripVTControlCharacters as mL}from"util";import Bt from"process";function T$(){if(Bt.platform!=="win32")return Bt.env.TERM!=="linux";return Boolean(Bt.env.CI)||Boolean(Bt.env.WT_SESSION)||Boolean(Bt.env.TERMINUS_SUBLIME)||Bt.env.ConEmuTask==="{cmd::Cmder}"||Bt.env.TERM_PROGRAM==="Terminus-Sublime"||Bt.env.TERM_PROGRAM==="vscode"||Bt.env.TERM==="xterm-256color"||Bt.env.TERM==="alacritty"||Bt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var cc=T$(),sp=()=>process.env.CI==="true";var V=(t,e)=>cc?t:e,tp=V("\u25C6","*"),lc=V("\u25A0","x"),uc=V("\u25B2","x"),Zr=V("\u25C7","o"),E$=V("\u250C","T"),j=V("\u2502","|"),fe=V("\u2514","\u2014"),wL=V("\u2510","T"),SL=V("\u2518","\u2014"),ic=V("\u25CF",">"),ps=V("\u25CB"," "),x$=V("\u25FB","[\u2022]"),ep=V("\u25FC","[+]"),np=V("\u25FB","[ ]"),$L=V("\u25AA","\u2022"),rp=V("\u2500","-"),v$=V("\u256E","+"),C$=V("\u251C","+"),A$=V("\u256F","+"),I$=V("\u2570","+"),bL=V("\u256D","+"),R$=V("\u25CF","\u2022"),O$=V("\u25C6","*"),_$=V("\u25B2","!"),P$=V("\u25A0","x"),gs=(t)=>{switch(t){case"initial":case"active":return y("cyan",tp);case"cancel":return y("red",lc);case"error":return y("yellow",uc);case"submit":return y("green",Zr);case"validating":return y("dim",tp)}},ip=(t)=>{switch(t){case"initial":case"active":return y("cyan",j);case"cancel":return y("red",j);case"error":return y("yellow",j);case"submit":return y("green",j)}};function ap(t,e,n){let r=n?`${y("cyan",j)} `:"",o=Pe(t,e.join(" \u2022 "),r).split(`
|
|
20
|
+
`);return n&&o.push(y("cyan",fe)),o}var op=(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}},ac=({cursor:t,options:e,style:n,output:r=process.stdout,maxItems:o=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:i=4})=>{let a=Zn(r)-s,c=nc(r),l=y("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,m=d<e.length&&p+d<e.length,h=Math.min(p+d,e.length),w=[],b=0;g&&b++,m&&b++;let v=p+(g?1:0),B=h-(m?1:0);for(let _=v;_<B;_++){let M=e[_],A=M!==void 0?n(M,_===t):"",C=en(A,a,{hard:!0,trim:!1}).split(`
|
|
21
|
+
`);w.push(C),b+=C.length}if(b>u){let _=0,M=0,A=b,C=t-v,G=u,Tt=()=>op(w,A,0,C,G),Pt=()=>op(w,A,C+1,w.length,G,!0);g?({lineCount:A,removals:_}=Tt(),A>G&&(m||(G-=1),{lineCount:A,removals:M}=Pt())):(m||(G-=1),{lineCount:A,removals:M}=Pt(),A>G&&(G-=1,{lineCount:A,removals:_}=Tt())),_>0&&(g=!0,w.splice(0,_)),M>0&&(m=!0,w.splice(w.length-M,M))}let K=[];g&&K.push(l);for(let _ of w)for(let M of _)K.push(M);return m&&K.push(l),K};var cp=(t)=>{let e=t.active??"Yes",n=t.inactive??"No";return new rc({active:e,inactive:n,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let r=t.withGuide??ft.withGuide,o=`${gs(this.state)} `,s=r?`${y("gray",j)} `:"",i=Pe(t.output,t.message,s,o),a=`${r?`${y("gray",j)}
|
|
22
|
+
`:""}${i}
|
|
23
|
+
`,c=this.value?e:n;switch(this.state){case"submit":{let l=r?`${y("gray",j)} `:"";return`${a}${l}${y("dim",c)}`}case"cancel":{let l=r?`${y("gray",j)} `:"";return`${a}${l}${y(["strikethrough","dim"],c)}${r?`
|
|
24
|
+
${y("gray",j)}`:""}`}default:{let l=r?`${y("cyan",j)} `:"",u=r?y("cyan",fe):"";return`${a}${l}${this.value?`${y("green",ic)} ${e}`:`${y("dim",ps)} ${y("dim",e)}`}${t.vertical?r?`
|
|
25
|
+
${y("cyan",j)} `:`
|
|
26
|
+
`:` ${y("dim","/")} `}${this.value?`${y("dim",ps)} ${y("dim",n)}`:`${y("green",ic)} ${n}`}
|
|
27
|
+
${u}
|
|
28
|
+
`}}}}).prompt()};var N$=[`${y("dim","\u2191/\u2193")} to navigate`,`${y("dim","Space:")} select`,`${y("dim","Enter:")} confirm`],zr=(t,e)=>t.split(`
|
|
29
|
+
`).map((n)=>e(n)).join(`
|
|
30
|
+
`),lp=(t)=>{let e=(o,s)=>{let i=o.label??String(o.value);return s==="disabled"?`${y("gray",np)} ${zr(i,(a)=>y(["strikethrough","gray"],a))}${o.hint?` ${y("dim",`(${o.hint??"disabled"})`)}`:""}`:s==="active"?`${y("cyan",x$)} ${i}${o.hint?` ${y("dim",`(${o.hint})`)}`:""}`:s==="selected"?`${y("green",ep)} ${zr(i,(a)=>y("dim",a))}${o.hint?` ${y("dim",`(${o.hint})`)}`:""}`:s==="cancelled"?`${zr(i,(a)=>y(["strikethrough","dim"],a))}`:s==="active-selected"?`${y("green",ep)} ${i}${o.hint?` ${y("dim",`(${o.hint})`)}`:""}`:s==="submitted"?`${zr(i,(a)=>y("dim",a))}`:`${y("dim",np)} ${zr(i,(a)=>y("dim",a))}`},n=t.required??!0,r=t.showInstructions??!0;return new oc({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
|
+
${y("reset",y("dim",`Press ${y(["gray","bgWhite","inverse"]," space ")} to select, ${y("gray",y("bgWhite",y("inverse"," enter ")))} to submit`))}`},render(){let o=t.withGuide??ft.withGuide,s=Pe(t.output,t.message,o?`${ip(this.state)} `:"",`${gs(this.state)} `),i=`${o?`${y("gray",j)}
|
|
32
|
+
`:""}${s}
|
|
33
|
+
`,a=this.value??[],c=(l,u)=>{if(l.disabled)return e(l,"disabled");let d=a.includes(l.value);return u&&d?e(l,"active-selected"):d?e(l,"selected"):e(l,u?"active":"inactive")};switch(this.state){case"submit":{let l=this.options.filter(({value:d})=>a.includes(d)).map((d)=>e(d,"submitted")).join(y("dim",", "))||y("dim","none"),u=Pe(t.output,l,o?`${y("gray",j)} `:"");return`${i}${u}`}case"cancel":{let l=this.options.filter(({value:d})=>a.includes(d)).map((d)=>e(d,"cancelled")).join(y("dim",", "));if(l.trim()==="")return`${i}${y("gray",j)}`;let u=Pe(t.output,l,o?`${y("gray",j)} `:"");return`${i}${u}${o?`
|
|
34
|
+
${y("gray",j)}`:""}`}case"error":{let l=o?`${y("yellow",j)} `:"",u=this.error.split(`
|
|
35
|
+
`).map((g,m)=>m===0?`${o?`${y("yellow",fe)} `:""}${y("yellow",g)}`:` ${g}`).join(`
|
|
36
|
+
`),d=i.split(`
|
|
37
|
+
`).length,p=u.split(`
|
|
38
|
+
`).length+1;return`${i}${l}${ac({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:l.length,rowPadding:d+p,style:c}).join(`
|
|
39
|
+
${l}`)}
|
|
40
|
+
${u}
|
|
41
|
+
`}default:{let l=o?`${y("cyan",j)} `:"",u=i.split(`
|
|
42
|
+
`).length,d=r?ap(t.output,N$,o):o?[y("cyan",fe)]:[],p=d.join(`
|
|
43
|
+
`),g=d.length+1;return`${i}${l}${ac({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:l.length,rowPadding:u+g,style:c}).join(`
|
|
44
|
+
${l}`)}
|
|
45
|
+
${p}
|
|
46
|
+
`}}}}).prompt()};var Et={message:(t=[],{symbol:e=y("gray",j),secondarySymbol:n=y("gray",j),output:r=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??ft.withGuide,c=a?n:"",l=a?`${e} `:"",u=a?`${n} `:"";for(let p=0;p<o;p++)i.push(c);let d=Array.isArray(t)?t:t.split(`
|
|
47
|
+
`);if(d.length>0){let[p,...g]=d;p.length>0?i.push(`${l}${p}`):i.push(a?e:"");for(let m of g)m.length>0?i.push(`${u}${m}`):i.push(a?n:"")}r.write(`${i.join(`
|
|
23
48
|
`)}
|
|
24
|
-
`)},info:(t,e)=>{
|
|
25
|
-
`)},Pc=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??vt.withGuide?`${C("gray",ut)}
|
|
26
|
-
${C("gray",wo)} `:"";n.write(`${r}${t}
|
|
49
|
+
`)},info:(t,e)=>{Et.message(t,{...e,symbol:y("blue",R$)})},success:(t,e)=>{Et.message(t,{...e,symbol:y("green",O$)})},step:(t,e)=>{Et.message(t,{...e,symbol:y("green",Zr)})},warn:(t,e)=>{Et.message(t,{...e,symbol:y("yellow",_$)})},warning:(t,e)=>{Et.warn(t,e)},error:(t,e)=>{Et.message(t,{...e,symbol:y("red",P$)})}},up=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??ft.withGuide?`${y("gray",fe)} `:"";n.write(`${r}${y("red",t)}
|
|
27
50
|
|
|
28
|
-
`)}
|
|
51
|
+
`)},dp=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??ft.withGuide?`${y("gray",E$)} `:"";n.write(`${r}${t}
|
|
52
|
+
`)},pp=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??ft.withGuide?`${y("gray",j)}
|
|
53
|
+
${y("gray",fe)} `:"";n.write(`${r}${t}
|
|
54
|
+
|
|
55
|
+
`)};var j$=(t)=>t,M$=(t,e,n)=>{let r={hard:!0,trim:!1},o=en(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 en(t,a,r)},gp=(t="",e="",n)=>{let r=n?.output??Bt.stdout,o=n?.withGuide??ft.withGuide,s=n?.format??j$,i=["",...M$(t,Zn(r)-6,s).split(`
|
|
57
|
+
`).map(s),""],a=mt(e),c=Math.max(i.reduce((p,g)=>{let m=mt(g);return m>p?m:p},0),a)+2,l=i.map((p)=>`${y("gray",j)} ${p}${" ".repeat(c-mt(p))}${y("gray",j)}`).join(`
|
|
58
|
+
`),u=o?`${y("gray",j)}
|
|
59
|
+
`:"",d=o?C$:I$;r.write(`${u}${y("green",Zr)} ${y("reset",e)} ${y("gray",rp.repeat(Math.max(c-a-1,1))+v$)}
|
|
60
|
+
${l}
|
|
61
|
+
${y("gray",d+rp.repeat(c+2)+A$)}
|
|
62
|
+
`)};var TL={light:V("\u2500","-"),heavy:V("\u2501","="),block:V("\u2588","#")};var D$=[`${y("dim","\u2191/\u2193")} to navigate`,`${y("dim","Enter:")} confirm`],ds=(t,e)=>t.includes(`
|
|
29
63
|
`)?t.split(`
|
|
30
64
|
`).map((n)=>e(n)).join(`
|
|
31
|
-
`):e(t),
|
|
65
|
+
`):e(t),mp=(t)=>{let e=(r,o)=>{if(r===void 0)return"";let s=r.label??String(r.value);switch(o){case"disabled":return`${y("gray",ps)} ${ds(s,(i)=>y("gray",i))}${r.hint?` ${y("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${ds(s,(i)=>y("dim",i))}`;case"active":return`${y("green",ic)} ${s}${r.hint?` ${y("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${ds(s,(i)=>y(["strikethrough","dim"],i))}`;default:return`${y("dim",ps)} ${ds(s,(i)=>y("dim",i))}`}},n=t.showInstructions??!0;return new Qd({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let r=t.withGuide??ft.withGuide,o=`${gs(this.state)} `,s=`${ip(this.state)} `,i=Pe(t.output,t.message,s,o),a=`${r?`${y("gray",j)}
|
|
32
66
|
`:""}${i}
|
|
33
|
-
`;switch(this.state){case"submit":{let c=r?`${
|
|
34
|
-
${
|
|
35
|
-
`).length,u=n?
|
|
36
|
-
`),p=u.length+1;return`${a}${c}${
|
|
67
|
+
`;switch(this.state){case"submit":{let c=r?`${y("gray",j)} `:"",l=Pe(t.output,e(this.options[this.cursor],"selected"),c);return`${a}${l}`}case"cancel":{let c=r?`${y("gray",j)} `:"",l=Pe(t.output,e(this.options[this.cursor],"cancelled"),c);return`${a}${l}${r?`
|
|
68
|
+
${y("gray",j)}`:""}`}default:{let c=r?`${y("cyan",j)} `:"",l=a.split(`
|
|
69
|
+
`).length,u=n?ap(t.output,D$,r):r?[y("cyan",fe)]:[],d=u.join(`
|
|
70
|
+
`),p=u.length+1;return`${a}${c}${ac({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:c.length,rowPadding:l+p,style:(g,m)=>e(g,g.disabled?"disabled":m?"active":"inactive")}).join(`
|
|
37
71
|
${c}`)}
|
|
38
72
|
${d}
|
|
39
|
-
`}}}}).prompt()};var
|
|
73
|
+
`}}}}).prompt()};var EL=`${y("gray",j)} `;var fp=(t)=>new sc({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??ft.withGuide,n=`${`${e?`${y("gray",j)}
|
|
74
|
+
`:""}${gs(this.state)} `}${t.message}
|
|
75
|
+
`,r=t.placeholder&&t.placeholder.length>0?y("inverse",t.placeholder[0])+y("dim",t.placeholder.slice(1)):y(["inverse","hidden"],"_"),o=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"validating":{let i=e?`${y("cyan",j)} `:"",a=e?y("cyan",fe):"",c=y("dim",o),l=y("dim","Validating...");return`${n}${i}${c}
|
|
76
|
+
${a} ${l}
|
|
77
|
+
`}case"error":{let i=this.error?` ${y("yellow",this.error)}`:"",a=e?`${y("yellow",j)} `:"",c=e?y("yellow",fe):"";return`${n.trim()}
|
|
78
|
+
${a}${o}
|
|
79
|
+
${c}${i}
|
|
80
|
+
`}case"submit":{let i=s?`${e?" ":""}${y("dim",s)}`:"",a=e?y("gray",j):"";return`${n}${a}${i}`}case"cancel":{let i=s?` ${y(["strikethrough","dim"],s)}`:"",a=e?y("gray",j):"";return`${n}${a}${i}${s.trim()?`
|
|
81
|
+
${a}`:""}`}default:{let i=e?`${y("cyan",j)} `:"",a=e?y("cyan",fe):"";return`${n}${i}${o}
|
|
82
|
+
${a}
|
|
83
|
+
`}}}}).prompt();function hp(t=process.stdin){return t.readableEnded||t.destroyed}async function yp({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 F$}from"util";var dc=cc?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],G$=80,H$=8,K$=3,U$="...",pc="\r\x1B[K",B$=80,W$=/\s*\n\s*/g,Qr=new Set;function wp(){for(let t of[...Qr])t.error()}function Sp({output:t=process.stdout}={}){let e=t.isTTY===!0&&!sp(),n=qr(t),r="",o=0,s=!1,i,a=(g)=>{t.write(e||n?g:F$(g))},c=()=>{let g=k.magenta(dc[o%dc.length]??""),m=".".repeat(Math.floor(o/H$)%(K$+1)),h=`${g} ${r.replace(W$," ")}${m}`;a(`${pc}${Bun.sliceAnsi(h,0,(t.columns||B$)-1)}`),o+=1},l=()=>e?c():a(`${k.magenta(dc[0]??"")} ${r}${U$}
|
|
84
|
+
`),u=()=>(clearInterval(i),Qr.delete(p)),d=(g,m)=>{if(u())a(`${e?pc:""}${g} ${m}
|
|
85
|
+
`)},p={cancel(g=r){s=Qr.has(p)||s,d(k.red(lc),g)},clear(){if(u()&&e)a(pc)},error(g=r){d(k.red(uc),g)},get isCancelled(){return s},message(g=r){let m=kp(g);if(m===r)return;if(r=m,Qr.has(p)&&!e)l()},start(g=""){if(p.clear(),s=!1,r=kp(g),o=0,Qr.add(p),a(`${k.gray(j)}
|
|
86
|
+
`),l(),!e)return;i=setInterval(c,G$),i.unref()},stop(g=r){d(k.green(Zr),g)}};return p}function kp(t){return t.replace(/\.+$/,"")}var J$="Pass the value as an argument or option instead";function q$(t){if(ls(t))throw new kt;return t}function Y$(t){if(Za())return;throw new T(`Cannot prompt for ${t} without a terminal`,J$)}async function ms(t,e,{edits:n=!1,hint:r}){if(Y$(e.message),hp(e.input))throw new kt;return z$(r),q$(await yp({...e,edits:n},(o)=>t({...e,signal:o})))}function X$(t){return t.map((e)=>e.key?`${k.bold(e.key)} ${k.dim(e.text)}`:k.dim(e.text)).join(k.dim(" \xB7 "))}function z$(t){Et.info(X$(t))}var fs={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 nn(t){return ms(cp,t,{hint:fs.confirm})}async function gc(t){return ms(fp,t,{edits:!0,hint:fs.text})}async function bn(t){return ms(mp,{showInstructions:!1,...t},{hint:fs.select})}async function hs(t){return ms(lp,{showInstructions:!1,...t},{hint:fs.multiselect})}function Tn(t){return Id()&&t.output===void 0?{...t,output:process.stderr}:t}function Qn(t){return(e,n={})=>t(e,Tn(n))}var lt={error:Qn(Et.error),info:Qn(Et.info),message:(t,e={})=>Et.message(t,Tn(e)),step:Qn(Et.step),success:Qn(Et.success),warn:Qn(Et.warn),warning:Qn(Et.warning)};function to(t,e={}){dp(t,Tn(e))}function rn(t,e={}){pp(t,Tn(e))}function mc(t,e={}){up(t,Tn(e))}function he(t,e,n={}){gp(t,e,Tn(n))}function ys(t={}){return Sp(Tn(t))}import{inspect as Z$}from"util";var Q$=4;function ks(t,e=[]){if(e.length>=Q$)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:Ss(s),message:ws(s)},...s instanceof Error?ks(s,r):[]])}function ws(t){return $s(t instanceof Error?t.message||t.name:t)}function Ss(t){return t instanceof f&&t.hint!==void 0?$s(t.hint):void 0}function $s(t){return typeof t==="string"?t:Z$(t,{breakLength:Number.POSITIVE_INFINITY})}var tb="Error",eb=27,nb=new RegExp(`${String.fromCharCode(eb)}\\[[\\d;]*m`,"g"),rb=9,ob=10,sb=31,ib=127,ab=159,cb=16,lb=4;function on(t,{json:e}){if(wp(),pb(t),e)_e(tn({error:ub(t)}));return $p(t)}function ub(t){let e=$p(t),n=fc(ws(t));if(!(t instanceof Error))return{_tag:tb,message:n,exitCode:e,causes:[]};let r=Ss(t);return{_tag:db(t),message:n,hint:r===void 0?void 0:fc(r),exitCode:e,causes:ks(t).map((o)=>fc(o.message))}}function $p(t){if(t instanceof kt)return At;if(t instanceof f)return Wo(t.exitCode)?t.exitCode:Kr;return Kr}function db(t){let e=Reflect.get(t,"_tag");return typeof e==="string"?e:$s(t.name)}function pb(t){if(t instanceof kt)return;let e=os(),n=bs(ws(t));if(t instanceof f){let r=Ss(t);if(lt.warn(k.yellow(n),{output:e}),r)lt.info(k.dim(bs(r)),{output:e})}else lt.error(k.red(n),{output:e});if(!(t instanceof Error))return;for(let r of ks(t))if(lt.info(k.dim(`caused by: ${bs(r.message)}`),{output:e}),r.hint)lt.info(k.dim(` ${bs(r.hint)}`),{output:e})}function bs(t){return Array.from(t.replace(nb,""),(e)=>{let n=e.charCodeAt(0);return n<=sb&&n!==rb&&n!==ob||n>=ib&&n<=ab?`\\u${n.toString(cb).padStart(lb,"0")}`:e}).join("")}var gb=500,mb="The command stopped before it finished because nothing was left for it to wait for";function bp({json:t}){let e={ending:void 0,failed:!1,settled:!1},n=(o,s)=>(e.ending??=fb(o,s),e.ending),r=(o)=>{if(e.failed||e.ending)return;e.failed=!0;let s=on(o,{json:t&&!Rd()});Od(),n(s,e.settled?void 0:gb)};return process.on("uncaughtException",r),process.on("unhandledRejection",r),process.on("beforeExit",()=>{if(!e.settled)r(Error(mb))}),{exit:(o)=>n(o),settle(){e.settled=!0}}}async function fb(t,e){process.exitCode=t,await Nd(e),process.exit(t)}var Ne=new Uint32Array(65536),hb=(t,e)=>{let n=t.length,r=e.length,o=1<<n-1,s=-1,i=0,a=n,c=n;while(c--)Ne[t.charCodeAt(c)]|=1<<c;for(c=0;c<r;c++){let l=Ne[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--)Ne[t.charCodeAt(c)]=0;return a},yb=(t,e)=>{let n=e.length,r=t.length,o=[],s=[],i=Math.ceil(n/32),a=Math.ceil(r/32);for(let m=0;m<i;m++)s[m]=-1,o[m]=0;let c=0;for(;c<a-1;c++){let m=0,h=-1,w=c*32,b=Math.min(32,r)+w;for(let v=w;v<b;v++)Ne[t.charCodeAt(v)]|=1<<v;for(let v=0;v<n;v++){let B=Ne[e.charCodeAt(v)],K=s[v/32|0]>>>v&1,_=o[v/32|0]>>>v&1,M=B|m,A=((B|_)&h)+h^h|B|_,C=m|~(A|h),G=h&A;if(C>>>31^K)s[v/32|0]^=1<<v;if(G>>>31^_)o[v/32|0]^=1<<v;C=C<<1|K,G=G<<1|_,h=G|~(M|C),m=C&M}for(let v=w;v<b;v++)Ne[t.charCodeAt(v)]=0}let l=0,u=-1,d=c*32,p=Math.min(32,r-d)+d;for(let m=d;m<p;m++)Ne[t.charCodeAt(m)]|=1<<m;let g=r;for(let m=0;m<n;m++){let h=Ne[e.charCodeAt(m)],w=s[m/32|0]>>>m&1,b=o[m/32|0]>>>m&1,v=h|l,B=((h|b)&u)+u^u|h|b,K=l|~(B|u),_=u&B;if(g+=K>>>r-1&1,g-=_>>>r-1&1,K>>>31^w)s[m/32|0]^=1<<m;if(_>>>31^b)o[m/32|0]^=1<<m;K=K<<1|w,_=_<<1|b,u=_|~(v|K),l=K&v}for(let m=d;m<p;m++)Ne[t.charCodeAt(m)]=0;return g},hc=(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 hb(t,e);return yb(t,e)},Tp=(t,e)=>{let n=1/0,r=0;for(let o=0;o<e.length;o++){let s=hc(t,e[o]);if(s<n)n=s,r=o}return e[r]};function Ts(t,e,n){let r=e.length>0?Tp(t,[...e]):void 0,o=`Run "${n} --help" for usage.`;return new T(`Unknown command: ${t}`,r?`Did you mean "${r}"? ${o}`:o)}function eo(t,e){if(Array.isArray(e))return[...e];if(!Ep(t)||!Ep(e))return e;return Object.fromEntries([...Object.entries(t),...Object.entries(e).map(([n,r])=>[n,eo(Object.hasOwn(t,n)?t[n]:void 0,r)])])}function Ep(t){if(t===null||typeof t!=="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function xp(t,e){return{name:t.name,bin:t.bin,version:t.version,description:t.description,exitCodes:{...ss},options:vp(Kt),commands:e.map((n)=>Es(n,`${t.bin} ${n.name}`))}}function Es(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:vp(t.args),examples:[...t.examples],commands:t.subcommands.map((n)=>Es(n,`${e} ${n.name}`))}}function vp(t){return Object.entries(t).map(([e,n])=>({name:e,flag:`--${ee(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 Cp}from"util";var kb=2,wb="0.0.0",Sb=(t)=>t,D={arg:k.magenta,cmd:k.cyan,default:k.bold,desc:Sb,flag:k.green,header:(t)=>k.bold(k.yellow(t)),hint:k.dim,name:(t)=>k.bold(k.cyan(t)),placeholder:k.magenta};function Ap(t){return`${D.name(t.name)} ${D.hint(t.version??wb)}`}function Ip(t,e){let n=`${D.name(t.name)}${t.version?` ${D.hint(`v${t.version}`)}`:""}`;return Op([[n,...t.description?[D.desc(t.description)]:[]],ye("Usage:",[` ${D.cmd(t.bin)} ${D.placeholder("[command]")} ${D.placeholder("[options]")}`]),ye("Commands:",_p(e)),ye("Options:",Np(Kt)),ye("Exit codes:",Pp()),[`${D.hint("Run")} ${D.cmd(`${t.bin} <command> --help`)} ${D.hint("for command details.")}`]])}function Rp(t,e){let n=t.json?{...t.args,json:Kt.json}:t.args,r=[...t.subcommands.length>0?[` ${D.cmd(e)} ${D.placeholder("<command>")} ${D.placeholder("[options]")}`]:[],...t.run?[` ${$b(t,e).join(" ")}`]:[],...t.prompts&&Object.keys(t.positionals).length>0?[` ${D.hint("Omit positional arguments to run interactively.")}`]:[],...t.passthrough?[` ${D.hint("Options end at the first argument; it and everything after it are passed on unchanged.")}`]:[]];return Op([[D.name(e),D.desc(t.description)],ye("Usage:",r),ye("Commands:",_p(t.subcommands)),ye("Arguments:",Tb(t.positionals)),ye("Options:",Np(n)),ye("Examples:",t.examples.map((o)=>` ${D.cmd(o)}`)),ye("Exit codes:",Pp())])}function $b(t,e){let n=bb(t.positionals);return t.passthrough?[D.cmd(e),D.placeholder("[options]"),D.placeholder("[--]"),...n]:[D.cmd(e),...n,D.placeholder("[options]")]}function ye(t,e){return e.length>0?[D.header(t),...e]:[]}function Op(t){return t.filter((e)=>e.length>0).map((e)=>e.join(`
|
|
40
87
|
`)).join(`
|
|
41
88
|
|
|
42
|
-
`)}function
|
|
43
|
-
`:void 0}function
|
|
44
|
-
`}function
|
|
45
|
-
`}function
|
|
46
|
-
`}function
|
|
89
|
+
`)}function _p(t){return xs(t.map((e)=>[` ${D.cmd(e.name)}`,D.desc(e.description)]))}function Pp(){return xs(Object.entries(ss).map(([t,e])=>[` ${t}`,e]))}function yc(t,e){return e.variadic?`${t}...`:t}function bb(t){return Object.entries(t).map(([e,n])=>n.required?D.arg(`<${yc(e,n)}>`):D.arg(`[${yc(e,n)}]`))}function Tb(t){return xs(Object.entries(t).map(([e,n])=>[` ${D.arg(yc(e,n))}`,`${D.desc(n.description??"")}${n.required?"":D.hint(" (optional)")}`]))}function Np(t){return xs(Object.entries(t).map(([e,n])=>{let r=n.alias?`${D.flag(`-${n.alias}`)}, `:" ",o=n.type==="boolean"?"":` ${D.placeholder(`<${n.type==="number"?"number":"value"}>`)}`,s=Eb(n),i=s===void 0?"":` (default: ${D.default(s)})`;return[` ${r}${D.flag(`--${ee(e)}`)}${o}`,`${D.desc(n.description??"")}${i}`]}))}function Eb(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 xs(t){let e=Math.max(0,...t.map(([n])=>Cp(n).length));return t.map(([n,r])=>`${n}${" ".repeat(e-Cp(n).length+kb)}${r}`)}function vs(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=xb(t,n,r);if(e=!0,o!==void 0)_e(o)}}}function xb(t,e,n){if(t)return tn(e);return n?`${n(e)}
|
|
90
|
+
`:void 0}function Cs(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 As(t,e,n,r){let o=await Pd(n.json,async()=>{let s=await t.run?.(n);return typeof s==="number"?vb(e,s):At});if(n.json&&!r.emitted())throw Error(`${e} finished in JSON mode without calling ctx.output.result`);return o}function vb(t,e){if(Wo(e))return e;throw Error(`${t} returned ${e}, which is not an exit code from ${At} to ${gd}`)}var kc="__exit__",jp="__run__",Cb="Back",Ab="Return to previous menu";async function Mp(t,e){if(e)throw new T("Interactive mode cannot be combined with --json","Pass a command and its arguments instead");if(!Yr())throw new T("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(t.interactive.clearOnStart)console.clear();let n=t.info.version?` v${t.info.version}`:"";to(k.bgCyan(k.black(` ${t.info.name}${n} `)));let r={commands:t.commands,message:t.interactive.promptMessage,path:t.info.bin,root:!0};return await Dp(t,new Map,r),rn(t.interactive.goodbyeMessage),At}async function Dp(t,e,n){while(!0){let r=await Ib(t,e,n);if(r===void 0)return;if(e.set(n.path,r),r===jp&&n.owner){await Lp(t,n.owner,n.path);continue}let o=n.commands.find((s)=>s.name===r);if(o)await Rb(t,e,o,`${n.path} ${r}`)}}async function Ib(t,e,n){let r=n.root?{hint:t.interactive.exitHint,label:t.interactive.exitLabel,value:kc}:{hint:Ab,label:Cb,value:kc};try{let o=await bn({initialValue:e.get(n.path),message:n.message,options:[...n.owner?[{hint:n.owner.description,label:n.owner.name,value:jp}]:[],...n.commands.map((s)=>({hint:s.description,label:s.name,value:s.name})),r]});return o===kc?void 0:o}catch(o){if(o instanceof kt)return;throw o}}async function Rb(t,e,n,r){if(n.subcommands.length===0)return Lp(t,n,r);return Dp(t,e,{commands:n.subcommands,message:`${n.name}:`,path:r,root:!1,...n.run?{owner:n}:{}})}async function Lp(t,e,n){try{await Ob(t,e,n)}catch(r){if(r instanceof kt)return;if(!(r instanceof f))throw r;on(r,{json:!1})}}async function Ob(t,e,n){let{args:r}=Jr([],e.args),o=Zo([],e.positionals),s=e.prompts?null:Qo(o,e.positionals);if(s)throw new T(s,`Run "${n} --help" for usage.`);let i=vs(!1),a={args:Xo(r,e.args),interactive:e.prompts,json:!1,positionals:o};await As(e,n,Cs(t,a,i),i)}var _b="--",Pb=/^(?:--json(?:=true)?|-[^-=]*j[^-=]*(?:=true)?)$/,Nb=/^(?:--no-(?:help|json)|(?:--(?:help|json)|-[hj]+)(?:=(?:true|false))?)$/;async function wc(t,e){try{return await jb(t,e)}catch(n){return{code:on(n,{json:$c(e)}),menu:!1}}}function Sc(t,e){let{command:n,restArgs:r}=Yo(e,Kt),o=n===void 0||n===Sn?void 0:Hp(t,n,r);if(!o||o instanceof T||!o.command.passthrough)return{operands:[],options:[...e]};let s=wd(o.tokens,{...o.command.args,...zn}),i=s<0?[]:o.tokens.slice(s);return{operands:i,options:e.slice(0,e.length-i.length)}}async function jb(t,{options:e,operands:n}){let{command:r,flags:o,restArgs:s}=Ya(e,Kt,zn),i=o.json===!0,a={code:At,menu:!1};if(r===void 0){if(o.interactive&&!o.help&&!o.version)return{code:await Mp(t,i),menu:!0};return _e(o.version&&!o.help?Db(t,i):Fp(t,i)),a}let c=o.interactive?"--interactive":o.version?"--version":void 0;if(c)throw new T(`${c} cannot be combined with a command`,`Run "${t.info.bin} ${c}" on its own.`);if(r===Sn)return _e(Lb(t,s,i)),a;let l=Fb(t,r,s);if(o.help)return _e(bc(l.command,l.path,i)),a;return{code:await Gb(t,l,n,i),menu:!1}}function $c({options:t}){let{before:e,restArgs:n}=Yo(t,Kt);return[e,n].some((r)=>Mb(r).some((o)=>Pb.test(o)))}function Mb(t){let e=t.indexOf(_b);return e<0?t:t.slice(0,e)}function Db({info:t},e){return e?tn({name:t.name,bin:t.bin,version:t.version}):`${Ap(t)}
|
|
91
|
+
`}function Fp(t,e){return e?tn(xp(t.info,t.commands)):`${Ip(t.info,t.commands)}
|
|
92
|
+
`}function bc(t,e,n){return n?tn(Es(t,e)):`${Rp(t,e)}
|
|
93
|
+
`}function Lb(t,e,n){let{args:r,rawPositionals:o}=Jr(e,zn);if(qo(r,zn,`Run "${t.info.bin} ${Sn} [command]" for usage.`,e),o.length===0)return Fp(t,n);let{command:s,path:i}=Gp(t.commands,o,t.info.bin);return bc(s,i,n)}function Gp(t,e,n){let[r="",...o]=e,s=t.find((a)=>a.name===r);if(!s)throw Ts(r,Tc(t),n);let i=`${n} ${r}`;return o.length===0?{command:s,path:i}:Gp(s.subcommands,o,i)}function Tc(t){return t.map((e)=>e.name)}function Fb(t,e,n){let r=Hp(t,e,n);if(r instanceof T)throw r;return r}function Hp(t,e,n){let r=t.commands.find((o)=>o.name===e);if(!r)return Ts(e,Tc(t.commands),t.info.bin);return Kp({command:r,path:`${t.info.bin} ${e}`,tokens:n})}function Kp(t){let{command:e,path:n,tokens:r}=t;if(e.subcommands.length===0)return t;let o=r.findIndex((a)=>!Nb.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 Kp({command:i,path:`${n} ${s}`,tokens:r.toSpliced(o,1)});if(e.run&&Object.keys(e.positionals).length>0)return t;return Ts(s,Tc(e.subcommands),n)}async function Gb(t,{command:e,path:n,tokens:r},o,s){let i=`Run "${n} --help" for usage.`,a={...e.args,...zn},c=Jr(r,a),{args:l}=c,u=[...c.rawPositionals,...o];if(e.strict)qo(l,a,i,r);if(s&&!e.json)throw new T(`${n} does not support --json`,i);let d=e.strict?$d(u,e.positionals):void 0;if(d!==void 0)throw new T(`Unexpected argument: ${d}`,i);if(!e.run)return _e(bc(e,n,s)),At;let p=Zo(u,e.positionals),g=Qo(p,e.positionals);if(g)throw new T(g,i);let m=e.prompts&&u.length===0&&Yr()&&!s,h={args:Xo(l,e.args),interactive:m,json:s,positionals:p},w=vs(s);try{return await As(e,n,Cs(t,h,w),w)}catch(b){return on(b,{json:s&&!w.emitted()})}}var Hb={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",promptMessage:"What would you like to do?"};function Ec(t){let e=`CLI "${t.name}"`;if(es(e,t.commands),t.commands.some((r)=>r.name===Sn))throw Error(`${e} cannot define a command named "${Sn}": 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:{...Hb,...t.interactive}};return{async main(r=process.argv.slice(2)){_d();let o=Sc(n,r),s=bp({json:$c(o)}),i=await wc(n,o);if(s.settle(),i.code===At&&!i.menu)return;await s.exit(i.code)},async run(r=process.argv.slice(2)){return(await wc(n,Sc(n,r))).code}}}import ke from"fs";import Rc from"path";var En=(t)=>(t.map=(e)=>En((n)=>e(t(n))),t.or=(e)=>En((n)=>{try{return t(n)}catch(r){return e(n)}}),t),Is=()=>"bad banditype"();var Up=()=>En((t)=>t),Bp=(t)=>En((e)=>t.includes(e)?e:Is()),xc=(t)=>En((e)=>typeof e===typeof t?e:Is()),je=()=>xc(""),Wp=()=>xc(0),Vp=()=>xc(!0);var Rs=()=>En((t)=>t===null?t:Is()),no=(t)=>En((e)=>e instanceof t?e:Is()),Jp=(t)=>no(Object).map((e)=>{let n={};for(let r in e){let o=t(e[r]);o!==void 0&&(n[r]=o)}return n}),Os=(t)=>no(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 qp=(t)=>no(Array).map((e)=>e.map(t));import tr from"fs";var Kb=".lock",Ub=".break",Yp=10,Bb=1e4,Wb=5000;function Xp(t,e){let n=`${t}${Kb}`,r=crypto.randomUUID();Vb(n,r);try{return e()}finally{zp(n,r)}}function Vb(t,e){let n=Date.now()+Bb;while(!Zp(t,e)){if(Date.now()>n)throw Error(`timed out waiting for ${t}, which another process holds`);if(vc(t))Jb(t,e);else Bun.sleepSync(Yp)}}function zp(t,e){if(qb(t)===e)tr.rmSync(t,{force:!0})}function Jb(t,e){let n=`${t}${Ub}`;if(!Zp(n,e)){if(vc(n))tr.rmSync(n,{force:!0});else Bun.sleepSync(Yp);return}try{if(vc(t))tr.rmSync(t,{force:!0})}finally{zp(n,e)}}function Zp(t,e){try{return tr.writeFileSync(t,e,{flag:"wx"}),!0}catch(n){if(Qp(n)==="EEXIST")return!1;throw n}}function vc(t){let e=tr.statSync(t,{throwIfNoEntry:!1})?.mtimeMs;return e!==void 0&&Date.now()-e>Wb}function qb(t){try{return tr.readFileSync(t,"utf8")}catch(e){if(Qp(e)==="ENOENT")return;throw e}}function Qp(t){return t instanceof Error?Reflect.get(t,"code"):void 0}import Cc from"fs";import xn from"path";var Yb="..",Xb=40;function eg(t){let{root:e}=xn.parse(xn.resolve(t)),n=tg(xn.resolve(t)),r=e,o=0;for(let s=n.shift();s!==void 0;s=n.shift()){if(s===Yb){r=xn.dirname(Cc.realpathSync(r));continue}let i=xn.join(r,s);if(!Cc.lstatSync(i,{throwIfNoEntry:!1})?.isSymbolicLink()){r=i;continue}if(o+=1,o>Xb)throw Error(`too many symbolic links in ${t}`);let a=Cc.readlinkSync(i);if(xn.isAbsolute(a))r=e;n.unshift(...tg(a))}return r}function tg(t){return t.split(xn.sep).filter((e)=>e!==""&&e!==".")}function Ic(t,e){JSON.parse(t);let n=JSON.parse(JSON.stringify(e)),r=zb(t),o=t.match(/^[\t ]+(?=\S)/m)?.[0]??" ",s=t.includes(`\r
|
|
47
94
|
`)?`\r
|
|
48
95
|
`:`
|
|
49
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(`
|
|
50
|
-
`));let
|
|
51
|
-
`));let
|
|
52
|
-
`)?
|
|
53
|
-
`))});return`${p?"[":"{"}${
|
|
54
|
-
`,u-1)+1,
|
|
55
|
-
`,
|
|
56
|
-
`;if(
|
|
57
|
-
`)}var
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
`)}function
|
|
63
|
-
`);if(e[0
|
|
64
|
-
`),
|
|
65
|
-
`)
|
|
97
|
+
`));let g=p?u.map((C,G)=>String(G)):[...new Set([...l.entries.map((C)=>C.key).filter((C)=>Object.hasOwn(u,C)),...Object.keys(u)])];if(g.length===0)return p?"[]":"{}";let m=l.entries[0],h=l.entries.at(-1);if(!m||!h)return c(u,l.start,d.includes(`
|
|
98
|
+
`));let w=(C)=>p?u[Number(C)]:u[C];if(g.length===l.entries.length&&g.every((C,G)=>C===l.entries[G]?.key)){let C=l.start,G="";for(let Tt of l.entries)G+=t.slice(C,Tt.node.start)+a(Tt.node,w(Tt.key)),C=Tt.node.end;return G+t.slice(C,l.end)}let b=t.slice(l.start+1,m.start),v=t.slice(h.node.end,l.end-1),B=l.entries[1],K=B?t.slice(m.node.end,B.start):`,${b.includes(`
|
|
99
|
+
`)?b:i}`,_=p?"":t.slice(m.start,m.node.start).match(/:\s*$/)?.[0]??": ",M=new Map(l.entries.map((C)=>[C.key,C])),A=g.map((C)=>{let G=M.get(C);if(G)return t.slice(G.start,G.node.start)+a(G.node,w(C));return(p?"":JSON.stringify(C)+_)+c(w(C),m.start,b.includes(`
|
|
100
|
+
`))});return`${p?"[":"{"}${b}${A.join(K)}${v}${p?"]":"}"}`}function c(l,u,d){if(!d)return Ac(l,i);let p=t.lastIndexOf(`
|
|
101
|
+
`,u-1)+1,g=t.slice(p,u).match(/^[\t ]*/)?.[0]??"";return JSON.stringify(l,null,o).replaceAll(`
|
|
102
|
+
`,s+g)}return t.slice(0,r.start)+a(r,n)+t.slice(r.end)}function Ac(t,e){if(Array.isArray(t))return`[${t.map((o)=>Ac(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}${Ac(s,e)}`);return`{${e}${r.join(`,${e}`)}${e}}`}function zb(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 Zb=2,Oc="ConfigError",Qb=no(Object);class _c{loaded;configPath;defaultConfig;options;constructor(t,e,n={}){this.configPath=Rc.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 ke.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 f(`Cannot overwrite unreadable config at ${this.configPath}`,"Repair the file and try again",void 0,{cause:t,tag:Oc})}readStored(){try{let t=this.readConfigFile();if(t===void 0)return structuredClone(this.defaultConfig);return eo(structuredClone(this.defaultConfig),ng(t))}catch(t){throw this.unreadable(t)}}update(t){try{let e=this.savePath();Xp(e,()=>this.write(e,t(this.readStored())))}catch(e){throw e instanceof f?e:this.saveFailure(e)}}savePath(){let t=this.exists()?ke.realpathSync(this.configPath):eg(this.configPath);return ke.mkdirSync(Rc.dirname(t),{recursive:!0}),t}write(t,e){let n=`${t}.${crypto.randomUUID()}.tmp`;try{let r=this.exists()?ke.statSync(this.configPath).mode:void 0,o=this.exists()?Ic(ke.readFileSync(this.configPath,"utf-8"),e):`${JSON.stringify(e,null,Zb)}
|
|
103
|
+
`;if(ke.writeFileSync(n,o,{flag:"wx",mode:r}),r!==void 0)ke.chmodSync(n,r);ke.renameSync(n,t)}finally{ke.rmSync(n,{force:!0})}}saveFailure(t){return new f(`Cannot save config at ${this.configPath}: ${rg(t)}`,`Check that ${Rc.dirname(this.configPath)} is writable and that no other process is saving the file`,void 0,{cause:t,tag:Oc})}load(){let{parse:t,strict:e}=this.options;try{let n=this.readConfigFile();if(n===void 0)return{config:structuredClone(this.defaultConfig)};let r=eo(structuredClone(this.defaultConfig),ng(n));return{config:t?t(r):r}}catch(n){if(e)return{config:structuredClone(this.defaultConfig),failure:this.loadFailure(n)};return lt.warn(k.yellow(`Config file corrupted at ${this.configPath}. Using defaults.`),{output:os()}),{config:structuredClone(this.defaultConfig),error:n}}}loadFailure(t){return new f(`Cannot read config at ${this.configPath}: ${rg(t)}`,"Repair the file and try again",void 0,{cause:t,tag:Oc})}readConfigFile(){try{return ke.readFileSync(this.configPath,"utf-8")}catch(t){if(t.code==="ENOENT")return;throw t}}}function ng(t){let e=JSON.parse(t);if(Array.isArray(e))throw Error("Config must be an object");return Qb(e)}function rg(t){return t instanceof Error?t.message:String(t)}var _s="0.3.0";var E=ts();var eT=["GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_PREFIX","GIT_WORK_TREE"],ne=Object.fromEntries(eT.map((t)=>[t,void 0]));var ag={SIGHUP:129,SIGINT:130,SIGTERM:143},og=Object.keys(ag),sg={SIGHUP:()=>Pc("SIGHUP"),SIGINT:()=>Pc("SIGINT"),SIGTERM:()=>Pc("SIGTERM")},er=[],Nc={interrupted:!1};function Wt(t){if(er.length===0)for(let e of og)process.on(e,sg[e]);return er.push(t),()=>{let e=er.indexOf(t);if(e===-1)return;if(er.splice(e,1),er.length===0)for(let n of og)process.off(n,sg[n])}}function cg(){return Nc.interrupted}function Pc(t){if(Nc.interrupted)return;Nc.interrupted=!0;let e=ag[t],n=er.toReversed().flatMap((r)=>nT(r)??[]);if(n.length===0)process.exit(e);Promise.all(n).finally(()=>process.exit(e))}function nT(t){try{let e=t();return e instanceof Promise?e.catch(ig):null}catch(e){return ig(e),null}}function ig(t){let e=t instanceof Error?t.message:String(t);process.stderr.write(`ari could not clean up after an interrupt: ${e}
|
|
104
|
+
`)}var rT=["ESRCH","EPERM"];function re(t,e){try{process.kill(-t,e)}catch(n){if(!rT.includes(n.code))throw n}}var lg=new Map;function J(t,e){return e.some((n)=>sT(n).match(t))}function jc(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 oT(t)}function vn(t){let e=jc(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 oT(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 sT(t){let e=lg.get(t);if(e)return e;let n=new Bun.Glob(t);return lg.set(t,n),n}class x extends Error{_tag="ValidationError"}var iT=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,aT=/^[A-Za-z_$][A-Za-z0-9_$]*$/,cT="must be lower-case letters and digits separated by single hyphens",lT=new Set(Object.getOwnPropertyNames(Object.prototype)),uT=je(),dT=Vp(),Ps=Wp(),pT=qp(Up()),gT=je().or(Rs());function wt(t,e,n){try{return n()}catch(r){if(r instanceof x)throw new f(`Invalid ${t}: ${r.message}`,e);throw r}}function S(t,e){if(typeof e==="number")return`${t}[${e}]`;if(!aT.test(e))return`${t}[${JSON.stringify(e)}]`;return t.length===0?e:`${t}.${e}`}function R(t,e,n){let r=pg(t,e),o=Object.keys(r).find((s)=>!n.includes(s));if(o!==void 0)throw new x(`${e} has unknown key ${JSON.stringify(o)}; expected ${n.join(", ")}`);return r}function Me(t,e,n){return Object.entries(pg(t,e)).map(([r,o])=>{if(lT.has(r))throw new x(`${S(e,r)} uses a reserved name`);return[r,n(o,S(e,r),r)]})}function F(t,e,n){return t===void 0?e:n(t)}function tt(t,e,n){return t===void 0||t===null?e:n(t)}function It(t,e,n){if(t===void 0||t===null)throw new x(`${e} is required`);return n(t,e)}function I(t,e){return De(uT,t,e,"must be a string")}function it(t,e){let n=I(t,e);if(n.trim().length===0)throw new x(`${e} must not be empty`);return n}function Nt(t,e){return De(gT,t,e,"must be a string or null")}function oe(t,e){let n=I(t,e);if(!iT.test(n))throw new x(`${e} ${cT}, got ${JSON.stringify(n)}`);return n}function we(t,e){return De(dT,t,e,"must be true or false")}function se(t,e){let n=De(Ps,t,e,"must be a positive integer");if(!Number.isInteger(n)||n<=0)throw new x(`${e} must be a positive integer`);return n}function Vt(t,e){let n=De(Ps,t,e,"must be a non-negative integer");if(!Number.isInteger(n)||n<0)throw new x(`${e} must be a non-negative integer`);return n}function nr(t,e){let n=De(Ps,t,e,"must be a positive number");if(!Number.isFinite(n)||n<=0)throw new x(`${e} must be a positive number`);return n}function Mc(t,e){let n=De(Ps,t,e,"must be a number greater than 0 and at most 1");if(!(n>0&&n<=1))throw new x(`${e} must be a number greater than 0 and at most 1`);return n}function z(t,e,n){return De(Bp(t),e,n,`must be one of ${t.join(", ")}`)}function H(t,e,n){return De(pT,t,e,"must be a list").map((o,s)=>n(o,S(e,s)))}function jt(t,e){return H(t,e,I)}function Ns(t,e){return H(t,e,(n,r)=>dg(n,r,jc))}function ug(t,e){return H(t,e,(n,r)=>dg(n,r,vn))}function dg(t,e,n){let r=I(t,e),o=n(r);if(o!==null)throw new x(`${e} ${o}`);return r}function pg(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw new x(`${e} must be an object`);return t}function De(t,e,n,r){try{return t(e)}catch{throw new x(`${n} ${r}`)}}var mT=["task","review"],Dc=["task"],Rt="{prompt}",oo="{model}",fT=["command","reviewCommand","model","modelFlag","env","timeoutSeconds","roles"],hT=["default","stages","review"],yT=["agent","model"],kT=/^[A-Za-z_][A-Za-z0-9_]*$/,wT=":",ST="-",js={default:null,review:null,stages:{}};function Cn(t){return t.roles??Dc}function mg(t){let e=Me(t,"agents",$T);for(let[n]of e)oe(n,"agent name");return Object.fromEntries(e)}function $T(t,e){let n=R(t,e,fT),r={command:gg(n.command,S(e,"command"))};if(n.reviewCommand!==void 0)r.reviewCommand=gg(n.reviewCommand,S(e,"reviewCommand"));if(n.model!==void 0)r.model=it(n.model,S(e,"model"));if(n.modelFlag!==void 0)r.modelFlag=ET(n.modelFlag,S(e,"modelFlag"));if(n.env!==void 0)r.env=xT(n.env,S(e,"env"));if(n.timeoutSeconds!==void 0)r.timeoutSeconds=nr(n.timeoutSeconds,S(e,"timeoutSeconds"));if(n.roles!==void 0)r.roles=vT(n.roles,S(e,"roles"));return r}function fg(t){let e=R(t,"routing",hT);return{default:F(e.default,js.default,(n)=>ro(n,"routing.default")),review:F(e.review,js.review,(n)=>ro(n,"routing.review")),stages:Object.fromEntries(F(e.stages,[],(n)=>Me(n,"routing.stages",bT)))}}function ro(t,e){if(t===null)return null;if(typeof t==="string")return TT(t,e);let n=R(t,e,yT),r=oe(n.agent,S(e,"agent")),o=F(n.model,null,(s)=>it(s,S(e,"model")));return{agent:r,model:o}}function bT(t,e){let n=ro(t,e);if(n!==null)return n;throw new x(`${e} must name an agent; leave the stage out to use routing.default`)}function TT(t,e){let n=t.indexOf(wT);if(n===-1)return{agent:oe(t,e),model:null};let r=oe(t.slice(0,n),`${e} (agent)`),o=it(t.slice(n+1),`${e} (model)`);return{agent:r,model:o}}function hg(t){let{agents:e,review:n,routing:r}=t,o=[["routing.default",r.default,"task"],...Object.entries(r.stages).map(([s,i])=>[S("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 x(`${s} names agent "${i.agent}", which agents does not define`);if(!Cn(c).includes(a))throw new x(`${s} names agent "${i.agent}", whose roles do not include "${a}"; add it to agents.${i.agent}.roles`)}}function gg(t,e){let n=H(t,e,it);if(n.length===0)throw new x(`${e} must not be empty`);return n}function ET(t,e){let n=I(t,e);if(n.startsWith(ST)&&n.trim()===n&&n.length>1)return n;throw new x(`${e} must be an option such as "--model"`)}function xT(t,e){let n=H(t,e,(r,o)=>{let s=I(r,o);if(kT.test(s))return s;throw new x(`${o} must be an environment variable name, not a value`)});return yg(n,e)}function vT(t,e){let n=yg(H(t,e,(r,o)=>z(mT,r,o)),e);if(n.length===0)throw new x(`${e} must name at least one role`);return n}function yg(t,e){let n=t.find((r,o)=>t.indexOf(r)!==o);if(n!==void 0)throw new x(`${e} repeats ${JSON.stringify(n)}`);return t}var rr=["task","review","both"],Lc="--model",ie=[{binary:"claude",command:["claude","-p",Rt,"--permission-mode","acceptEdits"],label:"Claude Code",modelFlag:Lc,name:"claude",reviewCommand:["claude","-p",Rt,"--tools","Read,Grep,Glob","--permission-mode","dontAsk"]},{binary:"codex",command:["codex","exec","--sandbox","workspace-write",Rt],label:"Codex CLI",modelFlag:Lc,name:"codex",reviewCommand:["codex","exec","--sandbox","read-only",Rt]},{binary:"gemini",command:["gemini","--approval-mode","auto_edit","-p",Rt],label:"Gemini CLI",modelFlag:Lc,name:"gemini",reviewCommand:["gemini","--approval-mode","plan","-p",Rt]}];function kg(t){let e=ie.find((n)=>n.name===t);if(e!==void 0)return e;throw new T(`ari has no agent preset "${t}"`,`Choose one of: ${ie.map((n)=>n.name).join(", ")}, or add the agent to .ari/config.json yourself`)}function wg(t){let e=t??"task",n=rr.find((r)=>r===e);if(n!==void 0)return n;throw new T(`Unknown role "${e}"`,`Choose one of: ${rr.join(", ")}`)}function or(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 CT="--version",AT=5000,IT=200;async function Sg(){return Promise.all(ie.map(RT))}async function RT(t){return{...await Fc([t.binary]),label:t.label,preset:t.name}}async function Fc(t){for(let e of t){let n=Bun.which(e);if(n!==null)return{binary:e,path:n,version:await OT(n)}}return{binary:t[0]??"",path:null,version:null}}async function OT(t){let e;try{e=Bun.spawn([t,CT],{detached:!0,env:{...process.env,...ne},stderr:"ignore",stdin:"ignore",stdout:"pipe"})}catch{return null}let n=()=>re(e.pid,"SIGKILL"),r=Wt(n),o=setTimeout(n,AT),[s,i]=await Promise.all([new Response(e.stdout).text(),e.exited]);clearTimeout(o),n(),r();let a=s.split(`
|
|
105
|
+
`).map((c)=>c.trim()).find((c)=>c.length>0);return i===0&&a!==void 0?a.slice(0,IT):null}import{isDeepStrictEqual as aC}from"util";function so(t){if(typeof t!=="object"||t===null||Object.isFrozen(t))return t;for(let e of Object.values(t))so(e);return Object.freeze(t)}var _T="basic",PT=300,NT=6000,jT=20,MT=1200,DT=60000,LT=25,FT=0.95,GT=0.75,HT=["**/*.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__/**"],KT="Fix the reported value in .ari/config.json",UT=["$schema","pack","requireTask","checkTimeoutSeconds","testGlobs","regression","review","context","knowledge","agents","routing"],BT=["maxEntryBytes","maxBytes","decayAfterTasks","duplicateSimilarity","mergeSimilarity"],St=so({agents:{},checkTimeoutSeconds:PT,context:{budget:NT,journalTail:jT},knowledge:{decayAfterTasks:LT,duplicateSimilarity:FT,maxBytes:DT,maxEntryBytes:MT,mergeSimilarity:GT},pack:_T,regression:{setup:[]},requireTask:!1,review:{command:null},routing:js,testGlobs:HT});function An(t){return structuredClone(wt("config",KT,()=>$g(t)))}function Ms(t){try{return $g(t),null}catch(e){if(e instanceof x)return e.message;throw e}}function $g(t){let e=R(t,"config",UT);if(e.$schema!==void 0)I(e.$schema,"$schema");let n={agents:F(e.agents,St.agents,mg),checkTimeoutSeconds:F(e.checkTimeoutSeconds,St.checkTimeoutSeconds,(r)=>nr(r,"checkTimeoutSeconds")),context:F(e.context,St.context,WT),knowledge:F(e.knowledge,St.knowledge,VT),pack:F(e.pack,St.pack,(r)=>oe(r,"pack")),regression:F(e.regression,St.regression,JT),requireTask:F(e.requireTask,St.requireTask,(r)=>we(r,"requireTask")),review:F(e.review,St.review,qT),routing:F(e.routing,St.routing,fg),testGlobs:F(e.testGlobs,St.testGlobs,(r)=>ug(r,"testGlobs"))};return hg(n),n}function WT(t){let e=R(t,"context",["budget","journalTail"]),n=St.context;return{budget:F(e.budget,n.budget,(r)=>se(r,"context.budget")),journalTail:F(e.journalTail,n.journalTail,(r)=>Vt(r,"context.journalTail"))}}function VT(t){let e=R(t,"knowledge",BT),n={decayAfterTasks:io(e,"decayAfterTasks",se),duplicateSimilarity:io(e,"duplicateSimilarity",Mc),maxBytes:io(e,"maxBytes",se),maxEntryBytes:io(e,"maxEntryBytes",se),mergeSimilarity:io(e,"mergeSimilarity",Mc)};if(n.mergeSimilarity>n.duplicateSimilarity)throw new x("knowledge.mergeSimilarity must not exceed knowledge.duplicateSimilarity");if(n.maxEntryBytes>n.maxBytes)throw new x("knowledge.maxEntryBytes must not exceed knowledge.maxBytes");return n}function io(t,e,n){return F(t[e],St.knowledge[e],(r)=>n(r,`knowledge.${e}`))}function JT(t){let e=R(t,"regression",["setup"]);return{setup:F(e.setup,St.regression.setup,(n)=>H(n,"regression.setup",it))}}function qT(t){let e=R(t,"review",["command","agent","model"]),n=F(e.command,St.review.command,(s)=>Nt(s,"review.command"));if(n!==null&&n.trim().length===0)throw new x("review.command must be a command or null");let r=F(e.agent,null,(s)=>s===null?null:oe(s,"review.agent")),o=F(e.model,null,(s)=>s===null?null:it(s,"review.model"));if(n!==null&&r!==null)throw new x("review.command and review.agent are alternatives; set only one of them");if(o!==null&&r===null)throw new x("review.model needs review.agent");return{command:n,...r===null?{}:{agent:r},...o===null?{}:{model:o}}}import{randomUUID as zv}from"crypto";import{chmodSync as Zv,existsSync as Sl,mkdirSync as Qv,readFileSync as Vm,renameSync as tC,rmSync as eC,statSync as nC,writeFileSync as rC}from"fs";import{basename as oC,dirname as Wm,join as $l}from"path";import{isDeepStrictEqual as Tg}from"util";var YT=/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g,XT=/"(?:[^"\\\n]|\\.)*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,zT=/[^\r\n]/g,ZT=/(?:^|\n)([\t ]*)[^\n]*$/,QT=/^[\t ]*\r?\n/,tE=/^[\t ]+(?=\S)/m,eE=" ",ao=",";function Gc(t){return t.replace(XT,(e)=>e.startsWith('"')?e:e.replace(zT," "))}function Ds(t,e){let n=tE.exec(t)?.[0]??eE,r=t.includes(`\r
|
|
106
|
+
`)?`\r
|
|
107
|
+
`:`
|
|
108
|
+
`,o=(i,a)=>{let c=t.slice(i.start,i.end);if(Tg(i.value,a))return c;let l=r+(ZT.exec(t.slice(0,i.start))?.[1]??""),u=(A,C)=>JSON.stringify(A,null,n).replaceAll(`
|
|
109
|
+
`,C);if(!bg(i.value)||!bg(a)||Array.isArray(i.value)!==Array.isArray(a))return u(a,l);let d=nE(i,a),p=[],g="",m=i.start+1,h=(A)=>{let C=t.slice(m,A);return g+(g.length===0||QT.test(C)?"":r)+C};for(let A of i.entries){let C=h(A.start),G=d.get(A);if(g="",G!==void 0){let Tt=o(A.node,a[G]);p.push(C+t.slice(A.start,A.node.start)+Tt+t.slice(A.node.end,A.end))}else if(C.trim().length>0)g=C.trimEnd();m=t[A.end]===ao?A.end+1:A.end}let w=new Set(d.values()),b=l+n,v=Object.keys(a).filter((A)=>!w.has(A)).map((A)=>{let C=Array.isArray(a)?"":`${JSON.stringify(A)}: `;return b+C+u(a[A],b)}),B=h(i.end-1),K=B.trimEnd(),_=v.length===0?B.slice(K.length):l,M=p.length>0&&v.length>0?ao:"";return c[0]+p.join(ao)+M+K+v.join(ao)+_+c.at(-1)},s=rE(Gc(t));return t.slice(0,s.start)+o(s,JSON.parse(JSON.stringify(e)))+t.slice(s.end)}function nE({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||Tg(o.node.value,e[s]))&&Object.hasOwn(e,s))r.set(o,s)}return r}function bg(t){return typeof t==="object"&&t!==null}function rE(t){let e=[...t.matchAll(YT)],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]===ao?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 Lm,readlinkSync as Dv,realpathSync as Lv,statSync as Fv}from"fs";import{basename as Gv,dirname as go,isAbsolute as Hv,join as li,relative as Kv,resolve as Fm,sep as Uv}from"path";import{copyFileSync as lE,existsSync as uE,mkdtempSync as dE,readFileSync as pE,readlinkSync as gE,rmSync as mE,utimesSync as fE}from"fs";import{tmpdir as hE}from"os";import{join as Ls,resolve as yE}from"path";function L(t,e){if(t<e)return-1;if(t>e)return 1;return 0}function xt(t){return new Bun.CryptoHasher("sha256").update(t).digest("hex")}import{lstatSync as oE,statSync as sE}from"fs";import{dirname as iE,join as aE}from"path";var cE=["ENOENT","ENOTDIR","ELOOP"];function sn(t){return Eg(()=>oE(t))}function Hc(t){return Eg(()=>sE(t))}function sr(t,e,n=new Map){let r=iE(e);if(r===".")return!1;let o=n.get(r);if(o!==void 0)return o;let s=sn(aE(t,r))?.isSymbolicLink()===!0||sr(t,r,n);return n.set(r,s),s}function Eg(t){try{return t()}catch(e){if(cE.includes(e.code))return null;throw e}}var Fs="\x00",Ot=0,kE=128,wE=128,Rg=1,Og=1,SE=1,$E="ari-index-",Kc=["diff","--name-only","--no-renames","--ignore-submodules=untracked","-z"],bE=["git","--no-optional-locks","--no-replace-objects",...["core.fsmonitor=false","core.untrackedCache=false","core.trustctime=true","core.checkStat=default"].flatMap((t)=>["-c",t])],xg=1,TE=/^(?:[a-z]|S) /,vg=/^s/i,EE=2,xE="symlink:",vE=["--no-assume-unchanged","--no-skip-worktree"],Cg="worktree ",CE="bare",AE="prunable",Ag=/^(?:error|fatal): /;async function O(t,e,n={}){let r=[...bE,...e],o=OE(r,t,n),[s,i,a]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if((n.allowedExitCodes??[Ot]).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 ir(t){let e=await O(t,["rev-parse","--show-toplevel"],{allowedExitCodes:[Ot,kE]});if(e.exitCode!==Ot)throw new f(`${t} is not inside a git working tree`,"Run ari from inside a git repository");return e.stdout.trim()}async function an(t,e){let n=await O(t,["rev-parse","--git-path",e]);return yE(t,n.stdout.trim())}async function Gs(t){let e=await O(t,["rev-parse","--verify","--quiet","HEAD^{commit}"],{allowedExitCodes:[Ot,Rg]});if(e.exitCode!==Ot)throw new f("The repository has no commits yet","Make a first commit, then run the command again");return e.stdout.trim()}async function _g(t){let e=await O(t,["config","user.name"],{allowedExitCodes:[Ot,Og]}),n=e.stdout.trim();return e.exitCode===Ot&&n.length>0?n:null}async function Jt(t,e){let n=await Mg(t,async(s)=>(await jg(t,await Ks(t),s),O(t,[...Kc,e,"--"],{env:s}))),r=await O(t,[...Kc,"--cached",e,"--"]),o=await O(t,["ls-files","--others","--exclude-standard","-z"]);return Bc([n,r,o].flatMap((s)=>ae(s.stdout)))}async function Hs(t,e,n){let r=await O(t,[...Kc,e,n,"--"]);return Bc(ae(r.stdout))}async function ar(t,e){let n=await O(t,["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],{allowedExitCodes:[Ot,Rg]});if(n.exitCode!==Ot)throw new f(`"${e}" does not name a commit`,"Pass a branch, tag or commit that this repository has");return n.stdout.trim()}async function Pg(t,e,n){let r=await O(t,["merge-base",e,n],{allowedExitCodes:[Ot,SE]});if(r.exitCode!==Ot)throw new f(`${e} and ${n} share no history`,"Pass a ref that the current branch was integrated with");return r.stdout.trim()}async function Ng(t){let e=await O(t,["worktree","list","--porcelain","-z"]),n=[],r=null;for(let o of[...e.stdout.split(Fs),""])if(o.startsWith(Cg))r=o.slice(Cg.length);else if(o===CE||o.startsWith(AE))r=null;else if(o===""&&r!==null)n.push(r),r=null;return n}async function Se(t,e){return Mg(t,async(n)=>{await jg(t,await Ks(t),n);let r=await O(t,["add","--all","--sparse","--","."],{allowedExitCodes:[Ot,wE],env:n});if(r.exitCode!==Ot)throw new f(`git cannot hash the working tree: ${Uc(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 O(t,["rm","--cached","-r","-q","--sparse","--ignore-unmatch","--",...s],{env:n})}return(await O(t,["write-tree"],{env:n})).stdout.trim()})}async function Le(t,e){if(e.length===0)return{};let n=await O(t,["ls-files","--cached","--others","--exclude-standard","-z"]),r=new Map,o=Bc(ae(n.stdout)).filter((s)=>J(s,e)&&!sr(t,s,r));return Object.fromEntries(o.flatMap((s)=>{let i=RE(Ls(t,s));return i===null?[]:[[s,i]]}))}function Uc(t){let e=t.split(`
|
|
110
|
+
`).map((r)=>r.trim()).filter((r)=>r.length>0),n=e.filter((r)=>Ag.test(r)).map((r)=>r.replace(Ag,""));return(n.length>0?n:e).join("; ")||"no output"}async function Ks(t){let e=await O(t,["ls-files","-v","-z"]),n=ae(e.stdout).filter((o)=>TE.test(o)),r=n.some((o)=>vg.test(o))&&await IE(t);return n.filter((o)=>!(r&&vg.test(o))||sn(Ls(t,Ig(o)))!==null).map(Ig)}async function IE(t){return(await O(t,["config","--type=bool","core.sparseCheckout"],{allowedExitCodes:[Ot,Og]})).stdout.trim()==="true"}function Ig(t){return t.slice(EE)}async function jg(t,e,n){if(e.length===0)return;let r=`${e.join(Fs)}${Fs}`;for(let o of vE)await O(t,["update-index",o,"-z","--stdin"],{env:n,stdin:r})}async function Mg(t,e){let n=dE(Ls(hE(),$E)),r=Ls(n,"index"),o=()=>mE(n,{force:!0,recursive:!0}),s=Wt(o);try{let i=await an(t,"index");if(uE(i))lE(i,r),fE(r,xg,xg);return await e({GIT_INDEX_FILE:r})}finally{o(),s()}}function RE(t){let e=sn(t);if(e?.isSymbolicLink())return`${xE}${xt(gE(t))}`;return e?.isFile()?xt(pE(t)):null}function OE(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 ae(t){return t.split(Fs).filter((e)=>e.length>0)}function Bc(t){return[...new Set(t)].sort(L)}import{randomUUID as yv}from"crypto";import{appendFileSync as kv,existsSync as Ue,linkSync as wv,mkdirSync as gm,readdirSync as Sv,readFileSync as uo,renameSync as mm,rmSync as ri,writeFileSync as fm}from"fs";import{basename as $v,dirname as hm,join as ot}from"path";var co='writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys',_E=/"(?:[^"\\]|\\.)*"|'(?:[^']|'')*'/sy,PE=/(?:[^,[\]{}:#\n]|:(?![ \t\n,[\]{}]|$)|(?<![ \t\n])#)+/sy,NE=/(?:[ \t\n]|(?<=[ \t\n])#[^\n]*)+/sy,jE=/[&!*][^\s,[\]{}]*|\?(?=[ \t\n])/sy,ME=/[ \t\n,[\]{}]/;function Vc(t){return`defines "${t}" twice`}function Jc(t,e){return Us(_E,t,e)}function qc(t){return String(Bun.YAML.parse(t))}function Dg(t,e){let n=[],r=e,o=!1;while(r<t.length){let s=LE(t,r,o);if(r+=s.text.length,s.kind==="space")continue;let i=DE(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 DE(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?Wc(n):null;case"comma":{let o=r?Wc(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,Wc(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"?qc(t.text):t.text.trim();return null;case"space":return null}}function Wc(t){let{key:e,keys:n}=t;if(e===null||n===null)return null;if(n.has(e))return Vc(e);return n.add(e),null}function LE(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||ME.test(t[e+1]??" ")))return{kind:"colon",text:r};let o=Us(NE,t,e);if(o!==null)return{kind:"space",text:o};let s=Jc(t,e);if(s!==null)return{kind:"quoted",text:s};let i=Us(jE,t,e);if(i!==null)return{kind:"special",text:i};return{kind:"plain",text:Us(PE,t,e)??r}}function Us(t,e,n){return t.lastIndex=n,t.exec(e)?.[0]??null}var FE=/^(?:---|\.\.\.)(?=[ \t]|$)/,GE=/^( *)((?:-(?: +|$))*)(.*)$/s,Lg=/^(?:[&!][^ \t]*(?:[ \t]+|$))+/,HE=/^#/,KE=/^[{[]/,UE=/^\?(?:[ \t]|$)/,BE=/^\*.*:(?:[ \t]|$)/s,Fg=/^[ \t]*:(?:[ \t]+|$)/,WE=/^([^\s|>%@`"'&*!#,[\]{}](?:(?![ \t]#).)*?)[ \t]*:(?:[ \t]+(.*))?$/s,Gg=-1;function Hg(t){let e=[],n=null,r=0,o=0;for(let s of t.split(`
|
|
111
|
+
`)){let i=o;if(o+=s.length+1,i<r)continue;let a=s.match(FE)?.[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(GE)??[];if(n!==null&&l.length>n)continue;if(u===""&&Kg(d))continue;let p=l.length+u.length;YE(e,u===""?p:l.length);let g=VE(d);if(g===co)return g;if(g!==null){let{keys:b}=XE(e,p);if(b.has(g.name))return Vc(g.name);b.add(g.name)}let m=qE(g===null?d:g.value),h=u===""?e.at(-1)?.column??Gg:c.lastIndexOf("-",p-1);if(n=m.kind==="text"?g===null?h:p:null,m.kind!=="flow")continue;let w=Dg(t,i+c.length-m.text.length);if(w.problem!==null)return w.problem;if(r=w.end,g===null&&Fg.test(t.slice(w.end,o).trimEnd()))return co}return null}function VE(t){if(UE.test(t)||BE.test(t))return co;let e=t.replace(Lg,""),n=JE(e);return n!==null&&e!==t?co:n}function JE(t){let e=Jc(t,0);if(e===null){let[,r,o=""]=t.match(WE)??[];return r===void 0?null:{name:r,value:o}}let n=t.slice(e.length).match(Fg)?.[0];return n===void 0?null:{name:qc(e),value:t.slice(e.length+n.length)}}function qE(t){let e=t.replace(Lg,"");if(Kg(e))return{kind:"block",text:e};return{kind:KE.test(e)?"flow":"text",text:e}}function Kg(t){return t.trim()===""||HE.test(t)}function YE(t,e){while((t.at(-1)?.column??Gg)>e)t.pop()}function XE(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 cr="---",zE=/^\uFEFF+/,ZE=/\r\n?/g;function Bs(t){return t.replace(zE,"").replace(ZE,`
|
|
112
|
+
`)}function Ws(t){let e=Bs(t).split(`
|
|
113
|
+
`);if(e[0]?.trimEnd()!==cr)throw new x(`the file must start with a "${cr}" line that opens the front matter`);let n=e.findIndex((r,o)=>o>0&&r.trimEnd()===cr);if(n===-1)throw new x(`the front matter has no closing "${cr}" line`);return{body:e.slice(n+1).join(`
|
|
114
|
+
`),data:Yc(e.slice(1,n).join(`
|
|
115
|
+
`),"the front matter")}}function Vs(t,e){return`${cr}
|
|
66
116
|
${t.join(`
|
|
67
117
|
`)}
|
|
68
|
-
${
|
|
69
|
-
${e}`}function
|
|
70
|
-
`)}function
|
|
71
|
-
`}function
|
|
72
|
-
`)}function ai(t){return t.normalize("NFC").toLowerCase().replace(uw," ").trim()}function pw(t,e){let{body:n,data:r}=ts(e),s=I(r,"front matter",dw),o=ht(s.created,"created",E);if(!lw.test(o))throw new O(`created must be a YYYY-MM-DD date, got "${o}"`);let i=n.trim();if(i.length===0)throw new O("the entry text is empty");return{created:o,id:t,kind:ht(s.kind,"kind",(a,c)=>rt(Pe,a,c)),scope:q(s.scope,[],(a)=>zr(a,"scope")),sources:q(s.sources,[],(a)=>xt(a,"sources")),status:q(s.status,"active",(a)=>rt(cw,a,"status")),supersededBy:q(s.supersededBy,null,(a)=>bt(a,"supersededBy")),supersedes:q(s.supersedes,[],(a)=>xt(a,"supersedes")),text:i}}var du=200,mw=/\{id\}/g,fw="Fix the pack file; see the packs section of the Ariadne design",gw=["all","criteria","expect:pass","expect:fail","expect:regression"],hw=["pass","fail"],os={kind:"criteria"},ke={kind:"invariants"},jt={kind:"scope"},ne={kind:"locked"},ci={kind:"tests-unchanged"},yw={kind:"regression"},cu={kind:"approval"},kw={kind:"review"};function Lt(t,e){return{expect:e,kind:"checks",select:t}}function lu(t){return{kind:"artifact",minBytes:du,path:t}}var uu=In([{description:"Implement the contract and prove it with its checks",name:"basic",stages:[{gates:[os,Lt("criteria","pass"),ke,jt,ne],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:[lu(".ari/designs/{id}.md"),cu],instruction:"Write the design to .ari/designs/{id}.md, then ask a human to approve it.",name:"design"},{gates:[os,Lt("all","pass"),ke,jt,ne],instruction:"Implement the approved design inside the scope until every check passes.",name:"implement"},{gates:[kw,Lt("all","pass"),ke,jt,ne],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:[os,Lt("criteria","fail"),jt],instruction:"Write failing tests for every criterion. Do not implement the change yet.",name:"red"},{gates:[Lt("all","pass"),ci,ke,jt,ne],instruction:"Make every check pass with the smallest change. Do not edit the tests.",name:"green"},{gates:[Lt("all","pass"),ci,ke,jt,ne],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:[Lt("expect:regression","fail"),jt],instruction:"Write a regression check that fails because of the bug. Do not fix it yet.",name:"reproduce"},{gates:[yw,Lt("all","pass"),ke,jt,ne],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:[os,cu],instruction:"Specify the criteria and their checks in the contract, run ari amend, then ask a human to approve.",name:"specify"},{gates:[Lt("all","pass"),ke,jt,ne],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:[ci,Lt("all","pass"),ke,jt,ne],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:[lu(".ari/designs/{id}.md"),jt,ne],instruction:"Explore inside the scope and write the findings to .ari/designs/{id}.md.",name:"explore"}]}]),pu={approval:(t,e)=>we(t,e,"approval"),artifact:Ew,checks:Sw,command:(t,e)=>{let n=I(t,e,["kind","run"]);return{kind:"command",run:Qt(n.run,k(e,"run"))}},criteria:(t,e)=>we(t,e,"criteria"),invariants:(t,e)=>we(t,e,"invariants"),locked:(t,e)=>we(t,e,"locked"),regression:(t,e)=>we(t,e,"regression"),review:(t,e)=>we(t,e,"review"),scope:(t,e)=>we(t,e,"scope"),"tests-unchanged":(t,e)=>we(t,e,"tests-unchanged")},ww=Object.keys(pu);function is(t,e="pack"){return st(e,fw,()=>$w(ri(t,"the pack file")))}function Ne(t){let e=new Map(t.map((o)=>[o.name,o])),n=uu.map((o)=>e.get(o.name)??o),r=new Set(uu.map((o)=>o.name)),s=t.filter((o)=>!r.has(o.name)).sort((o,i)=>N(o.name,i.name));return[...n,...s]}function De(t,e){let n=Ne(e),r=n.find((o)=>o.name===t);if(r)return r;let s=n.map((o)=>o.name).join(", ");throw new g(`Unknown pack "${t}"`,`Use one of ${s}, or add .ari/packs/${t}.yaml`)}function as(t,e){let{regression:n,review:r,testGlobs:s}=e,o=t.stages.map(({gates:i,name:a})=>({gates:i,name:a}));return $t(ot({regression:n,review:r,stages:o,testGlobs:s}))}function on(t,e){return t.instruction.replace(mw,e)}function $w(t){let e=I(t,"pack",["name","description","stages"]),n=U(e.stages,"stages",bw);if(n.length===0)throw new O("stages must list at least one stage");let r=new Set;for(let[s,o]of n.entries()){if(r.has(o.name))throw new O(`stages[${s}].name repeats "${o.name}"`);r.add(o.name)}return{description:q(e.description,"",(s)=>E(s,"description")),name:tn(e.name,"name"),stages:n}}function bw(t,e){let n=I(t,e,["name","instruction","gates"]),r=U(n.gates,k(e,"gates"),xw);if(r.length===0)throw new O(`${k(e,"gates")} must list at least one gate`);let s=new Set(r.map((o)=>o.kind));if(s.has("tests-unchanged")&&!s.has("scope"))throw new O(`${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:Qt(n.instruction,k(e,"instruction")),name:tn(n.name,k(e,"name"))}}function xw(t,e){let n=I(t,e,["kind","select","expect","path","minBytes","run"]),r=rt(ww,n.kind,k(e,"kind"));return pu[r](n,e)}function we(t,e,n){return I(t,e,["kind"]),{kind:n}}function Sw(t,e){let n=I(t,e,["kind","select","expect"]);return Lt(q(n.select,"all",(r)=>rt(gw,r,k(e,"select"))),q(n.expect,"pass",(r)=>rt(hw,r,k(e,"expect"))))}function Ew(t,e){let n=I(t,e,["kind","path","minBytes"]),r=Qt(n.path,k(e,"path"));if(r.startsWith("/")||r.split("/").includes(".."))throw new O(`${k(e,"path")} must stay inside the repository`);return{kind:"artifact",minBytes:q(n.minBytes,du,(o)=>At(o,k(e,"minBytes"))),path:r}}var mu="attempt budget exhausted",fu="failedAttempts",Tw={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 Ut(t,e,n={}){return{at:e,by:n.by??null,detail:n.detail??null,stage:n.stage??null,type:t}}function li(t,e){return{approvals:[],attempts:0,base:null,contractHash:null,evidence:[],gatesHash:null,history:[Ut("created",e)],id:t,journalStats:null,knowledgeUsed:[],lastFailure:null,lockHashes:{},notes:[],question:null,stage:0,stageTestHashes:{},status:"draft"}}function hu(t){let e=t.history[0]?.at??"";return ot(t)===ot(li(t.id,e))}function ui(t,e){return re(t,["draft"],"mark ready"),{...t,history:[...t.history,Ut("ready",e)],status:"ready"}}function yu(t,e,n,r){return re(t,["ready"],"start"),{...t,attempts:0,...Tu(n),base:e,history:[...t.history,Ut("started",r,{detail:e})],stage:0,status:"active"}}function ku(t,e,n,r){if(re(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 s=t.stage+1>=n,o=Ut(s?"done":"advanced",e.at,{stage:e.stage});return{...t,evidence:[...t.evidence,e],history:[...t.history,o],lastFailure:null,stage:s?t.stage:t.stage+1,stageTestHashes:{...r},status:s?"done":"active"}}function wu(t,e,n){if(re(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,s=e.gates.filter((c)=>!c.ok).map((c)=>c.gate),o=Ut("failed",e.at,{detail:`attempt ${r} of ${n}: ${s.join(", ")||"no failing gate recorded"}`,stage:e.stage}),i=r>=n,a=Ut("blocked",e.at,{detail:mu,stage:e.stage});return{...t,attempts:r,history:i?[...t.history,o,a]:[...t.history,o],lastFailure:e,question:i?mu:t.question,status:i?"blocked":"active"}}function di(t,e,n){re(t,["draft","ready","active","blocked"],"amend");let r=Dn(e.reason,"Amending a task needs a reason","Pass --reason <text>"),s=e.base!==null&&e.base!==t.base;if(s)re(t,["active","blocked"],"move the base of");let o=s?e.base:t.base,i=`gates ${e.gatesHash}, locks ${gu(e.lockHashes)}, tests ${gu(e.stageTestHashes)}`,a=s?`, base ${t.base} -> ${o}`:"",c=`${r} (contract ${e.contractHash}, ${i}${a})`;return{...t,...Tu(e),approvals:t.approvals.filter((l)=>l.stage!==e.stage),base:o,history:[...t.history,Ut("amended",n,{detail:c})]}}function $u(t,e,n){re(t,["active"],"block");let r=Dn(e,"Blocking a task needs a question for a human","Pass --reason <text>");return{...t,history:[...t.history,Ut("blocked",n,{detail:r})],question:r,status:"blocked"}}function pi(t,e,n){re(t,["blocked"],"resolve");let r=Dn(e,"Resolving a task needs an answer","Pass --answer <text>");return{...t,attempts:0,history:[...t.history,Ut("resolved",n,{detail:r})],notes:[...t.notes,{at:n,promoted:!1,text:r}],question:null,status:"active"}}function bu(t,e,n){re(t,["active"],"approve");let{artifactHashes:r,stage:s,treeHash:o}=e,i=Dn(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:s,treeHash:o}],history:[...t.history,Ut("approved",n,{by:i,stage:s})]}}function xu(t,e,n){let r=Dn(e,"A note needs text","Pass the note text as an argument");return{...t,notes:[...t.notes,{at:n,promoted:!1,text:r}]}}function cs(t,e){let n=new Map(Object.entries(t.journalStats??{}).filter(([s])=>s!==fu));for(let s of e)n.set(s.type,(n.get(s.type)??0)+1);let r=t.history.filter((s)=>s.type==="failed").length;return{...t,journalStats:{...Object.fromEntries(n),[fu]:r}}}function Su(t,e){let n=[...new Set([...t.knowledgeUsed,...e])].sort(N);return{...t,knowledgeUsed:n}}function Eu(t,e){let n=`Run 'ari sleep' to list the unpromoted notes of "${t.id}"`;for(let s of e){let o=t.notes[s];if(o===void 0)throw new g(`Task "${t.id}" has no note ${s}`,n);if(o.promoted)throw new g(`Note ${s} of task "${t.id}" is already promoted`,n)}let r=new Set(e);return{...t,notes:t.notes.map((s,o)=>r.has(o)?{...s,promoted:!0}:s)}}function Tu({contractHash:t,gatesHash:e,lockHashes:n,stageTestHashes:r}){return{contractHash:t,gatesHash:e,lockHashes:{...n},stageTestHashes:{...r}}}function gu(t){return $t(ot(t))}function re(t,e,n){if(e.includes(t.status))return;throw new g(`Cannot ${n} task "${t.id}": it is ${t.status}, not ${e.join(" or ")}`,Tw[t.status](t.id))}function Dn(t,e,n){let r=t.trim();if(r.length===0)throw new g(e,n);return r}import{mkdirSync as vw,readFileSync as Cw,rmSync as ls,statSync as Aw,writeFileSync as Ow}from"fs";import{dirname as Rw}from"path";var Iw="EEXIST",_w="ENOENT",Pw="ESRCH",Nw=".break",Dw=20,jw=1e4,Lw=1000,Mw=10,Gw=0;function fi(t,e,n){Hw(t,e);try{return n()}finally{ls(t,{force:!0})}}function Hw(t,e){vw(Rw(t),{recursive:!0});let n=Date.now()+jw;while(!vu(t)){if(mi(t))Fw(t);if(Date.now()>=n)throw new g(`Another ari process is still changing task "${e}"`,`Run the command again once it finishes; if no ari process is running, delete ${t}`);Bun.sleepSync(Dw)}}function Fw(t){let e=`${t}${Nw}`;if(!vu(e)){if(mi(e))ls(e,{force:!0});return}try{if(mi(t))ls(t,{force:!0})}finally{ls(e,{force:!0})}}function vu(t){try{return Ow(t,`${process.pid}`,{flag:"wx"}),!0}catch(e){if(gi(e)===Iw)return!1;throw e}}function mi(t){let e=Kw(t);if(e===null)return!1;if(Number.isNaN(e.pid))return Date.now()-e.modifiedMs>Lw;return!Uw(e.pid)}function Kw(t){try{return{modifiedMs:Aw(t).mtimeMs,pid:Number.parseInt(Cw(t,"utf8"),Mw)}}catch(e){if(gi(e)===_w)return null;throw e}}function Uw(t){try{return process.kill(t,Gw),!0}catch(e){return gi(e)!==Pw}}function gi(t){return t.code}var Bw=["draft","ready","active","blocked","done"],Ww=["pass","fail"],Vw=["criteria","checks","invariants","scope","locked","tests-unchanged","regression","artifact","approval","review","command"],Jw=["created","ready","started","advanced","done","failed","amended","blocked","resolved","approved"],qw=["edit","shell","tool","check","done","context","note","stop","compact","session"],Yw=["approvals","attempts","base","contractHash","evidence","gatesHash","history","id","journalStats","knowledgeUsed","lastFailure","lockHashes","notes","question","stage","stageTestHashes","status"],Xw=["command","durationMs","exitCode","expect","name","ok","outputSha256","outputTail","timedOut"];function Cu(t,e){return st(`task record "${t}"`,`Restore .ari/tasks/${t}.json from git; only ari writes it`,()=>{let n=zw(e);if(n.id!==t)throw new O(`id is "${n.id}" but the file belongs to task "${t}"`);return n})}function ds(t){let e=I(t,"event",["at","detail","task","type"]);return{at:E(e.at,"at"),detail:Object.fromEntries(ye(e.detail,"detail",o$)),task:E(e.task,"task"),type:rt(qw,e.type,"type")}}function zw(t){let e=I(t,"record",Yw);return{approvals:U(e.approvals,"approvals",Zw),attempts:At(e.attempts,"attempts"),base:bt(e.base,"base"),contractHash:bt(e.contractHash,"contractHash"),evidence:U(e.evidence,"evidence",e$),gatesHash:J(e.gatesHash,null,(n)=>bt(n,"gatesHash")),history:U(e.history,"history",t$),id:E(e.id,"id"),journalStats:e.journalStats===null?null:s$(e.journalStats,"journalStats"),knowledgeUsed:xt(e.knowledgeUsed,"knowledgeUsed"),lastFailure:e.lastFailure===null?null:n$(e.lastFailure,"lastFailure"),lockHashes:us(e.lockHashes,"lockHashes"),notes:U(e.notes,"notes",Qw),question:bt(e.question,"question"),stage:At(e.stage,"stage"),stageTestHashes:us(e.stageTestHashes,"stageTestHashes"),status:rt(Bw,e.status,"status")}}function Zw(t,e){let n=I(t,e,["artifactHashes","at","by","stage","treeHash"]);return{artifactHashes:J(n.artifactHashes,{},(r)=>us(r,k(e,"artifactHashes"))),at:E(n.at,k(e,"at")),by:E(n.by,k(e,"by")),stage:E(n.stage,k(e,"stage")),treeHash:J(n.treeHash,null,(r)=>bt(r,k(e,"treeHash")))}}function Qw(t,e){let n=I(t,e,["at","promoted","text"]);return{at:E(n.at,k(e,"at")),promoted:Ie(n.promoted,k(e,"promoted")),text:E(n.text,k(e,"text"))}}function t$(t,e){let n=I(t,e,["at","by","detail","stage","type"]);return{at:E(n.at,k(e,"at")),by:bt(n.by,k(e,"by")),detail:bt(n.detail,k(e,"detail")),stage:bt(n.stage,k(e,"stage")),type:rt(Jw,n.type,k(e,"type"))}}function e$(t,e){let n=I(t,e,["at","gates","stage","testHashes","treeHash"]);return{at:E(n.at,k(e,"at")),gates:U(n.gates,k(e,"gates"),Au),stage:E(n.stage,k(e,"stage")),testHashes:us(n.testHashes,k(e,"testHashes")),treeHash:E(n.treeHash,k(e,"treeHash"))}}function n$(t,e){let n=I(t,e,["at","gates","stage","treeHash"]);return{at:E(n.at,k(e,"at")),gates:U(n.gates,k(e,"gates"),Au),stage:E(n.stage,k(e,"stage")),treeHash:E(n.treeHash,k(e,"treeHash"))}}function Au(t,e){let n=I(t,e,["checks","details","gate","ok","summary"]);return{checks:U(n.checks,k(e,"checks"),r$),details:xt(n.details,k(e,"details")),gate:rt(Vw,n.gate,k(e,"gate")),ok:Ie(n.ok,k(e,"ok")),summary:E(n.summary,k(e,"summary"))}}function r$(t,e){let n=I(t,e,Xw),r=k(e,"exitCode");return{command:E(n.command,k(e,"command")),durationMs:At(n.durationMs,k(e,"durationMs")),exitCode:n.exitCode===null?null:At(n.exitCode,r),expect:rt(Ww,n.expect,k(e,"expect")),name:E(n.name,k(e,"name")),ok:Ie(n.ok,k(e,"ok")),outputSha256:E(n.outputSha256,k(e,"outputSha256")),outputTail:E(n.outputTail,k(e,"outputTail")),timedOut:Ie(n.timedOut,k(e,"timedOut"))}}function us(t,e){return Object.fromEntries(ye(t,e,E))}function s$(t,e){return Object.fromEntries(ye(t,e,At))}function o$(t,e){if(typeof t==="string"||typeof t==="boolean")return t;if(typeof t==="number"&&Number.isFinite(t))return t;return xt(t,e)}var W=".ari",je=".ari/tasks/*.json",Pu=".ari/tasks/*.md",jn=".ari/config.json",an="ids",d$=`${W}/`,ms="tasks",Nu="knowledge",Du="packs",p$="ari",yi="active.json",m$="journal",ju=".md",Lu=".json",Mu=".md",hi=".yaml",f$=".jsonl",ki=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Gu=`
|
|
73
|
-
`,g$=".ari-",h$=".tmp",y$="ENOENT",Hu="EEXIST",k$=new Set(["EPERM","ENOTSUP","ENOSYS","EXDEV"]),w$="locks",$$=".lock";function cn(t){return t===W||t.startsWith(d$)}function yt(t){return t.filter((e)=>!cn(e))}function ln(t){if(Bt(X(t,W)))return;throw new g("Ariadne is not initialised in this repository","Run 'ari init'")}function Fu(t){let e=X(t,jn);if(Bt(e))return!1;return Ei(e,ot(dt)),!0}function Y(t){ln(t);let e=X(t,jn);if(!Bt(e))return Pn({});return Pn(Si(e,jn,"Fix the JSON syntax of .ari/config.json"))}function wi(t){return ki.test(t)}function un(t){if(wi(t))return t;throw new g(`"${t}" is not a task id`,"Task ids are lower-case words joined by hyphens; run 'ari list'")}function pt(t){return`${W}/${ms}/${un(t)}${ju}`}function se(t){return`${W}/${ms}/${un(t)}${Lu}`}function $i(t){return`${W}/${Du}/${t}${hi}`}function Mt(t){return ln(t),hs(X(t,W,ms),ju)}function Mn(t){return ln(t),hs(X(t,W,ms),Lu)}function Q(t,e,n){ln(t);let r=X(t,pt(e));if(!Bt(r))throw new g(`Task "${e}" does not exist`,"Run 'ari list' to see the tasks of this repository");let s=Ln(r,"utf8");return{contractText:s,task:{contract:ns(e,s,n),record:Me(t,e)}}}function Gt(t,e){let n={invalid:[],tasks:[]};for(let r of Mt(t))try{n.tasks.push(Q(t,r,e).task)}catch(s){if(!(s instanceof g))throw s;n.invalid.push({hint:s.hint??"",id:r,problem:s.message})}return n}function Ku(t,e,n,r){let{id:s}=n,o=pt(s),i=()=>new g(`Task "${s}" already exists at ${o}`,"Run 'ari list'");fi(qu(e,s),s,()=>{if(Bt(X(t,o))||!Ju(t,s))throw i();Bu(t,n),Xu(X(t,o),r,i)})}function Uu(t){let e=Mt(t);return[...e,...Mn(t).filter((n)=>!e.includes(n)&&!Ju(t,n))]}function Bu(t,e){Ei(X(t,se(e.id)),ot(e))}function Ot(t,e,n,r){return fi(qu(e,n),n,()=>{let s=r(Me(t,n));return Bu(t,s),s})}function $e(t){ln(t);let e=X(t,W,Du);return hs(e,hi).map((n)=>{let r=$i(n),s=is(Ln(X(t,r),"utf8"),r);if(s.name===n)return s;throw new g(`${r} declares the pack "${s.name}"`,`Rename the file to ${s.name}${hi} or fix its name`)})}function oe(t){return ln(t),hs(X(t,W,Nu),Mu)}function ie(t){return oe(t).map((e)=>rs(e,Ln(Yu(t,e),"utf8")))}function fs(t,e){if(!ki.test(e.id))throw Error(`Knowledge entry id "${e.id}" is not a slug`);let n=Yu(t,e.id);Xu(n,ss(e),()=>Error(`Knowledge entry ${n} already exists`))}async function tt(t){return Re(t,p$)}function it(t){let e=X(t,yi);if(!Bt(e))return null;let n=`Delete ${e}, then run 'ari next', which offers to adopt the task again`,r=Si(e,e,n);return st("active task pointer",n,()=>{let s=I(r,"pointer",["since","task"]);return{since:E(s.since,"since"),task:E(s.task,"task")}})}function bi(t,e){Ei(X(t,yi),ot(e))}function Wu(t){ps(X(t,yi),{force:!0})}function Le(t,e){let n=xi(t,e.task);Ou(_u(n),{recursive:!0});let r=JSON.stringify(JSON.parse(ot(e)));a$(n,`${r}${Gu}`)}function gs(t,e){ps(xi(t,e),{force:!0})}function Vu(t,e){let n=xi(t,e);if(!Bt(n))return[];return Ln(n,"utf8").split(Gu).flatMap((r)=>{if(r.trim().length===0)return[];let s=b$(r);return s===null||s.task!==e?[]:[s]})}function b$(t){try{return ds(JSON.parse(t))}catch(e){if(e instanceof SyntaxError||e instanceof O)return null;throw e}}function xi(t,e){return X(t,m$,`${un(e)}${f$}`)}function Me(t,e){let n=se(e),r=X(t,n);if(!Bt(r))throw new g(`Task "${e}" has a contract but no record at ${n}`,`Restore ${n} from git; only ari writes it`);return Cu(e,Si(r,n,`Restore ${n} from git; only ari writes it`))}function Ju(t,e){if(!Bt(X(t,se(e))))return!0;try{return hu(Me(t,e))}catch(n){if(n instanceof g)return!1;throw n}}function qu(t,e){return X(t,w$,`${un(e)}${$$}`)}function Yu(t,e){return X(t,W,Nu,`${e}${Mu}`)}function Si(t,e,n){let r=Ln(t,"utf8");try{return JSON.parse(r)}catch(s){let o=s instanceof Error?s.message:String(s);throw new g(`${e} is not valid JSON (${o})`,n)}}function hs(t,e){return x$(t).filter((r)=>r.endsWith(e)).map((r)=>u$(r,e)).filter((r)=>ki.test(r)).sort(N)}function x$(t){try{return l$(t)}catch(e){if(e.code===y$)return[];throw e}}function Ei(t,e){let n=zu(t);try{Iu(n,e),Ru(n,t)}catch(r){throw ps(n,{force:!0}),r}}function Xu(t,e,n){let r=zu(t);try{Iu(r,e),S$(r,t)}catch(s){if(s.code===Hu)throw n();throw s}finally{ps(r,{force:!0})}}function S$(t,e){try{c$(t,e)}catch(n){if(!k$.has(n.code??""))throw n;if(Bt(e))throw Object.assign(Error(`${e} already exists`),{code:Hu});Ru(t,e)}}function zu(t){let e=_u(t);return Ou(e,{recursive:!0}),X(e,`${g$}${i$()}${h$}`)}async function ys(t){let e=Y(t),n=await tt(t),r={config:e,drift:null,root:t,state:n,task:null},s=it(n)?.task??null;if(s===null)return r;if(!Mt(t).includes(s)){if(Mn(t).includes(s)&&Zu(Me(t,s)))throw E$(s);return r}let{contractText:o,task:i}=Q(t,s,e);if(!Zu(i.record))return r;return{...r,drift:T$(i,o),task:i}}function Zu({status:t}){return t==="active"||t==="blocked"}function E$(t){return new g(`the contract of the active task "${t}" is missing`,`Restore ${pt(t)}`)}function T$({contract:t,record:e},n){if(e.contractHash===null||ee(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 ${pt(t.id)}`}async function Qu(t,e={}){let n=e.staged??!1,{config:r,drift:s,task:o}=await ys(t);if(o===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=yt(n?await v$(t):await Ct(t,o.record.base??"HEAD")),a=i.filter((d)=>!K(d,o.contract.scope)),c=Z(a.length,"changed file lies","changed files lie"),l=a.length===0?null:`${a.length} ${c} outside the scope of "${o.contract.id}"`,u=i.length===0?null:s??l;return{checked:i,ok:u===null,outside:a,reason:u,staged:n,task:o.contract.id}}async function v$(t){let e=await A(t,["diff","--cached","--name-only","--no-renames","-z"]);return Zt(e.stdout)}var td=1.2,ed=0.75,nd=0.5,C$=/[\p{Variation_Selector}\p{Me}]/gu,A$=/[\p{L}\p{N}][\p{L}\p{M}\p{N}]*/gu;function rd(t){return t.normalize("NFC").toLowerCase().replace(C$,"").match(A$)??[]}function ks(t,e){let n=[...new Set(rd(t))].sort(N),r=e.map(O$),s=r.reduce((a,c)=>a+c.length,0),o=r.length===0?0:s/r.length,i=new Map(n.map((a)=>[a,R$(a,r)]));return r.map((a)=>({id:a.id,score:I$(a,n,i,o)})).sort((a,c)=>c.score-a.score||N(a.id,c.id))}function O$(t){let e=rd(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 R$(t,e){let n=e.filter((r)=>r.frequencies.has(t)).length;return Math.log(1+(e.length-n+nd)/(n+nd))}function I$(t,e,n,r){let s=r===0?1:t.length/r,o=td*(1-ed+ed*s);return e.reduce((i,a)=>{let c=t.frequencies.get(a)??0,l=n.get(a)??0;return i+l*c*(td+1)/(c+o)},0)}function et(t){return Buffer.byteLength(t,"utf8")}function Ti(t){return Math.ceil(et(t)/4)}import{readFileSync as Q$}from"fs";import{join as pd}from"path";import{copyFileSync as K$,mkdirSync as U$,readlinkSync as B$,rmSync as Ci,symlinkSync as W$}from"fs";import{dirname as V$,join as ws}from"path";import{existsSync as _$,mkdtempSync as P$,readFileSync as N$,realpathSync as D$,rmSync as sd}from"fs";import{tmpdir as j$}from"os";import{join as vi}from"path";var Gn=0,od=128,L$="ari-base-",M$="gitdir",G$=".git",H$=["-c","core.hooksPath=/dev/null"];async function ad(t,e,n){let r=D$(P$(vi(j$(),L$))),s={admin:null,directory:r},o=ge(()=>id(t,s));try{return await F$(t,e,s),await n(r)}finally{id(t,s),o()}}async function F$(t,e,n){let{directory:r}=n,s=await A(t,[...H$,"worktree","add","--detach",r,e],{allowedExitCodes:[Gn,od],env:{GIT_INDEX_FILE:void 0}});if(s.exitCode!==Gn)throw Error(`git worktree add ${r} ${e} failed in ${t}: ${Xo(s.stderr)}`);let o=await A(r,["rev-parse","--absolute-git-dir"],{allowedExitCodes:[Gn,od],env:Ur}),i=o.stdout.trim();if(o.exitCode===Gn&&cd(i,r))n.admin=i}function id(t,e){let{admin:n,directory:r}=e,s=Bun.spawnSync(["git","worktree","remove","--force",r],{cwd:t,env:{...process.env,GIT_INDEX_FILE:void 0},stderr:"ignore",stdin:"ignore",stdout:"ignore"});if(sd(r,{force:!0,recursive:!0}),s.exitCode===Gn||n===null)return;if(cd(n,r))sd(n,{force:!0,recursive:!0})}function cd(t,e){let n=vi(t,M$);return _$(n)&&N$(n,"utf8").trim()===vi(e,G$)}var J$="@base",q$=12;async function ld(t){let e=t.contract.checks.filter((p)=>p.expect==="regression");if(e.length===0)return z("regression",!1,"the contract has no check with expect: regression");let n=t.base.slice(0,q$),r=yt(t.changedFiles).filter((p)=>K(p,t.config.testGlobs)),s=await ad(t.root,t.base,(p)=>Y$(t,e,r,p)),o=await wt(e,"pass",t.root),i=[...s.setup,...s.checks,...o],c=s.setup.some((p)=>!p.ok)?[`regression checks did not run on ${n} because its setup failed`]:[],l=[...Ae(i),...c],u=l.length===0,d=u?`every regression check fails on ${n} and passes on the working tree`:`${l.length} regression ${Z(l.length,"problem","problems")} against ${n}`;return z("regression",u,d,l,i)}async function Y$(t,e,n,r){for(let i of n)z$(t.root,r,i);let s=await wt(X$(t.config),"pass",r);if(s.some((i)=>!i.ok))return{checks:[],setup:s};let o=e.map((i)=>({...i,name:`${i.name}${J$}`}));return{checks:await wt(o,"fail",r),setup:s}}function X$(t){return t.regression.setup.map((e,n)=>({name:`setup[${n}]`,run:e,timeoutSeconds:t.checkTimeoutSeconds}))}function z$(t,e,n){let r=ws(t,n),s=ws(e,n),o=ze(t,n)?null:he(r);if(o===null){Z$(e,n);return}if(!o.isFile()&&!o.isSymbolicLink())return;if(ud(e,n),Ci(s,{force:!0,recursive:!0}),o.isFile())K$(r,s);else W$(B$(r),s)}function Z$(t,e){let n=ws(t,e);if(ze(t,e)||he(n)?.isDirectory()!==!1)return;Ci(n,{force:!0})}function ud(t,e){let n=V$(e);if(n===".")return;ud(t,n);let r=ws(t,n),s=he(r);if(s?.isDirectory())return;if(s!==null)Ci(r,{force:!0});U$(r)}var tb="{id}",eb=[".ari/tasks/**",".ari/knowledge/**"];async function Oi(t){let e=ae(t.task,t.pack),r={...t,changedFiles:()=>Ct(t.root,gd(t.task)),stage:e},s=[],o=[];for(let[i,a]of e.gates.entries()){let c=await nb(a,r);if(s.push(c),c.ok&&ub(a)&&i<e.gates.length-1)o.push({index:i,result:await db(a.kind,c,r)})}for(let i of o)s[i.index]=await i.result();return s}function ae(t,e){let n=e.stages[t.record.stage];if(n)return n;throw new g(`Task "${t.contract.id}" is at stage ${t.record.stage}, but pack "${e.name}" has ${e.stages.length}`,`Restore the stages of pack "${e.name}", or amend the task's pack`)}async function Hn(t,e,n){let r=await zt(t,e.testGlobs);return Object.fromEntries(Object.entries(r).filter(([s])=>!cn(s)&&K(s,n.scope)))}async function Ri(t,e,n){let s=e.gates.flatMap((o)=>o.kind==="artifact"?[md(o.path,n)]:[]).flatMap((o)=>{let i=pd(t,o);return qo(i)?.isFile()?[[o,$t(Q$(i))]]:[]});return{artifactHashes:Object.fromEntries(s),treeHash:await Qe(t,eb)}}function Fn(t,e){return[...new Set([...Object.keys(t),...Object.keys(e)])].sort(N).flatMap((r)=>{let s=t[r],o=e[r];if(s===o)return[];if(s===void 0)return[`added ${r}`];return o===void 0?[`deleted ${r}`]:[`changed ${r}`]})}async function nb(t,e){switch(t.kind){case"criteria":return rb(e.task.contract);case"checks":return sb(t.select,t.expect,e);case"invariants":return ob(e);case"scope":return ib(e);case"locked":return ab(e);case"tests-unchanged":return cb(e);case"regression":return ld({base:gd(e.task),changedFiles:await e.changedFiles(),config:e.config,contract:e.task.contract,root:e.root});case"artifact":return lb(t.path,t.minBytes,e);case"approval":return Ii("approval",e);case"review":return pb(e);case"command":return mb(t.run,e)}}function rb(t){let e=ii(t),n=e.length===0?`${t.criteria.length} ${Z(t.criteria.length,"criterion","criteria")} bound to existing checks`:`${e.length} criteria ${Z(e.length,"problem","problems")}`;return z("criteria",e.length===0,n,e)}async function sb(t,e,n){let r=sn(n.task.contract,t);if(r.length===0)return z("checks",!1,`no check matches the selection "${t}"`);let s=await wt(r,e,n.root),o=Ae(s),i=e==="pass"?"passed":"failed as expected",a=`${s.length-o.length} of ${s.length} ${Z(s.length,"check","checks")} ${i}`;return z("checks",o.length===0,a,o,s)}async function ob(t){let e=t.task.contract.invariants.map((o,i)=>({name:`invariants[${i}]`,run:o,timeoutSeconds:t.config.checkTimeoutSeconds})),n=await wt(e,"pass",t.root),r=Ae(n),s=`${n.length-r.length} of ${n.length} ${Z(n.length,"invariant","invariants")} passed`;return z("invariants",r.length===0,s,r,n)}async function ib(t){let e=yt(await t.changedFiles()),n=e.filter((s)=>!K(s,t.task.contract.scope)),r=n.length===0?`${e.length} changed ${Z(e.length,"file","files")} inside the scope`:`${n.length} of ${e.length} changed ${Z(e.length,"file","files")} outside the scope`;return z("scope",n.length===0,r,n)}async function ab(t){let e=await zt(t.root,t.task.contract.lock),n=Fn(t.task.record.lockHashes,e),r=Object.keys(t.task.record.lockHashes).length,s=n.length===0?`${r} locked ${Z(r,"file","files")} unchanged`:`${n.length} locked ${Z(n.length,"file","files")} changed`;return z("locked",n.length===0,s,n)}async function cb(t){let e=await Hn(t.root,t.config,t.task.contract),n=Fn(t.task.record.stageTestHashes,e),r=Object.keys(t.task.record.stageTestHashes).length,s=n.length===0?`${r} test ${Z(r,"file","files")} unchanged since the stage started`:`${n.length} test ${Z(n.length,"file","files")} changed since the stage started`;return z("tests-unchanged",n.length===0,s,n)}function lb(t,e,n){let r=md(t,n.task.contract.id),s=qo(pd(n.root,r));if(!s?.isFile())return z("artifact",!1,`${r} does not exist`);let o=s.size>=e,i=o?`${r} has ${s.size} bytes`:`${r} has ${s.size} bytes; it needs at least ${e}`;return z("artifact",o,i)}function md(t,e){return t.replaceAll(tb,e)}function ub(t){return t.kind==="approval"||t.kind==="review"}async function db(t,e,n){if(t==="approval"||n.config.review.command===null)return()=>Ii(t,n);let r=await Ai(n);return async()=>{if(fd(r,await Ai(n)))return e;return z(t,!1,"the working tree changed while the gates after the review ran",[],e.checks)}}function Ai(t){return Ri(t.root,t.stage,t.task.contract.id)}function fd(t,e){return t.treeHash===e.treeHash&&Fn(t.artifactHashes,e.artifactHashes).length===0}async function Ii(t,e){let n=e.stage.name,r=`a human runs 'ari approve ${e.task.contract.id}'`,s=e.task.record.approvals.filter((c)=>c.stage===n);if(s.length===0)return z(t,!1,`stage ${n} has no approval; ${r}`);let o=await Ai(e),i=s.filter((c)=>fd(c,o));if(i.length>0)return z(t,!0,`stage ${n} approved by ${dd(i)}`);let a=`the working tree changed after ${dd(s)} approved stage ${n}`;return z(t,!1,`${a}; ${r} again`)}function dd(t){return[...new Set(t.map((e)=>e.by))].join(", ")}async function pb(t){let e=t.config.review.command;if(e===null)return Ii("review",t);let n={name:"review",run:e,timeoutSeconds:t.config.checkTimeoutSeconds},r=await wt([n],"pass",t.root),s=Ae(r),o=s.length===0?"the review command passed":"the review command failed";return z("review",s.length===0,o,s,r)}async function mb(t,e){let n={name:"command",run:t,timeoutSeconds:e.config.checkTimeoutSeconds},r=await wt([n],"pass",e.root),s=Ae(r),o=s.length===0?`${t} passed`:`${t} failed`;return z("command",s.length===0,o,s,r)}function gd(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 fb,existsSync as gb,fstatSync as hb,openSync as yb,readSync as kb}from"fs";import{join as wb}from"path";var $b="journal",bb=".jsonl",hd=65536,xb=1000,$s=10;function bs(t,e,n){let r=[];if(n===0)return r;for(let s of Eb(kd(t,e))){let o=wd(s,e);if(o!==null)r.push(o);if(r.length===n)break}return r.reverse()}function*yd(t,e){let n=[];for(let r of Sb(kd(t,e))){let s=wd(r,e);if(s===null)continue;if(n.push(s),n.length<xb)continue;yield n,n=[]}if(n.length>0)yield n}function kd(t,e){return wb(t,$b,`${un(e)}${bb}`)}function wd(t,e){try{let n=ds(JSON.parse(t.toString("utf8")));return n.task===e?n:null}catch(n){if(n instanceof SyntaxError||n instanceof O)return null;throw n}}function*Sb(t){let e=[];for(let n of $d(t,!1)){let r=0;for(let s=n.indexOf($s);s!==-1;s=n.indexOf($s,r))yield Buffer.concat([...e,n.subarray(r,s)]),e=[],r=s+1;e.push(n.subarray(r))}yield Buffer.concat(e)}function*Eb(t){let e=[];for(let n of $d(t,!0)){let r=n.length;for(let s=n.lastIndexOf($s);s!==-1;s=s===0?-1:n.lastIndexOf($s,s-1))yield Buffer.concat([n.subarray(s+1,r),...e]),e=[],r=s;e.unshift(n.subarray(0,r))}yield Buffer.concat(e)}function*$d(t,e){if(!gb(t))return;let n=yb(t,"r");try{let{size:r}=hb(n);for(let s=0;s<r;s+=hd){let o=Math.min(hd,r-s),i=Buffer.alloc(o),a=kb(n,i,0,o,e?r-s-o:s);yield i.subarray(0,a)}}finally{fb(n)}}import{randomUUID as Rb}from"crypto";import{mkdirSync as Ib,readFileSync as _b,renameSync as Pb,rmSync as Nb,writeFileSync as Db}from"fs";import{basename as jb,dirname as bd,join as xd}from"path";var Tb=/\p{M}+/gu,vb=/[\u00DF\u00E6\u0111\u00F0\u0127\u0131\u0142\u0153\u00F8\u00FE]/g,Cb=/[^a-z0-9]+/,Ab={\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 Kn(t,e){if(!Number.isInteger(e)||e<=0)throw Error(`slugify needs a positive maxWords, got ${e}`);let r=t.toLowerCase().normalize("NFKD").replace(Tb,"").replace(vb,(s)=>Ab[s]??"").split(Cb).filter((s)=>s.length>0).slice(0,e).join("-");return Ob(r)}function Ob(t){if(t.length<=64)return t;let e=t.lastIndexOf("-",64);return e>0?t.slice(0,e):t.slice(0,64)}function Un(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 Lb=["constraint","decision"],Mb=6,Gb=10,Hb="knowledge",Fb=".md",Kb=4,Ub="\x00",Bb=",",Wb={"[":"]","{":"}"},Vb="\\",Jb=()=>new Date().toISOString();function _i(t,e,n){let r=Qt(t.text,`${e}.text`).trim(),s=et(r);if(s>n)throw new O(`${e}.text is ${s} bytes, but a knowledge entry holds at most ${n}`);return{kind:rt(Pe,t.kind,`${e}.kind`),scope:zr(t.scope,`${e}.scope`),text:r}}function Sd(t){return Pe.includes(t)}function qb(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 Yb(t,e){let n=Kn(t.text,Mb),r=Un(n.length>0?n:t.kind,e);return e.add(r),r}function xs(t,e,n,r){for(;;){let s=qb(e,{...n,id:Yb(e,r)});try{return fs(t,s),s}catch(o){if(!oe(t).includes(s.id))throw o}}}function Ge(t,e){return{...t,status:"archived",supersededBy:e}}function He(t){return Lb.includes(t.kind)}function Ss(t){return t.slice(0,Gb)}function Es(t,e){let n=Rd(t,e.id),r=xd(bd(n),`.${jb(n)}.${process.pid}.${Rb()}.tmp`);Ib(bd(n),{recursive:!0});try{Db(r,ss(e)),Pb(r,n)}catch(s){throw Nb(r,{force:!0}),s}}function Xb(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 Ts(t){let e=await A(t,["ls-files","--cached","--others","--exclude-standard","-z"]);return yt([...new Set(e.stdout.split(Ub).filter((n)=>n.length>0))])}function vs(t,e,n){if(t.length===0||e.length===0)return!0;return t.some((s)=>e.some((o)=>s===o||K(s,[o])||K(o,[s])))||n.some((s)=>K(s,t)&&K(s,e))}function Ed(t){let e=[],n=[],r="";for(let s=0;s<t.length;s++){let o=t[s]??"";if(o===Vb){r+=t.slice(s,s+2),s++;continue}let i=Wb[o];if(i!==void 0)n.push(i);else if(o===n.at(-1))n.pop();if(o===Bb&&n.length===0){e.push(r.trim()),r="";continue}r+=o}return e.push(r.trim()),e.filter((s)=>s.length>0)}function zb(t,e,n={}){let r=Y(t),s=st("note","Shorten the text or fix the --kind and --scope values",()=>_i(e,"note",r.knowledge.maxEntryBytes)),i={created:Ss((n.clock??Jb)()),sources:[...n.sources??[]],supersedes:[]};return xs(t,s,i,new Set(oe(t)))}async function Td(t,e,n={}){Y(t);let r=it(await tt(t))?.task,s=r!==void 0&&Mt(t).includes(r)?[r]:[];return zb(t,e,{...n,sources:s})}function Pi(t,e={}){return Y(t),{entries:ie(t).filter((r)=>e.all===!0||r.status==="active")}}function vd(t,e,n={}){let{entries:r}=Pi(t,n),s=new Map(r.map((a)=>[a.id,a]));return{matches:ks(e,r.map((a)=>({id:a.id,text:a.text}))).flatMap(({id:a,score:c})=>{let l=s.get(a);return l===void 0||c<=0?[]:[{entry:l,score:Zb(c)}]}),query:e}}function Cd(t,e,n){return{entry:Od(t,e),uses:Xb(n).get(e)??0}}function Ad(t,e,n={}){let r=Od(t,e);if(r.status==="archived")throw new g(`Knowledge entry "${e}" is already archived`,"Run 'ari knowledge list' to see the active entries");if(He(r)&&n.force!==!0)throw new g(`Knowledge entry "${e}" is a ${r.kind}; ${r.kind} entries are archived only on purpose`,`Run 'ari knowledge archive ${e} --force' if it no longer holds`);let s=Ge(r,null);return Es(t,s),s}function Od(t,e){if(Y(t),oe(t).includes(e))return rs(e,_b(Rd(t,e),"utf8"));throw new g(`Knowledge entry "${e}" does not exist`,"Run 'ari knowledge list --all' to see every entry")}function Rd(t,e){return xd(t,W,Hb,`${e}${Fb}`)}function Zb(t){let e=10**Kb;return Math.round(t*e)/e}var Qb=4,Rt=`
|
|
118
|
+
${cr}
|
|
119
|
+
${e}`}function $e(t){return JSON.stringify(t.toWellFormed())}function lr(t){return`[${t.map($e).join(", ")}]`}function Yc(t,e){let n=Bs(t),r=QE(n,e),o=Hg(n);if(o===null)return r;throw new x(`${e} ${o}`)}function QE(t,e){try{return Bun.YAML.parse(t)}catch(n){let r=n instanceof Error?n.message:String(n);throw new x(`${e} is not valid YAML (${r})`)}}var zc=3,Bg="spike",tx=/^[A-Za-z][A-Za-z0-9._-]*$/,ex=["pass","fail","regression"],nx={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"},rx=["title","pack","scope","lock","depends","criteria","checks","invariants","budget"],ox="AC-1",sx="Describe the change, its constraints and how a reviewer can verify it.";function Js(t,e,n){return wt(`contract "${t}"`,`Fix the front matter of .ari/tasks/${t}.md`,()=>ix(t,e,n))}function Fe(t){return xt(Bs(t))}function Wg(t,e){let n=e===Bg?["criteria: []"]:["criteria:",` - id: ${$e(ox)}`,' text: ""'," checks: []"],r=[`title: ${$e(t)}`,`pack: ${$e(e)}`,"scope: []","lock: []","depends: []",...n,"checks: {}","invariants: []","budget:",` attempts: ${zc}`];return Vs(r,`${sx}
|
|
120
|
+
`)}function ur(t,e){let n=e.find((o)=>o.name===t.pack),r=[...mx(t),...Zc(t)];return[...ux(t),...dx(t,n,e,r.length>0),...Ug("scope",t.scope,!0),...Ug("lock",t.lock,!1),...gx(t),...r,...fx(t),...hx(t)]}function dr(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 Xc(t,"pass");case"expect:fail":return Xc(t,"fail");case"expect:regression":return Xc(t,"regression")}}function Xc(t,e){return t.checks.filter((n)=>n.expect===e)}function Zc(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 ix(t,e,n){let{body:r,data:o}=Ws(e),s=R(o,"front matter",rx);return{body:r.trim(),budget:tt(s.budget,{attempts:zc},ax),checks:tt(s.checks,[],(i)=>lx(i,n.checkTimeoutSeconds)),criteria:tt(s.criteria,[],(i)=>H(i,"criteria",cx)),depends:tt(s.depends,[],(i)=>jt(i,"depends")),id:t,invariants:tt(s.invariants,[],(i)=>jt(i,"invariants")),lock:tt(s.lock,[],(i)=>jt(i,"lock")),pack:tt(s.pack,n.pack,(i)=>I(i,"pack")),scope:It(s.scope,"scope",jt),title:It(s.title,"title",I)}}function ax(t){let e=R(t,"budget",["attempts"]);return{attempts:tt(e.attempts,zc,(n)=>se(n,"budget.attempts"))}}function cx(t,e){let n=R(t,e,["id","text","checks"]);return{checks:tt(n.checks,[],(r)=>jt(r,S(e,"checks"))),id:It(n.id,S(e,"id"),I),text:It(n.text,S(e,"text"),I)}}function lx(t,e){return Me(t,"checks",(n,r,o)=>{if(!tx.test(o))throw new x(`${r} must be named with a letter followed by letters, digits, ".", "_" or "-"`);let s=R(n,r,["run","expect","timeout"]);return{expect:tt(s.expect,"pass",(i)=>z(ex,i,S(r,"expect"))),name:o,run:It(s.run,S(r,"run"),I),timeoutSeconds:tt(s.timeout,e,(i)=>nr(i,S(r,"timeout")))}}).map(([,n])=>n)}function ux(t){return t.title.trim().length===0?["title must not be empty"]:[]}function dx(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(px)))].filter((s)=>!r||s!=="all"&&s!=="criteria").filter((s)=>dr(t,s).length===0).map((s)=>`pack "${e.name}" needs at least one ${nx[s]}`)}function px(t){if(t.kind==="regression")return["expect:regression"];return t.kind==="checks"?[t.select]:[]}function Ug(t,e,n){let r=n&&e.length===0?[`${t} must list at least one glob`]:[],o=e.flatMap((s)=>{let i=vn(s);return i===null?[]:[`${t} glob ${JSON.stringify(s)} ${i}`]});return[...r,...o]}function gx(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 mx(t){let n=t.pack!==Bg&&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 fx(t){return t.checks.filter((e)=>e.run.trim().length===0).map((e)=>`check ${e.name} must have a run command`)}function hx(t){return t.invariants.some((e)=>e.trim().length===0)?["invariants must not contain an empty command"]:[]}var yx=2;function $t(t){return`${JSON.stringify(t,kx,yx)}
|
|
121
|
+
`}function kx(t,e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;return Object.fromEntries(Object.entries(e).sort(([n],[r])=>L(n,r)))}var ce=["fact","decision","constraint","pattern","gotcha"],wx=["active","archived"],Sx=/^\d{4}-\d{2}-\d{2}$/,$x=/\s+/g,bx=["kind","scope","sources","status","supersedes","supersededBy","created"];function qs(t,e){return wt(`knowledge entry "${t}"`,`Restore .ari/knowledge/${t}.md from git`,()=>Tx(t,e))}function Ys(t){let e=[`kind: ${$e(t.kind)}`,`scope: ${lr(t.scope)}`,`sources: ${lr(t.sources)}`,`status: ${$e(t.status)}`,`supersedes: ${lr(t.supersedes)}`,`supersededBy: ${t.supersededBy===null?"null":$e(t.supersededBy)}`,`created: ${$e(t.created)}`];return Vs(e,`${t.text.trim()}
|
|
122
|
+
`)}function Qc(t){return t.normalize("NFC").toLowerCase().replace($x," ").trim()}function Tx(t,e){let{body:n,data:r}=Ws(e),o=R(r,"front matter",bx),s=It(o.created,"created",I);if(!Sx.test(s))throw new x(`created must be a YYYY-MM-DD date, got "${s}"`);let i=n.trim();if(i.length===0)throw new x("the entry text is empty");return{created:s,id:t,kind:It(o.kind,"kind",(a,c)=>z(ce,a,c)),scope:tt(o.scope,[],(a)=>Ns(a,"scope")),sources:tt(o.sources,[],(a)=>jt(a,"sources")),status:tt(o.status,"active",(a)=>z(wx,a,"status")),supersededBy:tt(o.supersededBy,null,(a)=>Nt(a,"supersededBy")),supersedes:tt(o.supersedes,[],(a)=>jt(a,"supersedes")),text:i}}var Yg=200,Ex=/\{id\}/g,xx="Fix the pack file; see the packs section of the Ariadne design",vx=["all","criteria","expect:pass","expect:fail","expect:regression"],Cx=["pass","fail"],Xs={kind:"criteria"},cn={kind:"invariants"},le={kind:"scope"},Ge={kind:"locked"},tl={kind:"tests-unchanged"},Ax={kind:"regression"},Vg={kind:"approval"},Ix={kind:"review"};function ue(t,e){return{expect:e,kind:"checks",select:t}}function Jg(t){return{kind:"artifact",minBytes:Yg,path:t}}var qg=so([{description:"Implement the contract and prove it with its checks",name:"basic",stages:[{gates:[Xs,ue("criteria","pass"),cn,le,Ge],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:[Jg(".ari/designs/{id}.md"),Vg],instruction:"Write the design to .ari/designs/{id}.md, then ask a human to approve it.",name:"design"},{gates:[Xs,ue("all","pass"),cn,le,Ge],instruction:"Implement the approved design inside the scope until every check passes.",name:"implement"},{gates:[Ix,ue("all","pass"),cn,le,Ge],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:[Xs,ue("criteria","fail"),le],instruction:"Write failing tests for every criterion. Do not implement the change yet.",name:"red"},{gates:[ue("all","pass"),tl,cn,le,Ge],instruction:"Make every check pass with the smallest change. Do not edit the tests.",name:"green"},{gates:[ue("all","pass"),tl,cn,le,Ge],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"),le],instruction:"Write a regression check that fails because of the bug. Do not fix it yet.",name:"reproduce"},{gates:[Ax,ue("all","pass"),cn,le,Ge],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:[Xs,Vg],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"),cn,le,Ge],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:[tl,ue("all","pass"),cn,le,Ge],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:[Jg(".ari/designs/{id}.md"),le,Ge],instruction:"Explore inside the scope and write the findings to .ari/designs/{id}.md.",name:"explore"}]}]),Xg={approval:(t,e)=>ln(t,e,"approval"),artifact:jx,checks:Nx,command:(t,e)=>{let n=R(t,e,["kind","run"]);return{kind:"command",run:it(n.run,S(e,"run"))}},criteria:(t,e)=>ln(t,e,"criteria"),invariants:(t,e)=>ln(t,e,"invariants"),locked:(t,e)=>ln(t,e,"locked"),regression:(t,e)=>ln(t,e,"regression"),review:(t,e)=>ln(t,e,"review"),scope:(t,e)=>ln(t,e,"scope"),"tests-unchanged":(t,e)=>ln(t,e,"tests-unchanged")},Rx=Object.keys(Xg);function zs(t,e="pack"){return wt(e,xx,()=>Ox(Yc(t,"the pack file")))}function He(t){let e=new Map(t.map((s)=>[s.name,s])),n=qg.map((s)=>e.get(s.name)??s),r=new Set(qg.map((s)=>s.name)),o=t.filter((s)=>!r.has(s.name)).sort((s,i)=>L(s.name,i.name));return[...n,...o]}function In(t,e){let n=He(e),r=n.find((s)=>s.name===t);if(r)return r;let o=n.map((s)=>s.name).join(", ");throw new f(`Unknown pack "${t}"`,`Use one of ${o}, or add .ari/packs/${t}.yaml`)}function Zs(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 xt($t({regression:r,review:o,stages:i,testGlobs:s,...a}))}function pr(t,e){return t.instruction.replace(Ex,e)}function Ox(t){let e=R(t,"pack",["name","description","stages"]),n=H(e.stages,"stages",_x);if(n.length===0)throw new x("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 x(`stages[${o}].name repeats "${s.name}"`);r.add(s.name)}return{description:tt(e.description,"",(o)=>I(o,"description")),name:oe(e.name,"name"),stages:n}}function _x(t,e){let n=R(t,e,["name","instruction","gates"]),r=H(n.gates,S(e,"gates"),Px);if(r.length===0)throw new x(`${S(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 x(`${S(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:it(n.instruction,S(e,"instruction")),name:oe(n.name,S(e,"name"))}}function Px(t,e){let n=R(t,e,["kind","select","expect","path","minBytes","run"]),r=z(Rx,n.kind,S(e,"kind"));return Xg[r](n,e)}function ln(t,e,n){return R(t,e,["kind"]),{kind:n}}function Nx(t,e){let n=R(t,e,["kind","select","expect"]);return ue(tt(n.select,"all",(r)=>z(vx,r,S(e,"select"))),tt(n.expect,"pass",(r)=>z(Cx,r,S(e,"expect"))))}function jx(t,e){let n=R(t,e,["kind","path","minBytes"]),r=it(n.path,S(e,"path"));if(r.startsWith("/")||r.split("/").includes(".."))throw new x(`${S(e,"path")} must stay inside the repository`);return{kind:"artifact",minBytes:tt(n.minBytes,Yg,(s)=>Vt(s,S(e,"minBytes"))),path:r}}var zg="attempt budget exhausted",Zg="failedAttempts",Mx={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 be(t,e,n={}){return{at:e,by:n.by??null,detail:n.detail??null,stage:n.stage??null,type:t}}function el(t,e){return{approvals:[],attempts:0,base:null,contractHash:null,evidence:[],gatesHash:null,history:[be("created",e)],id:t,journalStats:null,knowledgeUsed:[],lastFailure:null,lockHashes:{},notes:[],question:null,stage:0,stageTestHashes:{},status:"draft"}}function tm(t){let e=t.history[0]?.at??"";return $t(t)===$t(el(t.id,e))}function nl(t,e){return Ke(t,["draft"],"mark ready"),{...t,history:[...t.history,be("ready",e)],status:"ready"}}function em(t,e,n,r){return Ke(t,["ready"],"start"),{...t,attempts:0,...lm(n),base:e,history:[...t.history,be("started",r,{detail:e})],stage:0,status:"active"}}function nm(t,e,n,r){if(Ke(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=be(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 rm(t,e,n){if(Ke(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=be("failed",e.at,{detail:`attempt ${r} of ${n}: ${o.join(", ")||"no failing gate recorded"}`,stage:e.stage}),i=r>=n,a=be("blocked",e.at,{detail:zg,stage:e.stage});return{...t,attempts:r,history:i?[...t.history,s,a]:[...t.history,s],lastFailure:e,question:i?zg:t.question,status:i?"blocked":"active"}}function rl(t,e,n){Ke(t,["draft","ready","active","blocked"],"amend");let r=lo(e.reason,"Amending a task needs a reason","Pass --reason <text>"),o=e.base!==null&&e.base!==t.base;if(o)Ke(t,["active","blocked"],"move the base of");let s=o?e.base:t.base,i=`gates ${e.gatesHash}, locks ${Qg(e.lockHashes)}, tests ${Qg(e.stageTestHashes)}`,a=o?`, base ${t.base} -> ${s}`:"",c=`${r} (contract ${e.contractHash}, ${i}${a})`;return{...t,...lm(e),approvals:t.approvals.filter((l)=>l.stage!==e.stage),base:s,history:[...t.history,be("amended",n,{detail:c})]}}function om(t,e,n){Ke(t,["active"],"block");let r=lo(e,"Blocking a task needs a question for a human","Pass --reason <text>");return{...t,history:[...t.history,be("blocked",n,{detail:r})],question:r,status:"blocked"}}function ol(t,e,n){Ke(t,["blocked"],"resolve");let r=lo(e,"Resolving a task needs an answer","Pass --answer <text>");return{...t,attempts:0,history:[...t.history,be("resolved",n,{detail:r})],notes:[...t.notes,{at:n,promoted:!1,text:r}],question:null,status:"active"}}function sm(t,e,n){Ke(t,["active"],"approve");let{artifactHashes:r,stage:o,treeHash:s}=e,i=lo(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,be("approved",n,{by:i,stage:o})]}}function im(t,e,n){let r=lo(e,"A note needs text","Pass the note text as an argument");return{...t,notes:[...t.notes,{at:n,promoted:!1,text:r}]}}function Qs(t,e){let n=new Map(Object.entries(t.journalStats??{}).filter(([o])=>o!==Zg));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),[Zg]:r}}}function am(t,e){let n=[...new Set([...t.knowledgeUsed,...e])].sort(L);return{...t,knowledgeUsed:n}}function cm(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 f(`Task "${t.id}" has no note ${o}`,n);if(s.promoted)throw new f(`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 lm({contractHash:t,gatesHash:e,lockHashes:n,stageTestHashes:r}){return{contractHash:t,gatesHash:e,lockHashes:{...n},stageTestHashes:{...r}}}function Qg(t){return xt($t(t))}function Ke(t,e,n){if(e.includes(t.status))return;throw new f(`Cannot ${n} task "${t.id}": it is ${t.status}, not ${e.join(" or ")}`,Mx[t.status](t.id))}function lo(t,e,n){let r=t.trim();if(r.length===0)throw new f(e,n);return r}import{mkdirSync as Dx,readFileSync as Lx,rmSync as ti,statSync as Fx,writeFileSync as Gx}from"fs";import{dirname as Hx}from"path";var Kx="EEXIST",Ux="ENOENT",Bx="ESRCH",Wx=".break",Vx=20,Jx=1e4,qx=1000,Yx=10,Xx=0;function il(t,e,n){zx(t,e);try{return n()}finally{ti(t,{force:!0})}}function zx(t,e){Dx(Hx(t),{recursive:!0});let n=Date.now()+Jx;while(!um(t)){if(sl(t))Zx(t);if(Date.now()>=n)throw new f(`Another ari process is still changing task "${e}"`,`Run the command again once it finishes; if no ari process is running, delete ${t}`);Bun.sleepSync(Vx)}}function Zx(t){let e=`${t}${Wx}`;if(!um(e)){if(sl(e))ti(e,{force:!0});return}try{if(sl(t))ti(t,{force:!0})}finally{ti(e,{force:!0})}}function um(t){try{return Gx(t,`${process.pid}`,{flag:"wx"}),!0}catch(e){if(al(e)===Kx)return!1;throw e}}function sl(t){let e=Qx(t);if(e===null)return!1;if(Number.isNaN(e.pid))return Date.now()-e.modifiedMs>qx;return!tv(e.pid)}function Qx(t){try{return{modifiedMs:Fx(t).mtimeMs,pid:Number.parseInt(Lx(t,"utf8"),Yx)}}catch(e){if(al(e)===Ux)return null;throw e}}function tv(t){try{return process.kill(t,Xx),!0}catch(e){return al(e)!==Bx}}function al(t){return t.code}var ev=["draft","ready","active","blocked","done"],nv=["pass","fail"],rv=["criteria","checks","invariants","scope","locked","tests-unchanged","regression","artifact","approval","review","command"],ov=["created","ready","started","advanced","done","failed","amended","blocked","resolved","approved"],sv=["edit","shell","tool","check","done","context","note","stop","compact","session"],iv=["approvals","attempts","base","contractHash","evidence","gatesHash","history","id","journalStats","knowledgeUsed","lastFailure","lockHashes","notes","question","stage","stageTestHashes","status"],av=["command","durationMs","exitCode","expect","name","ok","outputSha256","outputTail","timedOut"];function dm(t,e){return wt(`task record "${t}"`,`Restore .ari/tasks/${t}.json from git; only ari writes it`,()=>{let n=cv(e);if(n.id!==t)throw new x(`id is "${n.id}" but the file belongs to task "${t}"`);return n})}function ni(t){let e=R(t,"event",["at","detail","task","type"]);return{at:I(e.at,"at"),detail:Object.fromEntries(Me(e.detail,"detail",hv)),task:I(e.task,"task"),type:z(sv,e.type,"type")}}function cv(t){let e=R(t,"record",iv);return{approvals:H(e.approvals,"approvals",lv),attempts:Vt(e.attempts,"attempts"),base:Nt(e.base,"base"),contractHash:Nt(e.contractHash,"contractHash"),evidence:H(e.evidence,"evidence",pv),gatesHash:F(e.gatesHash,null,(n)=>Nt(n,"gatesHash")),history:H(e.history,"history",dv),id:I(e.id,"id"),journalStats:e.journalStats===null?null:fv(e.journalStats,"journalStats"),knowledgeUsed:jt(e.knowledgeUsed,"knowledgeUsed"),lastFailure:e.lastFailure===null?null:gv(e.lastFailure,"lastFailure"),lockHashes:ei(e.lockHashes,"lockHashes"),notes:H(e.notes,"notes",uv),question:Nt(e.question,"question"),stage:Vt(e.stage,"stage"),stageTestHashes:ei(e.stageTestHashes,"stageTestHashes"),status:z(ev,e.status,"status")}}function lv(t,e){let n=R(t,e,["artifactHashes","at","by","stage","treeHash"]);return{artifactHashes:F(n.artifactHashes,{},(r)=>ei(r,S(e,"artifactHashes"))),at:I(n.at,S(e,"at")),by:I(n.by,S(e,"by")),stage:I(n.stage,S(e,"stage")),treeHash:F(n.treeHash,null,(r)=>Nt(r,S(e,"treeHash")))}}function uv(t,e){let n=R(t,e,["at","promoted","text"]);return{at:I(n.at,S(e,"at")),promoted:we(n.promoted,S(e,"promoted")),text:I(n.text,S(e,"text"))}}function dv(t,e){let n=R(t,e,["at","by","detail","stage","type"]);return{at:I(n.at,S(e,"at")),by:Nt(n.by,S(e,"by")),detail:Nt(n.detail,S(e,"detail")),stage:Nt(n.stage,S(e,"stage")),type:z(ov,n.type,S(e,"type"))}}function pv(t,e){let n=R(t,e,["at","gates","stage","testHashes","treeHash"]);return{at:I(n.at,S(e,"at")),gates:H(n.gates,S(e,"gates"),pm),stage:I(n.stage,S(e,"stage")),testHashes:ei(n.testHashes,S(e,"testHashes")),treeHash:I(n.treeHash,S(e,"treeHash"))}}function gv(t,e){let n=R(t,e,["at","gates","stage","treeHash"]);return{at:I(n.at,S(e,"at")),gates:H(n.gates,S(e,"gates"),pm),stage:I(n.stage,S(e,"stage")),treeHash:I(n.treeHash,S(e,"treeHash"))}}function pm(t,e){let n=R(t,e,["checks","details","gate","ok","summary"]);return{checks:H(n.checks,S(e,"checks"),mv),details:jt(n.details,S(e,"details")),gate:z(rv,n.gate,S(e,"gate")),ok:we(n.ok,S(e,"ok")),summary:I(n.summary,S(e,"summary"))}}function mv(t,e){let n=R(t,e,av),r=S(e,"exitCode");return{command:I(n.command,S(e,"command")),durationMs:Vt(n.durationMs,S(e,"durationMs")),exitCode:n.exitCode===null?null:Vt(n.exitCode,r),expect:z(nv,n.expect,S(e,"expect")),name:I(n.name,S(e,"name")),ok:we(n.ok,S(e,"ok")),outputSha256:I(n.outputSha256,S(e,"outputSha256")),outputTail:I(n.outputTail,S(e,"outputTail")),timedOut:we(n.timedOut,S(e,"timedOut"))}}function ei(t,e){return Object.fromEntries(Me(t,e,I))}function fv(t,e){return Object.fromEntries(Me(t,e,Vt))}function hv(t,e){if(typeof t==="string"||typeof t==="boolean")return t;if(typeof t==="number"&&Number.isFinite(t))return t;return jt(t,e)}var X=".ari",Rn=".ari/tasks/*.json",ym=".ari/tasks/*.md",et=".ari/config.json",gr="ids",bv=`${X}/`,oi="tasks",km="knowledge",wm="packs",Tv="ari",ll="active.json",Ev="journal",Sm=".md",$m=".json",bm=".md",cl=".yaml",xv=".jsonl",ul=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Tm=`
|
|
123
|
+
`,vv=".ari-",Cv=".tmp",Av="ENOENT",Em="EEXIST",Iv=new Set(["EPERM","ENOTSUP","ENOSYS","EXDEV"]),Rv="locks",Ov=".lock";function mr(t){return t===X||t.startsWith(bv)}function _t(t){return t.filter((e)=>!mr(e))}function fr(t){if(Ue(ot(t,X)))return;throw new f("Ariadne is not initialised in this repository","Run 'ari init'")}function xm(){return $t(St)}function U(t){fr(t);let e=ot(t,et);if(!Ue(e))return An({});return An(fl(e,et,"Fix the JSON syntax of .ari/config.json"))}function dl(t){return ul.test(t)}function hr(t){if(dl(t))return t;throw new f(`"${t}" is not a task id`,"Task ids are lower-case words joined by hyphens; run 'ari list'")}function ut(t){return`${X}/${oi}/${hr(t)}${Sm}`}function Be(t){return`${X}/${oi}/${hr(t)}${$m}`}function pl(t){return`${X}/${wm}/${t}${cl}`}function de(t){return fr(t),ai(ot(t,X,oi),Sm)}function po(t){return fr(t),ai(ot(t,X,oi),$m)}function st(t,e,n){fr(t);let r=ot(t,ut(e));if(!Ue(r))throw new f(`Task "${e}" does not exist`,"Run 'ari list' to see the tasks of this repository");let o=uo(r,"utf8");return{contractText:o,task:{contract:Js(e,o,n),record:_n(t,e)}}}function pe(t,e){let n={invalid:[],tasks:[]};for(let r of de(t))try{n.tasks.push(st(t,r,e).task)}catch(o){if(!(o instanceof f))throw o;n.invalid.push({hint:o.hint??"",id:r,problem:o.message})}return n}function vm(t,e,n,r){let{id:o}=n,s=ut(o),i=()=>new f(`Task "${o}" already exists at ${s}`,"Run 'ari list'");il(_m(e,o),o,()=>{if(Ue(ot(t,s))||!Om(t,o))throw i();Am(t,n),jm(ot(t,s),r,i)})}function Cm(t){let e=de(t);return[...e,...po(t).filter((n)=>!e.includes(n)&&!Om(t,n))]}function Am(t,e){Nm(ot(t,Be(e.id)),$t(e))}function qt(t,e,n,r){return il(_m(e,n),n,()=>{let o=r(_n(t,n));return Am(t,o),o})}function Te(t){fr(t);let e=ot(t,X,wm);return ai(e,cl).map((n)=>{let r=pl(n),o=zs(uo(ot(t,r),"utf8"),r);if(o.name===n)return o;throw new f(`${r} declares the pack "${o.name}"`,`Rename the file to ${o.name}${cl} or fix its name`)})}function We(t){return fr(t),ai(ot(t,X,km),bm)}function Ve(t){return We(t).map((e)=>qs(e,uo(Pm(t,e),"utf8")))}function si(t,e){if(!ul.test(e.id))throw Error(`Knowledge entry id "${e.id}" is not a slug`);let n=Pm(t,e.id);jm(n,Ys(e),()=>Error(`Knowledge entry ${n} already exists`))}async function q(t){return an(t,Tv)}function dt(t){let e=ot(t,ll);if(!Ue(e))return null;let n=`Delete ${e}, then run 'ari next', which offers to adopt the task again`,r=fl(e,e,n);return wt("active task pointer",n,()=>{let o=R(r,"pointer",["since","task"]);return{since:I(o.since,"since"),task:I(o.task,"task")}})}function gl(t,e){Nm(ot(t,ll),$t(e))}function Im(t){ri(ot(t,ll),{force:!0})}function On(t,e){let n=ml(t,e.task);gm(hm(n),{recursive:!0});let r=JSON.stringify(JSON.parse($t(e)));kv(n,`${r}${Tm}`)}function ii(t,e){ri(ml(t,e),{force:!0})}function Rm(t,e){let n=ml(t,e);if(!Ue(n))return[];return uo(n,"utf8").split(Tm).flatMap((r)=>{if(r.trim().length===0)return[];let o=_v(r);return o===null||o.task!==e?[]:[o]})}function _v(t){try{return ni(JSON.parse(t))}catch(e){if(e instanceof SyntaxError||e instanceof x)return null;throw e}}function ml(t,e){return ot(t,Ev,`${hr(e)}${xv}`)}function _n(t,e){let n=Be(e),r=ot(t,n);if(!Ue(r))throw new f(`Task "${e}" has a contract but no record at ${n}`,`Restore ${n} from git; only ari writes it`);return dm(e,fl(r,n,`Restore ${n} from git; only ari writes it`))}function Om(t,e){if(!Ue(ot(t,Be(e))))return!0;try{return tm(_n(t,e))}catch(n){if(n instanceof f)return!1;throw n}}function _m(t,e){return ot(t,Rv,`${hr(e)}${Ov}`)}function Pm(t,e){return ot(t,X,km,`${e}${bm}`)}function fl(t,e,n){let r=uo(t,"utf8");try{return JSON.parse(r)}catch(o){let s=o instanceof Error?o.message:String(o);throw new f(`${e} is not valid JSON (${s})`,n)}}function ai(t,e){return Pv(t).filter((r)=>r.endsWith(e)).map((r)=>$v(r,e)).filter((r)=>ul.test(r)).sort(L)}function Pv(t){try{return Sv(t)}catch(e){if(e.code===Av)return[];throw e}}function Nm(t,e){let n=Mm(t);try{fm(n,e),mm(n,t)}catch(r){throw ri(n,{force:!0}),r}}function jm(t,e,n){let r=Mm(t);try{fm(r,e),Nv(r,t)}catch(o){if(o.code===Em)throw n();throw o}finally{ri(r,{force:!0})}}function Nv(t,e){try{wv(t,e)}catch(n){if(!Iv.has(n.code??""))throw n;if(Ue(e))throw Object.assign(Error(`${e} already exists`),{code:Em});mm(t,e)}}function Mm(t){let e=hm(t);return gm(e,{recursive:!0}),ot(e,`${vv}${yv()}${Cv}`)}async function ci(t){let e=U(t),n=await q(t),r={config:e,drift:null,root:t,state:n,task:null},o=dt(n)?.task??null;if(o===null)return r;if(!de(t).includes(o)){if(po(t).includes(o)&&Dm(_n(t,o)))throw jv(o);return r}let{contractText:s,task:i}=st(t,o,e);if(!Dm(i.record))return r;return{...r,drift:Mv(i,s),task:i}}function Dm({status:t}){return t==="active"||t==="blocked"}function jv(t){return new f(`the contract of the active task "${t}" is missing`,`Restore ${ut(t)}`)}function Mv({contract:t,record:e},n){if(e.contractHash===null||Fe(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 ${ut(t.id)}`}var Gm=".git",Bv="..",ui=0,Wv=1,Hm=128,Vv=40,Jv=["rev-parse","--show-toplevel","--absolute-git-dir","--git-common-dir"];function Km(){let t=new Map,e=new Map,n=new Map,r=[],o=(c)=>hl(t,c,()=>qv(c)),s=(c)=>hl(e,c.root,async()=>{let l=await Xv(c);return r.push(l),l}),i=async(c)=>{let l=[],u=null;for(let d of Um(c).filter((p)=>Lm(li(p,Gm)))){let p=await o(d);if(p===null)continue;if(u!==null&&await Yv(u,p))break;if(u=p,Lm(li(d,X)))l.push(await s(p))}return l},a=(c)=>{let l=Bm(bt(c));return hl(n,l,()=>i(l))};return{at:async(c)=>(await a(c))[0]??null,governing:a,opened:()=>r}}function bt(t,e=Vv){let n=kl(()=>Lv(t));if(n!==null)return n;let r=go(t);if(r===t)return t;let o=li(bt(r,e),Gv(t)),s=e>0?yl(o):null;return s===null?o:bt(Fm(go(o),s),e-1)}function yl(t){return kl(()=>Dv(t))}function di(t){return kl(()=>Fv(t).isDirectory())??!1}function Ee(t,e){let n=Kv(t,e),r=n.split(Uv);return r[0]===Bv||Hv(n)?null:r.join("/")}function kl(t){try{return t()}catch{return null}}function hl(t,e,n){let r=t.get(e);if(r!==void 0)return r;let o=n();return t.set(e,o),o}function Um(t){let e=go(t);return e===t?[t]:[t,...Um(e)]}function Bm(t){return di(t)||go(t)===t?t:Bm(go(t))}async function qv(t){let e=await O(t,Jv,{allowedExitCodes:[ui,Hm]});if(e.exitCode!==ui)return{fault:`git cannot read the repository at ${t}`,gitDirectories:[li(t,Gm)],root:t};let[n="",r="",o=""]=e.stdout.split(`
|
|
124
|
+
`);if(bt(n)!==t)return null;let s=[r,Fm(t,o)].map((i)=>bt(i));return{fault:null,gitDirectories:[...new Set(s)],root:t}}async function Yv(t,e){if(t.fault===null&&t.gitDirectories.at(-1)===e.gitDirectories.at(-1))return!0;if(e.fault!==null)return!1;return(await O(e.root,["check-ignore","-q","--",t.root],{allowedExitCodes:[ui,Wv,Hm]})).exitCode===ui}async function Xv({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 ci(n)}}catch(r){if(!(r instanceof f))throw r;return{fault:wl(r),gitDirectories:e,root:n,workspace:null}}}function wl({hint:t,message:e}){return t===void 0?e:`${e} (${t})`}var sC=2;function mo(t,e){let n=Y(t,e);return n===null?null:Mt(e,n)}function Y(t,e){let n=$l(t,e);return Sl(n)?Vm(n,"utf8"):null}function Mt(t,e){let n;try{n=JSON.parse(Gc(e))}catch(r){let o=r instanceof Error?r.message:String(r);throw new f(`${t} is not valid JSON (${o})`,`Fix ${t}, then run the command again`)}if(W(n))return n;throw new f(`${t} does not hold a JSON object`,`Fix ${t}, then run the command again`)}function pi(t,e,n){if(!Sl(t))return n;try{return e(JSON.parse(Vm(t,"utf8")))}catch{return n}}function fo(t,e,n){return Yt(t,e,Pn(Y(t,e),n))}function Pn(t,e){return t===null?`${JSON.stringify(e,null,sC)}
|
|
125
|
+
`:Ds(t,e)}function Yt(t,e,n){let r=$l(t,e),o=Y(t,e),s=bl(o,n);if(s!=="unchanged")Nn(r,n,iC(r));return s}function bl(t,e){if(t===e)return"unchanged";return t===null?"created":"updated"}function Nn(t,e,n){let r=bt(t);Qv(Wm(r),{recursive:!0});let o=$l(Wm(r),`.${oC(r)}.${process.pid}.${zv()}.tmp`);try{if(rC(o,e),n!==void 0)Zv(o,n);tC(o,r)}finally{eC(o,{force:!0})}}function iC(t){return Sl(t)?nC(t).mode:void 0}function W(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}var Tl="agents",Jm=1;function qm(t,e){let n=kg(e.preset),r=e.name??n.name,o=or(n,e.role,e.model),{agents:s,settings:i}=zm(t),a=s[r];if(a!==void 0&&aC(a,o))return{action:"unchanged",entry:o,name:r,preset:n.name};if(a!==void 0)throw new f(`agents.${r} already exists with other settings`,`Choose another name with --name, or run 'ari agents remove ${r}' first`,Jm,{tag:"AgentExists"});let c={...i,[Tl]:{...s,[r]:o}};return Zm(c,`ari cannot add agent "${r}"`,"Choose another name with --name"),{action:fo(t,et,c),entry:o,name:r,preset:n.name}}function Ym(t,e){let{agents:n,settings:r}=zm(t);if(n[e]===void 0)return{action:"unchanged",name:e};let{[e]:o,...s}=n,i={...r,[Tl]:s};return Zm(i,`ari cannot remove agent "${e}"`,`Change the routing and review settings that name "${e}" in ${et} first`),fo(t,et,i),{action:"removed",name:e}}function Xm(t){let e=U(t);return{agents:Object.entries(e.agents).sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>({command:o.command,env:o.env??[],model:o.model??null,modelFlag:o.modelFlag??null,name:r,reviewCommand:o.reviewCommand??null,roles:Cn(o),timeoutSeconds:o.timeoutSeconds??null})),routing:e.routing}}function gi(t){if(t===null)return"none";return t.model===null?t.agent:`${t.agent} (${t.model})`}function zm(t){U(t);let e=mo(t,et)??{},n=e[Tl]??{};return{agents:W(n)?n:{},settings:e}}function Zm(t,e,n){let r=Ms(t);if(r!==null)throw new f(`${e}: ${r}`,n,Jm,{tag:"InvalidConfig"})}var cC=" ";async function P(){return ir(process.cwd())}function jn(t){if(t===void 0)return[];return t.split(",").map((e)=>e.trim()).filter((e)=>e.length>0)}function un(t,e,n){if(t!==void 0&&t.trim().length>0)return t;throw new T(`${e} is required`,`Run ${n}`)}function xe(t,e){if(t===void 0||t.trim().length>0)return t;throw new T(`${e} must not be empty`,`Leave ${e} out, or give it a value`)}function mi(t){return t.flatMap((e)=>lC(e)).join(`
|
|
126
|
+
`)}function lC(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(`
|
|
127
|
+
`).map((s)=>`${cC}${s}`)]);return[e,...n,...r]}var uC=ie.map((t)=>t.name).join(", "),dC=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(Xm(await P()),fC)}}),pC=E({args:N({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: ${rr.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:rt({preset:{description:`Preset: ${uC}`,required:!0}}),run:async(t)=>{let e=qm(await P(),{model:xe(t.args.model,"--model"),name:xe(t.args.name,"--name"),preset:t.positionals.preset,role:wg(t.args.role)});t.output.result(e,tf)}}),gC=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:rt({name:{description:"Agent name in config.agents",required:!0}}),run:async(t)=>{t.output.result(Ym(await P(),t.positionals.name),tf)}}),mC=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 Sg()},({agents:e})=>e.map(hC).join(`
|
|
128
|
+
`))}}),Qm=E({description:"Configure the agents that 'ari run' and 'ari review' start",name:"agents",subcommands:[dC,pC,gC,mC]});function fC(t){let e=t.agents.map((a)=>{let c=a.model===null?"":`, model ${a.model}`;return`${a.name} ${a.roles.join("+")}${c}: ${a.command.join(" ")}`}),{default:n,review:r,stages:o}=t.routing,s=Object.entries(o).map(([a,c])=>` stage ${a}: ${gi(c)}`),i=[`routing default: ${gi(n)}`,...s,`routing review: ${gi(r)}`];return[...e.length===0?["No agents are configured; run 'ari agents add <preset>'"]:e,...i].join(`
|
|
129
|
+
`)}function tf(t){return`Agent "${t.name}" ${t.action} in .ari/config.json`}function hC(t){if(t.path===null)return`${t.preset} not found on PATH`;return`${t.preset} ${t.path} ${t.version??"version unknown"}`}var ef=1.2,nf=0.75,rf=0.5,yC=/[\p{Variation_Selector}\p{Me}]/gu,kC=/[\p{L}\p{N}][\p{L}\p{M}\p{N}]*/gu;function of(t){return t.normalize("NFC").toLowerCase().replace(yC,"").match(kC)??[]}function fi(t,e){let n=[...new Set(of(t))].sort(L),r=e.map(wC),o=r.reduce((a,c)=>a+c.length,0),s=r.length===0?0:o/r.length,i=new Map(n.map((a)=>[a,SC(a,r)]));return r.map((a)=>({id:a.id,score:$C(a,n,i,s)})).sort((a,c)=>c.score-a.score||L(a.id,c.id))}function wC(t){let e=of(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 SC(t,e){let n=e.filter((r)=>r.frequencies.has(t)).length;return Math.log(1+(e.length-n+rf)/(n+rf))}function $C(t,e,n,r){let o=r===0?1:t.length/r,s=ef*(1-nf+nf*o);return e.reduce((i,a)=>{let c=t.frequencies.get(a)??0,l=n.get(a)??0;return i+l*c*(ef+1)/(c+s)},0)}function pt(t){return Buffer.byteLength(t,"utf8")}function El(t){return Math.ceil(pt(t)/4)}import{readFileSync as IA}from"fs";import{join as _f}from"path";var bC=1000,TC=2147483647,EC=60,lf=8192,uf=lf*2,xC=1000,vC=`exec 2>&1
|
|
130
|
+
`,CC=192,AC=128,sf=`
|
|
131
|
+
`,IC=[126,127],af=128,RC=31;async function df(t,e){let n=performance.now(),r=Bun.spawn(["sh","-c",`${vC}${t}`],{cwd:e.cwd,detached:!0,env:{...process.env,...ne},stderr:"pipe",stdin:"ignore",stdout:"pipe"}),o=Wt(()=>xl(r.pid));try{return await OC(r,t,e,n)}finally{o()}}async function OC(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)=>_C(u,o))),a={timedOut:!1},c=setTimeout(()=>{a.timedOut=!0,xl(t.pid)},Math.min(n.timeoutSeconds*bC,TC));await t.exited,clearTimeout(c);let l=await PC(i,xC);if(xl(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:ff(o.window),timedOut:a.timedOut}}function pf(t){return t.exitCode===0&&!t.timedOut}function gf(t){return t.exitCode!==0&&!t.timedOut&&!vl(t)&&!Cl(t)}function vl(t){let{exitCode:e}=t;return e===null||e>af&&e<=af+RC}function Cl(t){return t.exitCode!==null&&!t.timedOut&&IC.includes(t.exitCode)}async function _C(t,e){for(;;){let{done:n,value:r}=await t.read();if(n)return;e.hasher.update(r),e.window=Al(NC(e.window,r),uf)}}async function PC(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 xl(t){re(t,"SIGKILL")}function mf(t){return ff(Al(new TextEncoder().encode(t),uf))}function ff(t){let n=new TextDecoder().decode(cf(t)).split(sf);if(n.at(-1)==="")n.pop();let r=new TextEncoder().encode(n.slice(-EC).join(sf));return new TextDecoder().decode(cf(Al(r,lf)))}function cf(t){let e=0;while(e<t.length&&((t[e]??0)&CC)===AC)e++;return t.subarray(e)}function Al(t,e){return t.length<=e?t:t.subarray(t.length-e)}function NC(t,e){let n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function nt(t,e,n,r=[],o=[]){return{checks:[...o],details:[...r],gate:t,ok:e,summary:n}}async function Dt(t,e,n){let r=[];for(let o of t){let s=await df(o.run,{cwd:n,timeoutSeconds:o.timeoutSeconds});r.push(jC(o.name,e,s))}return r}function jC(t,e,n){let r=e==="pass"?pf(n):gf(n);return{...n,expect:e,name:t,ok:r}}function Il(t){return`${t.name} should ${t.expect} but ${MC(t)}`}function Mn(t){return t.filter((e)=>!e.ok).map(Il)}function at(t,e,n){return t===1?e:n}function MC(t){if(t.timedOut)return`timed out after ${t.durationMs} ms`;if(Cl(t))return`could not run (exit code ${t.exitCode})`;if(!vl(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 JC,mkdirSync as qC,readlinkSync as YC,rmSync as Ol,symlinkSync as XC}from"fs";import{dirname as zC,join as yi}from"path";import{existsSync as DC,mkdtempSync as LC,readFileSync as FC,realpathSync as GC,rmSync as hf}from"fs";import{tmpdir as HC}from"os";import{join as Rl}from"path";var ho=0,yf=128,KC="ari-base-",UC="gitdir",BC=".git",WC=["-c","core.hooksPath=/dev/null"];async function hi(t,e,n){let r=GC(LC(Rl(HC(),KC))),o={admin:null,directory:r},s=Wt(()=>kf(t,o));try{return await VC(t,e,o),await n(r)}finally{kf(t,o),s()}}async function VC(t,e,n){let{directory:r}=n,o=await O(t,[...WC,"worktree","add","--detach",r,e],{allowedExitCodes:[ho,yf],env:{GIT_INDEX_FILE:void 0}});if(o.exitCode!==ho)throw Error(`git worktree add ${r} ${e} failed in ${t}: ${Uc(o.stderr)}`);let s=await O(r,["rev-parse","--absolute-git-dir"],{allowedExitCodes:[ho,yf],env:ne}),i=s.stdout.trim();if(s.exitCode===ho&&wf(i,r))n.admin=i}function kf(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(hf(r,{force:!0,recursive:!0}),o.exitCode===ho||n===null)return;if(wf(n,r))hf(n,{force:!0,recursive:!0})}function wf(t,e){let n=Rl(t,UC);return DC(n)&&FC(n,"utf8").trim()===Rl(e,BC)}var ZC="@base",QC=12;async function Sf(t){let e=t.contract.checks.filter((p)=>p.expect==="regression");if(e.length===0)return nt("regression",!1,"the contract has no check with expect: regression");let n=t.base.slice(0,QC),r=_t(t.changedFiles).filter((p)=>J(p,t.config.testGlobs)),o=await hi(t.root,t.base,(p)=>tA(t,e,r,p)),s=await Dt(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=[...Mn(i),...c],u=l.length===0,d=u?`every regression check fails on ${n} and passes on the working tree`:`${l.length} regression ${at(l.length,"problem","problems")} against ${n}`;return nt("regression",u,d,l,i)}async function tA(t,e,n,r){for(let i of n)nA(t.root,r,i);let o=await Dt(eA(t.config),"pass",r);if(o.some((i)=>!i.ok))return{checks:[],setup:o};let s=e.map((i)=>({...i,name:`${i.name}${ZC}`}));return{checks:await Dt(s,"fail",r),setup:o}}function eA(t){return t.regression.setup.map((e,n)=>({name:`setup[${n}]`,run:e,timeoutSeconds:t.checkTimeoutSeconds}))}function nA(t,e,n){let r=yi(t,n),o=yi(e,n),s=sr(t,n)?null:sn(r);if(s===null){rA(e,n);return}if(!s.isFile()&&!s.isSymbolicLink())return;if($f(e,n),Ol(o,{force:!0,recursive:!0}),s.isFile())JC(r,o);else XC(YC(r),o)}function rA(t,e){let n=yi(t,e);if(sr(t,e)||sn(n)?.isDirectory()!==!1)return;Ol(n,{force:!0})}function $f(t,e){let n=zC(e);if(n===".")return;$f(t,n);let r=yi(t,n),o=sn(r);if(o?.isDirectory())return;if(o!==null)Ol(r,{force:!0});qC(r)}import{readFileSync as bA}from"fs";import{join as TA}from"path";var oA=2,Dn=1,sA=5000,iA=1000,aA=2147483647,cA=1048576,lA=["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 Ln(t,e){let n=e.agent??e.route?.agent;if(n===void 0)throw new f(`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",Dn,{tag:"NoAgentChosen"});let r=t.agents[n];if(r===void 0)throw new f(`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`,Dn,{tag:"AgentNotConfigured"});if(!Cn(r).includes(e.role))throw new f(`Agent "${n}" is not configured as a ${e.role} agent`,`Add "${e.role}" to agents.${n}.roles in .ari/config.json`,Dn,{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 ki(i,""),i}function ki(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(Rt)))throw new f(`The command of agent "${o}" has no ${Rt} argument`,`Put ${Rt} where the agent takes its prompt in ${c}`,Dn,{tag:"AgentCommandInvalid"});let l=a.some((p)=>p.includes(oo));if(l&&r===null)throw new f(`Agent "${o}" needs a model for ${oo} in ${c}`,`Set agents.${o}.model, give a model in routing, or pass --model`,Dn,{tag:"AgentCommandInvalid"});if(!l&&r!==null&&n.modelFlag===void 0)throw new f(`Agent "${o}" has no way to take the model "${r}"`,`Put ${oo} in ${c}, or set agents.${o}.modelFlag`,Dn,{tag:"AgentCommandInvalid"});let u=a.map((p)=>p.replaceAll(Rt,()=>e).replaceAll(oo,()=>r??"")),d=!l&&r!==null&&n.modelFlag!==void 0?[n.modelFlag,r]:[];return[...u,...d]}function wi(t){if(t.env===void 0)return{...process.env,...ne};let e=[...lA,...t.env].filter((n)=>!(n in ne));return Object.fromEntries(e.flatMap((n)=>process.env[n]===void 0?[]:[[n,process.env[n]]]))}async function Si(t,e,n){let r=ki(t,e),o=uA(t.name,r,n),s=Wt(()=>bf(o)),i={timedOut:!1},a=n.timeoutSeconds??t.config.timeoutSeconds,c=a===void 0?void 0:setTimeout(()=>{i.timedOut=!0,bf(o)},Math.min(a*iA,aA)),l=n.stdout==="capture"?dA(o):Promise.resolve({overflowed:!1,text:""}),u=await o.exited;if(clearTimeout(c),cg())await new Promise(()=>{return});if(t.role==="review")re(o.pid,"SIGKILL");s();let{overflowed:d,text:p}=await l;return{exitCode:u,overflowed:d,stdout:p,timedOut:i.timedOut}}function uA(t,e,n){let r=n.stdout==="inherit"?"inherit":n.stdout==="capture"?"pipe":oA;try{return Bun.spawn(e,{cwd:n.cwd,detached:!0,env:n.environment,stderr:"inherit",stdin:"ignore",stdout:r})}catch(o){throw new f(`Agent "${t}" could not start: ${e[0]??""}`,`Fix agents.${t}.command in .ari/config.json`,Dn,{cause:o,tag:"AgentStartFailed"})}}async function dA(t){let e=t.stdout;if(!(e instanceof ReadableStream))return{overflowed:!1,text:""};let n=[],r=0,o=!1;for await(let s of e){if(r+s.length>cA){o=!0,re(t.pid,"SIGKILL");break}n.push(s),r+=s.length}return{overflowed:o,text:new TextDecoder().decode(Buffer.concat(n))}}async function bf(t){re(t.pid,"SIGTERM"),await Promise.race([t.exited,Bun.sleep(sA)]),re(t.pid,"SIGKILL")}var _l=["critical","major","minor","info"],pA=["critical","major"],gA=["pass","fail"],mA=["verdict","findings"],Tf=["severity","file","line","summary"],fA=/^```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```$/;function Ef(t){let e=t.trim();if(e.length===0)return{problem:"the review agent printed nothing",verdict:null};let n=fA.exec(e)?.[1]??e,r;try{r=JSON.parse(n)}catch{return{problem:"the review agent's answer is not one JSON object",verdict:null}}try{return{problem:null,verdict:hA(r)}}catch(o){if(o instanceof x)return{problem:`the review agent's answer: ${o.message}`,verdict:null};throw o}}function xf(t){return t.findings.filter((e)=>pA.includes(e.severity))}function $i(t){let e=t.file===null?"":` ${t.file}${t.line===null?"":`:${t.line}`}`;return`${t.severity}${e}: ${t.summary}`}function hA(t){let e=R(t,"verdict object",mA),n=z(gA,e.verdict,"verdict");return{findings:H(e.findings,"findings",yA),verdict:n}}function yA(t,e){let n=R(t,e,Tf);for(let r of Tf)if(!(r in n))throw new x(`${S(e,r)} is required`);return{file:n.file===null?null:it(n.file,S(e,"file")),line:n.line===null?null:se(n.line,S(e,"line")),severity:z(_l,n.severity,S(e,"severity")),summary:it(n.summary,S(e,"summary"))}}var kA=120000,wA=12,Pl=`
|
|
132
|
+
|
|
133
|
+
`,vf="```",SA='{"verdict":"fail","findings":[{"severity":"major","file":"src/a.ts","line":12,"summary":"\u2026"}]}';function Cf(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(`
|
|
134
|
+
`),["Answer with exactly one JSON object and nothing else, for example:",SA,'- "verdict" is "pass" when the change meets the contract and has no critical or major problem, otherwise "fail".',`- "severity" is one of ${_l.join(", ")}; "file" and "line" may be null; "findings" may be empty.`].join(`
|
|
135
|
+
`),`## Contract (${t.contractPath})
|
|
136
|
+
|
|
137
|
+
${t.contractText.trim()}`,[`## Files changed since ${t.base.slice(0,wA)}`,"",...t.changedFiles.length===0?["(none)"]:t.changedFiles.map((s)=>`- ${s}`)].join(`
|
|
138
|
+
`)].join(Pl),o=kA-Buffer.byteLength(r)-Pl.length*2;return[r,`## Diff
|
|
74
139
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
`)){if(a-=et(d)+1,a<0)break;c.push(d)}let l=c.flatMap((d,p)=>nx.test(d)?[p]:[]),u=l.length%2===0?c:c.slice(0,l.at(-1));return Cs(r,[u.join(`
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
`)
|
|
84
|
-
${t.replace(
|
|
85
|
-
|
|
86
|
-
`)
|
|
87
|
-
${m}`,Os)}let u=Ss((n.clock??Ax)()),d=new Set(oe(t)),p=[],f=[];for(let m of o.merges){let h=m.replace.map((b)=>i.get(b)).filter((b)=>b!==void 0),y=[...new Set(h.flatMap((b)=>b.sources))].sort(N),{id:x}=xs(t,m.entry,{created:u,sources:y,supersedes:[...m.replace]},d);p.push(...h.map((b)=>Ge(b,x))),f.push({id:x,kind:m.entry.kind,origin:"merge"})}for(let m of o.promotions){let h={created:u,sources:[m.task],supersedes:[]},{id:y}=xs(t,m.entry,h,d);f.push({id:y,kind:m.entry.kind,origin:"promotion"})}for(let m of o.archive){let h=i.get(m);if(h!==void 0)p.push(Ge(h,null))}for(let m of p)Es(t,m);for(let{notes:m,task:h}of o.promotions)Ot(t,s,h,(y)=>Eu(y,m));return{archived:p.map((m)=>({id:m.id,supersededBy:m.supersededBy})),created:f,promoted:o.promotions.map((m)=>({notes:[...m.notes],task:m.task}))}}function Rx(t,e){let n=e.flatMap((r)=>{let s=r.detail[an];return r.type==="context"&&Array.isArray(s)?s:[]});return cs(Su(t,n),e)}function Bn(t){return[...t.values()].filter((e)=>e.status==="active").sort((e,n)=>N(e.id,n.id))}function Wd(t){return t.reduce((e,n)=>e+et(n.text),0)}function Vd(t,e){return N(t.created,e.created)||N(t.id,e.id)}function Ix(t,e){let n=[],r=[];for(let s of Bn(t).filter((o)=>!He(o)).sort(Vd)){let o=n.find((i)=>i.kind===s.kind&&Yd(i.text,s.text,e.knowledge.duplicateSimilarity)>=e.knowledge.duplicateSimilarity);if(o===void 0){n.push(s);continue}t.set(s.id,Ge(s,o.id)),r.push({id:s.id,reason:"duplicate",supersededBy:o.id})}return r}function _x(t,e,n){let r=qd(e).slice(0,n.knowledge.decayAfterTasks);if(r.length<n.knowledge.decayAfterTasks)return[];let s=new Set(r.flatMap((i)=>Jd(i,t))),o=r.map((i)=>Ss(i.record.history[0]?.at??"")).sort(N)[0]??"";return Bn(t).flatMap((i)=>{if(!bx.includes(i.kind)||s.has(i.id))return[];if(N(i.created,o)>=0)return[];return t.set(i.id,Ge(i,null)),[{id:i.id,reason:"decay",supersededBy:null}]})}function Px(t,e,n){let r=new Map;for(let a of qd(e).flatMap((c)=>Jd(c,t)))r.set(a,(r.get(a)??0)+1);let s=Bn(t).filter((a)=>!He(a)).sort((a,c)=>(r.get(a.id)??0)-(r.get(c.id)??0)||Vd(a,c)),o=[],i=Wd(Bn(t));for(let a of s){if(i<=n.knowledge.maxBytes)break;t.set(a.id,Ge(a,null)),i-=et(a.text),o.push({id:a.id,reason:"budget",supersededBy:null})}return o}function Jd(t,e){return[...new Set(t.record.knowledgeUsed.map((n)=>Nx(n,e)))]}function Nx(t,e){let n=new Set([t]),r=t;for(;;){let s=e.get(r)?.supersededBy??null;if(s===null||n.has(s)||!e.has(s))return r;n.add(s),r=s}}function qd(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)=>N(e(r),e(n))||N(n.contract.id,r.contract.id))}function Yd(t,e,n){let r=ai(t),s=ai(e),o=Math.max(r.length,s.length);if(o>0&&Math.min(r.length,s.length)/o<n)return 0;return Kd(r,s)}function Dx(t,e){let n=new Map(t.map((i)=>[i.id,i.id])),r=new Map,s=(i)=>{let a=n.get(i)??i;return a===i?i:s(a)};t.forEach((i,a)=>{for(let c of t.slice(a+1)){let l=Yd(i.text,c.text,e.knowledge.mergeSimilarity);if(l<e.knowledge.mergeSimilarity)continue;let[u,d]=[s(i.id),s(c.id)].sort(N);n.set(d,u),r.set(u,Math.max(r.get(u)??0,r.get(d)??0,l))}});let o=new Map;for(let i of t){let a=s(i.id);o.set(a,[...o.get(a)??[],i.id])}return[...o.entries()].filter(([,i])=>i.length>1).map(([i,a])=>({ids:a,similarity:Mx(r.get(i)??0)})).sort((i,a)=>N(i.ids[0]??"",a.ids[0]??""))}function jx(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 Lx(t,e){let n=t.filter((r)=>r.kind==="decision");return n.flatMap((r,s)=>n.slice(s+1).filter((o)=>vs(r.scope,o.scope,e)).map((o)=>({ids:[r.id,o.id]})))}function Mx(t){let e=10**xx;return Math.round(t*e)/e}function Gx(t,e){let n=I(t,"proposal",Sx);return{archive:J(n.archive,[],(r)=>U(r,"archive",E)),merges:J(n.merges,[],(r)=>U(r,"merges",(s,o)=>{let i=I(s,o,Ex);return{entry:Ud(i.entry,`${o}.entry`,e),replace:ht(i.replace,`${o}.replace`,(a,c)=>U(a,c,E))}})),promotions:J(n.promotions,[],(r)=>U(r,"promotions",(s,o)=>{let i=I(s,o,Tx);return{entry:Ud(i.entry,`${o}.entry`,e),notes:ht(i.notes,`${o}.notes`,(a,c)=>U(a,c,At)),task:ht(i.task,`${o}.task`,E)}}))}}function Ud(t,e,n){let r=ht(t,e,(s,o)=>I(s,o,vx));return _i({kind:r.kind,scope:r.scope??[],text:r.text},e,n)}function Hx(t,e,n,r){let s=[],o=new Map,i=(c,l)=>{let u=e.get(c),d=o.get(c);if(u===void 0)s.push(`${l} names the unknown entry "${c}"`);else if(u.status!=="active")s.push(`${l} names the archived entry "${c}"`);else if(He(u)&&!r)s.push(`${l} retires the ${u.kind} "${c}"; pass --force to retire ${u.kind} entries`);if(d!==void 0)s.push(`${l} names "${c}", which ${d} already retires`);o.set(c,l)};t.merges.forEach((c,l)=>{if(c.replace.length<Cx)s.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){s.push(`${u}.task names the unknown or unreadable task "${c.task}"`);return}if(c.notes.length===0)s.push(`${u}.notes is empty`);let p=a.get(c.task)??new Set;for(let f of c.notes){let m=d.notes[f];if(m===void 0)s.push(`${u}.notes names note ${f}, but "${c.task}" has none`);else if(m.promoted)s.push(`${u}.notes names note ${f}, which is already promoted`);if(p.has(f))s.push(`${u}.notes names note ${f} of "${c.task}" twice`);p.add(f)}a.set(c.task,p)}),s}function Rs(t,e){let n=new Set,r=(s,o)=>{for(let i of e(s)){if(i===t)return[...o,t];if(n.has(i))continue;n.add(i);let a=r(i,[...o,i]);if(a)return a}return null};return r(t,[t])}function Is(t){return`depends forms a cycle: ${t.join(" -> ")}`}var Fx=["ari check","ari done"],Kx=["ari next"],Ux='ari new "<title>"',Xd=["active","blocked"];function Hi(t){let e=[...t.tasks].sort((u,d)=>N(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 Bx(n,t.packs);if(n?.record.status==="blocked")return Wx(n,t.packs);let r=e.filter((u)=>!t.claimed.has(u.contract.id)),o=r.filter((u)=>Xd.includes(u.record.status)).find((u)=>Ki(u,t.packs)===null);if(o)return Vx(o,t.packs);let i=Xx(r,t),a=Zx(e,r.filter((u)=>!i.has(u.contract.id)));if(a)return qx(a,t.packs);let c=zx(e,r,t,i);if(c)return Jx(c);let l=e.find((u)=>u.record.status==="draft");if(l)return Yx(l);return{action:"new",commands:[Ux],instruction:"Create a task and write its contract: scope, criteria and checks.",stage:null,task:null}}function Bx(t,e){let n=Fi(t,e);return{action:"continue",commands:[...Fx],instruction:on(n,t.contract.id),stage:n.name,task:t.contract.id}}function Wx(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:Fi(t,e).name,task:t.contract.id}}function Vx(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:Fi(t,e).name,task:t.contract.id}}function Jx(t){return{action:"fix",commands:[...Kx],instruction:t.instruction,stage:null,task:t.id}}function qx(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 Yx(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 Fi(t,e){let n=Ki(t,e);if(n!==null)throw new g(n.message,n.hint);let r=e.find((s)=>s.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 Ki(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 Xx(t,{packs:e,uncoveredLocks:n}){let s=t.filter((o)=>o.record.status==="ready").map((o)=>{let i=n.get(o.contract.id),a=i===void 0?[]:[`lock glob ${JSON.stringify(i)} matches no file that git tracks or would track`];return[o.contract.id,[...rn(o.contract,e),...a]]});return new Map(s.filter(([,o])=>o.length>0))}function zx(t,e,{invalid:n,packs:r},s){let o=new Map(t.map((p)=>[p.contract.id,p])),i=new Set(n.map((p)=>p.id)),a=(p)=>o.get(p)?.contract.depends??[],c=e.filter((p)=>p.record.status==="ready").flatMap((p)=>{let f=p.contract.id,m=p.contract.depends.find((y)=>!o.has(y)&&!i.has(y));if(m!==void 0)return[{id:f,instruction:`depends names the unknown task "${m}". Fix the depends of .ari/tasks/${f}.md`}];let h=Rs(f,a);return h?[{id:f,instruction:`${Is(h)}. Remove one of these dependencies`}]:[]}),l=[...s].map(([p,f])=>({id:p,instruction:`The contract can no longer start: ${f.join("; ")}. Fix .ari/tasks/${p}.md`})),u=e.filter((p)=>Xd.includes(p.record.status)).flatMap((p)=>{let f=Ki(p,r);return f===null?[]:[{id:p.contract.id,instruction:`${f.message}. ${f.hint}`}]});return[...n.map((p)=>({id:p.id,instruction:`${p.problem}. ${p.hint}`})),...u,...l,...c].sort((p,f)=>N(p.id,f.id))[0]}function Zx(t,e){let n=new Map(t.map((i)=>[i.contract.id,i])),r=new Map,s=(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)=>s(p,u)))+1;return r.set(i,d),d};for(let i of t)s(i.contract.id,new Set);let o=(i)=>i.contract.depends.every((a)=>n.get(a)?.record.status==="done");return e.filter((i)=>i.record.status==="ready"&&o(i)).sort((i,a)=>(r.get(i.contract.id)??0)-(r.get(a.contract.id)??0)||N(i.contract.id,a.contract.id))[0]}import{realpathSync as Qx}from"fs";import{resolve as tS}from"path";var eS="ENOENT";async function Ui(t){let e=zd(t),n=new Map;for(let r of await Jl(t)){if(zd(r)===e)continue;let s=nS(await tt(r));if(s!==null&&!n.has(s.task))n.set(s.task,r)}return n}function nS(t){try{return it(t)}catch(e){if(e instanceof g)return null;throw e}}function zd(t){try{return Qx(t)}catch(e){if(e.code===eS)return tS(t);throw e}}var rS=8,sS=6,oS=10,Zd=`
|
|
140
|
+
${vf}diff
|
|
141
|
+
${$A(t.diff,o)}
|
|
142
|
+
${vf}`].join(Pl)}function $A(t,e){let n=Buffer.from(t.trimEnd());if(n.length<=e)return n.toString();let r=`
|
|
143
|
+
[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 EA={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"},Af=["--no-color","--no-ext-diff","--no-textconv","--no-renames"],If=[":(glob,exclude).ari/tasks/*.json",":(glob,exclude).ari/knowledge/**"],xA="review:",vA=1;async function Rf(t){let{config:e,root:n,task:r}=t,{agent:o,model:s}=e.review,i=Ln(e,{agent:o,model:s,role:"review",route:null}),a=bA(TA(n,ut(r.contract.id)),"utf8"),c=await Nl({...t,contractText:a},i),l=c.ok?"passed":"failed",u=[...c.problems,...c.findings.map($i)],d=`the review agent ${c.agent} ${l} the change`;return nt("review",c.ok,d,u,[c.evidence])}async function Nl(t,e){let{config:n,root:r,task:o}=t,s=AA(o),i=await Se(r,[]),a=await CA(r,i,s,o.contract.id),c=ae((await O(r,["diff","--name-only","-z",...Af,s,a,"--",".",...If])).stdout),l=(await O(r,["diff",...Af,s,a,"--",".",...If])).stdout,u=Cf({base:s,changedFiles:c,contract:o.contract,contractPath:ut(o.contract.id),contractText:t.contractText,diff:l,stage:t.stage}),d=e.config.timeoutSeconds??n.checkTimeoutSeconds,p=performance.now(),g=await hi(r,a,async(M)=>{let A=await Si(e,u,{cwd:M,environment:wi(e.config),stdout:"capture",timeoutSeconds:d});return{copyChanged:await Se(M,[])!==i,ran:A}}),m=Math.round(performance.now()-p),h=await Se(r,[])!==i,{ran:w}=g,b=Ef(w.stdout),v=b.verdict===null?[]:xf(b.verdict),B=[...w.timedOut?[`the review agent did not finish within ${d} seconds`]:[],...!w.timedOut&&w.exitCode!==0?[`the review agent exited with ${w.exitCode}`]:[],...w.overflowed?["the review agent printed more than 1 MiB"]:[],...g.copyChanged?["the review agent changed files in its copy of the repository"]:[],...h?["the working tree changed while the review ran"]:[],...b.problem===null?[]:[b.problem],...b.verdict?.verdict==="pass"&&v.length>0?[`the verdict is pass, but ${v.length} finding(s) are critical or major`]:[]],K=B.length===0&&b.verdict?.verdict==="pass",_={command:ki(e,Rt).join(" "),durationMs:m,exitCode:w.timedOut?null:w.exitCode,expect:"pass",name:`${xA}${e.name}`,ok:K,outputSha256:xt(w.stdout),outputTail:mf(w.stdout),timedOut:w.timedOut};return{agent:e.name,durationMs:m,evidence:_,exitCode:w.exitCode,findings:b.verdict?.findings??[],model:e.model,ok:K,problems:B,timedOut:w.timedOut,verdict:b.verdict?.verdict??null}}async function CA(t,e,n,r){let o=`ari review snapshot of ${r}`;return(await O(t,["commit-tree","--no-gpg-sign",e,"-p",n,"-m",o],{env:EA})).stdout.trim()}function AA(t){if(t.record.base!==null)return t.record.base;throw new f(`Task "${t.contract.id}" has not started, so it has no change to review`,`Run 'ari start ${t.contract.id}' first`,vA,{tag:"TaskNotStarted"})}var RA="{id}",OA=[".ari/tasks/**",".ari/knowledge/**"];async function Ml(t){let e=Je(t.task,t.pack),r={...t,changedFiles:()=>Jt(t.root,jf(t.task)),stage:e},o=[],s=[];for(let[i,a]of e.gates.entries()){let c=await _A(a,r);if(o.push(c),c.ok&&GA(a)&&i<e.gates.length-1)s.push({index:i,result:await HA(a.kind,c,r)})}for(let i of s)o[i.index]=await i.result();return o}function Je(t,e){let n=e.stages[t.record.stage];if(n)return n;throw new f(`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 yo(t,e,n){let r=await Le(t,e.testGlobs);return Object.fromEntries(Object.entries(r).filter(([o])=>!mr(o)&&J(o,n.scope)))}async function Dl(t,e,n){let o=e.gates.flatMap((s)=>s.kind==="artifact"?[Pf(s.path,n)]:[]).flatMap((s)=>{let i=_f(t,s);return Hc(i)?.isFile()?[[s,xt(IA(i))]]:[]});return{artifactHashes:Object.fromEntries(o),treeHash:await Se(t,OA)}}function ko(t,e){return[...new Set([...Object.keys(t),...Object.keys(e)])].sort(L).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 _A(t,e){switch(t.kind){case"criteria":return PA(e.task.contract);case"checks":return NA(t.select,t.expect,e);case"invariants":return jA(e);case"scope":return MA(e);case"locked":return DA(e);case"tests-unchanged":return LA(e);case"regression":return Sf({base:jf(e.task),changedFiles:await e.changedFiles(),config:e.config,contract:e.task.contract,root:e.root});case"artifact":return FA(t.path,t.minBytes,e);case"approval":return Ll("approval",e);case"review":return KA(e);case"command":return UA(t.run,e)}}function PA(t){let e=Zc(t),n=e.length===0?`${t.criteria.length} ${at(t.criteria.length,"criterion","criteria")} bound to existing checks`:`${e.length} criteria ${at(e.length,"problem","problems")}`;return nt("criteria",e.length===0,n,e)}async function NA(t,e,n){let r=dr(n.task.contract,t);if(r.length===0)return nt("checks",!1,`no check matches the selection "${t}"`);let o=await Dt(r,e,n.root),s=Mn(o),i=e==="pass"?"passed":"failed as expected",a=`${o.length-s.length} of ${o.length} ${at(o.length,"check","checks")} ${i}`;return nt("checks",s.length===0,a,s,o)}async function jA(t){let e=t.task.contract.invariants.map((s,i)=>({name:`invariants[${i}]`,run:s,timeoutSeconds:t.config.checkTimeoutSeconds})),n=await Dt(e,"pass",t.root),r=Mn(n),o=`${n.length-r.length} of ${n.length} ${at(n.length,"invariant","invariants")} passed`;return nt("invariants",r.length===0,o,r,n)}async function MA(t){let e=_t(await t.changedFiles()),n=e.filter((o)=>!J(o,t.task.contract.scope)),r=n.length===0?`${e.length} changed ${at(e.length,"file","files")} inside the scope`:`${n.length} of ${e.length} changed ${at(e.length,"file","files")} outside the scope`;return nt("scope",n.length===0,r,n)}async function DA(t){let e=await Le(t.root,t.task.contract.lock),n=ko(t.task.record.lockHashes,e),r=Object.keys(t.task.record.lockHashes).length,o=n.length===0?`${r} locked ${at(r,"file","files")} unchanged`:`${n.length} locked ${at(n.length,"file","files")} changed`;return nt("locked",n.length===0,o,n)}async function LA(t){let e=await yo(t.root,t.config,t.task.contract),n=ko(t.task.record.stageTestHashes,e),r=Object.keys(t.task.record.stageTestHashes).length,o=n.length===0?`${r} test ${at(r,"file","files")} unchanged since the stage started`:`${n.length} test ${at(n.length,"file","files")} changed since the stage started`;return nt("tests-unchanged",n.length===0,o,n)}function FA(t,e,n){let r=Pf(t,n.task.contract.id),o=Hc(_f(n.root,r));if(!o?.isFile())return nt("artifact",!1,`${r} does not exist`);let s=o.size>=e,i=s?`${r} has ${o.size} bytes`:`${r} has ${o.size} bytes; it needs at least ${e}`;return nt("artifact",s,i)}function Pf(t,e){return t.replaceAll(RA,e)}function GA(t){return t.kind==="approval"||t.kind==="review"}async function HA(t,e,n){let{agent:r,command:o}=n.config.review;if(t==="approval"||o===null&&r===void 0)return()=>Ll(t,n);let s=await jl(n);return async()=>{if(Nf(s,await jl(n)))return e;return nt(t,!1,"the working tree changed while the gates after the review ran",[],e.checks)}}function jl(t){return Dl(t.root,t.stage,t.task.contract.id)}function Nf(t,e){return t.treeHash===e.treeHash&&ko(t.artifactHashes,e.artifactHashes).length===0}async function Ll(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 nt(t,!1,`stage ${n} has no approval; ${r}`);let s=await jl(e),i=o.filter((c)=>Nf(c,s));if(i.length>0)return nt(t,!0,`stage ${n} approved by ${Of(i)}`);let a=`the working tree changed after ${Of(o)} approved stage ${n}`;return nt(t,!1,`${a}; ${r} again`)}function Of(t){return[...new Set(t.map((e)=>e.by))].join(", ")}async function KA(t){let{agent:e,command:n}=t.config.review;if(e!==void 0){let{config:a,root:c,stage:l,task:u}=t;return Rf({config:a,root:c,stage:l.name,task:u})}if(n===null)return Ll("review",t);let r={name:"review",run:n,timeoutSeconds:t.config.checkTimeoutSeconds},o=await Dt([r],"pass",t.root),s=Mn(o),i=s.length===0?"the review command passed":"the review command failed";return nt("review",s.length===0,i,s,o)}async function UA(t,e){let n={name:"command",run:t,timeoutSeconds:e.config.checkTimeoutSeconds},r=await Dt([n],"pass",e.root),o=Mn(r),s=o.length===0?`${t} passed`:`${t} failed`;return nt("command",o.length===0,s,o,r)}function jf(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 BA,existsSync as WA,fstatSync as VA,openSync as JA,readSync as qA}from"fs";import{join as YA}from"path";var XA="journal",zA=".jsonl",Mf=65536,ZA=1000,bi=10;function Ti(t,e,n){let r=[];if(n===0)return r;for(let o of tI(Lf(t,e))){let s=Ff(o,e);if(s!==null)r.push(s);if(r.length===n)break}return r.reverse()}function*Df(t,e){let n=[];for(let r of QA(Lf(t,e))){let o=Ff(r,e);if(o===null)continue;if(n.push(o),n.length<ZA)continue;yield n,n=[]}if(n.length>0)yield n}function Lf(t,e){return YA(t,XA,`${hr(e)}${zA}`)}function Ff(t,e){try{let n=ni(JSON.parse(t.toString("utf8")));return n.task===e?n:null}catch(n){if(n instanceof SyntaxError||n instanceof x)return null;throw n}}function*QA(t){let e=[];for(let n of Gf(t,!1)){let r=0;for(let o=n.indexOf(bi);o!==-1;o=n.indexOf(bi,r))yield Buffer.concat([...e,n.subarray(r,o)]),e=[],r=o+1;e.push(n.subarray(r))}yield Buffer.concat(e)}function*tI(t){let e=[];for(let n of Gf(t,!0)){let r=n.length;for(let o=n.lastIndexOf(bi);o!==-1;o=o===0?-1:n.lastIndexOf(bi,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*Gf(t,e){if(!WA(t))return;let n=JA(t,"r");try{let{size:r}=VA(n);for(let o=0;o<r;o+=Mf){let s=Math.min(Mf,r-o),i=Buffer.alloc(s),a=qA(n,i,0,s,e?r-o-s:o);yield i.subarray(0,a)}}finally{BA(n)}}import{randomUUID as iI}from"crypto";import{mkdirSync as aI,readFileSync as cI,renameSync as lI,rmSync as uI,writeFileSync as dI}from"fs";import{basename as pI,dirname as Hf,join as Kf}from"path";var eI=/\p{M}+/gu,nI=/[\u00DF\u00E6\u0111\u00F0\u0127\u0131\u0142\u0153\u00F8\u00FE]/g,rI=/[^a-z0-9]+/,oI={\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 wo(t,e){if(!Number.isInteger(e)||e<=0)throw Error(`slugify needs a positive maxWords, got ${e}`);let r=t.toLowerCase().normalize("NFKD").replace(eI,"").replace(nI,(o)=>oI[o]??"").split(rI).filter((o)=>o.length>0).slice(0,e).join("-");return sI(r)}function sI(t){if(t.length<=64)return t;let e=t.lastIndexOf("-",64);return e>0?t.slice(0,e):t.slice(0,64)}function So(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 gI=["constraint","decision"],mI=6,fI=10,hI="knowledge",yI=".md",kI=4,wI="\x00",SI=",",$I={"[":"]","{":"}"},bI="\\",TI=()=>new Date().toISOString();function Fl(t,e,n){let r=it(t.text,`${e}.text`).trim(),o=pt(r);if(o>n)throw new x(`${e}.text is ${o} bytes, but a knowledge entry holds at most ${n}`);return{kind:z(ce,t.kind,`${e}.kind`),scope:Ns(t.scope,`${e}.scope`),text:r}}function Uf(t){return ce.includes(t)}function EI(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 xI(t,e){let n=wo(t.text,mI),r=So(n.length>0?n:t.kind,e);return e.add(r),r}function Ei(t,e,n,r){for(;;){let o=EI(e,{...n,id:xI(e,r)});try{return si(t,o),o}catch(s){if(!We(t).includes(o.id))throw s}}}function Fn(t,e){return{...t,status:"archived",supersededBy:e}}function Gn(t){return gI.includes(t.kind)}function xi(t){return t.slice(0,fI)}function vi(t,e){let n=Xf(t,e.id),r=Kf(Hf(n),`.${pI(n)}.${process.pid}.${iI()}.tmp`);aI(Hf(n),{recursive:!0});try{dI(r,Ys(e)),lI(r,n)}catch(o){throw uI(r,{force:!0}),o}}function vI(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 Ci(t){let e=await O(t,["ls-files","--cached","--others","--exclude-standard","-z"]);return _t([...new Set(e.stdout.split(wI).filter((n)=>n.length>0))])}function Ai(t,e,n){if(t.length===0||e.length===0)return!0;return t.some((o)=>e.some((s)=>o===s||J(o,[s])||J(s,[o])))||n.some((o)=>J(o,t)&&J(o,e))}function Bf(t){let e=[],n=[],r="";for(let o=0;o<t.length;o++){let s=t[o]??"";if(s===bI){r+=t.slice(o,o+2),o++;continue}let i=$I[s];if(i!==void 0)n.push(i);else if(s===n.at(-1))n.pop();if(s===SI&&n.length===0){e.push(r.trim()),r="";continue}r+=s}return e.push(r.trim()),e.filter((o)=>o.length>0)}function CI(t,e,n={}){let r=U(t),o=wt("note","Shorten the text or fix the --kind and --scope values",()=>Fl(e,"note",r.knowledge.maxEntryBytes)),i={created:xi((n.clock??TI)()),sources:[...n.sources??[]],supersedes:[]};return Ei(t,o,i,new Set(We(t)))}async function Wf(t,e,n={}){U(t);let r=dt(await q(t))?.task,o=r!==void 0&&de(t).includes(r)?[r]:[];return CI(t,e,{...n,sources:o})}function Gl(t,e={}){return U(t),{entries:Ve(t).filter((r)=>e.all===!0||r.status==="active")}}function Vf(t,e,n={}){let{entries:r}=Gl(t,n),o=new Map(r.map((a)=>[a.id,a]));return{matches:fi(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:AI(c)}]}),query:e}}function Jf(t,e,n){return{entry:Yf(t,e),uses:vI(n).get(e)??0}}function qf(t,e,n={}){let r=Yf(t,e);if(r.status==="archived")throw new f(`Knowledge entry "${e}" is already archived`,"Run 'ari knowledge list' to see the active entries");if(Gn(r)&&n.force!==!0)throw new f(`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=Fn(r,null);return vi(t,o),o}function Yf(t,e){if(U(t),We(t).includes(e))return qs(e,cI(Xf(t,e),"utf8"));throw new f(`Knowledge entry "${e}" does not exist`,"Run 'ari knowledge list --all' to see every entry")}function Xf(t,e){return Kf(t,X,hI,`${e}${yI}`)}function AI(t){let e=10**kI;return Math.round(t*e)/e}var II=4,Xt=`
|
|
144
|
+
|
|
145
|
+
`,nh=`
|
|
146
|
+
`,RI=3,OI=/`+/g,_I=/^ {0,3}(?:```|~~~)/,PI=/\n+$/,NI=/\n/g,rh=`
|
|
147
|
+
`,Bl="none",zf={constraint:0,decision:1},Wl={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"}},jI=["failure","rules","notes","knowledge","journal"],MI=/y$/,DI=()=>new Date().toISOString();async function yr(t,e={}){let n=U(t),r=await q(t),o=e.id??LI(r),s=e.budget??n.context.budget,{task:i}=st(t,o,n),a=Ve(t).filter((g)=>g.status==="active"),c=(await Ci(t)).filter((g)=>J(g,i.contract.scope)),l=HI(t,i),u=KI(i),d=[...UI(i.record.lastFailure),...BI(i,a,c),...WI(i.record.notes),...VI(i,a,c),...JI(Ti(r,o,n.context.journalTail))],p=FI(o,s,l,u,d);if(i.record.status!=="done"){let g=(e.clock??DI)(),m={[gr]:p.knowledge,tokens:p.estimatedTokens};On(r,{at:g,detail:m,task:o,type:"context"})}return p}function LI(t){let e=dt(t);if(e!==null)return e.task;throw new f("No task is active in this worktree","Pass a task id: ari context <id>")}function FI(t,e,n,r,o){let s=e*II,i=[n,Ii(r.fields,r.body)],a=Zf(o,pt(i.join(Xt)),Number.POSITIVE_INFINITY),c=pt(Qf(i,a.sections,null))<=s,l=pt(`${Xt}${eh(e,th(o))}`),u=c?i:[n,GI(t,n,r,s-l)],d=u.join(Xt),p=c?a:Zf(o,pt(d)+l,s),g=th(p.omitted),m=Qf(u,p.sections,g.length===0?null:eh(e,g)),h=[Hl("task",u[0]??"",1),Hl("contract",u[1]??"",1),...p.sections.map((w)=>Hl(w.name,oh(w),w.items.length))];return{budget:e,estimatedTokens:El(m),knowledge:p.sections.flatMap((w)=>w.knowledge),omitted:g,sections:h,sha256:xt(m),task:t,text:m}}function GI(t,e,{body:n,fields:r},o){let s=Ii(r,n);if(pt([e,s].join(Xt))<=o)return s;let i=`_The contract body is shortened to fit the budget; read ${ut(t)}._`,a=o-pt([e,Ii(r,i)].join(Xt))-Xt.length,c=[];for(let d of n.split(`
|
|
148
|
+
`)){if(a-=pt(d)+1,a<0)break;c.push(d)}let l=c.flatMap((d,p)=>_I.test(d)?[p]:[]),u=l.length%2===0?c:c.slice(0,l.at(-1));return Ii(r,[u.join(`
|
|
149
|
+
`).trim(),i].filter((d)=>d.length>0).join(Xt))}function Ii(t,e){return e.length===0?t:`${t}${Xt}${e}`}function Zf(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?nh:`${Xt}${Vl(i.section)}${Xt}`,u=pt(l)+pt(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 Qf(t,e,n){return[...[...t,...e.map(oh)],...n===null?[]:[n]].join(Xt)}function oh(t){return`${Vl(t.name)}${Xt}${t.items.join(nh)}`}function Vl(t){return`## ${Wl[t].title}`}function Hl(t,e,n){return{estimatedTokens:El(e),items:n,name:t,text:e,title:Wl[t].title}}function th(t){return jI.flatMap((e)=>{let n=t.filter((r)=>r.section===e).length;return n===0?[]:[{count:n,section:e}]})}function eh(t,e){let n=e.map(({count:r,section:o})=>{let{unit:s}=Wl[o];return`${r} ${r===1?s:`${s.replace(MI,"ie")}s`}`});return`_Omitted to fit the budget of ${t} tokens: ${n.join(", ")}._`}function HI(t,e){let{contract:n,record:r}=e,o=In(n.pack,Te(t)),s=Je(e,o);return[`# ${n.id}: ${n.title}`,"",`- Status: ${r.status}`,`- Pack: ${o.name}`,`- Stage: ${s.name} (${r.stage+1} of ${o.stages.length})`,`- Instruction: ${dn(pr(s,n.id))}`,...r.question===null?[]:[`- Question: ${dn(r.question)}`]].join(`
|
|
150
|
+
`)}function KI(t){let{contract:e}=t,n=e.criteria.map((i)=>{let a=i.checks.length===0?Bl:i.checks.join(", ");return`- ${i.id}: ${dn(i.text)} (checks: ${a})`}),r=e.checks.map((i)=>`- ${i.name} (expect ${i.expect}, timeout ${i.timeoutSeconds}s): ${Ri(i.run)}`),o=e.invariants.map((i)=>`- ${Ri(i)}`),s=[Vl("contract"),"",`Scope: ${Ul(e.scope)}`,`Lock: ${Ul(e.lock)}`,...Kl("Criteria:",n),...Kl("Checks:",r),...Kl("Invariants:",o)];return{body:e.body.trim(),fields:s.join(`
|
|
151
|
+
`)}}function Kl(t,e){return e.length===0?[`${t} ${Bl}`]:[t,...e]}function UI(t){if(t===null)return[];let e=t.gates.filter((r)=>!r.ok).flatMap((r)=>[`- ${r.gate}: ${dn(r.summary)}`,...r.details.map((o)=>` - ${dn(o)}`),...r.checks.filter((o)=>!o.ok&&o.outputTail.length>0).map((o)=>` ${o.name} output:${rh}${dn(qI(o.outputTail))}`)]);return[{knowledgeId:null,section:"failure",text:[`Stage ${t.stage} at ${t.at}:`,...e].join(`
|
|
152
|
+
`)}]}function BI(t,e,n){return sh(t,e,n).sort((r,o)=>(zf[r.kind]??0)-(zf[o.kind]??0)).map((r)=>ih("rules",r))}function sh(t,e,n){return e.filter((r)=>Gn(r)&&Ai(r.scope,t.contract.scope,n))}function WI(t){return t.map((e,n)=>({index:n,note:e})).sort((e,n)=>L(n.note.at,e.note.at)||n.index-e.index).map(({note:e})=>({knowledgeId:null,section:"notes",text:`- ${e.at}: ${dn(e.text)}`}))}function VI(t,e,n){let r=new Set(sh(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(`
|
|
153
|
+
`);return fi(a,o.map((l)=>({id:l.id,text:l.text}))).flatMap(({id:l})=>{let u=s.get(l);return u===void 0?[]:[ih("knowledge",u)]})}function ih(t,e){let n=e.scope.length===0?"":` (scope: ${Ul(e.scope)})`;return{knowledgeId:e.id,section:t,text:`- ${e.kind} ${Ri(e.id)}${n}: ${dn(e.text)}`}}function JI(t){return t.map((e)=>({knowledgeId:null,section:"journal",text:`- ${e.at} ${e.type} ${JSON.stringify(JSON.parse($t(e.detail)))}`}))}function Ul(t){return t.length===0?Bl:t.map(Ri).join(", ")}function Ri(t){let e="`".repeat(ah(t)+1),n=t.startsWith("`")||t.endsWith("`")?" ":"";return`${e}${n}${t}${n}${e}`}function qI(t){let e="`".repeat(Math.max(RI,ah(t)+1));return`${e}
|
|
154
|
+
${t.replace(PI,"")}
|
|
155
|
+
${e}`}function ah(t){return Math.max(0,...[...t.matchAll(OI)].map((e)=>e[0].length))}function dn(t){return t.replace(NI,rh)}import{existsSync as YI,readFileSync as XI}from"fs";function ch(t,e){let n=Math.max(t.length,e.length);return n===0?1:1-hc(t,e)/n}var zI=["fact","pattern","gotcha"],ZI=3,QI=["merges","promotions","archive"],tR=["replace","entry"],eR=["task","notes","entry"],nR=["kind","scope","text"],Oi="Fix the proposal file, then run 'ari sleep --apply <file>' again",rR=1,oR=()=>new Date().toISOString();async function kr(t){let e=U(t),n=await q(t),{tasks:r}=pe(t,e),o=[],s=r.map((u)=>{let{id:d}=u.contract;if(u.record.status!=="done"||Ti(n,d,1).length===0)return u;let p=0,g=qt(t,n,d,(m)=>{let h=m;for(let w of Df(n,d))h=iR(h,w),p+=w.length;return h});return ii(n,d),o.push({events:p,task:d}),{contract:u.contract,record:g}}),i=new Map(Ve(t).map((u)=>[u.id,u])),a=[...aR(i,e),...cR(i,s,e),...lR(i,s,e)];for(let{id:u}of a){let d=i.get(u);if(d!==void 0)vi(t,d)}let c=$o(i),l=await Ci(t);return{activeBytes:dh(c),archived:a,candidates:{clusters:dR(c,e),decisions:gR(c,l),notes:pR(s)},maxBytes:e.knowledge.maxBytes,pruned:o}}function sR(t,e){if(!YI(t))throw new f(`The proposal file ${t} does not exist`,Oi);let n;try{n=JSON.parse(XI(t,"utf8"))}catch(r){let o=r instanceof Error?r.message:String(r);throw new f(`The proposal file ${t} is not valid JSON (${o})`,Oi)}return wt("sleep proposal",Oi,()=>fR(n,e.knowledge.maxEntryBytes))}async function uh(t,e,n={}){let r=U(t),o=await q(t),s=sR(e,r),i=new Map(Ve(t).map((m)=>[m.id,m])),{tasks:a}=pe(t,r),c=new Map(a.map((m)=>[m.contract.id,m.record])),l=hR(s,i,c,n.force===!0);if(l.length>0){let m=l.map((h)=>` - ${h}`).join(`
|
|
156
|
+
`);throw new f(`The sleep proposal has ${l.length} problem(s):
|
|
157
|
+
${m}`,Oi)}let u=xi((n.clock??oR)()),d=new Set(We(t)),p=[],g=[];for(let m of s.merges){let h=m.replace.map((v)=>i.get(v)).filter((v)=>v!==void 0),w=[...new Set(h.flatMap((v)=>v.sources))].sort(L),{id:b}=Ei(t,m.entry,{created:u,sources:w,supersedes:[...m.replace]},d);p.push(...h.map((v)=>Fn(v,b))),g.push({id:b,kind:m.entry.kind,origin:"merge"})}for(let m of s.promotions){let h={created:u,sources:[m.task],supersedes:[]},{id:w}=Ei(t,m.entry,h,d);g.push({id:w,kind:m.entry.kind,origin:"promotion"})}for(let m of s.archive){let h=i.get(m);if(h!==void 0)p.push(Fn(h,null))}for(let m of p)vi(t,m);for(let{notes:m,task:h}of s.promotions)qt(t,o,h,(w)=>cm(w,m));return{archived:p.map((m)=>({id:m.id,supersededBy:m.supersededBy})),created:g,promoted:s.promotions.map((m)=>({notes:[...m.notes],task:m.task}))}}function iR(t,e){let n=e.flatMap((r)=>{let o=r.detail[gr];return r.type==="context"&&Array.isArray(o)?o:[]});return Qs(am(t,n),e)}function $o(t){return[...t.values()].filter((e)=>e.status==="active").sort((e,n)=>L(e.id,n.id))}function dh(t){return t.reduce((e,n)=>e+pt(n.text),0)}function ph(t,e){return L(t.created,e.created)||L(t.id,e.id)}function aR(t,e){let n=[],r=[];for(let o of $o(t).filter((s)=>!Gn(s)).sort(ph)){let s=n.find((i)=>i.kind===o.kind&&fh(i.text,o.text,e.knowledge.duplicateSimilarity)>=e.knowledge.duplicateSimilarity);if(s===void 0){n.push(o);continue}t.set(o.id,Fn(o,s.id)),r.push({id:o.id,reason:"duplicate",supersededBy:s.id})}return r}function cR(t,e,n){let r=mh(e).slice(0,n.knowledge.decayAfterTasks);if(r.length<n.knowledge.decayAfterTasks)return[];let o=new Set(r.flatMap((i)=>gh(i,t))),s=r.map((i)=>xi(i.record.history[0]?.at??"")).sort(L)[0]??"";return $o(t).flatMap((i)=>{if(!zI.includes(i.kind)||o.has(i.id))return[];if(L(i.created,s)>=0)return[];return t.set(i.id,Fn(i,null)),[{id:i.id,reason:"decay",supersededBy:null}]})}function lR(t,e,n){let r=new Map;for(let a of mh(e).flatMap((c)=>gh(c,t)))r.set(a,(r.get(a)??0)+1);let o=$o(t).filter((a)=>!Gn(a)).sort((a,c)=>(r.get(a.id)??0)-(r.get(c.id)??0)||ph(a,c)),s=[],i=dh($o(t));for(let a of o){if(i<=n.knowledge.maxBytes)break;t.set(a.id,Fn(a,null)),i-=pt(a.text),s.push({id:a.id,reason:"budget",supersededBy:null})}return s}function gh(t,e){return[...new Set(t.record.knowledgeUsed.map((n)=>uR(n,e)))]}function uR(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 mh(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)=>L(e(r),e(n))||L(n.contract.id,r.contract.id))}function fh(t,e,n){let r=Qc(t),o=Qc(e),s=Math.max(r.length,o.length);if(s>0&&Math.min(r.length,o.length)/s<n)return 0;return ch(r,o)}function dR(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=fh(i.text,c.text,e.knowledge.mergeSimilarity);if(l<e.knowledge.mergeSimilarity)continue;let[u,d]=[o(i.id),o(c.id)].sort(L);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:mR(r.get(i)??0)})).sort((i,a)=>L(i.ids[0]??"",a.ids[0]??""))}function pR(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 gR(t,e){let n=t.filter((r)=>r.kind==="decision");return n.flatMap((r,o)=>n.slice(o+1).filter((s)=>Ai(r.scope,s.scope,e)).map((s)=>({ids:[r.id,s.id]})))}function mR(t){let e=10**ZI;return Math.round(t*e)/e}function fR(t,e){let n=R(t,"proposal",QI);return{archive:F(n.archive,[],(r)=>H(r,"archive",I)),merges:F(n.merges,[],(r)=>H(r,"merges",(o,s)=>{let i=R(o,s,tR);return{entry:lh(i.entry,`${s}.entry`,e),replace:It(i.replace,`${s}.replace`,(a,c)=>H(a,c,I))}})),promotions:F(n.promotions,[],(r)=>H(r,"promotions",(o,s)=>{let i=R(o,s,eR);return{entry:lh(i.entry,`${s}.entry`,e),notes:It(i.notes,`${s}.notes`,(a,c)=>H(a,c,Vt)),task:It(i.task,`${s}.task`,I)}}))}}function lh(t,e,n){let r=It(t,e,(o,s)=>R(o,s,nR));return Fl({kind:r.kind,scope:r.scope??[],text:r.text},e,n)}function hR(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(Gn(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<rR)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 m=d.notes[g];if(m===void 0)o.push(`${u}.notes names note ${g}, but "${c.task}" has none`);else if(m.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 _i(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 Pi(t){return`depends forms a cycle: ${t.join(" -> ")}`}var yR=["ari check","ari done"],kR=["ari next"],wR='ari new "<title>"',hh=["active","blocked"];function Jl(t){let e=[...t.tasks].sort((u,d)=>L(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 SR(n,t.packs);if(n?.record.status==="blocked")return $R(n,t.packs);let r=e.filter((u)=>!t.claimed.has(u.contract.id)),s=r.filter((u)=>hh.includes(u.record.status)).find((u)=>Yl(u,t.packs)===null);if(s)return bR(s,t.packs);let i=vR(r,t),a=AR(e,r.filter((u)=>!i.has(u.contract.id)));if(a)return ER(a,t.packs);let c=CR(e,r,t,i);if(c)return TR(c);let l=e.find((u)=>u.record.status==="draft");if(l)return xR(l);return{action:"new",commands:[wR],instruction:"Create a task and write its contract: scope, criteria and checks.",stage:null,task:null}}function SR(t,e){let n=ql(t,e);return{action:"continue",commands:[...yR],instruction:pr(n,t.contract.id),stage:n.name,task:t.contract.id}}function $R(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:ql(t,e).name,task:t.contract.id}}function bR(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:ql(t,e).name,task:t.contract.id}}function TR(t){return{action:"fix",commands:[...kR],instruction:t.instruction,stage:null,task:t.id}}function ER(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 xR(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 ql(t,e){let n=Yl(t,e);if(n!==null)throw new f(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 Yl(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 vR(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,[...ur(s.contract,e),...a]]});return new Map(o.filter(([,s])=>s.length>0))}function CR(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,m=p.contract.depends.find((w)=>!s.has(w)&&!i.has(w));if(m!==void 0)return[{id:g,instruction:`depends names the unknown task "${m}". Fix the depends of .ari/tasks/${g}.md`}];let h=_i(g,a);return h?[{id:g,instruction:`${Pi(h)}. 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)=>hh.includes(p.record.status)).flatMap((p)=>{let g=Yl(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)=>L(p.id,g.id))[0]}function AR(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)||L(i.contract.id,a.contract.id))[0]}import{realpathSync as IR}from"fs";import{resolve as RR}from"path";var OR="ENOENT";async function Xl(t){let e=yh(t),n=new Map;for(let r of await Ng(t)){if(yh(r)===e)continue;let o=_R(await q(r));if(o!==null&&!n.has(o.task))n.set(o.task,r)}return n}function _R(t){try{return dt(t)}catch(e){if(e instanceof f)return null;throw e}}function yh(t){try{return IR(t)}catch(e){if(e.code===OR)return RR(t);throw e}}var PR=8,NR=6,jR=10,kh=`
|
|
88
158
|
scope: []
|
|
89
|
-
`,
|
|
90
|
-
scope: ${
|
|
91
|
-
`)}function
|
|
92
|
-
`);throw new
|
|
93
|
-
${r}`,n)}function
|
|
159
|
+
`,MR="decision",zl=10,Sh={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>'`},DR=()=>new Date().toISOString();async function $h(t,e,n={}){let r=await Lt(t),o=e.trim(),s=wo(o,PR);if(s.length===0)throw new f(`The title "${e}" has no letters or digits to build a task id from`,'Run ari new "<title>"');let i=In(n.pack??r.config.pack,r.projectPacks).name,a=[...n.scope??[]],c=a.find((p)=>vn(p)!==null);if(c!==void 0)throw new f(`Scope glob ${JSON.stringify(c)} ${vn(c)}`,"Pass globs relative to the root");let l=So(s,Cm(t)),u=LR(Wg(o,i),a),d=el(l,ve(n)());return vm(t,r.state,d,u),{contractPath:ut(l),id:l,task:{contract:Js(l,u,r.config),record:d}}}async function bh(t,e,n={}){let r=await Lt(t),{task:o}=st(t,e,r.config),s=ve(n)();nl(o.record,s);let i=[...ur(o.contract,r.packs),...WR(o.contract,t),...tu(r,o.contract)];Zl(e,i,`Fix ${ut(e)}, then run 'ari ready ${e}'`);let a=qt(t,r.state,e,(c)=>nl(c,s));return{contract:o.contract,record:a}}async function wr(t,e,n={}){let r=await Lt(t),{contractText:o,task:s}=st(t,e,r.config),{contract:i}=s,a=ve(n)();if(JR(r,e),await HR(r,e),Ql(s.record.status))return GR(r,s,a);let c=await Gs(t),l=await Le(t,i.lock),u=await yo(t,r.config,i),d={contractHash:Fe(o),gatesHash:Mi(r,i),lockHashes:l,stageTestHashes:u},p=(h)=>em(h,c,d,a);p(s.record),Zl(e,ur(i,r.packs),`Fix ${ut(e)}, then start it again`),VR(r,i),await KR(t,e),Oh(i,l);let g=qt(t,r.state,e,p);gl(r.state,{since:a,task:e});let m={contract:i,record:g};return{...Di(m,pn(r,i)),task:m}}async function Th(t,e={}){let n=await Lt(t),{contractText:r,task:o}=Ph(n),s=pn(n,o.contract),i=Je(o,s),a=await Ml({config:n.config,pack:s,root:t,task:o}),c=a.every((d)=>d.ok);On(n.state,jh("check",o,i,a,ve(e)()));let l=Fe(r)!==o.record.contractHash,u=Mi(n,o.contract)!==o.record.gatesHash;return{contractChanged:l,gates:a,gatesChanged:u,ok:c,stage:i.name,task:o}}async function Eh(t,e={}){let n=await Lt(t),r=Ph(n),{task:o}=r,{contract:s}=o;Nh(n,r);let i=pn(n,s),a=Je(o,i),c=await Se(t,[Rn]),l=await Ml({config:n.config,pack:i,root:t,task:o}),u=ve(e)();On(n.state,jh("done",o,a,l,u));let d=s.budget.attempts,p={budget:d,gates:l,stage:a.name},g=Rm(n.state,s.id),m=(_)=>qt(t,n.state,s.id,(M)=>(YR(o.record,M),_({...M,knowledgeUsed:XR(M.knowledgeUsed,g)})));if(!l.every((_)=>_.ok)){let _=m((A)=>rm(A,{at:u,gates:l,stage:a.name,treeHash:c},d)),M=_.status==="blocked"?"blocked":"failed";return{...p,attempts:_.attempts,next:null,outcome:M,task:{contract:s,record:_}}}let h=await yo(t,n.config,s),w={at:u,gates:l,stage:a.name,testHashes:h,treeHash:c},b=m((_)=>{let M=nm(_,w,i.stages.length,h);return M.status==="done"?Qs(M,g):M}),v=b.status==="done",B={contract:s,record:b};if(v)return Im(n.state),ii(n.state,s.id),{...p,attempts:b.attempts,next:null,outcome:"done",task:B};let K=Di(B,i);return{...p,attempts:b.attempts,next:K,outcome:"advanced",task:B}}async function xh(t,e,n,r={}){let o=await Lt(t),{contractText:s,task:i}=st(t,e,o.config),{contract:a,record:c}=i,l=Ql(c.status);if(r.onto!==void 0&&!l)throw new f(`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 Le(t,a.lock),d=c.status!=="draft"&&c.status!=="done";if(d){let b=[...ur(a,o.packs),...tu(o,a)];Zl(e,b,`Fix ${ut(e)}, then run 'ari amend ${e}' again`)}if(l)UR(i,pn(o,a));let p=d?Je(i,pn(o,a)).name:null;if(l)Oh(a,u);let g=l?await yo(t,o.config,a):{...c.stageTestHashes},h={base:r.onto===void 0?null:await Pg(t,"HEAD",await ar(t,r.onto)),contractHash:Fe(s),gatesHash:Mi(o,a),lockHashes:u,reason:n,stage:p,stageTestHashes:g},w=ve(r)();return rl(c,h,w),{contract:a,record:qt(t,o.state,e,(b)=>rl(b,h,w))}}async function vh(t,e,n,r={}){let o=await Lt(t),{task:s}=st(t,e,o.config),i=ve(r)(),a=qt(t,o.state,e,(c)=>om(c,n,i));return{contract:s.contract,record:a}}async function Ch(t,e,n,r={}){let o=await Lt(t),{task:s}=st(t,e,o.config),i=ve(r)();ol(s.record,n,i);let a=n.trim(),c=o.config.knowledge.maxEntryBytes,l=pt(a);if(l>c)throw new f(`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=wo(a,NR),d=So(u.length>0?u:MR,We(t));si(t,{created:i.slice(0,jR),id:d,kind:"decision",scope:[...s.contract.scope],sources:[e],status:"active",supersededBy:null,supersedes:[],text:a});let p=qt(t,o.state,e,(g)=>ol(g,n,i));return{knowledgeId:d,task:{contract:s.contract,record:p}}}async function Ah(t,e,n,r={}){let o=await Lt(t),s=st(t,e,o.config),{contract:i,record:a}=s.task,c=pn(o,i);if(a.status==="active")Nh(o,s);let l=Je(s.task,c),u=await Dl(t,l,e),d=ve(r)(),p=qt(t,o.state,e,(g)=>(qR(a,g),sm(g,{...u,by:n,stage:l.name},d)));return{contract:i,record:p}}async function Ih(t,e,n={}){let r=await Lt(t),o=n.task??_h(r),{task:s}=st(t,o,r.config),i=ve(n)(),a=qt(t,r.state,o,(c)=>im(c,e,i));return{contract:s.contract,record:a}}async function Ni(t){let e=await Lt(t),n=dt(e.state),r=n===null?null:FR(e,n.task);if(r!==null&&Ql(r.record.status))return Jl({...{claimed:new Set,invalid:[],uncoveredLocks:new Map},active:n,packs:e.packs,tasks:[r]});let{invalid:o,tasks:s}=pe(t,e.config),i=new Set((await Xl(t)).keys()),a=await BR(t,s);return Jl({active:n,claimed:i,invalid:o,packs:e.packs,tasks:s,uncoveredLocks:a})}async function ji(t,e={}){let n=await Lt(t),r=pe(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 qe(t,e){let n=await Lt(t),{task:r}=st(t,e,n.config),s=r.record.status==="active"||r.record.status==="blocked"?Di(r,pn(n,r.contract)):null;return{active:dt(n.state)?.task===e,instruction:s?.instruction??null,stage:s?.stage??null,task:r}}async function Lt(t){let e=U(t),n=Te(t);return{config:e,packs:He(n),projectPacks:n,root:t,state:await q(t)}}function ve(t){return t.clock??DR}function Mi(t,e){let n=t.packs.find((r)=>r.name===e.pack);return n===void 0?null:Zs(n,t.config)}function pn(t,e){return In(e.pack,t.projectPacks)}function Di(t,e){let n=Je(t,e);return{instruction:pr(n,t.contract.id),stage:n.name}}function LR(t,e){if(e.length===0)return t;if(!t.includes(kh))throw Error("The contract template has no empty scope line");return t.replace(kh,()=>`
|
|
160
|
+
scope: ${lr(e)}
|
|
161
|
+
`)}function Zl(t,e,n){if(e.length===0)return;let r=e.map((o)=>` - ${o}`).join(`
|
|
162
|
+
`);throw new f(`The contract of "${t}" has ${e.length} problem(s):
|
|
163
|
+
${r}`,n)}function Ql(t){return t==="active"||t==="blocked"}function FR(t,e){return de(t.root).includes(e)?st(t.root,e,t.config).task:null}function GR(t,e,n){let r=e.contract.id;if(dt(t.state)?.task!==r)gl(t.state,{since:n,task:r});return{...Di(e,pn(t,e.contract)),task:e}}async function HR(t,e){let n=(await Xl(t.root)).get(e);if(n===void 0)return;throw new f(`Task "${e}" is already held by the worktree at ${n}`,"Continue it there, or run 'ari next' here for other work")}async function KR(t,e){let n=_t(await Jt(t,"HEAD"));if(n.length===0)return;let r=n.length-zl,o=r>0?` and ${r} more`:"",s=(await Ks(t)).filter((a)=>n.includes(a)),i=s.length===0?"":`; git hides ${s.slice(0,zl).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 f(`Task "${e}" cannot start with uncommitted changes outside .ari: ${n.slice(0,zl).join(", ")}${o}`,`Commit, stash or ignore them, then run 'ari start ${e}'; the scope gate counts every change since the start commit${i}`)}function UR(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 f(`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 BR(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 Le(t,r));return new Map(n.flatMap((s)=>{let i=Rh(s.contract,o);return i===void 0?[]:[[s.contract.id,i]]}))}function Rh(t,e){return t.lock.find((n)=>!e.some((r)=>J(r,[n])))}function Oh(t,e){let n=Rh(t,Object.keys(e));if(n===void 0)return;throw new f(`Lock glob ${JSON.stringify(n)} of task "${t.id}" matches no file that git tracks or would track`,`Fix the lock list in ${ut(t.id)}: escape [ ] { } * ? with a backslash, and lock only files that are not ignored`)}function tu(t,e){let{tasks:n}=pe(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=_i(e.id,(s)=>r.get(s)??[]);return o===null?[]:[Pi(o)]}function WR(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 VR(t,e){let n=new Set(de(t.root)),r=e.depends.filter((s)=>!n.has(s)||st(t.root,s,t.config).task.record.status!=="done");if(r.length===0)return;let o=tu(t,e).map((s)=>`; ${s}`);throw new f(`Task "${e.id}" depends on unfinished tasks: ${r.join(", ")}${o.join("")}`,"Finish those tasks first; 'ari next' shows the order")}function JR(t,e){let n=dt(t.state);if(n===null||n.task===e||!de(t.root).includes(n.task))return;let{status:r}=st(t.root,n.task,t.config).task.record;if(r!=="active"&&r!=="blocked")return;throw new f(`Task "${n.task}" is already ${r} in this worktree; one task runs per worktree`,Sh[r](n.task))}function _h(t){let e=dt(t.state);if(e!==null)return e.task;throw new f("No task is active in this worktree","Run 'ari next' to see what to do")}function Ph(t){let e=_h(t),n=st(t.root,e,t.config),{question:r,status:o}=n.task.record;if(o==="active")return n;if(o==="blocked")throw new f(`Task "${e}" is blocked: ${r??"no question was recorded"}`,Sh.blocked(e));throw new f(`Task "${e}" is ${o}, not active`,"Run 'ari next' to see what to do")}function Nh(t,{contractText:e,task:n}){let{contract:r}=n;if(Fe(e)!==n.record.contractHash)throw new f(`The contract of "${r.id}" changed after it was frozen`,`Run 'ari amend ${r.id} --reason <text>' to accept the change`);if(Mi(t,r)!==n.record.gatesHash)throw new f(`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 qR(t,e){if(t.stage===e.stage)return;throw new f(`Task "${e.id}" moved to another stage while its approval was recorded`,`Review the current stage, then run 'ari approve ${e.id}' again`)}function YR(t,e){if($t(wh(t))===$t(wh(e)))return;throw new f(`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 wh(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 XR(t,e){let n=e.flatMap((r)=>{let o=r.detail[gr];return r.type==="context"&&Array.isArray(o)?o:[]});return[...new Set([...t,...n])].sort(L)}function jh(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 zR=20,ZR=`
|
|
94
164
|
|
|
95
|
-
`,
|
|
96
|
-
`),a=n===null?[]:[
|
|
97
|
-
`)}function
|
|
98
|
-
${r.outputTail}`);return[`- ${t.gate}: ${t.summary}`,...e,...n]}
|
|
99
|
-
`)}
|
|
100
|
-
`)
|
|
101
|
-
`)
|
|
102
|
-
`)}function
|
|
103
|
-
`)
|
|
104
|
-
`)}
|
|
105
|
-
|
|
106
|
-
`)
|
|
107
|
-
|
|
108
|
-
`,s=(i,a)=>{let c=t.
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
`)}async function qE(t){let e=await A(t,["config","--get","core.hooksPath"],{allowedExitCodes:[Gp,BE]}),n=e.stdout.trim();if(e.exitCode===Gp&&n.length>0)return{hint:Bs(`${n}/`),name:`core.hooksPath (${n})`};let r=WE.find((s)=>Zn(Qn(t,s)));if(r!==void 0)return{hint:YE(r),name:`lefthook (${r})`};if(Zn(Qn(t,Hp)))return{hint:Bs(`${Hp}/`),name:"husky"};return null}function Bs(t){return`Add the lines yourself: ${gn.map((e)=>`${t}${e.name}: ${e.command}`).join("; ")}`}function YE(t){if(!VE.test(t))return Bs("lefthook ");let e=gn.map((n)=>`${n.name}:
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
run: ${n.command}`).join(`
|
|
116
|
-
`);return`Add to ${t}:
|
|
117
|
-
${e}`}import{realpathSync as ZE,rmSync as QE}from"fs";import{join as tT}from"path";import{join as Yp}from"path";var Xp="hooks.json",XE=384,zE=ul(Kr({installed:Xt(),original:Xt().or(Fr())}));function la(t,e){return zp(t)[e]??null}function ua(t,e,n){let{[e]:r,...s}=zp(t);if(n===null&&r===void 0)return;let o=n===null?s:{...s,[e]:n};Ke(Yp(t,Xp),`${JSON.stringify(o)}
|
|
118
|
-
`,XE)}function zp(t){return Us(Yp(t,Xp),zE,{})}var eT="ari hook",nT=1;function da(t,e){return`${eT} ${t} ${e}`}function tm(t,e,n){let{file:r,name:s,registrations:o}=e,i=le(t,r),a=fn(t,r)??{},c=la(n,r),l=nm(a,e)?void 0:i,u=c?.installed===i?c?.original:l,d=Xn(t,r,rm(a,e,o)),p=le(t,r)??"";return ua(n,r,u===void 0?null:{installed:p,original:u}),{action:d,agent:s,events:tr(e),file:r}}function em(t,e,n){let{file:r,name:s}=e;return{action:pa(t,e)?rT(t,e,n):"unchanged",agent:s,file:r}}function rT(t,e,n){let{file:r}=e,s=la(n,r);if(ua(n,r,null),s===null||s.installed!==le(t,r)){let o=fn(t,r)??{};return Xn(t,r,rm(o,e,[]))}if(s.original!==null)return zn(t,r,s.original);return QE(ZE(tT(t,r))),"removed"}function pa(t,e){let n=fn(t,e.file);return n!==null&&nm(n,e)}function tr(t){return[...new Set(t.registrations.map((e)=>e.event))]}function nm({hooks:t},e){if(!ue(t))return!1;return Object.values(t).flat().some((n)=>sm(n,e).length>0)}function rm({hooks:t={},...e},n,r){if(!ue(t))throw Zp(n,'"hooks" value that is not an object');let o=[...new Set([...Object.keys(t),...r.map(({agentEvent:a})=>a)])].flatMap((a)=>{let c=t[a]??[];if(!Array.isArray(c))throw Zp(n,`hooks.${a} that is not a list`);let l=sT(c,n,r.filter(({agentEvent:u})=>u===a));return l.length===0&&c.length>0?[]:[[a,l]]}),i=n.layout==="flat"?{version:e.version??nT}:{};return{...e,...i,...o.length===0?{}:{hooks:Object.fromEntries(o)}}}function Zp({file:t},e){return new g(`${t} has a ${e}`,`Fix ${t}`)}function sT(t,e,n){let r=new Set(n);return[...t.flatMap((o)=>{let i=sm(o,e),a=[...r].filter(({event:c})=>i.includes(da(e.name,c)));for(let c of a)r.delete(c);return[...oT(o,e),...a.map((c)=>Qp(e,c))]}),...[...r].map((o)=>Qp(e,o))]}function Qp(t,e){let n=t.handler(da(t.name,e.event),e);if(t.layout==="flat")return n;return e.matcher===null?{hooks:[n]}:{hooks:[n],matcher:e.matcher}}function oT(t,e){let n=om(t,e),r=n.filter((s)=>im(s,e).length===0);if(r.length===n.length)return[t];return r.length>0&&ue(t)?[{...t,hooks:r}]:[]}function sm(t,e){return om(t,e).flatMap((n)=>im(n,e))}function om(t,{layout:e}){if(e==="flat")return[t];return ue(t)&&Array.isArray(t.hooks)?t.hooks:[]}function im(t,{name:e}){let n=ue(t)?Object.values(t):[],r=da(e,"");return n.filter((s)=>typeof s==="string"&&s.startsWith(r))}import{join as Rv,resolve as Em}from"path";import{resolve as bm}from"path";var am=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"),iT=/[ \t\r\n]/,aT=/\$\(cat <<-?[ \t]*(["'])(\w+)\1\n[\s\S]*?\n[ \t]*\2\n\s*\)/g,cT=/\\[\s\S]/g,lT=/\\([$`"\\\n])/g,uT=/[$`]/,dT=/[$*?[]|\{./;var pT=/['"\\]/g,mT=/^\t+/;var fT=/[(`]/,gT=new Set(["-C","-c","--config-env","--exec-path","--git-dir","--namespace","--work-tree"]);function ma(t){let e=[],n=[],r=cm(""),s="words",o=null,i=0,a=(u,d)=>{o=(o??"")+u,r.literal&&=d},c=(u="words")=>{if(o!==null)r[s].push(o);o=null,s=u},l=(u)=>{if(c(),r.literal&&=!fT.test(u),r.words.length+r.inputs.length+r.outputs.length>0)e.push(r);r=cm(u)};while(i<t.length){am.lastIndex=i;let u=am.exec(t);if(u===null)break;let{arithmetic:d,blank:p,delimiter:f,double:m,escaped:h,input:y,output:x,plain:b,separator:H,single:M,tabs:T}=u.groups??{};if(i+=u[0].length,h!==void 0)a(h,!0);else if(M!==void 0)a(M,!0);else if(m!==void 0)a(yT(m),hT(m));else if(d!==void 0)a(d,!1);else if(b!==void 0)a(b,!dT.test(b)&&(o!==null||!b.startsWith("~")));else if(p!==void 0&&o!==null)c();else if(x!==void 0)c("outputs");else if(y!==void 0)c("inputs");else if(f!==void 0)c(),n.push({delimiter:f.replace(pT,""),tabs:T!==""});else if(H!==void 0){if(H===`
|
|
119
|
-
`)for(let D of n.splice(0)){let{body:S,end:w}=kT(t,i,D);r.inputs.push(S),i=w}l(H)}}return l(""),e}function fa(t){return ma(t).flatMap((e)=>[e,...[...e.words,...e.inputs].filter((n)=>iT.test(n)).flatMap(fa)])}function Ws(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(gT.has(r))n+=1;if(r==="-C")e.push(t[n]??"")}return null}function Ue(t){return t.slice(t.lastIndexOf("/")+1)}function cm(t){return{before:t,inputs:[],literal:!0,outputs:[],words:[]}}function hT(t){return!uT.test(t.replace(aT,"").replace(cT,""))}function yT(t){return t.replace(lT,(e,n)=>n===`
|
|
120
|
-
`?"":n)}function kT(t,e,{delimiter:n,tabs:r}){for(let s=e;s<t.length;){let o=t.indexOf(`
|
|
121
|
-
`,s),i=o===-1?t.length:o,a=t.slice(s,i);if((r?a.replace(mT,""):a)===n)return{body:t.slice(e,s),end:i};s=i+1}return{body:t.slice(e),end:t.length}}import{basename as wT,isAbsolute as $T,join as bT,resolve as Js}from"path";var xT=/^[A-Za-z_]\w*\+?=/,ST=new Set("! { builtin command do elif else env exec if nohup sudo then time until while".split(" ")),ET=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"]]]),TT=new Set("ari ariadne cat cd diff echo egrep file gh grep head jq ls popd printf pushd rg tail test wc".split(" ")),vT=new Set("add blame branch commit diff fetch grep log ls-files push show status tag".split(" ")),CT=new Set(["cd","popd","pushd"]),lm=new Set(["","&&",";",`
|
|
122
|
-
`]),AT="S suffix",OT=/^(?:-[a-z0-9E]*i|--in-place)/,RT=/^(?:-[a-zA-Z0-9]*[ef]|--expression|--file)/,IT="e f l expression file line-length",_T=/^-[a-zA-Z0-9]*[eE]/,PT="e E",NT=/^-\w+$/,DT=/^\.\w+$/,jT=/^(?:-[a-zA-Z]*t$|--target-directory)/,LT=/^(?:--staged|-[A-Za-z]*S)/,MT=/^(?:--worktree|-[A-Za-z]*W)/,um="of=",ha="--",ga=".";function pm(t,e){let n=e,r=e,s=!0,o=t.map((i,a)=>{let c=HT(i,n),[l="",u="-",...d]=qs(i);if(!CT.has(l))return s=!1,c;return s&&=l==="cd"&&i.literal&&!u.startsWith("-")&&d.length===0,s&&=lm.has(i.before)&&lm.has(t[a+1]?.before??""),r=s?Js(r,u):r,n=s?r:null,c});return{directory:r,steps:o}}function qs({words:t}){let e=t.findIndex((n)=>!xT.test(n)&&!ST.has(n));return e===-1?[]:[Ue(t[e]??""),...t.slice(e+1)]}function Ys(t,e=""){let n=new Set(e.split(" ")),r=t.indexOf(ha),s=[],o=r===-1?t:t.slice(0,r);for(let i=0;i<o.length;i+=1){let a=o[i]??"";if(!a.startsWith("-"))s.push(a);else if(n.has(GT(a)))i+=1}return[...s,...r===-1?[]:t.slice(r+1)].filter((i)=>i.length>0)}function GT(t){if(t.startsWith("--"))return t.slice(2);return NT.test(t)?t.slice(-1):""}function HT(t,e){if(!t.literal)return{command:t,resolved:!1,targets:[]};let[n="",...r]=qs(t),s=n==="git"?Ws(r):null,o=e===null?null:Js(e,...s?.directories??[]),i=s===null?mm(n,r,e):FT(s.subcommand,s.args,o),a=[...Vs(e,"file",t.outputs),...Vs(o,"file",i?.written),...Vs(o,"directory",i?.created),...Vs(o,"removed",i?.removed)],c=a.filter((l)=>l!==null);return{command:t,resolved:i!==null&&c.length===a.length,targets:c}}function Vs(t,e,n=[]){return n.flatMap((r)=>{if(t===null&&!$T(r))return null;let s=Js(t??r,r),o=e!=="removed"&&Ks(s);if(o&&e==="directory")return[];return{kind:o?"directory":e,path:s}})}function mm(t,e,n){let[r,s]=ET.get(t)??[];if(r!==void 0)return{[r]:Ys(e,s)};switch(t){case"dd":return{written:e.filter((o)=>o.startsWith(um)).map((o)=>o.slice(um.length))};case"cp":case"ln":case"mv":return KT(t,e,n);case"sed":return{written:dm(e,IT,RT)??[]};case"perl":{let o=dm(e,PT,_T);return o===null?null:{written:o}}default:return TT.has(t)?{}:null}}function FT(t,e,n){switch(t){case"checkout":return e.includes(ha)?{removed:e.slice(e.indexOf(ha)+1)}:null;case"restore":return e.some((s)=>LT.test(s))&&!e.some((s)=>MT.test(s))?{}:{removed:Ys(e,"s source pathspec-from-file")};case"rm":case"mv":return mm(t,e,n);default:return vT.has(t)?{}:null}}function KT(t,e,n){if(e.some((a)=>jT.test(a)))return null;let r=Ys(e,AT),[s=ga,o]=r.length<2?[ga,r]:[r.at(-1),r.slice(0,-1)],i=s.endsWith("/")||Ks(Js(n??ga,s));return{removed:t==="mv"?o:[],written:i?o.map((a)=>bT(s,wT(a))):[s]}}function dm(t,e,n){if(!t.some((o)=>OT.test(o)))return null;let r=Ys(t,e),s=r.length>1&&DT.test(r[0]??"")?r.slice(1):r;return t.some((o)=>n.test(o))?s:s.slice(1)}import{basename as fm,dirname as UT,join as gm}from"path";var BT=[`${W}/tasks/*.md`,`${W}/designs/**`],WT="x",VT=/\*\*.*/,JT=".git",qT=[/^(?:ari|hooks|info)(?:\/|$)/,/^(?:HEAD|commondir|config(?:\.worktree)?|gitdir|objects|packed-refs|refs|worktrees)$/,/^(?:objects|refs|worktrees)\/(?!.*\.lock$)/],YT="; pass the paths to change instead of their directory",XT="\x00",Xs=0,zT=1,hm=128;async function ym(t,e){let n=at(e),r=await t.governing(n),s=$m(t.opened(),n);if(s!==null)return s;return r.flatMap((i)=>{let a=Vt(i.root,n);return a===null||a.length===0?[]:er(i,a)??[]})[0]??null}async function km(t,e){let n=[],r=new Map;for(let{kind:s,path:o}of e){let a=s==="removed"&&ra(o)!==null?gm(at(UT(o)),fm(o)):at(o),c=await t.governing(a),l=$m(t.opened(),a);if(l!==null)n.push(l);let u=s==="removed"?t.opened().filter(({root:d})=>Vt(a,d)!==null):[];for(let d of new Set([...c,...u])){let p=r.get(d)??[];r.set(d,[...p,{file:Vt(d.root,a)??"",kind:s}])}}for(let[s,o]of r)n.push(...await ZT(s,o));return n}async function ZT(t,e){let n=e.filter(({kind:a})=>a==="removed").map(({file:a})=>a),r=n.length===0?[]:await nv(t,n),s=n.flatMap((a)=>r.filter((u)=>a.length===0||u===a||u.startsWith(`${a}/`)).flatMap((u)=>{let d=er(t,u);return d===null?[]:`${d}${u===a?"":YT}`}).slice(0,1)),o=e.flatMap(({file:a,kind:c})=>{if(c==="removed"||a.length===0)return[];let l=c==="file"?er(t,a):QT(t,a),u=c==="file"?a:`${a}/`;return l===null?[]:[{guarded:wm(t,a)!==null,name:u,reason:l}]}),i=await rv(t.root,o.filter(({guarded:a})=>!a).map(({name:a})=>a));return[...s,...o.filter(({name:a})=>!i.has(a)).map(({reason:a})=>a)]}function wm(t,e){if(cn(e)&&!K(e,BT))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)||K(e,n.contract.lock)?`${e} is locked by task "${n.contract.id}" and must stay unchanged`:null}function er(t,e,n=K){let r=wm(t,e);if(r!==null||cn(e))return r;let s=t.fault??t.workspace?.drift??null;if(s!==null)return`ari cannot check ${e}: ${s}`;let o=t.workspace?.task??null;if(o===null||n(e,o.contract.scope))return null;let{id:i,scope:a}=o.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 QT(t,e){return er(t,`${e}/${WT}`)===null?null:er(t,e,tv)}function tv(t,e){let n=t.split("/").length,r=e.map((s)=>s.replace(VT,"**").split("/").slice(0,n).join("/"));return K(t,r)}function $m(t,e){return t.some(({gitDirectories:r,root:s})=>Vt(gm(s,JT),e)===""||r.some((o)=>ev(o,e)))?`${fm(e)} belongs to git and to ari's own state; use git and ari commands instead`:null}function ev(t,e){let n=Vt(t,e);return n!==null&&qT.some((r)=>r.test(n))}async function nv({root:t,workspace:e},n){let r=await A(t,["--literal-pathspecs","ls-files","-z","-co","--exclude-standard","--",...n.map((o)=>o.length===0?".":o)],{allowedExitCodes:[Xs,hm]}),s=r.exitCode===Xs?Zt(r.stdout):n;return[...Object.keys(e?.task?.record.lockHashes??{}),W,...s]}async function rv(t,e){if(e.length===0)return new Set;let n=await A(t,["check-ignore","-z","--stdin"],{allowedExitCodes:[Xs,zT,hm],stdin:[...new Set(e)].join(XT)});return new Set(n.exitCode===Xs?Zt(n.stdout):[])}var sv="'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>'",ov="'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",iv="run it as a plain command with literal paths, or ask a person to run it",av=/(?:^|\/)(?:ari|ariadne)(?:@[^/]*)?$/,cv="approve",lv="git",uv="commit",dv="config",pv=/^core\.hookspath$/i,mv=/^(?:--config-env=)?core\.hookspath=|^GIT_CONFIG_KEY_\d+=core\.hookspath$/i,fv=/^(?:--)?unset/,gv=/^(?:--no-veri(?:f|fy)?|-[^-\smFcCtSu]*n\S*)$/,hv=/(?<![\w-])\.ari(?![\w.-])/,ya=/[\s'"`;&|()<>=,]+/,yv=[[/^(?: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)/]],kv=/^(?:ba|da|fi|k|z)?sh$/,wv=/^-[a-z]*c$/,$v=/^(?:bun|deno|node|perl|php|python|ruby)[\d.]*$/,bv=/^(?:-[a-zA-Z]*[ceEip]|--eval|--print)$/;async function xm(t,e,n){let{directory:r,steps:s}=pm(ma(e),n),o=[...new Set([...await t.governing(n),...await t.governing(r)])],i=xv(fa(e));if(i!==null&&(o.length>0||await Sv(t,e,n)))return{kind:"deny",reason:i};let a=await km(t,s.flatMap(({targets:d})=>d));if(a.length>0)return{kind:"deny",reason:[...new Set(a)].join("; ")};let c=s.filter(({resolved:d})=>!d).flatMap((d)=>Cv(d)??[])[0],l=o.filter(({fault:d,workspace:p})=>d!==null||p?.task!=null),u=c===void 0?null:Ov(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; ${iv}`}}function xv(t){if(t.some(Ev))return sv;return t.some(Tv)?ov:null}async function Sv(t,e,n){for(let r of new Set(e.split(ya)))if((await t.governing(bm(n,r))).length>0)return!0;return!1}function Ev({words:t}){return t.some((e,n)=>av.test(e)&&t.slice(n+1).find((r)=>!r.startsWith("-"))===cv)}function Tv({words:t}){if(t.some((e)=>mv.test(e)))return!0;return t.some((e,n)=>{let r=Ue(e)===lv?Ws(t.slice(n+1)):null;if(r?.subcommand===dv)return vv(r.args);return r?.subcommand===uv&&r.args.some((s)=>gv.test(s))})}function vv(t){let e=t.findIndex((n)=>pv.test(n));return e!==-1&&(e<t.length-1||t.some((n)=>fv.test(n)))}function Cv({command:t}){let[e]=qs(t),n=t.words.flatMap((s)=>s.split(ya)).filter((s)=>s.length>0);return n.map(Ue).find((s,o)=>Av(s,e,n,o+1))??(!t.literal&&t.outputs.length>0?">":null)}function Av(t,e,n,r){let s=yv.find(([c])=>c.test(t))?.[1];if(s===null)return!0;if(s!==void 0)return n.slice(r).some((c)=>s.test(c));let o=kv.test(t);if(!o&&!$v.test(t))return!1;let i=n.slice(r),a=i.findIndex((c)=>!c.startsWith("-"));if(a===-1&&t===e)return!0;return o?i.some((c)=>wv.test(c)):i.slice(0,a===-1?i.length:a).some((c)=>bv.test(c))}function Ov(t,e,n){if(t.length>0&&hv.test(e))return W;let r=new Set(e.split(ya));for(let{root:s,workspace:o}of t){let i=Object.keys(o?.task?.record.lockHashes??{}),a=new Set(i.map(Ue));for(let c of[...r].filter((l)=>a.has(Ue(l)))){let u=[s,...n].map((d)=>Vt(s,at(bm(d,c)))).find((d)=>d!==null&&i.includes(d));if(u!==void 0)return u}}return null}var Iv="stop.json",_v=500,Pv=20000,It={kind:"allow"},Nv={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"},Dv=Kr({task:Xt(),tree:Xt()});async function Tm(t){let e=Np();if(ce.has(t.event))return jv(Lv(e,t));let n=await e.at(t.cwd);if(n===null)return zs(It);if(n.workspace===null)return Sm(t,n.fault??"");try{return zs(await Gv(t,n.workspace))}catch(r){if(!(r instanceof g))throw r;return Sm(t,oa(r))}}function Sm({event:t},e){return{...zs(It),warning:`ari hook skipped ${t}: ${e}`}}async function jv(t){let e=Promise.withResolvers(),n=setTimeout(e.resolve,Pv,Nv);try{return await Promise.race([e.promise,t.then(zs)])}finally{clearTimeout(n)}}function zs(t){return{decision:t,expired:!1,warning:null}}async function Lv(t,e){let{command:n,cwd:r,event:s,paths:o}=e,i=await t.at(r);if(s==="before-shell"&&n!==null)return xm(t,n,r);if(s==="before-edit"&&o.length>0)return Mv(t,e);if(i===null)return It;return{kind:"ask",reason:`ari found no ${s==="before-edit"?"path":"command"} in the hook payload`}}async function Mv(t,e){let n=[];for(let r of e.paths){let s=await ym(t,Em(e.cwd,r));if(s!==null)n.push(s)}return n.length===0?It:{kind:"deny",reason:n.join("; ")}}async function Gv(t,e){switch(t.event){case"before-edit":case"before-shell":return It;case"after-tool":return Zs(e,Hv(t,e)),It;case"stop":return Fv(e);case"pre-compact":return Zs(e,{detail:{},type:"compact"}),await pn(e.root),It;case"session-start":return Kv(e)}}function Hv(t,e){let n=at(e.root),r=t.paths.flatMap((s)=>Vt(n,at(Em(t.cwd,s)))??[]);if(r.length>0)return{detail:{paths:r},type:"edit"};if(t.command!==null)return{detail:{command:t.command.slice(0,_v)},type:"shell"};return{detail:t.tool===null?{}:{tool:t.tool},type:"tool"}}async function Fv(t){let{task:e}=t;if(e===null||e.record.status!=="active")return It;let n=e.contract.id,r=await Qe(t.root,[je]);if(e.record.evidence.at(-1)?.treeHash===r)return It;let s=Rv(t.state,Iv),o=Us(s,Dv,null);if(o?.task===n&&o.tree===r)return It;return Ke(s,`${JSON.stringify({task:n,tree:r})}
|
|
123
|
-
`),Zs(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 Kv(t){if(t.task===null)return It;Zs(t,{detail:{},type:"session"});let{text:e}=await dn(t.root,{id:t.task.contract.id});return e.trim().length===0?It:{kind:"context",text:e}}function Zs(t,e){if(t.task===null)return;Le(t.state,{...e,at:new Date().toISOString(),task:t.task.contract.id})}var hn="git",Uv={amp:"Amp",opencode:"OpenCode"},Bv=".git/hooks";function ka(){return[...Gs.map((t)=>t.name),hn]}function Qs(t){let e=Gs.find((r)=>r.name===t);if(e!==void 0)return e;if(t===hn)throw new v("git hooks run 'ari scope --staged' and 'ari verify' directly","Run 'ari hooks install --agent git'");let n=Uv[t];if(n!==void 0)throw new g(`${n} hooks run only as in-process plugins, which ari does not ship`,"Rely on the AGENTS.md block from 'ari init', 'ari hooks install --agent git' and 'ari verify' in CI");throw new v(`Unknown agent "${t}"`,`Choose one of: ${ka().join(", ")}`)}function vm(t){if(t!==hn)Qs(t)}async function to(t,e){if(e===hn)return Vp(t);return tm(t,Qs(e),await tt(t))}async function Cm(t,e){if(e===hn)return Jp(t);return em(t,Qs(e),await tt(t))}async function Am(t){return[...Gs.map((n)=>({agent:n.name,events:tr(n),file:n.file,installed:pa(t,n),label:n.label,support:n.support})),{agent:hn,events:[...Bp],file:Bv,installed:await Wp(t),label:"git",support:"git"}]}async function Om(t,e,n,r){let s=Qs(t),o=Wv(s,e);try{let{decision:i,expired:a,warning:c}=await Tm(s.parse(o,Vv(n),r));return{expired:a,stdout:ta(s,o,i),warning:c}}catch(i){if(!ce.has(o))throw i;let a=`ari could not check this ${o} event: ${i instanceof Error?i.message:String(i)}`;return{expired:!1,stdout:ta(s,o,{kind:"deny",reason:a}),warning:a}}}function Wv(t,e){if(!Sp(e))throw new v(`Unknown hook event "${e}"`,`Choose one of: ${zi.join(", ")}`);if(tr(t).includes(e))return e;throw new v(`${t.label} has no ari adapter for "${e}"`,`Its adapter handles: ${tr(t).join(", ")}`)}function Vv(t){if(t.trim().length===0)return{};let e=null;try{e=JSON.parse(t)}catch{}if(ue(e))return e;throw new g("The hook payload on stdin is not a JSON object","Agents call 'ari hook' with a JSON object")}function Rm(t,e,n){let r=`ari hooks ${t} --agent`;return R({args:L({agent:{description:`Agent: ${ka().join(", ")}`,type:"string"}}),description:e,examples:[`${r} claude`,`${r} git`],json:!0,name:t,run:async(s)=>{let o=Se(s.args.agent,"--agent",`${r} <name>`);s.output.result(await n(await _(),o),Yv)}})}var Jv=R({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 Am(await _());t.output.result({agents:e},({agents:n})=>n.map(Xv).join(`
|
|
124
|
-
`))}}),Im=R({description:"Install, uninstall and list agent and git hook integrations",name:"hooks",subcommands:[Rm("install","Install ari hooks into an agent's project settings or into git",to),Rm("uninstall","Remove ari hooks from an agent's project settings or from git, and nothing else",Cm),Jv]}),_m=R({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:nt({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 Om(t.positionals.agent,t.positionals.event,e,process.cwd());if(n.warning!==null)process.stderr.write(`${n.warning}
|
|
165
|
+
`,QR=["advanced","done","failed"];async function eu(t,e={}){let n=await Eh(t,e),r=n.outcome==="done"?await kr(t):null;return{...n,sleep:r}}async function Mh(t,e){let n=U(t),r=(a)=>Ln(n,{agent:e.agent,model:e.model,role:"task",route:tO(n,a)});for(let a of eO(n,e))Ln(n,{agent:e.agent,model:e.model,role:"task",route:a});let o=await oO(t,e),s=[],i=null;for(;;){let a=await qe(t,o),c=r(a.stage??""),l=await iO(t,o,i),u=a.task.record.history.length,d=await Si(c,l,{cwd:t,environment:wi(c.config),stdout:e.output??"inherit"}),p=await nO(t,o,u)??await eu(t,{clock:e.clock}),g=p.gates.filter((m)=>!m.ok).map((m)=>m.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 tO(t,e){return t.routing.stages[e]??t.routing.default}function eO(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 nO(t,e,n){let r=await qe(t,e),{contract:o,record:s}=r.task,i=s.history.slice(n).findLast((c)=>QR.includes(c.type)),a=rO(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 rO(t,e){if(t==="done"||t==="blocked")return t;if(e==="failed")return"failed";return e==="advanced"?"advanced":null}async function oO(t,e){if(e.task===void 0)return sO(t,e.clock);let n=await qe(t,e.task),{question:r,status:o}=n.task.record,s=n.task.contract.id;switch(o){case"ready":return(await wr(t,s,{clock:e.clock})).task.contract.id;case"active":if(!n.active)await wr(t,s,{clock:e.clock});return s;case"blocked":throw new f(`Task "${s}" is blocked: ${r??"no question was recorded"}`,Dh(s));case"draft":throw new f(`Task "${s}" is a draft`,`Complete its contract, then run 'ari ready ${s}'`);case"done":throw new f(`Task "${s}" is already done`,"Run 'ari next' to see what to do")}}async function sO(t,e){let n=await Ni(t);if(n.task!==null&&n.action==="continue")return n.task;if(n.task!==null&&n.action==="start")return(await wr(t,n.task,{clock:e})).task.contract.id;if(n.task!==null&&n.action==="resolve")throw new f(`Task "${n.task}" is blocked`,Dh(n.task));throw new f(`No task can run: ${n.instruction}`,`Run ${n.commands.map((r)=>`'${r}'`).join(", ")}`)}function Dh(t){return`A human answers it with 'ari resolve ${t} --answer <text>'`}async function iO(t,e,n){let r=await qe(t,e),o=(await yr(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(`
|
|
166
|
+
`),a=n===null?[]:[aO(n)];return[o,s,...a,i].join(ZR)}function aO(t){let e=t.gates.filter((n)=>!n.ok).flatMap((n)=>cO(n));return[`'ari done' failed (attempt ${t.attempts} of ${t.budget}):`,...e].join(`
|
|
167
|
+
`)}function cO(t){let e=t.details.slice(0,zR).map((r)=>` - ${r}`),n=t.checks.filter((r)=>!r.ok).map((r)=>` ${r.name} output:
|
|
168
|
+
${r.outputTail}`);return[`- ${t.gate}: ${t.summary}`,...e,...n]}var Hn=["draft","ready","active","blocked","done"],lO="fact";function Lh(t){return{id:t.contract.id,pack:t.contract.pack,status:t.record.status,title:t.contract.title}}async function Li(t){return Ni(t)}async function Fi(t,e){let n=await ji(t,e.length===0?{}:{statuses:e});return{invalid:n.invalid,tasks:n.tasks.map(Lh)}}async function Gi(t,e){return qe(t,e)}async function Hi(t,e){let n=await $h(t,e.title,{pack:e.pack,scope:e.scope});return{contractPath:n.contractPath,...Lh(n.task)}}async function Ki(t,e){let n=await bh(t,e);return{id:n.contract.id,status:n.record.status}}async function Ui(t,e){let n=await wr(t,e),{record:r}=n.task;return{base:r.base,id:r.id,instruction:n.instruction,stage:n.stage}}async function Bi(t,e,n){let r=await vh(t,e,n);return{id:r.contract.id,question:r.record.question,status:r.record.status}}async function Wi(t){let e=await Th(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 Vi(t){let e=await eu(t);return{data:{attempts:e.attempts,budget:e.budget,gates:e.gates,next:e.next,outcome:e.outcome,sleep:e.sleep,stage:e.stage,task:e.task.contract.id},failed:e.outcome!=="done"&&e.outcome!=="advanced"}}async function Ji(t,e){let{global:n,kind:r,scope:o,text:s}=e;if(!n&&(r!==void 0||o!==void 0))throw new T("--kind and --scope apply only to knowledge entries","Add --global, or drop them");let i=r??lO;if(!Uf(i))throw new T(`--kind must be one of ${ce.join(", ")}, got "${i}"`,"Pass --kind fact");if(n)return{entry:await Wf(t,{kind:i,scope:[...o??[]],text:s}),target:"knowledge"};let a=await Ih(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 qi(t,e){let{budget:n}=e;if(n!==void 0&&(!Number.isInteger(n)||n<=0))throw new T(`--budget must be a positive whole number of tokens, got ${n}`,"Pass --budget 6000");return yr(t,{budget:n,id:e.id})}function Yi(t,e,n){return Vf(t,e,{all:n})}function Fh(t){return t.map((e)=>{let n=Hn.find((r)=>r===e);if(n!==void 0)return n;throw new T(`Unknown status "${e}"`,`Choose from ${Hn.join(", ")}`)})}async function Gh(t,e={}){let n=e.staged??!1,{config:r,drift:o,task:s}=await ci(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=_t(n?await uO(t):await Jt(t,s.record.base??"HEAD")),a=i.filter((d)=>!J(d,s.contract.scope)),c=at(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 uO(t){let e=await O(t,["diff","--cached","--name-only","--no-renames","-z"]);return ae(e.stdout)}var nu=1,Hh=E({description:"Print the one next action",examples:["ari next","ari next --json"],json:!0,name:"next",run:async(t)=>{t.output.result(await Li(await P()),dO)}}),Kh=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 Wi(await P());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[mi(n.gates),`${r} for "${n.task}"`,...s].join(`
|
|
169
|
+
`)}),e.failed?nu:void 0}}),Uh=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 Vi(await P());return t.output.result(e.data,pO),e.failed?nu:void 0}}),Bh=E({args:N({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 Gh(await P(),{staged:t.args.staged});return t.output.result(e,gO),e.ok?void 0:nu}});function dO(t){return[t.instruction,...t.commands.map((e)=>` ${e}`)].join(`
|
|
170
|
+
`)}function pO(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[mi(t.gates.filter((e)=>!e.ok)),`Stage ${t.stage} failed: attempt ${t.attempts} of ${t.budget}`].join(`
|
|
171
|
+
`);case"blocked":return[mi(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(`
|
|
172
|
+
`)}}function gO(t){if(t.task===null)return t.ok?"No active task; scope passes":`Scope fails: ${t.reason??""}`;if(t.ok){let e=at(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(`
|
|
173
|
+
`)}import{resolve as hO}from"path";var mO=/^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)/,fO=/\r?\n/;function bo(t,e){return typeof t==="object"&&t!==null?t[e]:void 0}function vt(t,e){let n=bo(t,e);return typeof n==="string"?n:null}function Xi(t,e){return vt(t,"cwd")??e}function Wh(t){return t.split(fO).flatMap((e)=>mO.exec(e.trim())?.[1]?.trim()??[])}function To(t,e,n){return{command:n.command??null,cwd:e,event:t,paths:n.paths??[],tool:n.tool??null}}var ru=["before-edit","before-shell","after-tool","stop","pre-compact","session-start"],Ye=new Set(["before-edit","before-shell"]);function Vh(t){return ru.includes(t)}var yO=30,kO=120,wO=new Set(["stop","pre-compact"]),SO=1000,$O="apply_patch",Jh="run_shell_command";function Q(t,e,n=null){let r=wO.has(t)?kO:yO;return{agentEvent:e,event:t,matcher:n,timeoutSeconds:r}}var qh=[Q("stop","Stop"),Q("pre-compact","PreCompact","manual|auto"),Q("session-start","SessionStart","startup|resume|clear|compact|fork")];function su(t){return{decision:"block",reason:t}}function ou(t){return(e)=>({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t,permissionDecisionReason:e}})}function Yh(t,e,n){let r=bo(e,"tool_input"),o=vt(r,"file_path")??vt(r,"notebook_path"),s=vt(r,"command"),i=vt(e,"tool_name"),a=i===Jh?vt(r,"dir_path"):null;return To(t,hO(Xi(e,n),a??""),{command:s,paths:o===null?[]:[o],tool:i})}function bO(t,e,n){let r=vt(e,"tool_name"),o=vt(bo(e,"tool_input"),"command"),s=r===$O?{paths:Wh(o??"")}:{command:o};return To(t,Xi(e,n),{...s,tool:r})}function TO(t,e,n){let r=vt(e,"cwd")??vt(bo(e,"workspace_roots"),"0")??n,o=vt(e,"file_path");return To(t,r,{command:vt(e,"command"),paths:t==="after-tool"&&o!==null?[o]:[]})}function EO(t,e,n){return To(t,Xi(e,n),{command:vt(xO(e),"command"),tool:vt(e,"toolName")})}function xO({toolArgs:t}){if(typeof t!=="string")return t;try{return JSON.parse(t)}catch{return null}}function iu({answers:t},e,n){let r=vO(t,e,n);return typeof r==="string"?r:JSON.stringify(r)}function vO(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 CO={answers:{ask:ou("ask"),block:su,context:(t)=>t,deny:ou("deny")},file:".claude/settings.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,...Ye.has(e)?{onFailure:"block"}:{},timeout:n,type:"command"}),label:"Claude Code",layout:"grouped",name:"claude",parse:Yh,registrations:[Q("before-edit","PreToolUse","Edit|Write|NotebookEdit"),Q("before-shell","PreToolUse","Bash|PowerShell|Monitor"),Q("after-tool","PostToolUse","Edit|Write|NotebookEdit|Bash|PowerShell|Monitor"),...qh],support:"verified"},AO={answers:{allow:(t)=>t==="stop"?{}:"",block:su,context:(t)=>t,deny:ou("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:bO,registrations:[Q("before-edit","PreToolUse","^apply_patch$"),Q("before-shell","PreToolUse","^Bash$"),Q("after-tool","PostToolUse","^(Bash|apply_patch)$"),...qh],support:"verified"},IO={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*SO,type:"command"}),label:"Gemini CLI",layout:"grouped",name:"gemini",parse:Yh,registrations:[Q("before-edit","BeforeTool","write_file|replace"),Q("before-shell","BeforeTool",Jh),Q("after-tool","AfterTool","write_file|replace|run_shell_command"),Q("stop","AfterAgent","*"),Q("pre-compact","PreCompress","*"),Q("session-start","SessionStart","*")],support:"verified"},RO={answers:{allow:(t)=>Ye.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,...Ye.has(e)?{failClosed:!0}:{},timeout:n}),label:"Cursor",layout:"flat",name:"cursor",parse:TO,registrations:[Q("before-shell","beforeShellExecution"),Q("after-tool","afterFileEdit"),Q("stop","stop"),Q("pre-compact","preCompact"),Q("session-start","sessionStart")],support:"partial"},OO={answers:{allow:(t)=>Ye.has(t)?{permissionDecision:"allow"}:"",block:su,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:EO,registrations:[Q("before-shell","preToolUse","bash|powershell"),Q("stop","agentStop"),Q("pre-compact","preCompact"),Q("session-start","sessionStart")],support:"partial"},Kn=[CO,AO,IO,RO,OO];import{existsSync as Eo,readFileSync as Qh,rmSync as _O,statSync as PO}from"fs";import{join as xo,relative as cu}from"path";var ty="# ari:managed",NO=493,jO=64,MO=1,Xh=0,Sr=[{command:"ari scope --staged",name:"pre-commit"},{command:"ari verify",name:"pre-push"}],DO=["","."].flatMap((t)=>["yml","yaml","json","toml"].map((e)=>`${t}lefthook.${e}`)),zh=".husky",Zh=/\.ya?ml$/,ey=Sr.map((t)=>t.name);async function Zi(t){let e=await an(t,"hooks");return Sr.every(({name:n})=>{let r=xo(e,n);return lu(r)&&oy(r)})}async function Qi(t){let e=await vo(t);for(let n of e)if(n.action!=="unchanged")Nn(n.target,n.script,NO);return{agent:"git",files:e.map(({action:n,hook:r,path:o})=>({action:n,hook:r,path:o}))}}async function vo(t){let e=await uu(t);if(e!==null)throw new f(`This repository manages git hooks with ${e.name}; ari will not write hooks beside it`,e.hint);let n=await an(t,"hooks"),r=Sr.map((s)=>({hook:s,path:xo(n,s.name),script:LO(s)})),o=r.filter(({path:s})=>Eo(s)&&!lu(s));if(o.length>0){let s=o.map(({hook:i})=>i.name).join(", ");throw new f(`Unmanaged git hooks already exist: ${s}`,`Add the lines yourself: ${zi("").join("; ")}`)}return r.map(({hook:s,path:i,script:a})=>{let c=Eo(i);return{action:c&&Qh(i,"utf8")===a&&oy(i)?"unchanged":c?"updated":"created",hook:s.name,path:cu(t,i),script:a,target:i}})}async function ny(t){return cu(t,await an(t,"hooks"))}async function ry(t){let e=await an(t,"hooks");return{agent:"git",files:Sr.map(({name:r})=>{let o=xo(e,r),s=lu(o);if(s)_O(o);return{action:s?"removed":"unchanged",hook:r,path:cu(t,o)}})}}function lu(t){return Eo(t)&&Qh(t,"utf8").includes(ty)}function oy(t){return(PO(t).mode&jO)!==0}function LO(t){return["#!/bin/sh",ty,"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(`
|
|
174
|
+
`)}async function uu(t){let e=await O(t,["config","--get","core.hooksPath"],{allowedExitCodes:[Xh,MO]}),n=e.stdout.trim();if(e.exitCode===Xh&&n.length>0)return au(`core.hooksPath (${n})`,zi(`${n}/`),"Add the lines yourself: ");let r=DO.find((o)=>Eo(xo(t,o)));if(r!==void 0){let o=Zh.test(r)?FO():zi("lefthook ");return au(`lefthook (${r})`,o,Zh.test(r)?`Add to ${r}:
|
|
175
|
+
`:"Add the lines yourself: ")}if(Eo(xo(t,zh)))return au("husky",zi(`${zh}/`),"Add the lines yourself: ");return null}function zi(t){return Sr.map((e)=>`${t}${e.name}: ${e.command}`)}function au(t,e,n){let r=n.endsWith(`
|
|
176
|
+
`)?`
|
|
177
|
+
`:"; ";return{hint:`${n}${e.join(r)}`,lines:e,name:t}}function FO(){return Sr.flatMap((t)=>[`${t.name}:`," commands:",` ari-${t.name}:`,` run: ${t.command}`])}import{realpathSync as KO,rmSync as UO}from"fs";import{join as BO}from"path";import{join as sy}from"path";var iy="hooks.json",GO=384,HO=Jp(Os({installed:je(),original:je().or(Rs())}));function $r(t,e,n=iy){return ay(t,n)[e]??null}function br(t,e,n,r=iy){let{[e]:o,...s}=ay(t,r);if(n===null&&o===void 0)return;let i=n===null?s:{...s,[e]:n};Nn(sy(t,r),`${JSON.stringify(i)}
|
|
178
|
+
`,GO)}function ay(t,e){return pi(sy(t,e),HO,{})}var WO="ari hook",VO=1;function du(t,e){return`${WO} ${t} ${e}`}function uy(t,e,n){let{file:r,name:o}=e,s=Y(t,r),i=s===null?{}:Mt(r,s),a=$r(n,r),c=py(i,e)?void 0:s,l=a?.installed===s?a?.original:c,u=Yt(t,r,Co(e,s)),d=Y(t,r)??"";return br(n,r,l===void 0?null:{installed:d,original:l}),{action:u,agent:o,events:Io(e),file:r}}function Co(t,e){let n=e===null?{}:Mt(t.file,e);return Pn(e,gy(n,t,t.registrations))}function dy(t,e,n){let{file:r,name:o}=e;return{action:Ao(t,e)?JO(t,e,n):"unchanged",agent:o,file:r}}function JO(t,e,n){let{file:r}=e,o=$r(n,r);if(br(n,r,null),o===null||o.installed!==Y(t,r)){let s=mo(t,r)??{};return fo(t,r,gy(s,e,[]))}if(o.original!==null)return Yt(t,r,o.original);return UO(KO(BO(t,r))),"removed"}function Ao(t,e){let n=mo(t,e.file);return n!==null&&py(n,e)}function Io(t){return[...new Set(t.registrations.map((e)=>e.event))]}function py({hooks:t},e){if(!W(t))return!1;return Object.values(t).flat().some((n)=>my(n,e).length>0)}function gy({hooks:t={},...e},n,r){if(!W(t))throw cy(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 cy(n,`hooks.${a} that is not a list`);let l=qO(c,n,r.filter(({agentEvent:u})=>u===a));return l.length===0&&c.length>0?[]:[[a,l]]}),i=n.layout==="flat"?{version:e.version??VO}:{};return{...e,...i,...s.length===0?{}:{hooks:Object.fromEntries(s)}}}function cy({file:t},e){return new f(`${t} has a ${e}`,`Fix ${t}`)}function qO(t,e,n){let r=new Set(n);return[...t.flatMap((s)=>{let i=my(s,e),a=[...r].filter(({event:c})=>i.includes(du(e.name,c)));for(let c of a)r.delete(c);return[...YO(s,e),...a.map((c)=>ly(e,c))]}),...[...r].map((s)=>ly(e,s))]}function ly(t,e){let n=t.handler(du(t.name,e.event),e);if(t.layout==="flat")return n;return e.matcher===null?{hooks:[n]}:{hooks:[n],matcher:e.matcher}}function YO(t,e){let n=fy(t,e),r=n.filter((o)=>hy(o,e).length===0);if(r.length===n.length)return[t];return r.length>0&&W(t)?[{...t,hooks:r}]:[]}function my(t,e){return fy(t,e).flatMap((n)=>hy(n,e))}function fy(t,{layout:e}){if(e==="flat")return[t];return W(t)&&Array.isArray(t.hooks)?t.hooks:[]}function hy(t,{name:e}){let n=W(t)?Object.values(t):[],r=du(e,"");return n.filter((o)=>typeof o==="string"&&o.startsWith(r))}import{join as SP,resolve as Ny}from"path";import{resolve as Oy}from"path";var yy=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"),XO=/[ \t\r\n]/,zO=/\$\(cat <<-?[ \t]*(["'])(\w+)\1\n[\s\S]*?\n[ \t]*\2\n\s*\)/g,ZO=/\\[\s\S]/g,QO=/\\([$`"\\\n])/g,t_=/[$`]/,e_=/[$*?[]|\{./;var n_=/['"\\]/g,r_=/^\t+/;var o_=/[(`]/,s_=new Set(["-C","-c","--config-env","--exec-path","--git-dir","--namespace","--work-tree"]);function pu(t){let e=[],n=[],r=ky(""),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&&=!o_.test(u),r.words.length+r.inputs.length+r.outputs.length>0)e.push(r);r=ky(u)};while(i<t.length){yy.lastIndex=i;let u=yy.exec(t);if(u===null)break;let{arithmetic:d,blank:p,delimiter:g,double:m,escaped:h,input:w,output:b,plain:v,separator:B,single:K,tabs:_}=u.groups??{};if(i+=u[0].length,h!==void 0)a(h,!0);else if(K!==void 0)a(K,!0);else if(m!==void 0)a(a_(m),i_(m));else if(d!==void 0)a(d,!1);else if(v!==void 0)a(v,!e_.test(v)&&(s!==null||!v.startsWith("~")));else if(p!==void 0&&s!==null)c();else if(b!==void 0)c("outputs");else if(w!==void 0)c("inputs");else if(g!==void 0)c(),n.push({delimiter:g.replace(n_,""),tabs:_!==""});else if(B!==void 0){if(B===`
|
|
179
|
+
`)for(let M of n.splice(0)){let{body:A,end:C}=c_(t,i,M);r.inputs.push(A),i=C}l(B)}}return l(""),e}function gu(t){return pu(t).flatMap((e)=>[e,...[...e.words,...e.inputs].filter((n)=>XO.test(n)).flatMap(gu)])}function ta(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(s_.has(r))n+=1;if(r==="-C")e.push(t[n]??"")}return null}function Un(t){return t.slice(t.lastIndexOf("/")+1)}function ky(t){return{before:t,inputs:[],literal:!0,outputs:[],words:[]}}function i_(t){return!t_.test(t.replace(zO,"").replace(ZO,""))}function a_(t){return t.replace(QO,(e,n)=>n===`
|
|
180
|
+
`?"":n)}function c_(t,e,{delimiter:n,tabs:r}){for(let o=e;o<t.length;){let s=t.indexOf(`
|
|
181
|
+
`,o),i=s===-1?t.length:s,a=t.slice(o,i);if((r?a.replace(r_,""):a)===n)return{body:t.slice(e,o),end:i};o=i+1}return{body:t.slice(e),end:t.length}}import{basename as l_,isAbsolute as u_,join as d_,resolve as na}from"path";var p_=/^[A-Za-z_]\w*\+?=/,g_=new Set("! { builtin command do elif else env exec if nohup sudo then time until while".split(" ")),m_=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"]]]),f_=new Set("ari ariadne cat cd diff echo egrep file gh grep head jq ls popd printf pushd rg tail test wc".split(" ")),h_=new Set("add blame branch commit diff fetch grep log ls-files push show status tag".split(" ")),y_=new Set(["cd","popd","pushd"]),wy=new Set(["","&&",";",`
|
|
182
|
+
`]),k_="S suffix",w_=/^(?:-[a-z0-9E]*i|--in-place)/,S_=/^(?:-[a-zA-Z0-9]*[ef]|--expression|--file)/,$_="e f l expression file line-length",b_=/^-[a-zA-Z0-9]*[eE]/,T_="e E",E_=/^-\w+$/,x_=/^\.\w+$/,v_=/^(?:-[a-zA-Z]*t$|--target-directory)/,C_=/^(?:--staged|-[A-Za-z]*S)/,A_=/^(?:--worktree|-[A-Za-z]*W)/,Sy="of=",fu="--",mu=".";function by(t,e){let n=e,r=e,o=!0,s=t.map((i,a)=>{let c=R_(i,n),[l="",u="-",...d]=ra(i);if(!y_.has(l))return o=!1,c;return o&&=l==="cd"&&i.literal&&!u.startsWith("-")&&d.length===0,o&&=wy.has(i.before)&&wy.has(t[a+1]?.before??""),r=o?na(r,u):r,n=o?r:null,c});return{directory:r,steps:s}}function ra({words:t}){let e=t.findIndex((n)=>!p_.test(n)&&!g_.has(n));return e===-1?[]:[Un(t[e]??""),...t.slice(e+1)]}function oa(t,e=""){let n=new Set(e.split(" ")),r=t.indexOf(fu),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(I_(a)))i+=1}return[...o,...r===-1?[]:t.slice(r+1)].filter((i)=>i.length>0)}function I_(t){if(t.startsWith("--"))return t.slice(2);return E_.test(t)?t.slice(-1):""}function R_(t,e){if(!t.literal)return{command:t,resolved:!1,targets:[]};let[n="",...r]=ra(t),o=n==="git"?ta(r):null,s=e===null?null:na(e,...o?.directories??[]),i=o===null?Ty(n,r,e):O_(o.subcommand,o.args,s),a=[...ea(e,"file",t.outputs),...ea(s,"file",i?.written),...ea(s,"directory",i?.created),...ea(s,"removed",i?.removed)],c=a.filter((l)=>l!==null);return{command:t,resolved:i!==null&&c.length===a.length,targets:c}}function ea(t,e,n=[]){return n.flatMap((r)=>{if(t===null&&!u_(r))return null;let o=na(t??r,r),s=e!=="removed"&&di(o);if(s&&e==="directory")return[];return{kind:s?"directory":e,path:o}})}function Ty(t,e,n){let[r,o]=m_.get(t)??[];if(r!==void 0)return{[r]:oa(e,o)};switch(t){case"dd":return{written:e.filter((s)=>s.startsWith(Sy)).map((s)=>s.slice(Sy.length))};case"cp":case"ln":case"mv":return __(t,e,n);case"sed":return{written:$y(e,$_,S_)??[]};case"perl":{let s=$y(e,T_,b_);return s===null?null:{written:s}}default:return f_.has(t)?{}:null}}function O_(t,e,n){switch(t){case"checkout":return e.includes(fu)?{removed:e.slice(e.indexOf(fu)+1)}:null;case"restore":return e.some((o)=>C_.test(o))&&!e.some((o)=>A_.test(o))?{}:{removed:oa(e,"s source pathspec-from-file")};case"rm":case"mv":return Ty(t,e,n);default:return h_.has(t)?{}:null}}function __(t,e,n){if(e.some((a)=>v_.test(a)))return null;let r=oa(e,k_),[o=mu,s]=r.length<2?[mu,r]:[r.at(-1),r.slice(0,-1)],i=o.endsWith("/")||di(na(n??mu,o));return{removed:t==="mv"?s:[],written:i?s.map((a)=>d_(o,l_(a))):[o]}}function $y(t,e,n){if(!t.some((s)=>w_.test(s)))return null;let r=oa(t,e),o=r.length>1&&x_.test(r[0]??"")?r.slice(1):r;return t.some((s)=>n.test(s))?o:o.slice(1)}import{basename as Ey,dirname as P_,join as xy}from"path";var N_=[`${X}/tasks/*.md`,`${X}/designs/**`],j_="x",M_=/\*\*.*/,D_=".git",L_=[/^(?:ari|hooks|info)(?:\/|$)/,/^(?:HEAD|commondir|config(?:\.worktree)?|gitdir|objects|packed-refs|refs|worktrees)$/,/^(?:objects|refs|worktrees)\/(?!.*\.lock$)/],F_="; pass the paths to change instead of their directory",G_="\x00",sa=0,H_=1,vy=128;async function Cy(t,e){let n=bt(e),r=await t.governing(n),o=Ry(t.opened(),n);if(o!==null)return o;return r.flatMap((i)=>{let a=Ee(i.root,n);return a===null||a.length===0?[]:Ro(i,a)??[]})[0]??null}async function Ay(t,e){let n=[],r=new Map;for(let{kind:o,path:s}of e){let a=o==="removed"&&yl(s)!==null?xy(bt(P_(s)),Ey(s)):bt(s),c=await t.governing(a),l=Ry(t.opened(),a);if(l!==null)n.push(l);let u=o==="removed"?t.opened().filter(({root:d})=>Ee(a,d)!==null):[];for(let d of new Set([...c,...u])){let p=r.get(d)??[];r.set(d,[...p,{file:Ee(d.root,a)??"",kind:o}])}}for(let[o,s]of r)n.push(...await K_(o,s));return n}async function K_(t,e){let n=e.filter(({kind:a})=>a==="removed").map(({file:a})=>a),r=n.length===0?[]:await V_(t,n),o=n.flatMap((a)=>r.filter((u)=>a.length===0||u===a||u.startsWith(`${a}/`)).flatMap((u)=>{let d=Ro(t,u);return d===null?[]:`${d}${u===a?"":F_}`}).slice(0,1)),s=e.flatMap(({file:a,kind:c})=>{if(c==="removed"||a.length===0)return[];let l=c==="file"?Ro(t,a):U_(t,a),u=c==="file"?a:`${a}/`;return l===null?[]:[{guarded:Iy(t,a)!==null,name:u,reason:l}]}),i=await J_(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 Iy(t,e){if(mr(e)&&!J(e,N_))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)||J(e,n.contract.lock)?`${e} is locked by task "${n.contract.id}" and must stay unchanged`:null}function Ro(t,e,n=J){let r=Iy(t,e);if(r!==null||mr(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 U_(t,e){return Ro(t,`${e}/${j_}`)===null?null:Ro(t,e,B_)}function B_(t,e){let n=t.split("/").length,r=e.map((o)=>o.replace(M_,"**").split("/").slice(0,n).join("/"));return J(t,r)}function Ry(t,e){return t.some(({gitDirectories:r,root:o})=>Ee(xy(o,D_),e)===""||r.some((s)=>W_(s,e)))?`${Ey(e)} belongs to git and to ari's own state; use git and ari commands instead`:null}function W_(t,e){let n=Ee(t,e);return n!==null&&L_.some((r)=>r.test(n))}async function V_({root:t,workspace:e},n){let r=await O(t,["--literal-pathspecs","ls-files","-z","-co","--exclude-standard","--",...n.map((s)=>s.length===0?".":s)],{allowedExitCodes:[sa,vy]}),o=r.exitCode===sa?ae(r.stdout):n;return[...Object.keys(e?.task?.record.lockHashes??{}),X,...o]}async function J_(t,e){if(e.length===0)return new Set;let n=await O(t,["check-ignore","-z","--stdin"],{allowedExitCodes:[sa,H_,vy],stdin:[...new Set(e)].join(G_)});return new Set(n.exitCode===sa?ae(n.stdout):[])}var q_="'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>'",Y_="'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",X_="run it as a plain command with literal paths, or ask a person to run it",z_=/(?:^|\/)(?:ari|ariadne)(?:@[^/]*)?$/,Z_="approve",Q_="git",tP="commit",eP="config",nP=/^core\.hookspath$/i,rP=/^(?:--config-env=)?core\.hookspath=|^GIT_CONFIG_KEY_\d+=core\.hookspath$/i,oP=/^(?:--)?unset/,sP=/^(?:--no-veri(?:f|fy)?|-[^-\smFcCtSu]*n\S*)$/,iP=/(?<![\w-])\.ari(?![\w.-])/,hu=/[\s'"`;&|()<>=,]+/,aP=[[/^(?: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)/]],cP=/^(?:ba|da|fi|k|z)?sh$/,lP=/^-[a-z]*c$/,uP=/^(?:bun|deno|node|perl|php|python|ruby)[\d.]*$/,dP=/^(?:-[a-zA-Z]*[ceEip]|--eval|--print)$/;async function _y(t,e,n){let{directory:r,steps:o}=by(pu(e),n),s=[...new Set([...await t.governing(n),...await t.governing(r)])],i=pP(gu(e));if(i!==null&&(s.length>0||await gP(t,e,n)))return{kind:"deny",reason:i};let a=await Ay(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)=>yP(d)??[])[0],l=s.filter(({fault:d,workspace:p})=>d!==null||p?.task!=null),u=c===void 0?null:wP(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; ${X_}`}}function pP(t){if(t.some(mP))return q_;return t.some(fP)?Y_:null}async function gP(t,e,n){for(let r of new Set(e.split(hu)))if((await t.governing(Oy(n,r))).length>0)return!0;return!1}function mP({words:t}){return t.some((e,n)=>z_.test(e)&&t.slice(n+1).find((r)=>!r.startsWith("-"))===Z_)}function fP({words:t}){if(t.some((e)=>rP.test(e)))return!0;return t.some((e,n)=>{let r=Un(e)===Q_?ta(t.slice(n+1)):null;if(r?.subcommand===eP)return hP(r.args);return r?.subcommand===tP&&r.args.some((o)=>sP.test(o))})}function hP(t){let e=t.findIndex((n)=>nP.test(n));return e!==-1&&(e<t.length-1||t.some((n)=>oP.test(n)))}function yP({command:t}){let[e]=ra(t),n=t.words.flatMap((o)=>o.split(hu)).filter((o)=>o.length>0);return n.map(Un).find((o,s)=>kP(o,e,n,s+1))??(!t.literal&&t.outputs.length>0?">":null)}function kP(t,e,n,r){let o=aP.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=cP.test(t);if(!s&&!uP.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)=>lP.test(c)):i.slice(0,a===-1?i.length:a).some((c)=>dP.test(c))}function wP(t,e,n){if(t.length>0&&iP.test(e))return X;let r=new Set(e.split(hu));for(let{root:o,workspace:s}of t){let i=Object.keys(s?.task?.record.lockHashes??{}),a=new Set(i.map(Un));for(let c of[...r].filter((l)=>a.has(Un(l)))){let u=[o,...n].map((d)=>Ee(o,bt(Oy(d,c)))).find((d)=>d!==null&&i.includes(d));if(u!==void 0)return u}}return null}var $P="stop.json",bP=500,TP=20000,zt={kind:"allow"},EP={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"},xP=Os({task:je(),tree:je()});async function jy(t){let e=Km();if(Ye.has(t.event))return vP(CP(e,t));let n=await e.at(t.cwd);if(n===null)return ia(zt);if(n.workspace===null)return Py(t,n.fault??"");try{return ia(await IP(t,n.workspace))}catch(r){if(!(r instanceof f))throw r;return Py(t,wl(r))}}function Py({event:t},e){return{...ia(zt),warning:`ari hook skipped ${t}: ${e}`}}async function vP(t){let e=Promise.withResolvers(),n=setTimeout(e.resolve,TP,EP);try{return await Promise.race([e.promise,t.then(ia)])}finally{clearTimeout(n)}}function ia(t){return{decision:t,expired:!1,warning:null}}async function CP(t,e){let{command:n,cwd:r,event:o,paths:s}=e,i=await t.at(r);if(o==="before-shell"&&n!==null)return _y(t,n,r);if(o==="before-edit"&&s.length>0)return AP(t,e);if(i===null)return zt;return{kind:"ask",reason:`ari found no ${o==="before-edit"?"path":"command"} in the hook payload`}}async function AP(t,e){let n=[];for(let r of e.paths){let o=await Cy(t,Ny(e.cwd,r));if(o!==null)n.push(o)}return n.length===0?zt:{kind:"deny",reason:n.join("; ")}}async function IP(t,e){switch(t.event){case"before-edit":case"before-shell":return zt;case"after-tool":return aa(e,RP(t,e)),zt;case"stop":return OP(e);case"pre-compact":return aa(e,{detail:{},type:"compact"}),await kr(e.root),zt;case"session-start":return _P(e)}}function RP(t,e){let n=bt(e.root),r=t.paths.flatMap((o)=>Ee(n,bt(Ny(t.cwd,o)))??[]);if(r.length>0)return{detail:{paths:r},type:"edit"};if(t.command!==null)return{detail:{command:t.command.slice(0,bP)},type:"shell"};return{detail:t.tool===null?{}:{tool:t.tool},type:"tool"}}async function OP(t){let{task:e}=t;if(e===null||e.record.status!=="active")return zt;let n=e.contract.id,r=await Se(t.root,[Rn]);if(e.record.evidence.at(-1)?.treeHash===r)return zt;let o=SP(t.state,$P),s=pi(o,xP,null);if(s?.task===n&&s.tree===r)return zt;return Nn(o,`${JSON.stringify({task:n,tree:r})}
|
|
183
|
+
`),aa(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 _P(t){if(t.task===null)return zt;aa(t,{detail:{},type:"session"});let{text:e}=await yr(t.root,{id:t.task.contract.id});return e.trim().length===0?zt:{kind:"context",text:e}}function aa(t,e){if(t.task===null)return;On(t.state,{...e,at:new Date().toISOString(),task:t.task.contract.id})}var Tr="git",PP={amp:"Amp",opencode:"OpenCode"},NP=".git/hooks";function yu(){return[...Kn.map((t)=>t.name),Tr]}function gn(t){let e=Kn.find((r)=>r.name===t);if(e!==void 0)return e;if(t===Tr)throw new T("git hooks run 'ari scope --staged' and 'ari verify' directly","Run 'ari hooks install --agent git'");let n=PP[t];if(n!==void 0)throw new f(`${n} hooks run only as in-process plugins, which ari does not ship`,"Rely on the AGENTS.md block from 'ari init', 'ari hooks install --agent git' and 'ari verify' in CI");throw new T(`Unknown agent "${t}"`,`Choose one of: ${yu().join(", ")}`)}function My(t){if(t!==Tr)gn(t)}async function Er(t,e){if(e===Tr)return Qi(t);return uy(t,gn(e),await q(t))}async function Dy(t,e){if(e===Tr)return ry(t);return dy(t,gn(e),await q(t))}async function ca(t){return[...Kn.map((n)=>({agent:n.name,events:Io(n),file:n.file,installed:Ao(t,n),label:n.label,support:n.support})),{agent:Tr,events:[...ey],file:NP,installed:await Zi(t),label:"git",support:"git"}]}async function Ly(t,e,n,r){let o=gn(t),s=jP(o,e);try{let{decision:i,expired:a,warning:c}=await jy(o.parse(s,MP(n),r));return{expired:a,stdout:iu(o,s,i),warning:c}}catch(i){if(!Ye.has(s))throw i;let a=`ari could not check this ${s} event: ${i instanceof Error?i.message:String(i)}`;return{expired:!1,stdout:iu(o,s,{kind:"deny",reason:a}),warning:a}}}function jP(t,e){if(!Vh(e))throw new T(`Unknown hook event "${e}"`,`Choose one of: ${ru.join(", ")}`);if(Io(t).includes(e))return e;throw new T(`${t.label} has no ari adapter for "${e}"`,`Its adapter handles: ${Io(t).join(", ")}`)}function MP(t){if(t.trim().length===0)return{};let e=null;try{e=JSON.parse(t)}catch{}if(W(e))return e;throw new f("The hook payload on stdin is not a JSON object","Agents call 'ari hook' with a JSON object")}function Fy(t,e,n){let r=`ari hooks ${t} --agent`;return E({args:N({agent:{description:`Agent: ${yu().join(", ")}`,type:"string"}}),description:e,examples:[`${r} claude`,`${r} git`],json:!0,name:t,run:async(o)=>{let s=un(o.args.agent,"--agent",`${r} <name>`);o.output.result(await n(await P(),s),FP)}})}var DP=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 ca(await P());t.output.result({agents:e},({agents:n})=>n.map(GP).join(`
|
|
184
|
+
`))}}),Gy=E({description:"Install, uninstall and list agent and git hook integrations",name:"hooks",subcommands:[Fy("install","Install ari hooks into an agent's project settings or into git",Er),Fy("uninstall","Remove ari hooks from an agent's project settings or from git, and nothing else",Dy),DP]}),Hy=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:rt({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 Ly(t.positionals.agent,t.positionals.event,e,process.cwd());if(n.warning!==null)process.stderr.write(`${n.warning}
|
|
125
185
|
`);if(n.stdout.length>0)process.stdout.write(`${n.stdout}
|
|
126
|
-
`);if(n.expired)await
|
|
127
|
-
`);let e="events"in t?`: ${t.events.join(", ")}`:"";return`${t.agent} hooks ${t.action} in ${t.file}${e}`}function
|
|
128
|
-
|
|
129
|
-
`,
|
|
130
|
-
|
|
131
|
-
${o}
|
|
132
|
-
|
|
133
|
-
`)
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
`)
|
|
138
|
-
`
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
`)}function _C(t){return t.trimEnd().split(`
|
|
186
|
+
`);if(n.expired)await LP()}});async function LP(){return await new Promise((t)=>process.stdout.write("",()=>t())),process.exit()}function FP(t){if("files"in t)return t.files.map((n)=>`git ${n.hook}: ${n.action} (${n.path})`).join(`
|
|
187
|
+
`);let e="events"in t?`: ${t.events.join(", ")}`:"";return`${t.agent} hooks ${t.action} in ${t.file}${e}`}function GP(t){let e=t.installed?"installed":"not installed";return`${t.agent} ${t.support} ${e} ${t.file} ${t.events.join(", ")}`}import{existsSync as y0}from"fs";import{join as k0}from"path";import{homedir as Ky}from"os";import{join as HP}from"path";var la=["project","user"],KP=".ari",UP="receipts",BP="~/";function ua(t){let e=t??"project",n=la.find((r)=>r===e);if(n!==void 0)return n;throw new T(`Unknown scope "${e}"`,`Choose one of: ${la.join(", ")}`)}async function Ce(t,e){if(t==="user")return{base:Ky(),receipts:HP(Ky(),KP,UP),scope:t};let n=await ir(e);return{base:n,receipts:await q(n),scope:t}}function ge(t,e){return t==="user"?`${BP}${e}`:e}function Oo(t,e,n){let r=t.find((o)=>o.agent===e);if(r!==void 0)return r;throw new T(`ari has no ${n} integration for "${e}"`,`Choose one of: ${t.map((o)=>o.agent).join(", ")}`)}function ku(t,e,n){return[...new Set(e)].map((r)=>Oo(t,r,n))}import{isDeepStrictEqual as QP}from"util";import{realpathSync as WP,rmSync as VP}from"fs";import{join as JP}from"path";function da(t){let{base:e,file:n,receipts:r}=t,o=Y(e,n),s=t.install(o),i=$r(r.directory,n,r.store),a=t.managed(o)?void 0:o,c=i?.installed===o?i.original:a,l=Yt(e,n,s),u=Y(e,n)??"";return br(r.directory,n,c===void 0?null:{installed:u,original:c},r.store),l}function pa(t){let{base:e,file:n,receipts:r}=t,o=Y(e,n);if(o===null||!t.managed(o))return"unchanged";let s=$r(r.directory,n,r.store),i=s?.installed===o?s.original:t.remove(o);if(br(r.directory,n,null,r.store),i!==null)return Yt(e,n,i);return VP(WP(JP(e,n))),"removed"}function ga(t){return t.managed(Y(t.base,t.file))}import{isDeepStrictEqual as qP}from"util";var xr="# ari:begin",_o="# ari:end",Po=`\r
|
|
188
|
+
`,Ae=`
|
|
189
|
+
`,YP=1,XP=/^\r?\n/,zP=/\r$/;function By(t){return(t??"").split(Ae).some((e)=>Su(e,xr))}function Wy(t,e){let n=t??"";wu(e.file,n);let r=n.includes(Po)?Po:Ae,o=[`${xr} managed by 'ari mcp install'; 'ari mcp uninstall' removes it`,...e.lines,_o].join(r),s=Jy(e.file,n);if(s===null&&Uy(wu(e.file,n),e.table)!==void 0)throw new f(`${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?ZP(n,o,r):n.slice(0,s.start)+o+n.slice(s.end),a;try{a=wu(e.file,i)}catch(c){throw new f(`ari cannot add [${e.table.join(".")}] to ${e.file} without breaking it`,`Add the table yourself:
|
|
190
|
+
${e.lines.join(Ae)}`,YP,{cause:c})}if(qP(Uy(a,e.table),e.value))return i;throw new f(`ari cannot add [${e.table.join(".")}] to ${e.file}: the file defines it in another way`,`Add the table yourself:
|
|
191
|
+
${e.lines.join(Ae)}`)}function Vy(t,e){let n=Jy(t,e);if(n===null)return e;let r=e.slice(0,n.start),o=e.slice(n.end).replace(XP,""),i=(r.endsWith(`${Po}${Po}`)?r.slice(0,-Po.length):r.endsWith(`${Ae}${Ae}`)?r.slice(0,-Ae.length):r)+o;return i.trim().length===0?null:i}function ZP(t,e,n){if(t.length===0)return`${e}${n}`;return`${t.endsWith(Ae)?t:`${t}${n}`}${n}${e}${n}`}function Jy(t,e){let n=[],r=0;for(let i of e.split(Ae)){let a=r+i.replace(zP,"").length;if(Su(i,xr))n.push({end:a,kind:xr,start:r});else if(Su(i,_o))n.push({end:a,kind:_o,start:r});r+=i.length+Ae.length}let[o,s]=n;if(o===void 0)return null;if(n.length!==2||o.kind!==xr||s?.kind!==_o)throw new f(`${t} has a damaged ari block: expect one '${xr}' line followed by one '${_o}' 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 Su(t,e){let n=t.trim();return n===e||n.startsWith(`${e} `)}function wu(t,e){try{return Bun.TOML.parse(e)}catch(n){let r=n instanceof Error?n.message:String(n);throw new f(`${t} is not valid TOML (${r})`,`Fix ${t}, then run the command again`)}}function Uy(t,e){return e.reduce((n,r)=>typeof n==="object"&&n!==null?n[r]:void 0,t)}var Ie="ari",$u="ari",fa=["mcp","serve"],No="mcpServers",t0="mcp.json",qy=900,e0=1000,n0=2,ma={command:$u,args:fa},Xe=[{agent:"claude",entry:ma,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 ${Ie} -- ${$u} ${fa.join(" ")}'`},{agent:"codex",entry:{...ma,tool_timeout_sec:qy},format:"toml",label:"Codex CLI",project:".codex/config.toml",user:".codex/config.toml",userHint:null},{agent:"gemini",entry:{...ma,timeout:qy*e0},format:"json",label:"Gemini CLI",project:".gemini/settings.json",user:".gemini/settings.json",userHint:null},{agent:"cursor",entry:{type:"stdio",...ma},format:"json",label:"Cursor",project:".cursor/mcp.json",user:".cursor/mcp.json",userHint:null}];function Bn(t){return Oo(Xe,t,"MCP")}function vr(t,e){return ya(t,e)}function Cr(t,e){let n=ya(t,e);return{...zy(t,e,n.file),action:da(n)}}function Xy(t,e){let n=ya(t,e);return{...zy(t,e,n.file),action:pa(n)}}function ha(t,e){return Xe.map((n)=>({agent:n.agent,files:[t,e].flatMap((r)=>{let o=n[r.scope];if(o===null)return[];let s=ga(ya(n,r));return[{file:ge(r.scope,o),installed:s,scope:r.scope}]}),label:n.label}))}function zy(t,e,n){return{agent:t.agent,file:ge(e.scope,n),scope:e.scope,server:Ie}}function ya(t,e){let n=t[e.scope];if(n===null)throw new f(`ari does not write ${t.label}'s ${e.scope}-scope MCP configuration`,t.userHint??"");let r={directory:e.receipts,store:t0},o={base:e.base,file:n,receipts:r};return t.format==="toml"?{...o,...r0(t,n)}:{...o,...o0(t,n)}}function r0(t,e){let n={file:e,lines:[`[mcp_servers.${Ie}]`,...s0(t.entry)],table:["mcp_servers",Ie],value:t.entry};return{install:(r)=>Wy(r,n),managed:By,remove:(r)=>Vy(e,r)}}function o0(t,e){let n=(o)=>{let s=o[No]??{};if(W(s))return s;throw new f(`${e} has a "${No}" value that is not an object`,`Fix ${e}`)},r=(o,s)=>o===null?`${JSON.stringify(s,null,n0)}
|
|
192
|
+
`:Ds(o,s);return{install:(o)=>{let s=o===null?{}:Mt(e,o),i=n(s),a=i[Ie];if(a!==void 0&&!Yy(a))throw new f(`${e} already has an MCP server named "${Ie}" that ari did not write`,`Rename or remove mcpServers.${Ie} in ${e}, then run the command again`);let c={...W(a)?a:{},...t.entry};return r(o,{...s,[No]:{...i,[Ie]:c}})},managed:(o)=>o!==null&&Yy(n(Mt(e,o))[Ie]),remove:(o)=>{let{[No]:s,...i}=Mt(e,o),{[Ie]:a,...c}=n(Mt(e,o));return r(o,Object.keys(c).length===0?i:{...i,[No]:c})}}}function s0(t){let{args:e,command:n,...r}=t;return Object.entries({command:n,args:e,...r}).map(([o,s])=>`${o} = ${Zy(s)}`)}function Zy(t){if(Array.isArray(t))return`[${t.map(Zy).join(", ")}]`;return typeof t==="number"?String(t):JSON.stringify(t)}function Yy(t){if(!W(t)||t.command!==$u||!Array.isArray(t.args))return!1;return QP(t.args.slice(0,fa.length),fa)}import{existsSync as g0,readdirSync as m0,rmdirSync as f0}from"fs";import{dirname as ek,join as nk}from"path";var me="ariadne",Qy="SKILL.md",ka="<!-- ari:managed by 'ari skills install'; 'ari skills uninstall' removes it -->";var i0=["---","name: ariadne","description: Work through this repository's Ariadne (ari) tasks, whose contracts, gates and memory the ari CLI keeps. Use it whenever the repository has an .ari/ directory, before changing code there, and when asked to pick up, check, finish or write an ari task.","---"],a0=["# Ariadne","","This repository tracks work as Ariadne tasks. A task's contract (`.ari/tasks/<id>.md`) says what \"done\" means, and `ari` decides when it is done by running the contract's checks itself. Never report a task as finished on your own word: only `ari done` finishes a stage."],c0=["## The loop","","1. Run `ari next` and follow the one action it prints.","2. Change only files inside the active task's `scope`. Files the contract locks must stay byte-identical.","3. Run `ari check` to evaluate the current stage's gates. It records nothing.","4. Run `ari done`. It records the evidence and advances to the next stage, or prints every failing gate with its output and exits 1. Fix what it reports and run it again.","","Repeat until `ari done` reports `done`. Each failed `ari done` spends an attempt, and a spent budget (3 by default) blocks the task for a person, so run `ari check` first. Add `--json` to any of these commands for one JSON document on stdout. `ari show <id>` prints a task with its stage and instruction, and `ari list` lists the tasks.","","When ari's MCP server is connected, the tools `ari_next`, `ari_check`, `ari_done` and the others do the same and return the same JSON documents."],l0=["## Writing a contract","",'`ari new "<title>" --scope "src/feature/**"` creates a draft contract. Complete its YAML front matter:',"","```markdown","---","title: Add profile inheritance","pack: basic","scope:"," - src/profiles/**","lock:"," - src/profiles/inheritance.test.ts","criteria:"," - id: AC-1"," text: A child profile's values override its parent's"," checks: [inheritance]","checks:"," inheritance:"," run: bun test src/profiles/inheritance.test.ts"," expect: pass","invariants:"," - bun run lint","---","What the implementer should know.","```","","- `scope` lists globs of the files the task may change. Write `src/**`, never `src/`.","- Bind every criterion to at least one check. A check is a shell command run from the repository root.","- `lock` keeps files, such as the tests that define the work, unchanged from `ari start` onwards.","- `pack` chooses the stages: `basic`, `sdlc`, `tdd`, `bugfix`, `spec-driven`, `refactor` or `spike`.","","Then `ari ready <id>` validates the contract and `ari start <id>` starts the task in this worktree. Starting needs a clean working tree outside `.ari/`."],u0=["## What the gates mean","","| Gate | Passes when |","| --- | --- |","| `criteria` | every criterion names a check that exists |","| `checks` | each selected check exits as the stage expects; in a `tdd` red stage they must fail |","| `invariants` | every invariant command exits 0 |","| `scope` | every file changed since the task started matches the scope |","| `locked` | the locked files are unchanged |","| `tests-unchanged` | the test files in the scope are unchanged since the stage started |","| `regression` | each regression check fails on the base commit and passes now |","| `artifact` | a file such as `.ari/designs/<id>.md` exists with enough content |","| `approval` | a person approved the stage and nothing has changed since |","| `review` | the review command, or the review agent's verdict, passed the change; `ari review` shows that verdict first and records nothing |","| `command` | the pack's command exits 0 |","","When `ari check` reports `contractChanged` or `gatesChanged`, the contract or the gates differ from the ones frozen at start, and `ari done` refuses. Ask a person to amend the task."],d0=["## Memory","",'- `ari note "<text>"` adds a note to the active task.','- `ari note --global --kind pattern "<text>"` adds project knowledge that outlives the task; the kinds are `fact`, `decision`, `constraint`, `pattern` and `gotcha`.',"- `ari knowledge search <query>` finds project knowledge, and `ari knowledge show <id>` prints one entry.","- `ari context` prints the active task's context pack: the contract, its notes and the relevant knowledge, within a token budget. Run it after your context is reset or compacted."],p0=["## What only people do","","- `ari approve`, `ari amend` and `ari resolve` are for people. Never run them; ask instead.",'- When you are stuck, or the contract looks wrong, run `ari block <id> --reason "<question>"` and stop.',"- Never edit `.ari/config.json`, `.ari/tasks/*.json` or `.ari/knowledge/**`: ari writes them. Edit only contracts (`.ari/tasks/*.md`) and designs (`.ari/designs/**`).","- Never skip the git hooks with `git commit --no-verify`.","","`ari --help --json` describes every command and option."];function tk(){let t=[a0,c0,l0,u0,d0,p0].map((e)=>e.join(`
|
|
193
|
+
`));return`${[...i0,"<!-- ari:managed by 'ari skills install'; 'ari skills uninstall' removes it -->",""].join(`
|
|
194
|
+
`)}
|
|
195
|
+
${t.join(`
|
|
196
|
+
|
|
197
|
+
`)}
|
|
198
|
+
`}var h0="skills.json";function mn(t){return nk(t,me,Qy)}var ze=[{agent:"claude",label:"Claude Code",project:mn(".claude/skills"),user:mn(".claude/skills")},{agent:"codex",label:"Codex CLI",project:mn(".agents/skills"),user:mn(".agents/skills")},{agent:"gemini",label:"Gemini CLI",project:mn(".gemini/skills"),user:mn(".gemini/skills")},{agent:"cursor",label:"Cursor",project:mn(".cursor/skills"),user:mn(".cursor/skills")}];function Wn(t){return Oo(ze,t,"skill")}function Ar(t,e){return Sa(t,e)}function Ir(t,e){let n=Sa(t,e);return{...ok(t,e),action:da(n)}}function rk(t,e){let n=Sa(t,e),r=pa(n);if(r==="removed")sk(e.base,ek(n.file));return{...ok(t,e),action:r}}function wa(t,e){return ze.map((n)=>({agent:n.agent,files:[t,e].map((r)=>({file:ge(r.scope,n[r.scope]),installed:ga(Sa(n,r)),scope:r.scope})),label:n.label}))}function ok(t,e){let n=ge(e.scope,t[e.scope]);return{agent:t.agent,file:n,scope:e.scope,skill:me}}function Sa(t,e){let n=t[e.scope],r=(o)=>(o??"").includes(ka);return{base:e.base,file:n,install:(o)=>{if(o===null||r(o))return tk();throw new f(`${ge(e.scope,n)} exists and ari did not write it`,`Move or remove that skill, then run 'ari skills install --agent ${t.agent}' again`)},managed:r,receipts:{directory:e.receipts,store:h0},remove:()=>null}}function sk(t,e){let n=nk(t,e);if(e==="."||!g0(n)||m0(n).length>0)return;f0(n),sk(t,ek(e))}var Ct="AGENTS.md",bu="<!-- ari:begin -->",$a="<!-- ari:end -->",w0=/^ {0,3}(<!-- ari:(?:begin|end) -->)\s*$/,S0=/^ {0,3}(`{3,}(?=[^`]*$)|~{3,})/,$0=/^ {0,3}(`{3,}|~{3,})[ \t]*\r?$/,Tu=`${X}/config.json`,b0="git",ik=`\r
|
|
199
|
+
`,Eu=`
|
|
200
|
+
`,T0=[bu,"## Ariadne","","This repository tracks work as Ariadne (`ari`) tasks. Work in this loop:","","1. Run `ari next` and follow the one action it prints.","2. Change only files inside the active task's `scope`.","3. Run `ari check` to evaluate the current stage's gates.","4. Run `ari done`; it records evidence and advances. Fix what it reports and run it again.","",'Record learnings with `ari note "<text>"` and reload context with `ari context`. If you are stuck, ask a human with `ari block <id> --reason "<question>"`.',"Edit task contracts (`.ari/tasks/*.md`) and designs, never other files under `.ari/`: ari writes them. `ari --help --json` describes every command.",$a];function xu(t){let e=jo(Y(t,Ct));return{action:Yt(t,Ct,e),path:Ct}}function vu(t,e){return Yt(t,Tu,Cu(Y(t,Tu),e))}function Cu(t,e){let n=t??xm();if(e===null)return n;let r=Mt(Tu,n);if(An(r).pack===e)return n;return Pn(n,{...r,pack:e})}async function ak(t,e={}){let n=[...e.agents??[],...e.gitHooks===!0?[b0]:[]],r=[...new Set(n)];for(let m of r)My(m);let o=ku(Xe,e.mcp??[],"MCP"),s=ku(ze,e.skills??[],"skill"),i=y0(k0(t,X))?Te(t):[],a=e.pack===void 0?null:In(e.pack,i).name,c=vu(t,a),l=xu(t),u=[];for(let m of r)u.push(await Er(t,m));let d={base:t,receipts:await q(t),scope:"project"},p=o.map((m)=>Cr(m,d)),g=s.map((m)=>Ir(m,d));return{agentsMd:l,config:c,hooks:u,mcp:p,pack:U(t).pack,root:t,skills:g}}function jo(t){let e=t??"",n=e.includes(ik)?ik:Eu,r=T0.join(n),o=E0(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!==bu||i?.marker!==$a)throw new f(`${Ct} has a damaged ari block: expect one ${bu} followed by one ${$a}`,`Remove the ari markers and the lines between them from ${Ct}, then run 'ari init' again`);return`${e.slice(0,s.start)}${r}${e.slice(i.start+$a.length)}`}function E0(t){let e=[],n=null,r=0;for(let o of t.split(Eu)){let s=S0.exec(o)?.[1];if(n===null&&s!==void 0)n={mark:s,markers:e.length};else if(n!==null&&x0(o,n.mark))e.length=n.markers,n=null;let i=w0.exec(o)?.[1];if(i!==void 0)e.push({marker:i,start:r+o.indexOf(i)});r+=o.length+Eu.length}return e}function x0(t,e){return $0.exec(t)?.[1]?.startsWith(e)===!0}var ck=E({args:N({agents:{description:"Install agent hooks, comma-separated (claude,codex,gemini,cursor,copilot,git)",type:"string"},gitHooks:{default:!1,description:"Install the pre-commit and pre-push git hooks",type:"boolean"},mcp:{description:"Register ari's MCP server, comma-separated (claude,codex,gemini,cursor)",type:"string"},pack:{description:"Default methodology pack for new tasks",type:"string"},skills:{description:"Install the ariadne skill, comma-separated (claude,codex,gemini,cursor)",type:"string"}}),description:"Create .ari/ and the AGENTS.md block, and optionally install hooks, MCP servers and skills",examples:["ari init","ari init --pack tdd --agents claude,codex --git-hooks","ari init --agents claude --mcp claude --skills claude"],json:!0,name:"init",run:async(t)=>{let e=await P(),n=await ak(e,{agents:jn(t.args.agents),gitHooks:t.args.gitHooks,mcp:jn(t.args.mcp),pack:t.args.pack,skills:jn(t.args.skills)});t.output.result(n,v0)}});function v0(t){let e=t.hooks.flatMap((n)=>("files"in n)?n.files.map((r)=>`git ${r.hook}: ${r.action} (${r.path})`):[`${n.agent} hooks: ${n.action} (${n.file})`]);return[`.ari/config.json: ${t.config} (pack ${t.pack})`,`${t.agentsMd.path}: ${t.agentsMd.action}`,...e,...t.mcp.map((n)=>`${n.agent} MCP server: ${n.action} (${n.file})`),...t.skills.map((n)=>`${n.agent} skill: ${n.action} (${n.file})`),'Next: ari new "<title>"'].join(`
|
|
201
|
+
`)}import{dirname as lk}from"path";var gt=["claude","codex","gemini","cursor","copilot"],fn=["hooks","mcp","skill"],Rr={hooks:"hooks",mcp:"MCP server",skill:"skill"},Ru="config",hn="agents-md",Zt="git",Ta="claude mcp add --scope user ari -- ari mcp serve",Au=".ari/config.json",C0="AGENTS.md",uk=".claude/settings.json",dk=["cursor","copilot"],pk={cursor:["claude","codex"],gemini:["codex"]},A0=["claude","codex","gemini"],I0=":";function ht(t,e){return`${t}${I0}${e}`}function gk(t){return gt.includes(t)}function yt(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 Ea(t){let e=new Set(t.targets.filter(Pu).map((n)=>n.agent));return gt.filter((n)=>yt(t,n).path!==null||e.has(n))}function Vn(t,e,n,r){let o=t.initialised&&!r?[yk(t,hn,"project")]:[],s=fn.flatMap((i)=>gt.filter((a)=>e.includes(a)).map((a)=>L0(t,a,i,n)));return[...o,...s,F0(t)]}function R0(t,e,n,r){let s=Vn(t,e,n,r).filter((a)=>a.skip===null&&a.problem===null).map((a)=>a.id),i=new Set(va(t,s).map(({id:a})=>a));return s.filter((a)=>!i.has(a))}function mk(t,e,n,r){return Vn(t,e,n,r).map((o)=>o.id)}function fk(t,e,n,r){let o=Vn(t,e,n,r),s=new Set(o.filter((i)=>i.status!=="current"&&i.elsewhere===null).map((i)=>i.id));return R0(t,e,n,r).filter((i)=>s.has(i))}function hk(t,e){let n=t.configured.map((s)=>({...s,configured:!0})),r=new Set(n.map((s)=>s.name)),o=e.filter((s)=>yt(t,s).preset&&!r.has(s)).map((s)=>({configured:!1,model:null,name:s,roles:[]}));return[...n,...o]}function Ou(t,e){if(e.pack!==null&&!t.packs.some((d)=>d.name===e.pack))throw new T(`Unknown pack "${e.pack}"`,`Choose one of: ${t.packs.map((d)=>d.name).join(", ")}`);if(e.routing!==null)D0(t,e.routing,e.init);let n=e.init,r=Vn(t,e.agents,e.scope,n),o=new Set(e.targets),s=e.recommended?va(t,e.targets):[],i=new Map(s.map(({id:d,reason:p})=>[d,p])),a=n?[ba(Ru,null,"config","project",Au,null),ba(hn,null,"config","project",C0,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?G0(d.problem):null,m=d.skip??i.get(d.id)??g;return[ba(d.id,d.agent,d.kind,d.scope,d.file,m)]}),u=e.routing===null?[]:[ba("routing",null,"routing","project",Au,null)];return{init:n,pack:e.pack,routing:e.routing,scope:e.scope,targets:[...a,...l,...u],warnings:xa(t,{...e,targets:e.targets.filter((d)=>!i.has(d))})}}function xa(t,e){let n=Vn(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=kk(t),i=new Set([...[...r].filter((c)=>o.has(c)),...s]),a={answers:e,effective:i,installed:s,requested:r,state:t};return[...O0(a),..._0(a),...P0(a),...N0(a),...j0(a),...M0(a,n)]}function O0({answers:t,state:e}){return t.agents.flatMap((n)=>{let r=yt(e,n);if(r.path!==null)return[];return[Or("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 _0({answers:t,requested:e}){if(t.scope!=="user"||!e.has(ht("mcp","claude")))return[];return[Or("claude-user-mcp","Claude Code keeps user-scope MCP servers in its own state file, which ari does not edit",`Run: ${Ta}`)]}function P0({requested:t,state:e}){let n=e.hookManager;if(n===null||!t.has(Zt))return[];return[Or("git-hooks-managed",wk(n.name),n.hint)]}function N0({effective:t,installed:e,requested:n,state:r}){let o=ht("hooks","claude");if(!t.has(o))return[];return dk.flatMap((s)=>{let i=ht("hooks",s);if(!t.has(i)||!(n.has(i)||n.has(o)))return[];let a=yt(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 ${uk}, so every ari hook would run twice there`;return[Or("hooks-twice",u,l,c)]})}function j0({answers:t,effective:e,installed:n,requested:r,state:o}){return gt.flatMap((s)=>{let i=pk[s];if(i===void 0||!t.agents.includes(s))return[];let a=[s,...i].filter((h)=>e.has(ht("skill",h)));if(a.length<2||!a.some((h)=>r.has(ht("skill",h))))return[];let c=yt(o,s).label,l=ht("skill",s),u=r.has(l)&&!n.has(l)&&a.includes(s)?[l]:[],d=a.map((h)=>Iu(o,h)),p=a.filter((h)=>h!==s).map((h)=>Iu(o,h)),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((h)=>yt(o,h).label).join(" and ")} need them`,m=`${c} reads ${d.join(" and ")}, so it would load the ariadne skill ${H0(a.length)}`;return[Or("skill-twice",m,g,u)]})}function M0({requested:t},e){return e.flatMap((n)=>{if(n.problem===null||n.skip!==null||!t.has(n.id))return[];return[Or("target-blocked",n.problem.message,n.problem.hint)]})}function va(t,e){let n=new Set(e),r=kk(t),o=new Set([...n,...r]),s=o.has(ht("hooks","claude")),i=dk.flatMap((c)=>{let l=ht("hooks",c);if(!s||!n.has(l)||r.has(l))return[];let u=`${yt(t,c).label} runs Claude Code's hooks from ${uk}`;return[{id:l,reason:u}]}),a=gt.flatMap((c)=>{let l=ht("skill",c),u=(pk[c]??[]).find((g)=>o.has(ht("skill",g)));if(u===void 0||!n.has(l)||r.has(l))return[];let d=Iu(t,u),p=`${yt(t,c).label} also reads ${d}, where ${yt(t,u).label}'s copy is`;return[{id:l,reason:p}]});return[...i,...a]}function D0(t,e,n){if(!t.initialised&&!n)throw new T("Routing needs .ari/config.json, which does not exist yet","Pass --init to create it in the same run, or run 'ari init' first");let r=new Set([...t.configured.map((s)=>s.name),...A0]);for(let[s,i]of[["--task-agent",e.task],["--review-agent",e.review]]){if(r.has(i.agent))continue;throw new T(`${s} names "${i.agent}", which is neither a configured agent nor a preset`,`Choose one of: ${[...r].join(", ")}`)}let o=t.routing.reviewCommand;if(o===null)return;throw new f(`review.command (${o}) runs the review gate, so ari cannot also set review.agent`,`Remove review.command from ${Au}, or leave the review agent out`,1,{tag:"ReviewCommandSet"})}function L0(t,e,n,r){let o=yt(t,e),s=ht(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 ${Rr[n]} integration for ${o.label}`};if(i==="user"&&!o.userScope.includes(n))return{...a,skip:`${o.label} keeps user-scope MCP servers itself; run '${Ta}'`};let c=_u(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&&Pu(u)?u.scope:null;return{...a,elsewhere:d,file:c.file,problem:c.problem,skip:null,status:c.status}}function F0(t){let e=t.hookManager,n={agent:null,elsewhere:null,id:Zt,kind:"git",scope:"project"};if(e!==null)return{...n,file:t.gitHooksDirectory,problem:null,skip:wk(e.name),status:null};return yk(t,Zt,"project")}function yk(t,e,n){let r=_u(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 _u(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 kk(t){return new Set(t.targets.filter(Pu).map((e)=>e.id))}function Pu(t){return t.status!=="missing"&&t.agent!==null}function Iu(t,e){return lk(lk(_u(t,ht("skill",e),"project").file))}function wk(t){return`${t} manages this repository's git hooks, so ari leaves them alone`}function G0(t){return t.hint.length===0?t.message:`${t.message}. ${t.hint}`}function ba(t,e,n,r,o,s){return{agent:e,file:o,id:t,kind:n,scope:r,skip:s}}function Or(t,e,n,r=[]){return{code:t,drop:r,fix:n,message:e}}function H0(t){return t===2?"twice":`${t} times`}var K0="--hooks, --mcp, --skills or --git-hooks";function Sk(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:B0(t.agent),init:t.init,kinds:e.size===0?void 0:e,pack:Mo(t.pack,"--pack"),routing:W0(t),scope:t.scope===void 0?void 0:ua(t.scope)}}function $k(t){return Object.values(t).some((e)=>e!==void 0)}function Nu(t,e){return[...fn.filter((r)=>e.has(r)).flatMap((r)=>t.map((o)=>ht(r,o))),...e.has("git")?[Zt]:[]]}function ju(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?[]:Ea(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(K0);if(r.length>0)throw U0(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?mk(t,i,c,o):Nu(i,e.kinds??new Set)}}function U0(t,e){let n=t.join(" and ");return new T(`ari install needs ${n} when it cannot ask${e?"; no agent was found on PATH":""}`,`For example: ari install ${t.includes("--init")?"--init ":""}--agent claude,codex --yes. --yes installs every supported target; see 'ari install --help'`)}function B0(t){let e=[...new Set(t.split(",").map((n)=>n.trim()).filter((n)=>n.length>0))];if(e.length===0)throw new T("--agent needs at least one agent",`Choose from: ${gt.join(", ")}`);return e.map((n)=>{if(gk(n))return n;throw new T(`ari install has no agent "${n}"`,`Choose from: ${gt.join(", ")}`)})}function W0(t){let e=Mo(t.taskAgent,"--task-agent"),n=Mo(t.reviewAgent,"--review-agent"),r=Mo(t.taskModel,"--task-model"),o=Mo(t.reviewModel,"--review-model");if(e===void 0&&n===void 0){let s=r!==void 0?"--task-model":o!==void 0?"--review-model":null;if(s===null)return;throw new T(`${s} needs --task-agent and --review-agent`,"Pass both agents to set the routing")}if(e===void 0||n===void 0)throw new T(`Routing needs ${e===void 0?"--task-agent":"--review-agent"} as well`,"Pass --task-agent and --review-agent together");return{review:{agent:n,model:o??null},task:{agent:e,model:r??null}}}function Mo(t,e){if(t===void 0)return;let n=t.trim();if(n.length>0)return n;throw new T(`${e} must not be empty`,`Leave ${e} out, or give it a value`)}import{join as xk}from"path";import{isDeepStrictEqual as Du}from"util";var V0=1,J0=":",bk="routing.default",q0="review.agent";function Ek(t,e){let n=Mt(et,t),r=Mu(n,"agents"),o=Mu(n,"routing"),s=Mu(n,"review"),i=Y0(r,e),a=i.flatMap(({entry:g,name:m})=>g===null?[]:[[m,g]]),c=Q0(o.default,bk,e.task)?o.default:Z0(e.task),l=tN(s,e.review)?s:eN(s,e.review),u={...n,agents:{...r,...Object.fromEntries(a)},review:l,routing:{...o,default:c}},d=Ms(u);if(d!==null)throw new f(`ari cannot set the routing: ${d}`,`Fix ${et}, then run 'ari install' again`,1,{tag:"InvalidConfig"});return{changes:[...i.map(({action:g,name:m,roles:h})=>({action:g,agent:m,detail:`${h.join(" and ")} agent`,key:`agents.${m}`})),{action:Tk(o.default,c),agent:e.task.agent,detail:`tasks: ${Jn(e.task)}`,key:bk},{action:Tk(s.agent===void 0?void 0:s,l),agent:e.review.agent,detail:`reviews: ${Jn(e.review)}`,key:q0}],next:Pn(t,u)}}function Y0(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])=>X0(r,o,t[r]))}function Jn(t){return t.model===null?`${t.agent} (CLI default model)`:`${t.agent} (${t.model})`}function X0(t,e,n){let r=ie.find((l)=>l.name===t),o=e.length>1?"both":e[0]??"task";if(n===void 0){if(r!==void 0)return{action:"created",entry:or(r,o,void 0),name:t,roles:e};throw new T(`No agent named "${t}" is configured, and ari has no preset of that name`,`Choose a configured agent, or one of the presets: ${ie.map((l)=>l.name).join(", ")}`)}let s=z0(n);if(e.every((l)=>s.includes(l)))return{action:"unchanged",entry:null,name:t,roles:e};let i=W(n)&&typeof n.model==="string"?n.model:void 0,a=r!==void 0&&rr.some((l)=>Du(n,or(r,l,i)));if(r!==void 0&&a)return{action:"updated",entry:or(r,"both",i),name:t,roles:e};let c=e.filter((l)=>!s.includes(l));throw new f(`agents.${t} has no ${c.join(" or ")} role`,`Add ${c.map((l)=>`"${l}"`).join(" and ")} to agents.${t}.roles in ${et}, or choose another agent`,V0,{tag:"AgentRoleMismatch"})}function z0(t){if(!W(t)||!Array.isArray(t.roles))return Dc;return t.roles.filter((e)=>typeof e==="string")}function Mu(t,e){let n=t[e];return W(n)?n:{}}function Z0(t){return t.model===null?t.agent:`${t.agent}${J0}${t.model}`}function Q0(t,e,n){if(t===void 0||t===null)return!1;try{return Du(ro(t,e),n)}catch{return!1}}function tN(t,e){return t.agent===e.agent&&(t.model??null)===e.model}function eN(t,e){let{model:n,...r}=t;return{...r,agent:e.agent,...e.model===null?{}:{model:e.model}}}function Tk(t,e){if(t===void 0||t===null)return"created";return Du(t,e)?"unchanged":"updated"}var nN="Fix the cause, then run 'ari install' again; it keeps what is already done";async function Aa(t,e,n,r={}){let o={mode:n,plan:e,root:t,scopes:await dN(t),view:uN(n)},s=[],i=!1;for(let a of e.targets){if(i||a.skip!==null){s.push(Do(a,i?"pending":"skipped",i?null:a.skip));continue}r.start?.(a);try{let c=await rN(o,a);s.push(...c),r.done?.(a,c)}catch(c){let l={...Do(a,"failed",gN(c)),hint:mN(c)};s.push(l),r.failed?.(a,l),i=!0}}return{failed:i,rows:s}}async function rN(t,e){if(e.id===Ru)return[Ca(e,oN(t))];if(e.id===hn)return[Ca(e,sN(t))];let{agent:n}=e;switch(e.kind){case"hooks":return[Ca(e,await iN(t,vk(n)))];case"mcp":case"skill":return[Ca(e,aN(t,e.kind,vk(n),e.scope))];case"git":return cN(t,e);case"routing":return lN(t,e);case"config":throw Error(`ari has no configuration target "${e.id}"`)}}function oN({mode:t,plan:e,root:n,view:r}){if(t==="apply")return vu(n,e.pack);return Ia(r,n,et,(o)=>Cu(o,e.pack))}function sN({mode:t,root:e,view:n}){if(t==="apply")return xu(e).action;return Ia(n,e,Ct,jo)}async function iN({mode:t,root:e,view:n},r){let o=gn(r);if(t==="preview")return Ia(n,e,o.file,(i)=>Co(o,i));let s=await Er(e,r);return"action"in s?s.action:"unchanged"}function aN({mode:t,scopes:e,view:n},r,o,s){let i=e[s];if(t==="apply")return r==="mcp"?Cr(Bn(o),i).action:Ir(Wn(o),i).action;let a=r==="mcp"?vr(Bn(o),i):Ar(Wn(o),i);return Ia(n,a.base,a.file,(c)=>a.install(c))}async function cN({mode:t,root:e},n){return(t==="apply"?(await Qi(e)).files:await vo(e)).map(({action:o,path:s})=>({...Do(n,Lu(o),null),file:s}))}function lN({mode:t,plan:e,root:n,view:r},o){let s=e.routing;if(s===null)return[];let i=t==="apply"?Y(n,et):r.read(n,et);if(i===null)throw new f(`${et} does not exist, so ari cannot set the routing`,"Run 'ari init' first");let a=Ek(i,s);if(t==="apply")Yt(n,et,a.next);else r.write(n,et,a.next);return a.changes.map((c)=>({...Do(o,Lu(c.action),null),agent:c.agent,detail:c.detail,key:c.key}))}function Ia(t,e,n,r){let o=t.read(e,n),s=r(o);return t.write(e,n,s),bl(o,s)}function uN(t){let e=new Map;return{read:(n,r)=>e.get(xk(n,r))??Y(n,r),write:(n,r,o)=>{if(t==="preview")e.set(xk(n,r),o)}}}async function dN(t){return{project:{base:t,receipts:await q(t),scope:"project"},user:await Ce("user",t)}}function Ca(t,e){return Do(t,Lu(e),null)}function Do(t,e,n){let r=t.file===null?null:t.file;return{action:e,agent:t.agent,detail:null,file:r===null?null:pN(t.scope,r),hint:null,key:null,kind:t.kind,reason:n,scope:t.scope}}function pN(t,e){return t==="user"&&!e.startsWith("~/")?ge(t,e):e}function Lu(t){return t==="removed"?"updated":t}function vk(t){if(t!==null)return t;throw Error("This target needs an agent")}function gN(t){return t instanceof Error?t.message:String(t)}function mN(t){if(t instanceof f&&t.hint!==void 0&&t.hint.length>0)return t.hint;return nN}var fN=5000,hN=new Set(["created","updated","unchanged"]),yN="2025-11-25",Ak=2,kN="ari_next",wN=new Set(["hooks","mcp","skill","git"]),SN="<!-- ari:begin -->",Ik=".ari/config.json",$N=".git/hooks",Rk="Install ari globally (bun add -g @r5n/ariadne), then run 'ari install' again",bN=`---
|
|
202
|
+
name: ${me}
|
|
203
|
+
`;async function Fu(t,e,n={}){let r=e.filter((c)=>hN.has(c.action)),o=await Promise.all(TN(r).map((c)=>EN(t,c)));if(!r.some((c)=>wN.has(c.kind)))return o;let s=n.ari===void 0?Bun.which("ari"):n.ari,i=s===null?_r("ari on PATH","ari is not on PATH, so agents cannot start it",Rk):Gu("ari on PATH",s),a=s!==null&&r.some((c)=>c.kind==="mcp")?[await AN(s,t,n.timeoutMs??fN)]:[];return[i,...a,...o]}function TN(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 EN(t,e){let n=xN(e),r=e.kind==="routing"?Ik:e.kind==="git"?$N:e.file??"";try{let o=await vN(t,e);return o===null?Gu(n,CN(e,r)):_r(n,`${r}: ${o}`,"Run 'ari install' again to repair it")}catch(o){if(!(o instanceof Error))throw o;let s=o instanceof f&&o.hint!==void 0?o.hint:`Fix ${r}`;return _r(n,o.message,s)}}function xN(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===Ct?"AGENTS.md block":"configuration";case"routing":return"configuration"}}async function vN(t,e){let n=e.agent??"";switch(e.kind){case"hooks":return Ao(t,gn(n))?null:"has no ari hook entries";case"mcp":{let r=vr(Bn(n),await Ck(t,e.scope));return r.managed(Y(r.base,r.file))?null:"does not register the ari server"}case"skill":{let r=Ar(Wn(n),await Ck(t,e.scope)),o=Y(r.base,r.file)??"";return o.startsWith(bN)&&o.includes(ka)?null:"is not ari's skill"}case"git":return await Zi(t)?null:"pre-commit and pre-push do not both run ari";case"config":if(e.file===Ct)return(Y(t,Ct)??"").includes(SN)?null:"has no ari block";return U(t),null;case"routing":return U(t),null}}function CN(t,e){switch(t.kind){case"hooks":case"mcp":case"skill":return e;case"git":return"pre-commit and pre-push run ari";case"config":case"routing":return t.file===Ct?"AGENTS.md has the ari block":`${Ik} is valid`}}async function Ck(t,e){return Ce(e,t)}async function AN(t,e,n){let o=Bun.spawn([t,"mcp","serve"],{cwd:e,detached:!0,env:{...process.env,...ne},stderr:"pipe",stdin:"pipe",stdout:"pipe"}),s=()=>re(o.pid,"SIGKILL"),i=Wt(s),a=setTimeout(s,n);try{o.stdin.write(IN()),await o.stdin.flush();let c=await RN(o.stdout);return await o.stdin.end(),_N("ari mcp serve",c,n,await new Response(o.stderr).text())}catch(c){return _r("ari mcp serve",`'ari mcp serve' failed: ${c instanceof Error?c.message:String(c)}`,Rk)}finally{clearTimeout(a),s(),i()}}function IN(){return[{id:1,jsonrpc:"2.0",method:"initialize",params:{capabilities:{},clientInfo:{name:"ari-install",version:"1"},protocolVersion:yN}},{jsonrpc:"2.0",method:"notifications/initialized"},{id:Ak,jsonrpc:"2.0",method:"tools/list"}].map((e)=>`${JSON.stringify(e)}
|
|
204
|
+
`).join("")}async function RN(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=ON(s);if(i!==null&&i.id===Ak)return i}}return null}function ON(t){try{let e=JSON.parse(t);return W(e)?e:null}catch{return null}}function _N(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 _r(t,i,"Run 'ari mcp serve' in this repository to see why")}let o=PN(e);if(!o.includes(kN))return _r(t,"answered tools/list without ari's tools","Make sure 'ari' on PATH is @r5n/ariadne");return Gu(t,`answers, with ${o.length} tools`)}function PN(t){let e=t.result;if(!W(e)||!Array.isArray(e.tools))return[];return e.tools.flatMap((n)=>W(n)&&typeof n.name==="string"?[n.name]:[])}function Gu(t,e){return{detail:e,hint:null,name:t,ok:!0}}function _r(t,e,n){return{detail:e,hint:n,name:t,ok:!1}}import{existsSync as Ok}from"fs";import{join as _k}from"path";var NN={claude:["claude"],codex:["codex"],copilot:["copilot"],cursor:["cursor-agent","cursor"],gemini:["gemini"]},jN="<!-- ari:begin -->";async function Ku(t){let e=Ok(_k(t,et)),n=e?U(t):null,r=Ok(_k(t,X))?Te(t):[],o={project:await HN(t),user:await Ce("user",t)},[s,i,a,c]=await Promise.all([Promise.all(gt.map(MN)),uu(t),ny(t),ca(t)]),l=new Set(c.filter((d)=>d.installed).map((d)=>d.agent)),u=[...e?[LN(t)]:[],...Kn.map((d)=>Nk(ht("hooks",Hu(d.name)),Hu(d.name),"hooks","project",d.file,l.has(d.name),()=>Co(d,Y(t,d.file))===Y(t,d.file))),...Pk("mcp",o),...Pk("skill",o),...i===null?[await FN(t,l.has(Zt),a)]:[]];return{agents:s,configured:GN(n),gitHooksDirectory:a,hookManager:i,initialised:e,pack:n?.pack??null,packs:He(r).map(({description:d,name:p})=>({description:d,name:p})),root:t,routing:{review:n?.review.agent===void 0?null:{agent:n.review.agent,model:n.review.model??null},reviewCommand:n?.review.command??null,task:n?.routing.default??null},targets:u}}async function MN(t){let e=Kn.find((c)=>c.name===t),n=Xe.find((c)=>c.agent===t),r=ze.find((c)=>c.agent===t),o=NN[t],s=await Fc(o),i=[...e===void 0?[]:["hooks"],...n===void 0?[]:["mcp"],...r===void 0?[]:["skill"]],a=[...n?.user==null?[]:["mcp"],...r?.user==null?[]:["skill"]];return{agent:t,binaries:o,kinds:i,label:e?.label??t,path:s.path,preset:ie.some((c)=>c.name===t),support:e?.support??"partial",userScope:a,version:s.version}}function Pk(t,e){return(t==="mcp"?ha(e.project,e.user):wa(e.project,e.user)).flatMap((r)=>r.files.map((o)=>{let s=Hu(r.agent),i=DN(t,s,e[o.scope]),a=()=>i.install(Y(i.base,i.file))===Y(i.base,i.file);return Nk(ht(t,s),s,t,o.scope,i.file,o.installed,a)}))}function DN(t,e,n){if(t==="mcp"){let o=Xe.find((s)=>s.agent===e);if(o!==void 0)return vr(o,n)}let r=ze.find((o)=>o.agent===e);if(r!==void 0)return Ar(r,n);throw Error(`ari has no ${t} target for ${e}`)}function Nk(t,e,n,r,o,s,i){let a={agent:e,file:ge(r,o),id:t,kind:n,scope:r},c=jk(i);if(c.problem!==null)return{...a,problem:c.problem,status:s?"outdated":"missing"};return{...a,problem:null,status:Uu(s,c.value===!0)}}function LN(t){let e=Y(t,Ct),n={agent:null,file:Ct,id:hn,kind:"config",scope:"project"},r=(e??"").includes(jN),o=jk(()=>jo(e)===e);if(o.problem!==null)return{...n,problem:o.problem,status:"outdated"};return{...n,problem:null,status:Uu(r,o.value===!0)}}async function FN(t,e,n){let r={agent:null,file:n,id:Zt,kind:"git",scope:"project"};try{let o=await vo(t);return{...r,problem:null,status:Uu(e,o.every((s)=>s.action==="unchanged"))}}catch(o){return{...r,problem:Mk(o),status:e?"outdated":"missing"}}}function GN(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:Cn(n)}))}async function HN(t){return{base:t,receipts:await q(t),scope:"project"}}function Uu(t,e){if(!t)return"missing";return e?"current":"outdated"}function jk(t){try{return{problem:null,value:t()}}catch(e){return{problem:Mk(e),value:null}}}function Mk(t){if(t instanceof f)return{hint:t.hint??"",message:t.message};throw t}function Hu(t){let e=gt.find((n)=>n===t);if(e!==void 0)return e;throw Error(`ari has no install support for ${t}`)}import{homedir as KN}from"os";var Lo=72,Fk=['ari new "Describe the first task"',"ari next"],Vu=20,Dk=26,Bu=13,Gk=8,qn=11,Hk=34,Lk=12,UN=/\d+(?:\.\d+)+[\w.+-]*/,Kk="\u2026",BN="~",Ra=".ari/config.json",Uk=new Set(["created","updated"]),Ft=" ",WN=`${k.green("\u2713")} installed ${k.yellow("\u2191")} update ${k.dim("\xB7")} not installed ${k.dim("\u2013")} not supported`,VN={created:"create",failed:"fail",pending:"not run",skipped:"skip",unchanged:"unchanged",updated:"update"};function Bk(t,e){let n=t.initialised?`set up, pack ${t.pack??"basic"}`:`not set up yet (${k.yellow(".ari/config.json is missing")})`,r=t.targets.find((a)=>a.id==="agents-md"),o=[Pr("Repository",nj(t.root)),Pr("Ariadne",`${e} \xB7 ${n}`),...r===void 0?[]:[Pr("AGENTS.md",`${Xk(r)} ari block`)],...QN(t),Pr("Git hooks",tj(t))],s=k.dim([ct("Agent",Vu),ct("On PATH",Bu),...fn.map((a)=>ct(ej(a),Gk))].join("")),i=gt.map((a)=>zN(t,yt(t,a)));return[...o,"",s,...i,"",WN].map(yn).join(`
|
|
207
|
+
`)}function Wk(t,e,n){let r=new Map,o=[];for(let c of t){if(c.kind==="routing")continue;if(c.action==="skipped"){let u=Wu(c.reason??"",Lo-Ft.length*2).map((d)=>`${Ft}${Ft}${k.dim(d)}`);o.push(`${Ft}${Mr(e,c)}`,...u);continue}let l=XN(e,c);r.set(l,[...r.get(l)??[],JN(c)])}let s=[...r].flatMap(([c,l])=>[k.bold(c),...l]),i=n===null?[]:YN(t,n),a=o.length===0?[]:[k.bold("Skipped"),...o];return[...s,...i,...a].map(yn).join(`
|
|
208
|
+
`)}function Vk(t,e){let[n]=e;if(n===void 0)return"";if(n.kind==="routing"){let o=e.filter((i)=>Uk.has(i.action)).map((i)=>i.key??""),s=o.length===0?"unchanged":"updated";return yn(`${ct("Routing",Dk)}${Nr(s,!1)}${o.join(", ")||Ra}`)}let r=e.map((o)=>o.file??"").join(", ");return yn(`${ct(Mr(t,n),Dk)}${Nr(n.action,!1)}${r}`)}function Jk(t){return t.map((e)=>{let n=e.ok?k.green("\u2713"):k.red("\u2717"),r=e.ok?k.dim(e.detail):k.red(e.detail);return yn(`${n} ${ct(e.name,Vu)}${r}`)}).join(`
|
|
209
|
+
`)}function jr(t,e){return[...Wu(t,Lo),...Wu(e,Lo).map((r)=>k.dim(r))].join(`
|
|
210
|
+
`)}function Wu(t,e){let n=[];for(let r of t.split(`
|
|
211
|
+
`)){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 Ju(t){let e=["created","updated","unchanged","skipped","failed","pending"].map((o)=>[o,t.targets.filter((s)=>s.action===o).length]).filter(([,o])=>o>0).map(([o,s])=>`${s} ${o==="pending"?"not run":o}`),n=t.checks.filter((o)=>!o.ok).length,r=t.checks.length===0?[]:[`${t.checks.length-n} of ${t.checks.length} checks passed`];return[e.join(" \xB7 "),...r,"",k.bold("Next"),...t.next.map((o)=>`${Ft}${o}`)].map(yn).join(`
|
|
212
|
+
`)}function qk(t){let e=t.targets.map((i)=>{let a=[i.agent,i.kind,i.key].filter((u)=>u!==null).join(" "),c=i.reason===null?"":`: ${i.reason}`,l=i.hint===null?"":` (${i.hint})`;return`${ct(i.action,qn)}${ct(i.file??"-",Hk)} ${a}${c}${l}`}),n=t.warnings.flatMap((i)=>[`warning: ${i.message}`,` ${i.fix}`]),r=t.checks.map((i)=>`check ${i.ok?"ok":"FAILED"}: ${i.name}: ${i.detail}${i.hint===null?"":` (${i.hint})`}`),o=t.dryRun?["Dry run: nothing was written"]:t.upToDate?["Everything is up to date"]:[],s=t.ok&&!t.dryRun?t.next.map((i)=>`next: ${i}`):[];return[...e,...n,...r,...o,...s].join(`
|
|
213
|
+
`)}function Mr(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?"":`${Yk(t,e.agent)} `}${Rr[e.kind]}`}function Nr(t,e){let n=ct(e?VN[t]:t,qn);switch(t){case"created":return k.green(n);case"updated":return k.yellow(n);case"failed":return k.red(n);case"unchanged":case"skipped":case"pending":return k.dim(n)}}function yn(t){if(Bun.stringWidth(t)<=Lo)return t;return`${Bun.sliceAnsi(t,0,Lo-1)}${Kk}`}function Oa(t){if(t.path===null)return"not found";let e=UN.exec(t.version??"")?.[0]??t.version??"found";return e.length>Lk?`${e.slice(0,Lk-1)}${Kk}`:e}function JN(t){let e=t.kind==="config"&&t.file==="AGENTS.md"?"ari block":qN[t.kind],n=t.action==="failed"?k.red(t.reason??""):k.dim(e);return`${Ft}${Nr(t.action,!0)}${ct(t.file??"",Hk)} ${n}`}var qN={config:"configuration",git:"git hook",hooks:"hooks",mcp:"MCP server",routing:"routing",skill:"skill"};function YN(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)&&Uk.has(u.action)).map((u)=>u.key??""),i=s("agents."),a=[...s("routing."),...s("review.")],c=r!==void 0?[`${Ft}${Nr("failed",!0)}${k.red(r.reason??"")}`]:o?[`${Ft}${Nr("pending",!0)}${Ra}`]:i.length+a.length===0?[`${Ft}${Nr("unchanged",!0)}${Ra}`]:[...i.length===0?[]:[`${Ft}${k.green(ct("add",qn))}${i.join(", ")}`],...a.length===0?[]:[`${Ft}${k.yellow(ct("set",qn))}${a.join(", ")}`]];return[`${k.bold("Routing")} ${k.dim(Ra)}`,`${Ft}${ct("tasks",qn)}${Jn(e.task)}`,`${Ft}${ct("reviews",qn)}${Jn(e.review)}`,...c]}function XN(t,e){if(e.agent!==null)return Yk(t,e.agent);return e.kind==="git"?"Git hooks":"Repository"}function Yk(t,e){return t.agents.find((n)=>n.agent===e)?.label??e}function zN(t,e){let n=e.path===null?k.dim(ct("not found",Bu)):ct(Oa(e),Bu),r=fn.map((o)=>ct(ZN(t,e.agent,o),Gk));return[ct(e.label,Vu),n,...r].join("")}function ZN(t,e,n){if(!yt(t,e).kinds.includes(n))return k.dim("\u2013");let r=t.targets.filter((i)=>i.agent===e&&i.kind===n);if(r.some((i)=>i.problem!==null))return k.red("!");let o=r.filter((i)=>i.status!=="missing");if(o.length===0)return k.dim("\xB7");let s=o.some((i)=>i.status==="outdated")?k.yellow("\u2191"):k.green("\u2713");if(o.length>1)return`${s} both`;return o[0]?.scope==="user"?`${s} user`:s}function QN(t){let{review:e,task:n}=t.routing;if(n===null&&e===null)return[];let r=n===null?"tasks: not set":`tasks ${Jn(n)}`,o=e===null?"reviews: not set":`reviews ${Jn(e)}`;return[Pr("Routing",r),Pr("",o)]}function tj(t){if(t.hookManager!==null)return k.dim(`managed by ${t.hookManager.name}`);let e=t.targets.find((n)=>n.id==="git");if(e===void 0)return k.dim("\xB7");if(e.problem!==null)return`${k.red("!")} ${e.problem.message}`;return`${Xk(e)} ${e.status==="missing"?"not installed":"pre-commit, pre-push"}`}function Xk(t){if(t.problem!==null)return k.red("!");if(t.status==="current")return k.green("\u2713");return t.status==="outdated"?k.yellow("\u2191"):k.dim("\xB7")}function ej(t){return t==="mcp"?"MCP":t==="hooks"?"Hooks":"Skill"}function Pr(t,e){return`${ct(t,qn+1)}${e}`}function nj(t){let e=KN();return t===e||t.startsWith(`${e}/`)?`${BN}${t.slice(e.length)}`:t}function ct(t,e){let n=Bun.stringWidth(t);return n>=e?`${t} `:`${t}${" ".repeat(e-n)}`}var zk="basic",rj=2,oj="CLI default";async function ew(t,e){let{init:n,pack:r}=await sj(t,e),o=e.agents??await ij(t);fj(t,{agents:o,init:n,scope:"project",targets:[]},["agent-not-found"]);let s=e.scope??await aj(t,o);if(s==="user"&&o.includes("claude"))Dr("Claude Code keeps user-scope MCP servers in its own state file, which ari does not edit",`Run: ${Ta}`);let i=e.kinds===void 0?await cj(t,o,s,n):Nu(o,e.kinds),a=e.routing??await dj(t,o,t.initialised||n);return{agents:o,init:n,pack:r,recommended:!1,routing:a,scope:s,targets:i}}async function sj(t,e){let n=e.init===!0||e.pack!==void 0;if(t.initialised||n)return{init:n,pack:e.pack??null};if(Dr(".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 nn({initialValue:!0,message:"Set up ari in this repository?"}))return lt.info(k.dim("Skipped. Routing needs the setup, so that step is skipped too.")),{init:!1,pack:null};let o=await bn({initialValue:zk,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===zk?null:o}}async function ij(t){return hs({initialValues:Ea(t),message:"Which agents do you use in this repository?",options:gt.map((e)=>{let n=yt(t,e),r=n.path===null?"not on PATH":Oa(n),o=n.support==="verified"?"hooks verified":"hooks in part",s=n.kinds.filter((i)=>i!=="hooks").map((i)=>Rr[i]);return{hint:`${r} \xB7 ${[o,...s].join(", ")}`,label:n.label,value:e}}),required:!1})}async function aj(t,e){if(!e.some((r)=>yt(t,r).userScope.length>0))return"project";let n=e.includes("claude")?"; Claude Code's MCP server stays per repository":"";return bn({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 cj(t,e,n,r){await lj(t);let o=Vn(t,e,n,r).filter((u)=>u.skip===null);for(let u of o.filter((d)=>d.problem!==null))Dr(u.problem?.message??"",u.problem?.hint??"");let s=o.filter((u)=>u.problem===null);if(s.length===0)return lt.info(k.dim("There is nothing to install for these agents.")),t.hookManager===null?[]:[Zt];let i=s.map((u)=>u.id),a=new Map(va(t,i).map(({id:u,reason:d})=>[u,d])),c=await hs({initialValues:fk(t,e,n,r),message:"What should ari install?",options:s.map((u)=>({hint:a.get(u.id)??u.file??void 0,label:gj(t,u),value:u.id})),required:!1}),l=await uj(t,{agents:e,init:r,scope:n,targets:c});return t.hookManager===null?l:[...l,Zt]}async function lj(t){let e=t.hookManager;if(e===null)return;if(Dr(`${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"),he(e.lines.join(`
|
|
214
|
+
`),"Git hook lines",{format:(r)=>r}),!await nn({initialValue:!0,message:"Continue without git hooks?"}))throw new kt}async function uj(t,e){let n=[...e.targets],r=xa(t,rw({...e,targets:n})).filter((o)=>o.code==="hooks-twice"||o.code==="skill-twice");for(let o of r){if(Dr(o.message,o.fix),o.drop.length===0)continue;let s=o.drop.map((i)=>nw(t,i)).join(" and ");if(await nn({initialValue:!0,message:`Leave out the ${s}?`}))n=n.filter((i)=>!o.drop.includes(i))}return n}async function dj(t,e,n){let r=hk(t,e);if(!n||r.length<rj)return null;if(t.routing.reviewCommand!==null)return lt.info(k.dim("Routing skipped: review.command runs the review gate, so ari leaves review.agent alone.")),null;if(he(r.map((u)=>pj(t,u)).join(`
|
|
215
|
+
`),"Agents for 'ari run' and 'ari review'",{format:(u)=>u}),!await nn({initialValue:!1,message:"Run tasks and reviews on different agents or models?"}))return null;let s=await Zk("Which agent implements tasks?",r,t.routing.task?.agent??null),i=await Qk(`Model for ${s} on tasks`,tw(t.routing.task,s)),a=r.find((u)=>u.name!==s)?.name??null,c=await Zk("Which agent reviews changes?",r,t.routing.review?.agent??a),l=await Qk(`Model for ${c} on reviews`,tw(t.routing.review,c));return{review:{agent:c,model:l},task:{agent:s,model:i}}}async function Zk(t,e,n){let r=e.some((o)=>o.name===n)?n:e[0]?.name;return bn({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 Qk(t,e){let r=(await gc({initialValue:e??"",message:t,placeholder:oj})??"").trim();return r.length===0?null:r}function tw(t,e){return t!==null&&t.agent===e?t.model:null}function pj(t,e){let n=t.agents.find((i)=>i.agent===e.name),r=n===void 0?"":n.path===null?k.dim(" not on PATH"):k.dim(` ${Oa(n)}`),o=e.configured?`configured: ${e.roles.join(", ")}`:"preset, not configured yet",s=e.model===null?"":k.dim(` model ${e.model}`);return yn(`${e.name.padEnd(10)}${o}${s}${r}`)}function gj(t,e){return`${nw(t,e.id)}${mj(e)}`}function nw(t,e){if(e===Zt)return"Git hooks";if(e===hn)return"AGENTS.md block";let[n,r]=e.split(":"),o=gt.find((a)=>a===r),s=fn.find((a)=>a===n);return`${o===void 0?r??"":yt(t,o).label} ${s===void 0?n??"":Rr[s]}`}function mj(t){if(t.elsewhere!==null&&t.status==="missing")return k.dim(` (${t.elsewhere} scope)`);if(t.status==="current")return k.green(" \u2713");return t.status==="outdated"?k.yellow(" \u2191"):""}function rw(t){return{...t,pack:null,recommended:!1,routing:null}}function fj(t,e,n){for(let r of xa(t,rw(e)))if(n.includes(r.code))Dr(r.message,r.fix)}function Dr(t,e){lt.warn(jr(t,e))}var hj=1,Pa=new Set(["created","updated"]),Fo={format:(t)=>t},yj=N({agent:{description:`Agents to set up, comma-separated: ${gt.join(", ")}`,type:"string"},dryRun:{alias:"d",description:"Show the plan and write nothing",type:"boolean"},gitHooks:{description:"Install the pre-commit and pre-push git hooks",type:"boolean"},hooks:{description:"Install each agent's hooks",type:"boolean"},init:{description:"Create .ari/config.json and the AGENTS.md block when they are missing",type:"boolean"},mcp:{description:"Register ari's MCP server with each agent",type:"boolean"},pack:{description:"Default methodology pack when setting up (implies --init)",type:"string"},reviewAgent:{description:"Agent for the review gate and 'ari review' (with --task-agent)",type:"string"},reviewModel:{description:"Model for the review agent (default: the agent CLI's own)",type:"string"},scope:{description:"Where MCP servers and skills go: project or user (default: project)",type:"string"},skills:{description:"Install the ariadne skill for each agent",type:"boolean"},taskAgent:{description:"Agent that 'ari run' gives tasks to (with --review-agent)",type:"string"},taskModel:{description:"Model for the task agent (default: the agent CLI's own)",type:"string"},yes:{alias:"y",description:"Accept the recommended defaults: found agents, every supported target, no questions",type:"boolean"}}),sw=E({args:yj,description:"Set up ari here: configuration, hooks, MCP server, skill, git hooks and agent routing, in one guided step",examples:["ari install","ari install --yes","ari install --init --agent claude,codex --yes --dry-run","ari install --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)=>kj(t)});async function kj(t){let e=await P(),n=Sk(t.args),r=t.args.yes===!0,o=t.args.dryRun===!0,s=t.interactive,i=s&&!r,a=t.cli.version??"";if(s)to(`${k.bold("ari install")} ${k.dim(`Ariadne ${a}`)}`);let c=s?await iw("Looking at this repository",()=>Ku(e)):await Ku(e);if(s)he(Bk(c,a),"This repository",Fo);if(i&&!$k(n)){let h=await Sj(c,e);if(h!==null)return _a(t,c,h,{dryRun:o,upToDate:!0,visual:s})}let l=await ow(s,()=>i?ew(c,n):ju(c,n,r)),u=Ou(c,l),d=await Aa(e,u,"preview");if(s)Ej(c,u,d.rows,!i);if(d.failed||o){let h=o?d.rows:d.rows.map(wj);return _a(t,c,{checks:[],plan:u,rows:h},{dryRun:o,upToDate:!1,visual:s})}if(!d.rows.some((h)=>Pa.has(h.action))){let h=await qu(s,e,d.rows);return _a(t,c,{checks:h,plan:u,rows:d.rows},{dryRun:o,upToDate:!0,visual:s})}if(i)await ow(s,()=>xj());let g=await Aa(e,u,"apply",s?vj(c):{}),m=g.failed?[]:await qu(s,e,g.rows);return _a(t,c,{checks:m,plan:u,rows:g.rows},{dryRun:o,upToDate:!1,visual:s})}function wj(t){return Pa.has(t.action)?{...t,action:"pending"}:t}async function Sj(t,e){if(!t.initialised)return null;let n=$j(t);if(n===null||n.agents.length===0)return null;let r=Ou(t,n),o=await Aa(e,r,"preview");if(o.failed||o.rows.some((s)=>Pa.has(s.action)))return null;return{checks:await qu(!0,e,o.rows),plan:r,rows:o.rows}}function $j(t){try{return ju(t,bj(),!0)}catch{return null}}function bj(){return{agents:void 0,init:void 0,kinds:void 0,pack:void 0,routing:void 0,scope:void 0}}function _a(t,e,n,r){let o=n.rows.some((i)=>i.action==="failed")||n.checks.some((i)=>!i.ok),s={checks:n.checks,dryRun:r.dryRun,next:Fk,ok:!o,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)Tj(e,s);return t.output.result(s,r.visual?void 0:qk),o?hj:0}function Tj(t,e){let n=e.targets.find((r)=>r.action==="failed");if(n!==void 0){lt.error(jr(`${Mr(t,n)}: ${n.reason??""}`,n.hint??"")),rn(e.targets.some((r)=>Pa.has(r.action))&&!e.dryRun?"Stopped; run 'ari install' again to finish":"Nothing was written");return}if(e.dryRun){rn("Dry run: nothing was written");return}if(e.upToDate){he(Ju(e),"Everything is up to date",Fo),rn(k.dim("To add an agent: ari install --agent <name>"));return}he(Ju(e),e.ok?"Done":"Done, with problems",Fo),rn(e.ok?"ari is ready":"Fix the failed checks, then run 'ari install' again")}function Ej(t,e,n,r){if(r)for(let o of e.warnings)lt.warn(jr(o.message,o.fix));he(Wk(n,t,e.routing),"Plan",Fo)}async function xj(){if(await nn({initialValue:!0,message:"Write these changes?"}))return;throw new kt}async function ow(t,e){try{return await e()}catch(n){if(t&&n instanceof kt)mc("Cancelled, nothing changed");throw n}}async function qu(t,e,n){if(!t)return Fu(e,n);let r=await iw("Checking the installation",()=>Fu(e,n));if(r.length===0)return r;let o=r.filter((s)=>!s.ok);he(Jk(r),o.length===0?"Self-check passed":"Self-check found problems",Fo);for(let s of o)lt.error(jr(`${s.name}: ${s.detail}`,s.hint??""));return r}function vj(t){let e=ys();return{done:(n,r)=>e.stop(Vk(t,r)),failed:(n,r)=>e.error(`${Mr(t,r)} failed${n.file===null?"":` (${n.file})`}`),start:(n)=>e.start(`Writing ${n.file??Mr(t,{agent:n.agent,file:n.file,kind:n.kind})}`)}}async function iw(t,e){let n=ys();n.start(t);try{let r=await e();return n.clear(),r}catch(r){throw n.error(t),r}}var Lr=rt({id:{description:"Task id",required:!0}}),aw=E({description:"Validate a draft contract and mark it ready",examples:["ari ready add-profile-inheritance"],json:!0,name:"ready",positionals:Lr,run:async(t)=>{let e=await Ki(await P(),t.positionals.id);t.output.result(e,({id:n})=>`Task "${n}" is ready; run 'ari start ${n}'`)}}),cw=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:Lr,run:async(t)=>{let e=await Ui(await P(),t.positionals.id);t.output.result(e,({id:n,instruction:r,stage:o})=>`Task "${n}" is active at stage ${o}
|
|
216
|
+
${r}
|
|
217
|
+
Then: ari check, ari done`)}}),lw=E({args:N({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:Lr,run:async(t)=>{let e=un(t.args.reason,"--reason",`ari amend ${t.positionals.id} --reason <text>`),n=await xh(await P(),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`)}}),uw=E({args:N({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:Lr,run:async(t)=>{let e=un(t.args.reason,"--reason",`ari block ${t.positionals.id} --reason <question>`),n=await Bi(await P(),t.positionals.id,e);t.output.result(n,({id:r})=>`Task "${r}" is blocked; a human answers with 'ari resolve ${r} --answer <text>'`)}}),dw=E({args:N({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:Lr,run:async(t)=>{let e=un(t.args.answer,"--answer",`ari resolve ${t.positionals.id} --answer <text>`),n=await Ch(await P(),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`)}}),pw=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:Lr,run:async(t)=>{let e=await P(),n=await _g(e);if(n===null)throw new f("git user.name is not set",`Run 'git config user.name "<your name>"'`);let r=await Ah(e,t.positionals.id,n),o=r.record.approvals.at(-1),s={by:n,id:r.contract.id,stage:o?.stage??null};t.output.result(s,({id:i,stage:a})=>`Approved stage ${a??"unknown"} of "${i}" as ${n}`)}});import{stripVTControlCharacters as Cj}from"util";var gw=1,Aj=2,Ij=4,mw="Error",Rj="Call the tool with the arguments its inputSchema describes";function fw(t){if(t instanceof x){let r=`Invalid arguments: ${t.message}`;return{error:{_tag:"UsageError",causes:[],exitCode:Aj,hint:Rj,message:r}}}if(!(t instanceof Error))return{error:{_tag:mw,causes:[],exitCode:gw,message:Na(String(t))}};let e=t instanceof f,n=e&&typeof t.hint==="string"?{hint:Na(t.hint)}:{};return{error:{_tag:e?t._tag:t.name||mw,causes:Oj(t),exitCode:e?t.exitCode:gw,message:Na(t.message),...n}}}function Oj(t){let e=[],n=new Set([t]),r=t.cause;while(r!==void 0&&!n.has(r)&&e.length<Ij)n.add(r),e.push(Na(r instanceof Error?r.message:String(r))),r=r instanceof Error?r.cause:void 0;return e}function Na(t){return Cj(t)}var bw=["2026-07-28"],Da=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],Ga="2.0",_j=-32700,La=-32600,Pj=-32601,Fr=-32602,Nj=-32603,jj=-32022,Fa="_meta",Ma="io.modelcontextprotocol/protocolVersion",hw="io.modelcontextprotocol/clientCapabilities",Mj="io.modelcontextprotocol/serverInfo",Dj="complete",yw=3600000,kw="public",Lj="2025-06-18",ww={tools:{listChanged:!1}},Tw=[...bw,...Da];function Ew(t){let e={legacy:null},n=(c)=>{let l=Fj(c);if("error"in l)return Gt(l.error);let u=l.value,d=!("method"in u)&&(("result"in u)||("error"in u));if(!("id"in u)||d)return Gt(null);let p=Gj(u);if("error"in p)return Gt(p.error);let{id:g,method:m,params:h}=p.value,w=!Hj(h);if(w&&m==="initialize")return Gt(r(g,h));if(w&&m==="ping")return Gt(ja(g,{}));let b=Kj(g,h,e.legacy);if("error"in b)return Gt(b.error);switch(m){case"server/discover":return b.value.kind==="modern"?Gt(a(g,b.value,o())):Gt($w(g,m));case"tools/list":return Gt(a(g,b.value,s(b.value)));case"tools/call":return i(g,b.value,h);default:return Gt($w(g,m))}},r=(c,l)=>{let u=l.protocolVersion,d=typeof u==="string"&&Da.includes(u)?u:Da[0]??"";e.legacy=d;let{info:p,instructions:g}=t;return ja(c,{capabilities:ww,instructions:g,protocolVersion:d,serverInfo:p})},o=()=>({cacheScope:kw,capabilities:ww,instructions:t.instructions,supportedVersions:Tw,ttlMs:yw}),s=(c)=>{let l=t.tools.map(({annotations:u,description:d,inputSchema:p,name:g,title:m})=>({annotations:u,description:d,inputSchema:p,name:g,title:m}));return c.kind==="modern"?{cacheScope:kw,tools:l,ttlMs:yw}:{tools:l}},i=(c,l,u)=>{let{arguments:d={},name:p}=u;if(typeof p!=="string")return Gt(Ht(c,Fr,"tools/call needs a tool name"));let g=t.tools.find((h)=>h.name===p);if(g===void 0)return Gt(Ht(c,Fr,`Unknown tool: ${p}`));if(!W(d))return Gt(Ht(c,Fr,"tools/call arguments must be an object"));let m=async()=>{try{let h=await g.call(await t.root(),d);return a(c,l,Sw(l,h.data,h.failed))}catch(h){return a(c,l,Sw(l,fw(h),!0))}};return{kind:"queued",run:()=>m().catch((h)=>Bj(c,h))}},a=(c,l,u)=>{if(l.kind==="legacy")return ja(c,u);let d={[Mj]:t.info};return ja(c,{...u,[Fa]:d,resultType:Dj})};return{receive:n}}function Gt(t){return{kind:"now",message:t}}function Sw(t,e,n){let r=[{text:JSON.stringify(e,null,2),type:"text"}],o=t.kind==="modern"||t.version>=Lj;return{content:r,isError:n,...o?{structuredContent:e}:{}}}function Fj(t){let e;try{e=JSON.parse(t)}catch{return{error:Ht(null,_j,"Parse error: each line must hold one JSON-RPC message")}}if(Array.isArray(e))return{error:Ht(null,La,"JSON-RPC batches are not supported")};if(!W(e))return{error:Ht(null,La,"A JSON-RPC message must be an object")};return{value:e}}function Gj(t){let{id:e,jsonrpc:n,method:r,params:o={}}=t;if(!(typeof e==="string"||typeof e==="number"&&Number.isInteger(e)))return{error:Ht(null,La,"A request id must be a string or an integer")};if(n!==Ga||typeof r!=="string")return{error:Ht(e,La,'A request needs "jsonrpc": "2.0" and a method name')};if(!W(o))return{error:Ht(e,Fr,"params must be an object")};return{value:{id:e,method:r,params:o}}}function Hj(t){return W(t[Fa])&&Ma in t[Fa]}function Kj(t,e,n){let r=e[Fa];if(W(r)&&Ma in r){let s=r[Ma];if(typeof s!=="string"||!bw.includes(s))return{error:Uj(t,s)};if(!W(r[hw]))return{error:Ht(t,Fr,`_meta needs "${hw}"`)};return{value:{kind:"modern",version:s}}}if(n!==null)return{value:{kind:"legacy",version:n}};let o=`Missing _meta "${Ma}"; clients of protocol ${Da[0]} and earlier send initialize first`;return{error:Ht(t,Fr,o)}}function Uj(t,e){return{error:{code:jj,data:{requested:e,supported:Tw},message:"Unsupported protocol version"},id:t,jsonrpc:Ga}}function $w(t,e){return Ht(t,Pj,`Method not found: ${e}`)}function Bj(t,e){return Ht(t,Nj,`Internal error: ${e instanceof Error?e.message:String(e)}`)}function ja(t,e){return{id:t,jsonrpc:Ga,result:e}}function Ht(t,e,n){return{error:{code:e,message:n},id:t,jsonrpc:Ga}}var kn="arguments",Go={destructiveHint:!1,readOnlyHint:!0},Ho={destructiveHint:!1,readOnlyHint:!1},xw={readOnlyHint:!1},Pw={description:"Task id",type:"string"},Yu={items:{type:"string"},type:"array"};function Qt(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 Re(t){return{data:t,failed:!1}}function te(t,e){return R(t,kn,Object.keys(e))}function Oe(t,e){return it(t,`${kn}.${e}`)}function vw(t,e){return t===void 0?void 0:H(t,`${kn}.${e}`,I)}var Gr={},Hr={id:Pw},Cw={status:{...Yu,description:"Only tasks with these statuses",items:{enum:Hn}}},Aw={pack:{description:"Methodology pack (defaults to config.pack)",type:"string"},scope:{...Yu,description:"Globs of the files the task may change"},title:{description:"Task title",type:"string"}},Iw={global:{description:"Write a project knowledge entry instead of a task note",type:"boolean"},kind:{description:"Knowledge entry kind, with global",enum:ce},scope:{...Yu,description:"Globs the knowledge entry applies to, with global"},text:{description:"The note",type:"string"}},Rw={budget:{description:"Token budget (default: context.budget)",minimum:1,type:"integer"},id:{description:"Task id (default: the active task)",type:"string"}},Ow={id:Pw,reason:{description:"The question for a human",type:"string"}},_w={all:{description:"Include archived entries",type:"boolean"},query:{description:"Words to search for",type:"string"}},Nw=[Qt({annotations:Go,call:async(t,e)=>(te(e,Gr),Re(await Li(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:Gr,title:"Next action"}),Qt({annotations:Go,call:async(t,e)=>{let n=te(e,Cw),r=F(n.status,[],(o)=>H(o,`${kn}.status`,(s,i)=>z(Hn,s,i)));return Re(await Fi(t,r))},description:"List tasks (id, title, pack, status) and contracts or records that cannot be read.",name:"ari_list",properties:Cw,title:"List tasks"}),Qt({annotations:Go,call:async(t,e)=>Re(await Gi(t,Oe(te(e,Hr).id,"id"))),description:"Show a task's contract, record, current stage and stage instruction.",name:"ari_show",properties:Hr,required:["id"],title:"Show task"}),Qt({annotations:Ho,call:async(t,e)=>{let n=te(e,Aw),r=n.pack===void 0?void 0:Oe(n.pack,"pack"),o=vw(n.scope,"scope")??[];return Re(await Hi(t,{pack:r,scope:o,title:Oe(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:Aw,required:["title"],title:"New task"}),Qt({annotations:Ho,call:async(t,e)=>Re(await Ki(t,Oe(te(e,Hr).id,"id"))),description:"Validate a draft contract, its pack and its dependencies, and mark it ready.",name:"ari_ready",properties:Hr,required:["id"],title:"Ready task"}),Qt({annotations:Ho,call:async(t,e)=>Re(await Ui(t,Oe(te(e,Hr).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:Hr,required:["id"],title:"Start task"}),Qt({annotations:xw,call:async(t,e)=>(te(e,Gr),Wi(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:Gr,title:"Check stage"}),Qt({annotations:xw,call:async(t,e)=>(te(e,Gr),Vi(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:Gr,title:"Finish stage"}),Qt({annotations:Ho,call:async(t,e)=>{let n=te(e,Iw),r=F(n.global,!1,(i)=>we(i,`${kn}.global`)),o=n.kind===void 0?void 0:z(ce,n.kind,`${kn}.kind`),s=vw(n.scope,"scope");return Re(await Ji(t,{global:r,kind:o,scope:s,text:Oe(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:Iw,required:["text"],title:"Add note"}),Qt({annotations:Go,call:async(t,e)=>{let n=te(e,Rw),r=n.id===void 0?void 0:Oe(n.id,"id"),o=n.budget===void 0?void 0:se(n.budget,`${kn}.budget`);return Re(await qi(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:Rw,title:"Task context"}),Qt({annotations:Ho,call:async(t,e)=>{let n=te(e,Ow);return Re(await Bi(t,Oe(n.id,"id"),Oe(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:Ow,required:["id","reason"],title:"Block task"}),Qt({annotations:Go,call:async(t,e)=>{let n=te(e,_w),r=F(n.all,!1,(o)=>we(o,`${kn}.all`));return Re(Yi(t,Oe(n.query,"query"),r))},description:"Search the project's knowledge entries, ranked with BM25.",name:"ari_knowledge_search",properties:_w,required:["query"],title:"Search knowledge"})];var jw=`
|
|
218
|
+
`,Wj=/\r$/,Vj={name:"ari",title:"Ariadne",version:_s},Jj=["Ariadne tracks this repository's work as tasks with contracts and gates that it evaluates itself.","Loop: call ari_next and follow its action, change only files inside the active task's scope, call ari_check, then ari_done until it passes.","Ask a human with ari_block when stuck. Approving a stage, amending a contract and answering a blocked task are for humans only (ari approve, ari amend, ari resolve)."].join(" ");function qj(t){return Ew({info:Vj,instructions:Jj,root:()=>ir(t),tools:Nw})}async function Dw(t){let e=qj(t.cwd),n=(a)=>{if(a!==null)t.write(`${JSON.stringify(a)}${jw}`)},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(jw);i=c.pop()??"";for(let l of c)Mw(e,l,o)}Mw(e,i+s.decode(),o),await r}function Mw(t,e,n){let r=e.replace(Wj,"");if(r.trim().length>0)n(t.receive(r))}function Ha(t,e){let{agents:n,example:r,group:o,noun:s}=t,i=(c,l)=>{let u=`ari ${o} ${c} --agent`;return E({args:N({agent:{description:`Agent: ${n.join(", ")}`,type:"string"},scope:{description:`Where to write: ${la.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(un(d.args.agent,"--agent",`${u} <name>`)),g=await Ce(ua(d.args.scope),process.cwd()),m=l(p,g);d.output.result(m,(h)=>`${h.agent} ${s} ${h.action} in ${h.file} (${h.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 Ce("project",l),await Ce("user",l));c.output.result({agents:u},({agents:d})=>d.map(Yj).join(`
|
|
219
|
+
`))}});return[i("install",t.install),i("uninstall",t.uninstall),a]}function Yj(t){let e=t.files.map((n)=>`${n.scope} ${n.installed?"installed":"not installed"} ${n.file}`);return`${t.agent} ${e.join("; ")}`}var Xj=`ari mcp serve speaks the Model Context Protocol on stdin and stdout; an agent starts it. Press Ctrl-D to stop.
|
|
220
|
+
`,zj=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(Xj);await Dw({cwd:process.cwd(),input:Bun.stdin.stream(),write:(t)=>{process.stdout.write(t)}})}}),Zj=Ha({agents:Xe.map((t)=>t.agent),example:{project:"claude",user:"codex"},group:"mcp",install:Cr,noun:'MCP server "ari"',summaries:ha,target:Bn,uninstall:Xy},{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"}),Lw=E({description:"Serve ari's task tools to agents over MCP, and register the server with them",name:"mcp",subcommands:[zj,...Zj]});var Qj=1;async function Fw(t,e){let n=U(t),r=Ln(n,{...e,role:"review",route:tM(n)}),o=e.task??await eM(t),s=await qe(t,o),i=s.stage??s.task.record.status,{contractText:a}=st(t,o,n),{evidence:c,...l}=await Nl({config:n,contractText:a,root:t,stage:i,task:s.task},r);return{...l,stage:i,task:o}}function tM(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 eM(t){let e=dt(await q(t));if(e!==null)return e.task;throw new f("No task is active in this worktree","Pass --task <id>, or run 'ari next' to see what to do",Qj,{tag:"NoActiveTask"})}var nM=1,Gw=E({args:N({agent:{description:"Review agent from config.agents (default: routing.review, then review.agent)",type:"string"},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"],json:!0,name:"review",run:async(t)=>{let e=await Fw(await P(),{agent:xe(t.args.agent,"--agent"),model:xe(t.args.model,"--model"),task:xe(t.args.task,"--task")});return t.output.result(e,rM),e.ok?void 0:nM}});function rM(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((s)=>` - ${$i(s)}`),o=t.problems.map((s)=>` ! ${s}`);return[n,...o,...r].join(`
|
|
221
|
+
`)}var oM=1,Hw=E({args:N({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 Mh(await P(),{agent:xe(t.args.agent,"--agent"),model:xe(t.args.model,"--model"),output:t.json?"stderr":"inherit",task:t.args.task});return t.output.result(e,sM),e.outcome==="done"?void 0:oM}});function sM(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(`
|
|
222
|
+
`)}var Kw=E({description:`Install the ${me} skill, which teaches an agent the task loop`,name:"skills",subcommands:Ha({agents:ze.map((t)=>t.agent),example:{project:"claude",user:"codex"},group:"skills",install:Ir,noun:`skill "${me}"`,summaries:wa,target:Wn,uninstall:rk},{install:`Write the ${me} skill into an agent's skills directory`,list:`List the agents ari can install the ${me} skill for, and where it is installed`,uninstall:`Remove the ${me} skill that ari installed, and nothing else`})});var Uw=E({args:N({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:rt({title:{description:"Task title",required:!0}}),run:async(t)=>{let e=await Hi(await P(),{pack:t.args.pack,scope:jn(t.args.scope),title:t.positionals.title});t.output.result(e,({contractPath:n,id:r})=>`Created task "${r}" at ${n}
|
|
223
|
+
Complete its scope, criteria and checks, then run 'ari ready ${r}'`)}}),Bw=E({args:N({status:{description:`Only these statuses, comma-separated (${Hn.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=Fh(jn(t.args.status));t.output.result(await Fi(await P(),e),iM)}}),Ww=E({description:"Show a task's contract, record and current stage",examples:["ari show add-profile-inheritance --json"],json:!0,name:"show",positionals:rt({id:{description:"Task id",required:!0}}),run:async(t)=>{t.output.result(await Gi(await P(),t.positionals.id),aM)}});function iM(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(`
|
|
224
|
+
`)}function aM(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(`
|
|
225
|
+
`)}var Vw=E({name:"context",description:"Print the context pack of a task within a token budget",args:N({budget:{description:"Token budget (default: context.budget from .ari/config.json)",type:"number"}}),positionals:rt({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 qi(await P(),{budget:t.args.budget,id:t.positionals.id});t.output.result(e,({text:n})=>n)}});var cM=" ",lM=E({name:"list",description:"List project knowledge entries",args:N({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=Gl(await P(),{all:t.args.all});t.output.result(e,gM)}}),uM=E({name:"search",description:"Rank knowledge entries against a query with BM25",args:N({all:{default:!1,description:"Include archived entries",type:"boolean"}}),positionals:rt({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(cM),n=Yi(await P(),e,t.args.all);t.output.result(n,mM)}}),dM=E({name:"show",description:"Show one knowledge entry and how many done tasks used it",positionals:rt({id:{description:"Knowledge entry id",required:!0}}),json:!0,run:async(t)=>{let e=await P(),{tasks:n}=await ji(e);t.output.result(Jf(e,t.positionals.id,n),fM)}}),pM=E({name:"archive",description:"Archive a knowledge entry",args:N({force:{default:!1,description:"Allow archiving a constraint or decision",type:"boolean"}}),positionals:rt({id:{description:"Knowledge entry id",required:!0}}),json:!0,run:async(t)=>{let e=await P(),n=qf(e,t.positionals.id,{force:t.args.force});t.output.result(n,(r)=>`Archived ${r.kind} ${r.id}`)}}),Jw=E({name:"knowledge",description:"List, search, show and archive project knowledge",subcommands:[lM,uM,dM,pM]});function qw(t){let e=t.status==="active"?"":` [${t.status}]`,n=t.text.split(`
|
|
226
|
+
`)[0]??"";return`${t.id} (${t.kind})${e}: ${n}`}function gM(t){return t.entries.length===0?"No knowledge entries":t.entries.map(qw).join(`
|
|
227
|
+
`)}function mM(t){if(t.matches.length===0)return`No knowledge entry matches "${t.query}"`;return t.matches.map((e)=>`${e.score.toFixed(2)} ${qw(e.entry)}`).join(`
|
|
228
|
+
`)}function fM(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(`
|
|
229
|
+
`)}var hM=" ",Yw=E({name:"note",description:"Add a note to the active task, or a project knowledge entry with --global",args:N({global:{default:!1,description:"Write a project knowledge entry instead of a task note",type:"boolean"},kind:{description:`Entry kind with --global: ${ce.join(", ")} (default: fact)`,type:"string"},scope:{description:"Comma-separated globs the entry applies to, with --global (default: everywhere)",type:"string"}}),positionals:rt({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:Bf(r),text:t.positionals.text.join(hM)};t.output.result(await Ji(await P(),o),yM)}});function yM(t){return t.target==="task"?`Added note ${t.index} to ${t.task}`:`Added ${t.entry.kind} ${t.entry.id} to .ari/knowledge`}var Xu="HEAD~1",kM={fail:"fail",pass:"pass",regression:"pass"};async function Xw(t,e={}){let n=U(t),r=e.since??Xu,o=await ar(t,r),s=_t(await Jt(t,o)),{tasks:i}=pe(t,n),a=i.filter((u)=>u.record.status==="done"&&s.some((d)=>J(d,u.contract.scope))),c=Ve(t),l=[];for(let u of a){let d=await SM(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 wM(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 SM(t,e){let n=[];for(let r of e.contract.checks){let[o]=await Dt([bM(r)],$M(e,r),t);if(o!==void 0)n.push(wM(o))}return n}function $M(t,e){return(t.record.evidence.at(-1)?.gates.flatMap((r)=>r.checks)??[]).findLast((r)=>r.name===e.name)?.expect??kM[e.expect]}function bM(t){return{name:t.name,run:t.run,timeoutSeconds:t.timeoutSeconds}}var TM=1,zw=E({name:"replay",description:"Re-run the checks of done tasks whose scope changed since a reference",args:N({since:{default:Xu,description:"Reference to compare with",type:"string"}}),json:!0,examples:["ari replay","ari replay --since origin/develop --json"],run:async(t)=>{let e=await Xw(await P(),{since:t.args.since});return t.output.result(e,EM),e.regressed.length===0?void 0:TM}});function EM(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}`,xM(i.outputTail)]),...s]});return[e,...n].join(`
|
|
230
|
+
`)}function xM(t){return t.trimEnd().split(`
|
|
142
231
|
`).map((e)=>` ${e}`).join(`
|
|
143
|
-
`)}import{resolve as
|
|
144
|
-
`)[0]??""}`),...r.map((
|
|
145
|
-
`)}function
|
|
146
|
-
`)}import{existsSync as
|
|
147
|
-
`;async function
|
|
148
|
-
`)}function
|
|
232
|
+
`)}import{resolve as vM}from"path";var Ko="none",Zw=E({name:"sleep",description:"Consolidate memory: prune journals, archive duplicates, decay and enforce the budget",args:N({apply:{description:"Apply a validated JSON proposal of merges, promotions and archives",type:"string"},force:{default:!1,description:"With --apply, allow retiring constraint and decision entries",type:"boolean"}}),json:!0,examples:["ari sleep","ari sleep --json","ari sleep --apply proposal.json"],run:async(t)=>{let e=await P(),{apply:n,force:r}=t.args;if(n===void 0){if(r)throw new T("--force applies only with --apply","Run 'ari sleep --apply <file> --force'");t.output.result(await kr(e),CM);return}t.output.result(await uh(e,vM(process.cwd(),n),{force:r}),AM)}});function CM(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[`Pruned journals: ${t.pruned.length===0?Ko:t.pruned.map((s)=>s.task).join(", ")}`,`Archived entries: ${e.length===0?Ko:""}`.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(`
|
|
233
|
+
`)[0]??""}`),...r.map((s)=>` reconcile? ${s.ids.join(" and ")}`)].join(`
|
|
234
|
+
`)}function AM(t){return[`Created: ${t.created.length===0?Ko:t.created.map((e)=>e.id).join(", ")}`,`Archived: ${t.archived.length===0?Ko:t.archived.map((e)=>e.id).join(", ")}`,`Promoted notes: ${t.promoted.length===0?Ko:t.promoted.map((e)=>`${e.task} ${e.notes.join(", ")}`).join("; ")}`].join(`
|
|
235
|
+
`)}import{existsSync as fS}from"fs";import{basename as XM,extname as zM,join as hS}from"path";import{readFileSync as IM}from"fs";import{join as RM}from"path";var tS=["checks","invariants","scope","locked"];function eS(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?[...DM(t,e),...PM(e)]:[],i=e.record.evidence.flatMap(MM);if(!n)return[...s,...OM(e,r),...i];let a=o?LM(e,r):[];return[...s,...NM(e,r),...i,...a]}function nS(t,{exact:e}){let{evidence:n}=t.record;if(e)return n.at(-1)?.gates??[];return tS.flatMap((r)=>{let o=Ka(t,r),s=o.at(-1);return s===void 0?[]:[{...s,checks:rS(o)}]})}function OM(t,e){let n=e.stages.flatMap((u)=>u.gates),o=tS.filter((u)=>n.some((d)=>d.kind===u)).filter((u)=>Ka(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)=>_M(t.contract,u))),i=rS(Ka(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=Ka(t,"invariants").at(-1)?.checks.map((u)=>u.command),l=c===void 0||Zu(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 _M(t,e){return e.kind==="checks"&&e.expect==="pass"?dr(t,e.select):[]}function Ka(t,e){return t.record.evidence.flatMap((n)=>n.gates.filter((r)=>r.gate===e))}function rS(t){let e=t.flatMap((n)=>n.checks).filter((n)=>n.expect==="pass");return[...new Map(e.map((n)=>[zu(n),n])).values()]}function PM(t){return t.record.gatesHash===null?["the record has no frozen gates hash"]:[]}function NM(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} ${at(o,"stage","stages")}, but pack "${e.name}" expects ${r} at this point`],...n.evidence.flatMap((i,a)=>jM(i,e,a))]}function jM(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(Zu(o,s))return[];return[`the evidence of stage "${r.name}" records the gates [${o.join(", ")}], but the pack runs [${s.join(", ")}]`]}function MM(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 DM(t,e){let n=e.record.contractHash;if(n===null)return["the record has no frozen contract hash"];let r=IM(RM(t,ut(e.contract.id)),"utf8");if(Fe(r)===n)return[];return["the contract changed after 'ari start' or the last 'ari amend' froze it; a done contract must not change"]}function LM(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)=>FM(t.contract,o,s,i))}function FM(t,e,n,r){let o=e.gates[r];if(o===void 0||o.kind!==n.gate)return[];let s=GM(t,o);if(s===null)return[];let i=n.checks.map(HM);if(Zu(i.map(zu),s.map(zu)))return[];return[`the ${n.gate} evidence of stage "${e.name}" ran ${Qw(i)}, but the contract asks for ${Qw(s)}`]}function GM(t,e){switch(e.kind){case"checks":return dr(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 HM(t){return{command:t.command,expect:t.expect,name:t.name}}function zu(t){return JSON.stringify([t.name,t.command,t.expect])}function Qw(t){if(t.length===0)return"nothing";return t.map((e)=>`${e.name} (${JSON.stringify(e.command)}, expect ${e.expect})`).join(", ")}function Zu(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var wn=0,td=1,KM=128,UM=`
|
|
236
|
+
`;async function oS(t,e){let n=e.evidence.at(-1);if(e.status!=="done"||n===void 0)return null;let r=Be(e.id),o=await O(t,["log","--reverse","--format=%H","HEAD","--",r]),s=null;for(let i of o.stdout.split(UM).filter((a)=>a.length>0)){let a=uS(await Uo(t,i,r));if(a===null||a.created!==e.history[0]?.at)continue;if(a.base!==null)s??=i;if(BM(a,n))return{finished:i,started:s??i}}return null}async function sS(t,e,n){return uS(await Uo(t,e,Be(n)))?.status??null}async function Uo(t,e,n){let r=await O(t,["show",`${e}:${n}`],{allowedExitCodes:[wn,KM]});return r.exitCode===wn?r.stdout:null}async function iS(t,e){return await lS(t,e)!==null}async function aS(t,e){return lS(t,`${e}^`)}async function Bo(t,e,n){return(await O(t,["merge-base","--is-ancestor",e,n],{allowedExitCodes:[wn,td]})).exitCode===wn}async function ed(t,e,n){let r=await O(t,["merge-base",e,n],{allowedExitCodes:[wn,td]});return r.exitCode===wn?r.stdout.trim():null}async function nd(t,e,n){return Number((await O(t,["rev-list","--count",`${e}..${n}`])).stdout.trim())}async function cS(t){return(await O(t,["rev-parse","--is-shallow-repository"])).stdout.trim()==="true"}async function lS(t,e){let n=["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],r=await O(t,n,{allowedExitCodes:[wn,td]});return r.exitCode===wn?r.stdout.trim():null}function uS(t){let e=WM(t);if(!Qu(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:Qu(r)?r.at:null,evidence:Qu(n)?n:null,status:e.status}}function BM(t,{at:e,stage:n,treeHash:r}){let o=t.evidence;return o!==null&&o.at===e&&o.stage===n&&o.treeHash===r}function WM(t){if(t===null)return null;try{return JSON.parse(t)}catch(e){if(e instanceof SyntaxError)return null;throw e}}function Qu(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function rd({packs:t},e){return{exact:!0,pack:od(t,e.contract.pack)}}async function dS(t,e,n,r){let{gatesHash:o}=e.record,s=r===null?null:await VM(t,r,e.contract.pack),i=[n,s].find((a)=>a!==null&&JM(a,e)===o);if(i)return rd(i,e);return{exact:!1,pack:od((s??n).packs,e.contract.pack)}}async function VM(t,e,n){let r=pl(n),o=await Uo(t,e,r),s=await Uo(t,e,et);try{return{config:An(s===null?{}:JSON.parse(s)),packs:He(o===null?[]:[zs(o,r)])}}catch(i){if(i instanceof f||i instanceof SyntaxError)return null;throw i}}function JM({config:t,packs:e},n){let r=od(e,n.contract.pack);return r===null?null:Zs(r,t)}function od(t,e){return t.find((n)=>n.name===e)??null}async function gS(t){let{commits:e,record:n,root:r,target:o}=t,{base:s}=n;if(s===null)return mS("the record has no base commit");let i=await iS(r,s);if(e===null){if(!i)return sd(s);return Ua(await Jt(r,await pS(r,s,o,"HEAD")))}let{finished:a}=e,c=i&&await Bo(r,s,a),l=o===null?null:await ed(r,o,a);if(l===null||l===a)return YM(t,e,c?s:null);let u=c?await pS(r,s,o,a):await qM(r,l,t.otherFinishes,a);return Ua(await Hs(r,u,a))}async function pS(t,e,n,r){let o=n===null?null:await ed(t,n,r);return o!==null&&await Bo(t,e,o)?o:e}async function qM(t,e,n,r){let o={commit:e,distance:await nd(t,e,r)};for(let s of n){if(s===r||!await Bo(t,e,s)||!await Bo(t,s,r))continue;let i=await nd(t,s,r);if(i<o.distance)o={commit:s,distance:i}}return o.commit}async function YM(t,e,n){let{record:r,root:o}=t,{finished:s,started:i}=e;if(n===null&&await cS(o))return sd(r.base);let a=await aS(o,i),c=a===null?null:await Hs(o,a,s);if(n===null)return c===null?sd(r.base):Ua(c);let l=await Hs(o,n,s);return Ua(c===null?l:l.filter((u)=>c.includes(u)))}function Ua(t){return{files:t,problem:null}}function mS(t){return{files:[],problem:t}}function sd(t){return mS(`the base commit ${t} is not in this clone; fetch the full history`)}var ZM="\x00",id="HEAD",ud="done",ad=[Rn,ym],QM="invalid";async function yS(t,e){let n=U(t);await Gs(t);let r=pe(t,n),o=He(Te(t)),s=e.kind==="base"?await ar(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 tD(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 oS(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 rD(u,g));continue}let m=a.get(p)?.problem??nD(t,p);if(m===null)continue;d.push({gates:[],ok:!1,problems:[m],stage:null,status:QM,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 tD(t,e,n,r){let o=n??id,s=async(i)=>(r.get(i)?.record.status??await eD(t,i,o))===ud;switch(e.kind){case"all":return ld(po(t),s);case"base":{let i=["diff","--name-only","--no-renames","-z",o,id,"--",...ad],a=(await O(t,i)).stdout.split(ZM),c=new Set(cd(a,Rn));return ld(cd(a,...ad),async(l)=>c.has(l)||s(l))}case"local":{let i=dt(await q(t))?.task,a=await ld(cd(await Jt(t,id),...ad),s);return[...new Set([...i===void 0?[]:[i],...a])]}}}async function eD(t,e,n){if(!fS(hS(t,Be(e))))return sS(t,n,e);try{return _n(t,e).status}catch(r){if(r instanceof f)return ud;throw r}}function nD(t,e){let n=Be(e);return fS(hS(t,n))?`${n} has a record but no contract`:null}function cd(t,...e){let n=t.filter((r)=>J(r,e)).map((r)=>XM(r,zM(r)));return[...new Set(n)].filter(dl).sort(L)}async function ld(t,e){let n=[];for(let r of t)if(await e(r))n.push(r);return n}async function rD(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===ud?["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 dS(s,e,t,kS(t,e)?.finished??null):rd(t,e),a=eS(s,e,i),c=[];for(let u of nS(e,i)){let d=await oD(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 kS(t,e){return t.commits.get(e.contract.id)??null}async function oD(t,e,n){switch(n.gate){case"checks":case"invariants":{let r=sD(e,n.checks);return r.length===0?null:iD(t,e,r)}case"locked":return cD(t,e);case"scope":return lD(t,e);default:return null}}function sD(t,e){if(t.record.status==="done")return[...e];return e.filter((n)=>n.expect==="pass")}async function iD(t,e,n){let r=[],o=!0;for(let s of n){let i={name:s.name,run:s.command,timeoutSeconds:aD(t,e,s.name)},[a]=await Dt([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})`:Il(a))}return{current:o,details:r}}function aD(t,e,n){return e.contract.checks.find((o)=>o.name===n)?.timeoutSeconds??t.config.checkTimeoutSeconds}async function cD(t,e){let n=await Le(t.root,e.contract.lock),r=ko(e.record.lockHashes,n);return{current:r.length===0,details:r}}async function lD(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 gS({commits:kS(t,e),otherFinishes:s,record:e.record,root:r,target:o});if(i.problem!==null)return{current:!1,details:[i.problem]};let a=_t(i.files).filter((c)=>!J(c,e.contract.scope));return{current:a.length===0,details:a.map((c)=>`outside the scope: ${c}`)}}var uD=1,SS=E({name:"verify",description:"Re-evaluate the reproducible gates of done tasks against their evidence",args:N({all:{default:!1,description:"Verify every done task",type:"boolean"},base:{description:"Verify tasks whose record changed between this reference and HEAD (CI mode)",type:"string"}}),json:!0,examples:["ari verify","ari verify --base origin/develop","ari verify --all --json"],run:async(t)=>{let{all:e,base:n}=t.args;if(e&&n!==void 0)throw new T("--all and --base exclude each other","Pass one of them");let r=n!==void 0?{kind:"base",ref:n}:e?{kind:"all"}:{kind:"local"},o=await yS(await P(),r);return t.output.result(o,dD),o.failed.length===0?void 0:uD}});function dD(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 ${wS(i.recorded)}, now ${wS(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(`
|
|
237
|
+
`)}function wS(t){return t?"passed":"failed"}var $S=[Vw,Yw,Jw,Zw,zw,SS];var mD=".ari",fD="cli-state.json",hD=Ec({bin:"ari",commands:[ck,sw,Uw,Bw,Ww,aw,cw,Hh,Kh,Uh,lw,uw,dw,pw,Bh,...$S,Gy,Hy,Hw,Gw,Lw,Kw,Qm],config:new _c(gD(pD(),mD,fD),{}),description:"Task contracts, CLI-evaluated gates and tiered memory for coding agents",name:"Ariadne",version:_s});hD.main();
|