@r5n/ariadne 0.3.0 → 0.5.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 +35 -7
- package/dist/cli.js +241 -191
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,237 +1,287 @@
|
|
|
1
1
|
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
2
|
// @bun
|
|
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
|
|
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(s)r+=
|
|
9
|
-
`){if(o&&
|
|
10
|
-
`)}var
|
|
3
|
+
import{homedir as c5}from"os";import{join as l5}from"path";class vt extends Error{_tag="Cancel";constructor(t="Operation cancelled"){super(t)}}function j(t){return t}function ru(t){return t==null?[]:Array.isArray(t)?t:[t]}function oA(t,e,n,r){var o,s=t[e],i=~r.string.indexOf(e)?n==null||n===!0?"":String(n):typeof n==="boolean"?n:~r.boolean.indexOf(e)?n==="false"?!1:n==="true"||(t._.push((o=+n,o*0===0)?o:n),!!n):(o=+n,o*0===0)?o:n;t[e]=s==null?i:Array.isArray(s)?s.concat(i):[s,i]}function ou(t,e){t=t||[],e=e||{};var n,r,o,s,i,a={_:[]},c=0,l=0,u=0,d=t.length;let p=e.alias!==void 0,g=e.unknown!==void 0,f=e.default!==void 0;if(e.alias=e.alias||{},e.string=ru(e.string),e.boolean=ru(e.boolean),p)for(n in e.alias){r=e.alias[n]=ru(e.alias[n]);for(c=0;c<r.length;c++)(e.alias[r[c]]=r.concat(n)).splice(c,1)}for(c=e.boolean.length;c-- >0;){r=e.alias[e.boolean[c]]||[];for(l=r.length;l-- >0;)e.boolean.push(r[l])}for(c=e.string.length;c-- >0;){r=e.alias[e.string[c]]||[];for(l=r.length;l-- >0;)e.string.push(r[l])}if(f){for(n in e.default)if(s=typeof e.default[n],r=e.alias[n]=e.alias[n]||[],e[s]!==void 0){e[s].push(n);for(c=0;c<r.length;c++)e[s].push(r[c])}}let y=g?Object.keys(e.alias):[];for(c=0;c<d;c++){if(o=t[c],o==="--"){a._=a._.concat(t.slice(++c));break}for(l=0;l<o.length;l++)if(o.charCodeAt(l)!==45)break;if(l===0)a._.push(o);else if(o.substring(l,l+3)==="no-"){if(s=o.substring(l+3),g&&!~y.indexOf(s))return e.unknown(o);a[s]=!1}else{for(u=l+1;u<o.length;u++)if(o.charCodeAt(u)===61)break;s=o.substring(l,u),i=o.substring(++u)||(c+1===d||(""+t[c+1]).charCodeAt(0)===45||t[++c]),r=l===2?[s]:s;for(u=0;u<r.length;u++){if(s=r[u],g&&!~y.indexOf(s))return e.unknown("-".repeat(l)+s);oA(a,s,u+1<r.length||i,e)}}}if(f){for(n in e.default)if(a[n]===void 0)a[n]=e.default[n]}if(p)for(n in a){r=e.alias[n]||[];while(r.length>0)a[r.shift()]=a[n]}return a}var zt=0,ss=1,Tm=2,xm=255;function Ii(t){return Number.isInteger(t)&&t>=0&&t<=255}class m extends Error{hint;exitCode;_tag;constructor(t,e,n=1,r={}){super(t,"cause"in r?{cause:r.cause}:void 0);this.hint=e;this.exitCode=n;this._tag=r.tag??"Exit"}}class v extends m{constructor(t,e,n={}){super(t,e,2,{...n,tag:n.tag??"UsageError"})}}var Cm=1,sA=2,_i="--",Rm="-",Fn="no-",iA=new Set(["false","true"]),cs=/^--([^=]+)(?:=(.*))?$/s,ls=/^-([^-=][^=]*)(?:=(.*))?$/s,au=/^(?:---|-no-|-_|-[^-=][^=]*_)/,aA="_",is="\x00";function Me(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Zr(t){let e={alias:{},boolean:[],default:{},string:[]};for(let[n,r]of Object.entries(t)){if(r.type==="boolean")e.boolean.push(n);else e.string.push(n);if(r.alias)e.alias[r.alias]=n;let o=Me(n);if(o!==n)e.alias[o]=n;if(r.default!==void 0)e.default[n]=r.default}return e}function Oi(t,e){let n={};for(let[i,a]of Object.entries(e.alias))n[a]=[...n[a]??[],i];let{_:r,...o}=ou(Li(t,cA),{alias:n,boolean:[...e.boolean],default:{...e.default},string:[...e.string]}),s=Object.entries(o).map(([i,a])=>[su(i),su(a)]);return{...Object.fromEntries(s),_:r.map(su)}}function cA(t){if(t===Rm)return`${is}${t}`;let e=cs.exec(t);if(au.test(t)||lA(e?.[1]))return`--${is}${t}`;return(e?e[2]:ls.exec(t)?.[2])===""?`${t}${is}`:t}function lA(t){if(t===void 0)return!1;let e=t.startsWith(Fn)?t.slice(Fn.length):t;return e===aA||e in Object.prototype}function su(t){return typeof t==="string"&&t.startsWith(is)?t.slice(is.length):t}function as(t,e){return Object.hasOwn(e.alias,t)?e.alias[t]??t:t}function zr(t,e){if(Object.hasOwn(e,t))return`--${Me(t)}`;let n=Object.entries(e).find(([,r])=>r.alias===t)?.[0];if(n)return`--${Me(n)}`;return t.length===Cm?`-${t}`:`--${t}`}function Pi(t,e,n,r){let{alias:o}=Zr(e),s=Object.keys(t).find((i)=>!Object.hasOwn(e,i)&&!Object.hasOwn(o,i));if(s!==void 0)throw new v(`Unknown option: ${uA(s,r)}`,n)}function uA(t,e){if(t.startsWith("-"))return t;let n=e.indexOf(_i);for(let r of n<0?e:e.slice(0,n)){let o=cs.exec(r)?.[1];if(o===t||r===`--${Fn}${t}`)return`--${o}`;if(o===void 0&&ls.exec(r)?.[1]?.includes(t))return`-${t}`}return zr(t,{})}function Im(t,e){for(let[r,o]of Object.entries(t))if(Array.isArray(o))throw new v(`${zr(r,e)} can only be provided once`);let n={...t};for(let[r,o]of Object.entries(e)){let s=t[r];if(s===void 0)continue;if(o.type==="string"&&typeof s==="boolean")throw Om(zr(r,e));if(o.type!=="number")continue;let i=Number(s);if(typeof s==="boolean"||typeof s==="string"&&s.trim().length===0||!Number.isFinite(i)){let a=zr(r,e);throw new v(`Invalid number for ${a}: "${s}"`,`Use ${a}=<number> with a finite numeric value`)}n[r]=i}return n}function Om(t){return new v(`${t} needs a value`,`Use ${t}=<value>`)}function Ni(t,e){let n=Zr(e),r=lu([...t],n),o=Oi(r,n)._[0],s=o===void 0?-1:r.indexOf(o);return{before:s>=0?t.slice(0,s):[...t],command:o,restArgs:s>=0?t.slice(s+1):[]}}function _m(t,e){let n=Zr(e);for(let r=0;r<t.length;r+=1){let o=t[r]??"";if(o===_i)return-1;if(o===Rm||!o.startsWith("-"))return r;if(dA(o,n,e))r+=1}return-1}function dA(t,e,n){if(t.startsWith(`--${Fn}`))return!1;let r=cs.exec(t),o=r??ls.exec(t);if(!o||o[2]!==void 0)return!1;let s=r?o[1]??"":o[1]?.at(-1)??"",i=n[as(s,e)]?.type;return i==="string"||i==="number"}function cu(t,e,n=e){let r=Zr(e),{before:o,command:s,restArgs:i}=Ni(t,e),a=Zr(n);iu(o,r,e,!0),iu(t,a,n,!0);let{_:c,...l}=Oi(Pm(o,r,e),r);Pi(l,e,"Place command options after the command name",o);let{_:u,...d}=Oi(lu(i,a),a),p=Im({...Am(l,e,r),...Am(d,n,a)},e);return{command:s,flags:p,restArgs:i}}function Am(t,e,n){return Object.fromEntries(Object.entries(t).filter(([r])=>Object.hasOwn(e,r)||Object.hasOwn(n.alias,r)))}function Di(t,e){return Object.fromEntries(Object.keys(e).flatMap((n)=>{let r=t[n];return r===void 0?[]:[[n,r]]}))}function us(t,e={}){let n=Zr(e),r=pA(t,n);iu(r,n,e);let o=Oi(Pm(r,n,e),n),{_:s,...i}=o;return{args:Im(i,e),rawPositionals:s.map(String)}}function iu(t,e,n,r=!1){let o=new Set;for(let s of t){if(s===_i)break;let i=s.match(/^-+/)?.[0];if(!i||au.test(s))continue;let a=s.slice(i.length),c=a.split("=",Cm)[0]??"",l=a.startsWith(Fn)?[a.slice(Fn.length)]:i.length===sA?[c]:[...c];for(let u of l){let d=as(u,e);if(r&&!Object.hasOwn(n,d))continue;if(o.has(d))throw new v(`${zr(d,n)} can only be provided once`);o.add(d)}}}function Li(t,e){let n=t.indexOf(_i);return t.map((r,o)=>n>=0&&o>=n?r:e(r,t[o+1]))}function lu(t,e){return Li(t,(n)=>{let r=cs.exec(n)??ls.exec(n);if(!r||r[2]!==void 0||n.startsWith(`--${Fn}`))return n;let o=n.startsWith("--")?r[1]??"":r[1]?.at(-1)??"";return e.boolean.includes(as(o,e))?`${n}=true`:n})}function Pm(t,e,n){let r=(i)=>n[as(i,e)]?.type,o=(i)=>i!==void 0&&!i.startsWith("-"),s=Li(t,(i,a)=>{let c=cs.exec(i),l=c?null:ls.exec(i);if(i.startsWith(`--${Fn}`)||au.test(i))return i;let u=c?[c[1]??""]:[...l?.[1]??""],d=c?c[2]:l?.[2];for(let[p,g]of u.entries()){let f=r(g),y=p===u.length-1,S=zr(as(g,e),n),I=!y||d===void 0&&!o(a);if(f==="string"&&(I||d===""))throw Om(S);if(f==="number"&&I)throw new v(`${S} needs a value`,`Use ${S}=<number>`);if(f==="boolean"&&y&&d!==void 0&&!iA.has(d))throw new v(`Invalid value for ${S}: "${d}"`,`Use ${S}=true or ${S}=false`)}return i});return lu(s,e)}function pA(t,e){return Li(t,(n)=>n.replace(/^--(no-[^=]+)(=.*)?$/,(r,o,s)=>{let i=e.alias[o];return i&&e.boolean.includes(i)?`--${i}${s??""}`:r}))}function Mi(t,e){let n={},r=Object.entries(e);for(let[o,[s,i]]of r.entries())n[s]=i.variadic?t.slice(o):t[o];return n}function ji(t,e){for(let[n,r]of Object.entries(e)){if(!r.required)continue;let o=t[n];if(Array.isArray(o)?o.length===0:!o)return`Missing required argument: <${n}${r.variadic?"...":""}>`}return null}function Nm(t,e){let n=Object.values(e);if(n.some((r)=>r.variadic))return;return t[n.length]}var gA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,mA=new Set(["help","json"]),fA=/^[a-zA-Z0-9]$/,hA=new Set(["h","j"]);function Fi(){return(t)=>{let e={args:t.args??{},description:t.description,examples:t.examples??[],json:t.json??!1,name:t.name,passthrough:t.passthrough??!1,positionals:t.positionals??{},prompts:t.prompts??!1,run:t.run,strict:t.strict??!0,subcommands:t.subcommands??[]};return yA(e),Object.freeze(e)}}function Gi(t,e){let n=uu(e.map((r)=>r.name));if(n!==void 0)throw Error(`${t} has more than one command named "${n}"`)}function yA(t){let e=`Command "${t.name}"`;if(!gA.test(t.name))throw Error(`${e} must be named with a lower-case word such as "list" or "dry-run"`);if(!t.run&&t.subcommands.length===0)throw Error(`${e} needs run or subcommands`);for(let[u,d]of Object.entries(t.args)){if(mA.has(Me(u)))throw Error(`${e} cannot define the option "${u}": --${Me(u)} is a global flag`);if(d.alias!==void 0&&hA.has(d.alias))throw Error(`${e} cannot give "${u}" the alias -${d.alias}: it belongs to a global flag`)}let n=Object.keys(t.args).map(Me),r=uu(n);if(r!==void 0)throw Error(`${e} has more than one option named --${r}`);let o=Object.values(t.args).flatMap((u)=>u.alias??[]),s=o.find((u)=>!fA.test(u));if(s!==void 0)throw Error(`${e} uses the alias "${s}": an alias is one letter or digit`);let i=o.find((u)=>n.includes(u));if(i!==void 0)throw Error(`${e} uses the alias -${i}, which is also an option's name`);let a=uu(o);if(a!==void 0)throw Error(`${e} uses the alias -${a} more than once`);let c=Object.keys(t.positionals),l=c.find((u)=>t.positionals[u]?.variadic);if(l!==void 0&&l!==c.at(-1))throw Error(`${e} declares the variadic positional "${l}" before other positionals`);if(t.passthrough&&(!t.run||l===void 0))throw Error(`${e} uses passthrough, which needs run and a variadic last positional`);Gi(e,t.subcommands)}function uu(t){return t.find((e,n)=>t.indexOf(e)!==n)}function st(t){return t}import{Console as AA}from"console";import{Writable as CA}from"stream";import{format as RA,stripVTControlCharacters as IA}from"util";var Gn={active:!1};var kA=new Set(["0","false"]);function ds(t){if(process.env.NO_COLOR)return!1;let e=process.env.FORCE_COLOR;if(e!==void 0)return!kA.has(e);return t?.isTTY===!0}var wA=ds(process.stdout),Mm=["black","blue","cyan","gray","green","magenta","red","white","yellow"],SA=["bold","dim","italic","underline","reset"],jm={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",reset:"\x1B[0m",underline:"\x1B[4m"},vA={black:"\x1B[30m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",green:"\x1B[32m",magenta:"\x1B[35m",red:"\x1B[31m",white:"\x1B[37m",yellow:"\x1B[33m"},bA={black:"\x1B[40m",blue:"\x1B[44m",cyan:"\x1B[46m",gray:"\x1B[100m",green:"\x1B[42m",magenta:"\x1B[45m",red:"\x1B[41m",white:"\x1B[47m",yellow:"\x1B[43m"},Dm={"\x1B[30m":"\x1B[90m","\x1B[31m":"\x1B[91m","\x1B[32m":"\x1B[92m","\x1B[33m":"\x1B[93m","\x1B[34m":"\x1B[94m","\x1B[35m":"\x1B[95m","\x1B[36m":"\x1B[96m","\x1B[37m":"\x1B[97m"};function Hi(t){return(e)=>wA&&!Gn.active?`${t}${e}${jm.reset}`:e}function EA(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<32&&n!==27)return!1}return!0}function Lm({bright:t=!1,color:e}){let n=Bun.color(e,"ansi"),r=typeof n==="string"&&n.length>0&&EA(n)?n:vA[e];if(!r)return"";return t&&r in Dm?Dm[r]:r}var $A=Mm.reduce((t,e)=>{let n=Lm({color:e});if(n)t[e]=Hi(n);let r=Lm({bright:!0,color:e});if(r)t[`${e}Bright`]=Hi(r);return t},{}),TA=SA.reduce((t,e)=>(t[e]=Hi(jm[e]),t),{}),xA=Mm.reduce((t,e)=>{let n=bA[e];if(n){let r=`bg${e.charAt(0).toUpperCase()}${e.slice(1)}`;t[r]=Hi(n)}return t},{}),w={...$A,...TA,...xA};var OA=2,Hm=["clear","count","countReset","debug","dir","dirxml","group","groupCollapsed","groupEnd","info","log","table"],_A=[...Hm,"trace","write"],PA=1,NA="EPIPE",DA="EIO",dt={closedStreams:new Set,documentWritten:!1,jsonRuns:0,outputGuarded:!1,restoreStdout:void 0,sealed:!1,stdoutClosed:!1,stdoutWrite:void 0};function ps(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function ur(t){return ps()&&!Gn.active&&t?.json!==!0}function Um(){return Gn.active}function Hn(t){let e=JSON.stringify(t??null,null,OA);if(e===void 0)throw TypeError("JSON cannot represent the value");return`${e}
|
|
4
|
+
`}function Km(){return dt.documentWritten}function Bm(){dt.sealed=!0}function wn(t){if(dt.documentWritten=!0,dt.sealed||dt.stdoutClosed)return;let e=dt.stdoutWrite??process.stdout.write;try{e.call(process.stdout,t)}catch(n){if(!Ui(n,process.stdout))throw n;dt.stdoutClosed=!0}}function Vm(){if(dt.outputGuarded)return;dt.outputGuarded=!0,process.stdout.write=Fm(process.stdout.write,!0),console.write=Fm(console.write,0),process.stdout.on("error",(t)=>{if(!Ui(t,process.stdout))throw t;dt.stdoutClosed=!0}),process.stderr.on("error",(t)=>{if(!Ui(t,process.stderr))throw t});for(let t of[process.stdout,process.stderr])t.once("close",()=>dt.closedStreams.add(t))}function Fm(t,e){let n=(r)=>{let o=r.at(-1);if(typeof o==="function")queueMicrotask(()=>o());return e};return function(...o){if(dt.stdoutClosed)return n(o);try{return t.apply(this,o)}catch(s){if(!Ui(s,process.stdout))throw s;return dt.stdoutClosed=!0,n(o)}}}function Ui(t,e){if(!(t instanceof Error))return!1;let n=Reflect.get(t,"code");return n===NA||n===DA&&e.isTTY===!0}function Ki(){let t=ds(process.stderr);return new CA({decodeStrings:!1,write(e,n,r){process.stderr.write(t?e:IA(e)),r()}})}async function Wm(t,e){if(!t)return e();dt.jsonRuns+=1,dt.restoreStdout??=LA(),Gn.active=!0;try{return await e()}finally{if(dt.jsonRuns-=1,Gn.active=dt.jsonRuns>0,!Gn.active&&!dt.outputGuarded)dt.restoreStdout?.(),dt.restoreStdout=void 0}}async function Jm(t){let e=Promise.all([dt.stdoutClosed?void 0:Gm(process.stdout),Gm(process.stderr)]);await(t===void 0?e:Promise.race([e,Bun.sleep(t)]))}function Gm(t){if(t.writableFinished||dt.closedStreams.has(t))return Promise.resolve();return new Promise((e)=>{t.once("close",e),t.once("finish",e),t.once("error",()=>e()),t.end(()=>e())})}function LA(){let t=process.stdout.write,e=new AA({stderr:process.stderr,stdout:process.stderr}),n=Object.fromEntries(_A.map((o)=>[o,console[o]])),r=Object.fromEntries(Hm.map((o)=>[o,e[o].bind(e)]));return dt.stdoutWrite=t,process.stdout.write=process.stderr.write.bind(process.stderr),Object.assign(console,r,{trace:MA(e),write:jA}),()=>{process.stdout.write=t,Object.assign(console,n),dt.stdoutWrite=void 0}}function MA(t){let e=(...n)=>{let r={};Error.captureStackTrace(r,e);let o=r.stack?.split(`
|
|
5
|
+
`).slice(PA)??[];t.error([`Trace: ${RA(...n)}`,...o].join(`
|
|
6
|
+
`))};return e}function jA(...t){let e=Buffer.concat(t.map(FA));return process.stderr.write(e),e.byteLength}function FA(t){if(typeof t==="string")return Buffer.from(t);return ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t)}var Se={help:{alias:"h",description:"Show help",type:"boolean"},interactive:{alias:"i",description:"Open interactive mode",type:"boolean"},version:{alias:"v",description:"Show version",type:"boolean"},json:{alias:"j",description:"Write one JSON document to stdout",type:"boolean"}},Qr={help:Se.help,json:Se.json},dr="help",Bi={[zt]:"success",[ss]:"failure",[Tm]:"usage error"};import{stripVTControlCharacters as xu}from"util";import{styleText as QA}from"util";import{stdout as lf,stdin as tC}from"process";import eC from"readline";var qm=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(e)=>{let n=0;t.lastIndex=0;while(t.test(e))n+=1;return e.length-n}})(),Ym=(t)=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Xm=(t)=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var GA=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,HA=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,zm=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,UA=/\t{1,1000}/y,Zm=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,KA=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,BA=/\p{M}+/gu,VA={limit:1/0,ellipsis:""},Qm=(t,e={},n={})=>{let r=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?Qm(o,VA,n).width:0),i=0,a=n.controlWidth??0,c=n.tabWidth??8,l=n.emojiWidth??2,u=2,d=n.regularWidth??1,p=n.wideWidth??2,g=[[KA,d],[GA,0],[HA,a],[UA,c],[Zm,l],[zm,p]],f=0,y=0,S=t.length,I=0,C=!1,q=S,G=Math.max(0,r-s),N=0,H=0,A=0,R=0;t:while(!0){if(H>N||y>=S&&y>f){let B=t.slice(N,H)||t.slice(f,y);I=0;for(let _t of B.replaceAll(BA,"")){let Q=_t.codePointAt(0)||0;if(Ym(Q))R=2;else if(Xm(Q))R=p;else R=d;if(A+R>G)q=Math.min(q,Math.max(N,f)+I);if(A+R>r){C=!0;break t}I+=_t.length,A+=R}N=H=0}if(y>=S)break t;for(let B=0,_t=g.length;B<_t;B++){let[Q,Xr]=g[B];if(Q.lastIndex=y,Q.test(t)){if(I=Q===zm?qm(t.slice(y,Q.lastIndex)):Q===Zm?1:Q.lastIndex-y,R=I*Xr,A+R>G)q=Math.min(q,y+Math.floor((G-A)/Xr));if(A+R>r){C=!0;break t}A+=R,N=f,H=y,y=f=Q.lastIndex;continue t}}y+=1}return{width:C?G:A,index:C?q:S,truncated:C,ellipsed:C&&r>=s}},tf=Qm;var WA={limit:1/0,ellipsis:"",ellipsisWidth:0},JA=(t,e={})=>tf(t,WA,e).width,Lt=JA;var Vi="\x1B",sf="\x9B",qA=39,pu="\x07",af="[",YA="]",cf="m",gu=`${YA}8;;`,ef=new RegExp(`(?:\\${af}(?<code>\\d+)m|\\${gu}(?<uri>.*)${pu})`,"y"),nf=(t)=>{if(t>=30&&t<=37)return 39;if(t>=90&&t<=97)return 39;if(t>=40&&t<=47)return 49;if(t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0;return},rf=(t)=>`${Vi}${af}${t}${cf}`,of=(t)=>`${Vi}${gu}${t}${pu}`,du=(t,e,n)=>{let r=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:Lt(i),c=r.next(),l=r.next(),u=0;while(!c.done){let d=c.value,p=Lt(d);if(a+p<=n)t[t.length-1]+=d;else t.push(d),a=0;if(d===Vi||d===sf)o=!0,s=e.startsWith(gu,u+1);if(o){if(s){if(d===pu)o=!1,s=!1}else if(d===cf)o=!1}else if(a+=p,a===n&&!l.done)t.push(""),a=0;c=l,l=r.next(),u+=d.length}if(i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1)t[t.length-2]+=t.pop()},XA=(t)=>{let e=t.split(" "),n=e.length;while(n){if(Lt(e[n-1]))break;n--}if(n===e.length)return t;return e.slice(0,n).join(" ")+e.slice(n).join("")},zA=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let r="",o,s,i=t.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let p=i[d];if(n.trim!==!1){let f=a.at(-1)??"",y=f.trimStart();if(f.length!==y.length)a[a.length-1]=y,c=Lt(y)}if(d!==0){if(c>=e&&(n.wordWrap===!1||n.trim===!1))a.push(""),c=0;if(c||n.trim===!1)a[a.length-1]+=" ",c++}let g=Lt(p);if(n.hard&&g>e){let f=e-c,y=1+Math.floor((g-f-1)/e);if(Math.floor((g-1)/e)<y)a.push("");du(a,p,e),c=Lt(a.at(-1)??"");continue}if(c+g>e&&c&&g){if(n.wordWrap===!1&&c<e){du(a,p,e),c=Lt(a.at(-1)??"");continue}a.push(""),c=0}if(c+g>e&&n.wordWrap===!1){du(a,p,e),c=Lt(a.at(-1)??"");continue}a[a.length-1]+=p,c+=g}if(n.trim!==!1)a=a.map((d)=>XA(d));let l=a.join(`
|
|
7
|
+
`),u=!1;for(let d=0;d<l.length;d++){let p=l[d];if(r+=p,!u){if(u=p>="\uD800"&&p<="\uDBFF",u)continue}else u=!1;if(p===Vi||p===sf){ef.lastIndex=d+1;let f=ef.exec(l)?.groups;if(f?.code!==void 0){let y=Number.parseFloat(f.code);o=y===qA?void 0:y}else if(f?.uri!==void 0)s=f.uri.length===0?void 0:f.uri}if(l[d+1]===`
|
|
8
|
+
`){if(s)r+=of("");let g=o?nf(o):void 0;if(o&&g)r+=rf(g)}else if(p===`
|
|
9
|
+
`){if(o&&nf(o))r+=rf(o);if(s)r+=of(s)}}return r},ZA=/\r?\n/;function Un(t,e,n){return String(t).normalize().split(ZA).map((r)=>zA(r,e,n)).join(`
|
|
10
|
+
`)}var ve={to(t,e){if(!e)return`\x1B[${t+1}G`;return`\x1B[${e+1};${t+1}H`},move(t,e){let n="";if(t<0)n+=`\x1B[${-t}D`;else if(t>0)n+=`\x1B[${t}C`;if(e<0)n+=`\x1B[${-e}A`;else if(e>0)n+=`\x1B[${e}B`;return n},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"};var gs={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let n=0;n<t;n++)e+=this.line+(n<t-1?ve.up():"");if(t)e+=ve.left;return e}};function pr(t,e,n){if(!n.some((i)=>!i.disabled))return t;let r=t+e,o=Math.max(n.length-1,0),s=r<0?o:r>o?0:r;return n[s]?.disabled?pr(s,e<0?-1:1,n):s}var nC=["up","down","left","right","space","enter","cancel"],rC=["January","February","March","April","May","June","July","August","September","October","November","December"],Mt={actions:new Set(nC),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,accessible:void 0,date:{monthNames:[...rC],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:(t)=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:(t)=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function uf(t){if(t!==void 0)return t;if(Mt.accessible!==void 0)return Mt.accessible;let e=process.env.ACCESSIBLE;return e!==void 0&&e!==""&&e!=="0"&&e!=="false"}function df(t,e){if(typeof t=="string")return Mt.aliases.get(t)===e;for(let n of t)if(n!==void 0&&df(n,e))return!0;return!1}function oC(t,e){if(t===e)return;let n=t.split(`
|
|
11
11
|
`),r=e.split(`
|
|
12
|
-
`),o=Math.max(n.length,r.length),s=[];for(let i=0;i<o;i++)n[i]!==r[i]&&s.push(i);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:o}}var
|
|
12
|
+
`),o=Math.max(n.length,r.length),s=[];for(let i=0;i<o;i++)n[i]!==r[i]&&s.push(i);return{lines:s,numLinesBefore:n.length,numLinesAfter:r.length,numLines:o}}var Z5=globalThis.process.platform.startsWith("win"),Ji=Symbol("clack:cancel");function qi(t){return t===Ji}function Wi(t,e){let n=t;n.isTTY&&n.setRawMode(e)}var to=(t)=>("columns"in t)&&typeof t.columns=="number"?t.columns:80,mu=(t)=>("rows"in t)&&typeof t.rows=="number"?t.rows:20;function Sn(t,e,n,r=n,o=n,s){let i=to(t??lf),a=Lt(n);return Un(e,i-a,{hard:!0,trim:!1}).split(`
|
|
13
13
|
`).map((c,l,u)=>{let d=s?s(c,l):c;return l===0?`${r}${d}`:l===u.length-1?`${o}${d}`:`${n}${d}`}).join(`
|
|
14
|
-
`)}function
|
|
15
|
-
`),
|
|
16
|
-
`).length-1;this.output.write(
|
|
17
|
-
`);this.output.write(a[i]),this._prevFrame=e,this.output.write(
|
|
14
|
+
`)}function pf(t,e){if("~standard"in t){let n=t["~standard"].validate(e);return n instanceof Promise?n.then((r)=>r.issues?.at(0)?.message):n.issues?.at(0)?.message}return t(e)}var Yi=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return uf(this.opts.accessible)}constructor(e,n=!0){let{input:r=tC,output:o=lf,render:s,signal:i,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=s.bind(this),this._track=n,this._abortSignal=i,this.input=r,this.output=o}unsubscribe(){this._subscribers.clear()}setSubscriber(e,n){let r=this._subscribers.get(e)??[];r.push(n),this._subscribers.set(e,r)}on(e,n){this.setSubscriber(e,{cb:n})}once(e,n){this.setSubscriber(e,{cb:n,once:!0})}emit(e,...n){let r=this._subscribers.get(e)??[],o=[];for(let s of r)s.cb(...n),s.once&&o.push(()=>r.splice(r.indexOf(s),1));for(let s of o)s()}prompt(){return new Promise((e)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Ji);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=eC.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Wi(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(ve.show),this.output.off("resize",this.render),Wi(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(ve.show),this.output.off("resize",this.render),Wi(this.input,!1),e(Ji)})})}_isActionKey(e,n){return e==="\t"}_shouldSubmit(e,n){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,n){this.userInput=e??"",this.emit("userInput",this.userInput),n&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress(e,n){if(this.state!=="validating"){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(e,n)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),n?.name&&(!this._track&&Mt.aliases.has(n.name)&&this.emit("cursor",Mt.aliases.get(n.name)),Mt.actions.has(n.name)&&this.emit("cursor",n.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,n),n?.name==="return"&&this._shouldSubmit(e,n)){if(this.opts.validate){let r=pf(this.opts.validate,this.value),o;r instanceof Promise?(this.state="validating",this.render(),o=await r):o=r,o&&(this.error=o instanceof Error?o.message:o,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}df([e,n?.name,n?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
15
|
+
`),Wi(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Un(this._prevFrame,to(this.output),{hard:!0,trim:!1}).split(`
|
|
16
|
+
`).length-1;this.output.write(ve.move(-999,e*-1))}render(){let e=Un(this._render(this)??"",to(this.output),{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(ve.hide);else{let n=oC(this._prevFrame,e),r=mu(this.output);if(this.restoreCursor(),n){let o=Math.max(0,n.numLinesAfter-r),s=Math.max(0,n.numLinesBefore-r),i=n.lines.find((a)=>a>=o);if(i===void 0){this._prevFrame=e;return}if(n.lines.length===1){this.output.write(ve.move(0,i-s)),this.output.write(gs.lines(1));let a=e.split(`
|
|
17
|
+
`);this.output.write(a[i]),this._prevFrame=e,this.output.write(ve.move(0,a.length-i-1));return}else if(n.lines.length>1){if(o<s)i=o;else{let c=i-s;c>0&&this.output.write(ve.move(0,c))}this.output.write(gs.down());let a=e.split(`
|
|
18
18
|
`).slice(i);this.output.write(a.join(`
|
|
19
|
-
`)),this._prevFrame=e;return}}this.output.write(
|
|
20
|
-
`);return n&&o.push(
|
|
21
|
-
`);
|
|
19
|
+
`)),this._prevFrame=e;return}}this.output.write(gs.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};class fu extends Yi{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(e)=>{this.output.write(ve.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class hu extends Yi{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter((t)=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,e=this.value!==void 0&&this.value.length===t.length;this.value=e?[]:t.map((n)=>n.value)}toggleInvert(){let t=this.value;if(!t)return;let e=this._enabledOptions.filter((n)=>!t.includes(n.value));this.value=e.map((n)=>n.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter((e)=>e!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let e=Math.max(this.options.findIndex(({value:n})=>n===t.cursorAt),0);this.cursor=this.options[e]?.disabled?pr(e,1,this.options):e,this.on("key",(n,r)=>{r.name==="a"&&this.toggleAll(),r.name==="i"&&this.toggleInvert(),r.name===void 0&&n==="\u3000"&&this.toggleValue()}),this.on("cursor",(n)=>{switch(n){case"left":case"up":this.cursor=pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=pr(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var gf=class extends Yi{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let n=this.options.findIndex(({value:o})=>o===e.initialValue),r=n===-1?0:n;this.cursor=this.options[r]?.disabled?pr(r,1,this.options):r,this.changeValue(),this.on("cursor",(o)=>{switch(o){case"left":case"up":this.cursor=pr(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=pr(this.cursor,1,this.options);break}this.changeValue()})}};class yu extends Yi{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let e=t.slice(0,this.cursor),n=t.slice(this.cursor,this.cursor+1),r=t.slice(this.cursor+1);return`${e}${QA("inverse",n)}${r}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",(e)=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as h,stripVTControlCharacters as uY}from"util";import be from"process";function sC(){if(be.platform!=="win32")return be.env.TERM!=="linux";return Boolean(be.env.CI)||Boolean(be.env.WT_SESSION)||Boolean(be.env.TERMINUS_SUBLIME)||be.env.ConEmuTask==="{cmd::Cmder}"||be.env.TERM_PROGRAM==="Terminus-Sublime"||be.env.TERM_PROGRAM==="vscode"||be.env.TERM==="xterm-256color"||be.env.TERM==="alacritty"||be.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Su=sC(),wf=()=>process.env.CI==="true";var tt=(t,e)=>Su?t:e,mf=tt("\u25C6","*"),vu=tt("\u25A0","x"),bu=tt("\u25B2","x"),fs=tt("\u25C7","o"),iC=tt("\u250C","T"),U=tt("\u2502","|"),Ze=tt("\u2514","\u2014"),fY=tt("\u2510","T"),hY=tt("\u2518","\u2014"),ku=tt("\u25CF",">"),zi=tt("\u25CB"," "),aC=tt("\u25FB","[\u2022]"),ff=tt("\u25FC","[+]"),hf=tt("\u25FB","[ ]"),yY=tt("\u25AA","\u2022"),yf=tt("\u2500","-"),cC=tt("\u256E","+"),lC=tt("\u251C","+"),uC=tt("\u256F","+"),dC=tt("\u2570","+"),kY=tt("\u256D","+"),pC=tt("\u25CF","\u2022"),gC=tt("\u25C6","*"),mC=tt("\u25B2","!"),fC=tt("\u25A0","x"),Zi=(t)=>{switch(t){case"initial":case"active":return h("cyan",mf);case"cancel":return h("red",vu);case"error":return h("yellow",bu);case"submit":return h("green",fs);case"validating":return h("dim",mf)}},Sf=(t)=>{switch(t){case"initial":case"active":return h("cyan",U);case"cancel":return h("red",U);case"error":return h("yellow",U);case"submit":return h("green",U)}};function vf(t,e,n){let r=n?`${h("cyan",U)} `:"",o=Sn(t,e.join(" \u2022 "),r).split(`
|
|
20
|
+
`);return n&&o.push(h("cyan",Ze)),o}var kf=(t,e,n,r,o,s=!1)=>{let i=e,a=0;if(s)for(let c=r-1;c>=n;c--){let l=t[c];if(l&&(i-=l.length),a++,i<=o)break}else for(let c=n;c<r;c++){let l=t[c];if(l&&(i-=l.length),a++,i<=o)break}return{lineCount:i,removals:a}},wu=({cursor:t,options:e,style:n,output:r=process.stdout,maxItems:o=Number.POSITIVE_INFINITY,columnPadding:s=0,rowPadding:i=4})=>{let a=to(r)-s,c=mu(r),l=h("dim","..."),u=Math.max(c-i,0),d=Math.max(Math.min(o,u),5),p=0;t>=d-3&&(p=Math.max(Math.min(t-d+3,e.length-d),0));let g=d<e.length&&p>0,f=d<e.length&&p+d<e.length,y=Math.min(p+d,e.length),S=[],I=0;g&&I++,f&&I++;let C=p+(g?1:0),q=y-(f?1:0);for(let N=C;N<q;N++){let H=e[N],A=H!==void 0?n(H,N===t):"",R=Un(A,a,{hard:!0,trim:!1}).split(`
|
|
21
|
+
`);S.push(R),I+=R.length}if(I>u){let N=0,H=0,A=I,R=t-C,B=u,_t=()=>kf(S,A,0,R,B),Q=()=>kf(S,A,R+1,S.length,B,!0);g?({lineCount:A,removals:N}=_t(),A>B&&(f||(B-=1),{lineCount:A,removals:H}=Q())):(f||(B-=1),{lineCount:A,removals:H}=Q(),A>B&&(B-=1,{lineCount:A,removals:N}=_t())),N>0&&(g=!0,S.splice(0,N)),H>0&&(f=!0,S.splice(S.length-H,H))}let G=[];g&&G.push(l);for(let N of S)for(let H of N)G.push(H);return f&&G.push(l),G};var bf=(t)=>{let e=t.active??"Yes",n=t.inactive??"No";return new fu({active:e,inactive:n,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let r=t.withGuide??Mt.withGuide,o=`${Zi(this.state)} `,s=r?`${h("gray",U)} `:"",i=Sn(t.output,t.message,s,o),a=`${r?`${h("gray",U)}
|
|
22
22
|
`:""}${i}
|
|
23
|
-
`,c=this.value?e:n;switch(this.state){case"submit":{let l=r?`${
|
|
24
|
-
${
|
|
25
|
-
${
|
|
26
|
-
`:` ${
|
|
23
|
+
`,c=this.value?e:n;switch(this.state){case"submit":{let l=r?`${h("gray",U)} `:"";return`${a}${l}${h("dim",c)}`}case"cancel":{let l=r?`${h("gray",U)} `:"";return`${a}${l}${h(["strikethrough","dim"],c)}${r?`
|
|
24
|
+
${h("gray",U)}`:""}`}default:{let l=r?`${h("cyan",U)} `:"",u=r?h("cyan",Ze):"";return`${a}${l}${this.value?`${h("green",ku)} ${e}`:`${h("dim",zi)} ${h("dim",e)}`}${t.vertical?r?`
|
|
25
|
+
${h("cyan",U)} `:`
|
|
26
|
+
`:` ${h("dim","/")} `}${this.value?`${h("dim",zi)} ${h("dim",n)}`:`${h("green",ku)} ${n}`}
|
|
27
27
|
${u}
|
|
28
|
-
`}}}}).prompt()};var
|
|
28
|
+
`}}}}).prompt()};var hC=[`${h("dim","\u2191/\u2193")} to navigate`,`${h("dim","Space:")} select`,`${h("dim","Enter:")} confirm`],ms=(t,e)=>t.split(`
|
|
29
29
|
`).map((n)=>e(n)).join(`
|
|
30
|
-
`),
|
|
31
|
-
${
|
|
30
|
+
`),Ef=(t)=>{let e=(o,s)=>{let i=o.label??String(o.value);return s==="disabled"?`${h("gray",hf)} ${ms(i,(a)=>h(["strikethrough","gray"],a))}${o.hint?` ${h("dim",`(${o.hint??"disabled"})`)}`:""}`:s==="active"?`${h("cyan",aC)} ${i}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="selected"?`${h("green",ff)} ${ms(i,(a)=>h("dim",a))}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="cancelled"?`${ms(i,(a)=>h(["strikethrough","dim"],a))}`:s==="active-selected"?`${h("green",ff)} ${i}${o.hint?` ${h("dim",`(${o.hint})`)}`:""}`:s==="submitted"?`${ms(i,(a)=>h("dim",a))}`:`${h("dim",hf)} ${ms(i,(a)=>h("dim",a))}`},n=t.required??!0,r=t.showInstructions??!0;return new hu({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:n,cursorAt:t.cursorAt,validate(o){if(n&&(o===void 0||o.length===0))return`Please select at least one option.
|
|
31
|
+
${h("reset",h("dim",`Press ${h(["gray","bgWhite","inverse"]," space ")} to select, ${h("gray",h("bgWhite",h("inverse"," enter ")))} to submit`))}`},render(){let o=t.withGuide??Mt.withGuide,s=Sn(t.output,t.message,o?`${Sf(this.state)} `:"",`${Zi(this.state)} `),i=`${o?`${h("gray",U)}
|
|
32
32
|
`:""}${s}
|
|
33
|
-
`,a=this.value??[],c=(l,u)=>{if(l.disabled)return e(l,"disabled");let d=a.includes(l.value);return u&&d?e(l,"active-selected"):d?e(l,"selected"):e(l,u?"active":"inactive")};switch(this.state){case"submit":{let l=this.options.filter(({value:d})=>a.includes(d)).map((d)=>e(d,"submitted")).join(
|
|
34
|
-
${
|
|
35
|
-
`).map((g,
|
|
33
|
+
`,a=this.value??[],c=(l,u)=>{if(l.disabled)return e(l,"disabled");let d=a.includes(l.value);return u&&d?e(l,"active-selected"):d?e(l,"selected"):e(l,u?"active":"inactive")};switch(this.state){case"submit":{let l=this.options.filter(({value:d})=>a.includes(d)).map((d)=>e(d,"submitted")).join(h("dim",", "))||h("dim","none"),u=Sn(t.output,l,o?`${h("gray",U)} `:"");return`${i}${u}`}case"cancel":{let l=this.options.filter(({value:d})=>a.includes(d)).map((d)=>e(d,"cancelled")).join(h("dim",", "));if(l.trim()==="")return`${i}${h("gray",U)}`;let u=Sn(t.output,l,o?`${h("gray",U)} `:"");return`${i}${u}${o?`
|
|
34
|
+
${h("gray",U)}`:""}`}case"error":{let l=o?`${h("yellow",U)} `:"",u=this.error.split(`
|
|
35
|
+
`).map((g,f)=>f===0?`${o?`${h("yellow",Ze)} `:""}${h("yellow",g)}`:` ${g}`).join(`
|
|
36
36
|
`),d=i.split(`
|
|
37
37
|
`).length,p=u.split(`
|
|
38
|
-
`).length+1;return`${i}${l}${
|
|
38
|
+
`).length+1;return`${i}${l}${wu({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:l.length,rowPadding:d+p,style:c}).join(`
|
|
39
39
|
${l}`)}
|
|
40
40
|
${u}
|
|
41
|
-
`}default:{let l=o?`${
|
|
42
|
-
`).length,d=r?
|
|
43
|
-
`),g=d.length+1;return`${i}${l}${
|
|
41
|
+
`}default:{let l=o?`${h("cyan",U)} `:"",u=i.split(`
|
|
42
|
+
`).length,d=r?vf(t.output,hC,o):o?[h("cyan",Ze)]:[],p=d.join(`
|
|
43
|
+
`),g=d.length+1;return`${i}${l}${wu({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:l.length,rowPadding:u+g,style:c}).join(`
|
|
44
44
|
${l}`)}
|
|
45
45
|
${p}
|
|
46
|
-
`}}}}).prompt()};var
|
|
47
|
-
`);if(d.length>0){let[p,...g]=d;p.length>0?i.push(`${l}${p}`):i.push(a?e:"");for(let
|
|
46
|
+
`}}}}).prompt()};var Ut={message:(t=[],{symbol:e=h("gray",U),secondarySymbol:n=h("gray",U),output:r=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??Mt.withGuide,c=a?n:"",l=a?`${e} `:"",u=a?`${n} `:"";for(let p=0;p<o;p++)i.push(c);let d=Array.isArray(t)?t:t.split(`
|
|
47
|
+
`);if(d.length>0){let[p,...g]=d;p.length>0?i.push(`${l}${p}`):i.push(a?e:"");for(let f of g)f.length>0?i.push(`${u}${f}`):i.push(a?n:"")}r.write(`${i.join(`
|
|
48
48
|
`)}
|
|
49
|
-
`)},info:(t,e)=>{
|
|
49
|
+
`)},info:(t,e)=>{Ut.message(t,{...e,symbol:h("blue",pC)})},success:(t,e)=>{Ut.message(t,{...e,symbol:h("green",gC)})},step:(t,e)=>{Ut.message(t,{...e,symbol:h("green",fs)})},warn:(t,e)=>{Ut.message(t,{...e,symbol:h("yellow",mC)})},warning:(t,e)=>{Ut.warn(t,e)},error:(t,e)=>{Ut.message(t,{...e,symbol:h("red",fC)})}},$f=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Mt.withGuide?`${h("gray",Ze)} `:"";n.write(`${r}${h("red",t)}
|
|
50
50
|
|
|
51
|
-
`)},
|
|
52
|
-
`)},
|
|
53
|
-
${
|
|
51
|
+
`)},Tf=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Mt.withGuide?`${h("gray",iC)} `:"";n.write(`${r}${t}
|
|
52
|
+
`)},xf=(t="",e)=>{let n=e?.output??process.stdout,r=e?.withGuide??Mt.withGuide?`${h("gray",U)}
|
|
53
|
+
${h("gray",Ze)} `:"";n.write(`${r}${t}
|
|
54
54
|
|
|
55
|
-
`)};var
|
|
56
|
-
`),s=o.reduce((c,l)=>Math.max(
|
|
57
|
-
`).map(s),""],a=
|
|
58
|
-
`),u=o?`${
|
|
59
|
-
`:"",d=o?
|
|
55
|
+
`)};var yC=(t)=>t,kC=(t,e,n)=>{let r={hard:!0,trim:!1},o=Un(t,e,r).split(`
|
|
56
|
+
`),s=o.reduce((c,l)=>Math.max(Lt(l),c),0),i=o.map(n).reduce((c,l)=>Math.max(Lt(l),c),0),a=e-(i-s);return Un(t,a,r)},Af=(t="",e="",n)=>{let r=n?.output??be.stdout,o=n?.withGuide??Mt.withGuide,s=n?.format??yC,i=["",...kC(t,to(r)-6,s).split(`
|
|
57
|
+
`).map(s),""],a=Lt(e),c=Math.max(i.reduce((p,g)=>{let f=Lt(g);return f>p?f:p},0),a)+2,l=i.map((p)=>`${h("gray",U)} ${p}${" ".repeat(c-Lt(p))}${h("gray",U)}`).join(`
|
|
58
|
+
`),u=o?`${h("gray",U)}
|
|
59
|
+
`:"",d=o?lC:dC;r.write(`${u}${h("green",fs)} ${h("reset",e)} ${h("gray",yf.repeat(Math.max(c-a-1,1))+cC)}
|
|
60
60
|
${l}
|
|
61
|
-
${
|
|
62
|
-
`)};var
|
|
61
|
+
${h("gray",d+yf.repeat(c+2)+uC)}
|
|
62
|
+
`)};var wY={light:tt("\u2500","-"),heavy:tt("\u2501","="),block:tt("\u2588","#")};var wC=[`${h("dim","\u2191/\u2193")} to navigate`,`${h("dim","Enter:")} confirm`],Xi=(t,e)=>t.includes(`
|
|
63
63
|
`)?t.split(`
|
|
64
64
|
`).map((n)=>e(n)).join(`
|
|
65
|
-
`):e(t),
|
|
65
|
+
`):e(t),Cf=(t)=>{let e=(r,o)=>{if(r===void 0)return"";let s=r.label??String(r.value);switch(o){case"disabled":return`${h("gray",zi)} ${Xi(s,(i)=>h("gray",i))}${r.hint?` ${h("dim",`(${r.hint??"disabled"})`)}`:""}`;case"selected":return`${Xi(s,(i)=>h("dim",i))}`;case"active":return`${h("green",ku)} ${s}${r.hint?` ${h("dim",`(${r.hint})`)}`:""}`;case"cancelled":return`${Xi(s,(i)=>h(["strikethrough","dim"],i))}`;default:return`${h("dim",zi)} ${Xi(s,(i)=>h("dim",i))}`}},n=t.showInstructions??!0;return new gf({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let r=t.withGuide??Mt.withGuide,o=`${Zi(this.state)} `,s=`${Sf(this.state)} `,i=Sn(t.output,t.message,s,o),a=`${r?`${h("gray",U)}
|
|
66
66
|
`:""}${i}
|
|
67
|
-
`;switch(this.state){case"submit":{let c=r?`${
|
|
68
|
-
${
|
|
69
|
-
`).length,u=n?
|
|
70
|
-
`),p=u.length+1;return`${a}${c}${
|
|
67
|
+
`;switch(this.state){case"submit":{let c=r?`${h("gray",U)} `:"",l=Sn(t.output,e(this.options[this.cursor],"selected"),c);return`${a}${l}`}case"cancel":{let c=r?`${h("gray",U)} `:"",l=Sn(t.output,e(this.options[this.cursor],"cancelled"),c);return`${a}${l}${r?`
|
|
68
|
+
${h("gray",U)}`:""}`}default:{let c=r?`${h("cyan",U)} `:"",l=a.split(`
|
|
69
|
+
`).length,u=n?vf(t.output,wC,r):r?[h("cyan",Ze)]:[],d=u.join(`
|
|
70
|
+
`),p=u.length+1;return`${a}${c}${wu({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:c.length,rowPadding:l+p,style:(g,f)=>e(g,g.disabled?"disabled":f?"active":"inactive")}).join(`
|
|
71
71
|
${c}`)}
|
|
72
72
|
${d}
|
|
73
|
-
`}}}}).prompt()};var
|
|
74
|
-
`:""}${
|
|
75
|
-
`,r=t.placeholder&&t.placeholder.length>0?
|
|
73
|
+
`}}}}).prompt()};var SY=`${h("gray",U)} `;var Rf=(t)=>new yu({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??Mt.withGuide,n=`${`${e?`${h("gray",U)}
|
|
74
|
+
`:""}${Zi(this.state)} `}${t.message}
|
|
75
|
+
`,r=t.placeholder&&t.placeholder.length>0?h("inverse",t.placeholder[0])+h("dim",t.placeholder.slice(1)):h(["inverse","hidden"],"_"),o=this.userInput?this.userInputWithCursor:r,s=this.value??"";switch(this.state){case"validating":{let i=e?`${h("cyan",U)} `:"",a=e?h("cyan",Ze):"",c=h("dim",o),l=h("dim","Validating...");return`${n}${i}${c}
|
|
76
76
|
${a} ${l}
|
|
77
|
-
`}case"error":{let i=this.error?` ${
|
|
77
|
+
`}case"error":{let i=this.error?` ${h("yellow",this.error)}`:"",a=e?`${h("yellow",U)} `:"",c=e?h("yellow",Ze):"";return`${n.trim()}
|
|
78
78
|
${a}${o}
|
|
79
79
|
${c}${i}
|
|
80
|
-
`}case"submit":{let i=s?`${e?" ":""}${
|
|
81
|
-
${a}`:""}`}default:{let i=e?`${
|
|
80
|
+
`}case"submit":{let i=s?`${e?" ":""}${h("dim",s)}`:"",a=e?h("gray",U):"";return`${n}${a}${i}`}case"cancel":{let i=s?` ${h(["strikethrough","dim"],s)}`:"",a=e?h("gray",U):"";return`${n}${a}${i}${s.trim()?`
|
|
81
|
+
${a}`:""}`}default:{let i=e?`${h("cyan",U)} `:"",a=e?h("cyan",Ze):"";return`${n}${i}${o}
|
|
82
82
|
${a}
|
|
83
|
-
`}}}}).prompt();function
|
|
84
|
-
`),u=()=>(clearInterval(i),
|
|
85
|
-
`)},p={cancel(g=r){s=
|
|
86
|
-
`),l(),!e)return;i=setInterval(c,
|
|
83
|
+
`}}}}).prompt();function If(t=process.stdin){return t.readableEnded||t.destroyed}async function Of({edits:t,input:e=process.stdin,signal:n},r){let o=new AbortController,s=()=>o.abort(),i=(c,l)=>{if(l.sequence==="\x04"&&(!t||e.isPaused()))s()},a=r(n?AbortSignal.any([o.signal,n]):o.signal);e.on("keypress",i),e.once("end",s),e.once("close",s);try{return await a}finally{e.off("keypress",i),e.off("end",s),e.off("close",s)}}import{stripVTControlCharacters as vC}from"util";var Eu=Su?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],bC=80,EC=8,$C=3,TC="...",$u="\r\x1B[K",xC=80,AC=/\s*\n\s*/g,hs=new Set;function Pf(){for(let t of[...hs])t.error()}function Nf({output:t=process.stdout}={}){let e=t.isTTY===!0&&!wf(),n=ds(t),r="",o=0,s=!1,i,a=(g)=>{t.write(e||n?g:vC(g))},c=()=>{let g=w.magenta(Eu[o%Eu.length]??""),f=".".repeat(Math.floor(o/EC)%($C+1)),y=`${g} ${r.replace(AC," ")}${f}`;a(`${$u}${Bun.sliceAnsi(y,0,(t.columns||xC)-1)}`),o+=1},l=()=>e?c():a(`${w.magenta(Eu[0]??"")} ${r}${TC}
|
|
84
|
+
`),u=()=>(clearInterval(i),hs.delete(p)),d=(g,f)=>{if(u())a(`${e?$u:""}${g} ${f}
|
|
85
|
+
`)},p={cancel(g=r){s=hs.has(p)||s,d(w.red(vu),g)},clear(){if(u()&&e)a($u)},error(g=r){d(w.red(bu),g)},get isCancelled(){return s},message(g=r){let f=_f(g);if(f===r)return;if(r=f,hs.has(p)&&!e)l()},start(g=""){if(p.clear(),s=!1,r=_f(g),o=0,hs.add(p),a(`${w.gray(U)}
|
|
86
|
+
`),l(),!e)return;i=setInterval(c,bC),i.unref()},stop(g=r){d(w.green(fs),g)}};return p}function _f(t){return t.replace(/\.+$/,"")}var RC="Pass the value as an argument or option instead";function IC(t){if(qi(t))throw new vt;return t}function OC(t){if(ur())return;throw new v(`Cannot prompt for ${t} without a terminal`,RC)}async function Qi(t,e,{edits:n=!1,hint:r}){if(OC(e.message),If(e.input))throw new vt;return PC(r),IC(await Of({...e,edits:n},(o)=>t({...e,signal:o})))}function _C(t){return t.map((e)=>e.key?`${w.bold(e.key)} ${w.dim(e.text)}`:w.dim(e.text)).join(w.dim(" \xB7 "))}function PC(t){Ut.info(_C(t))}var ta={confirm:[{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],multiselect:[{key:"\u2191\u2193",text:"navigate"},{key:"Space",text:"toggle"},{key:"a",text:"all"},{key:"Enter",text:"confirm"},{key:"Esc",text:"cancel"}],select:[{key:"\u2191\u2193",text:"navigate"},{key:"Enter",text:"select"},{key:"Esc",text:"cancel"}],text:[{key:"Enter",text:"submit"},{key:"Esc",text:"cancel"}]};async function Ee(t){return Qi(bf,t,{hint:ta.confirm})}async function Tu(t){return Qi(Rf,t,{edits:!0,hint:ta.text})}async function gr(t){return Qi(Cf,{showInstructions:!1,...t},{hint:ta.select})}async function ea(t){return Qi(Ef,{showInstructions:!1,...t},{hint:ta.multiselect})}function mr(t){return Um()&&t.output===void 0?{...t,output:process.stderr}:t}function eo(t){return(e,n={})=>t(e,mr(n))}var bt={error:eo(Ut.error),info:eo(Ut.info),message:(t,e={})=>Ut.message(t,mr(e)),step:eo(Ut.step),success:eo(Ut.success),warn:eo(Ut.warn),warning:eo(Ut.warning)};function fr(t,e={}){Tf(t,mr(e))}function ce(t,e={}){xf(t,mr(e))}function ys(t,e={}){$f(t,mr(e))}function Nt(t,e,n={}){Af(t,e,mr(n))}function na(t={}){return Nf(mr(t))}import{inspect as NC}from"util";var DC=4;function ra(t,e=[]){if(e.length>=DC)return[];let n=t instanceof AggregateError?t.errors:[],r=[...e,t];return[...n,...t.cause!==void 0?[t.cause]:[]].filter((s)=>!r.includes(s)).flatMap((s)=>[{hint:sa(s),message:oa(s)},...s instanceof Error?ra(s,r):[]])}function oa(t){return ia(t instanceof Error?t.message||t.name:t)}function sa(t){return t instanceof m&&t.hint!==void 0?ia(t.hint):void 0}function ia(t){return typeof t==="string"?t:NC(t,{breakLength:Number.POSITIVE_INFINITY})}var LC="Error",MC=27,jC=new RegExp(`${String.fromCharCode(MC)}\\[[\\d;]*m`,"g"),FC=9,GC=10,HC=31,UC=127,KC=159,BC=16,VC=4;function Kn(t,{json:e}){if(Pf(),qC(t),e)wn(Hn({error:WC(t)}));return Df(t)}function WC(t){let e=Df(t),n=xu(oa(t));if(!(t instanceof Error))return{_tag:LC,message:n,exitCode:e,causes:[]};let r=sa(t);return{_tag:JC(t),message:n,hint:r===void 0?void 0:xu(r),exitCode:e,causes:ra(t).map((o)=>xu(o.message))}}function Df(t){if(t instanceof vt)return zt;if(t instanceof m)return Ii(t.exitCode)?t.exitCode:ss;return ss}function JC(t){let e=Reflect.get(t,"_tag");return typeof e==="string"?e:ia(t.name)}function qC(t){if(t instanceof vt)return;let e=Ki(),n=aa(oa(t));if(t instanceof m){let r=sa(t);if(bt.warn(w.yellow(n),{output:e}),r)bt.info(w.dim(aa(r)),{output:e})}else bt.error(w.red(n),{output:e});if(!(t instanceof Error))return;for(let r of ra(t))if(bt.info(w.dim(`caused by: ${aa(r.message)}`),{output:e}),r.hint)bt.info(w.dim(` ${aa(r.hint)}`),{output:e})}function aa(t){return Array.from(t.replace(jC,""),(e)=>{let n=e.charCodeAt(0);return n<=HC&&n!==FC&&n!==GC||n>=UC&&n<=KC?`\\u${n.toString(BC).padStart(VC,"0")}`:e}).join("")}var YC=500,XC="The command stopped before it finished because nothing was left for it to wait for";function Lf({json:t}){let e={ending:void 0,failed:!1,settled:!1},n=(o,s)=>(e.ending??=zC(o,s),e.ending),r=(o)=>{if(e.failed||e.ending)return;e.failed=!0;let s=Kn(o,{json:t&&!Km()});Bm(),n(s,e.settled?void 0:YC)};return process.on("uncaughtException",r),process.on("unhandledRejection",r),process.on("beforeExit",()=>{if(!e.settled)r(Error(XC))}),{exit:(o)=>n(o),settle(){e.settled=!0}}}async function zC(t,e){process.exitCode=t,await Jm(e),process.exit(t)}var vn=new Uint32Array(65536),ZC=(t,e)=>{let n=t.length,r=e.length,o=1<<n-1,s=-1,i=0,a=n,c=n;while(c--)vn[t.charCodeAt(c)]|=1<<c;for(c=0;c<r;c++){let l=vn[e.charCodeAt(c)],u=l|i;if(l|=(l&s)+s^s,i|=~(l|s),s&=l,i&o)a++;if(s&o)a--;i=i<<1|1,s=s<<1|~(u|i),i&=u}c=n;while(c--)vn[t.charCodeAt(c)]=0;return a},QC=(t,e)=>{let n=e.length,r=t.length,o=[],s=[],i=Math.ceil(n/32),a=Math.ceil(r/32);for(let f=0;f<i;f++)s[f]=-1,o[f]=0;let c=0;for(;c<a-1;c++){let f=0,y=-1,S=c*32,I=Math.min(32,r)+S;for(let C=S;C<I;C++)vn[t.charCodeAt(C)]|=1<<C;for(let C=0;C<n;C++){let q=vn[e.charCodeAt(C)],G=s[C/32|0]>>>C&1,N=o[C/32|0]>>>C&1,H=q|f,A=((q|N)&y)+y^y|q|N,R=f|~(A|y),B=y&A;if(R>>>31^G)s[C/32|0]^=1<<C;if(B>>>31^N)o[C/32|0]^=1<<C;R=R<<1|G,B=B<<1|N,y=B|~(H|R),f=R&H}for(let C=S;C<I;C++)vn[t.charCodeAt(C)]=0}let l=0,u=-1,d=c*32,p=Math.min(32,r-d)+d;for(let f=d;f<p;f++)vn[t.charCodeAt(f)]|=1<<f;let g=r;for(let f=0;f<n;f++){let y=vn[e.charCodeAt(f)],S=s[f/32|0]>>>f&1,I=o[f/32|0]>>>f&1,C=y|l,q=((y|I)&u)+u^u|y|I,G=l|~(q|u),N=u&q;if(g+=G>>>r-1&1,g-=N>>>r-1&1,G>>>31^S)s[f/32|0]^=1<<f;if(N>>>31^I)o[f/32|0]^=1<<f;G=G<<1|S,N=N<<1|I,u=N|~(C|G),l=G&C}for(let f=d;f<p;f++)vn[t.charCodeAt(f)]=0;return g},Au=(t,e)=>{if(t.length<e.length){let n=e;e=t,t=n}if(e.length===0)return t.length;if(t.length<=32)return ZC(t,e);return QC(t,e)},Mf=(t,e)=>{let n=1/0,r=0;for(let o=0;o<e.length;o++){let s=Au(t,e[o]);if(s<n)n=s,r=o}return e[r]};function ca(t,e,n){let r=e.length>0?Mf(t,[...e]):void 0,o=`Run "${n} --help" for usage.`;return new v(`Unknown command: ${t}`,r?`Did you mean "${r}"? ${o}`:o)}function ks(t,e){if(Array.isArray(e))return[...e];if(!jf(t)||!jf(e))return e;return Object.fromEntries([...Object.entries(t),...Object.entries(e).map(([n,r])=>[n,ks(Object.hasOwn(t,n)?t[n]:void 0,r)])])}function jf(t){if(t===null||typeof t!=="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Ff(t,e){return{name:t.name,bin:t.bin,version:t.version,description:t.description,exitCodes:{...Bi},options:Gf(Se),commands:e.map((n)=>la(n,`${t.bin} ${n.name}`))}}function la(t,e){return{name:t.name,path:e,description:t.description,json:t.json,prompts:t.prompts,passthrough:t.passthrough,positionals:Object.entries(t.positionals).map(([n,r])=>({name:n,required:r.required??!1,variadic:r.variadic??!1,description:r.description??""})),options:Gf(t.args),examples:[...t.examples],commands:t.subcommands.map((n)=>la(n,`${e} ${n.name}`))}}function Gf(t){return Object.entries(t).map(([e,n])=>({name:e,flag:`--${Me(e)}`,...n.alias?{alias:`-${n.alias}`}:{},type:n.type,...n.default===void 0?{}:{default:n.default},...n.displayDefault===void 0?{}:{displayDefault:n.displayDefault},description:n.description??""}))}import{stripVTControlCharacters as Hf}from"util";var tR=2,eR="0.0.0",nR=(t)=>t,V={arg:w.magenta,cmd:w.cyan,default:w.bold,desc:nR,flag:w.green,header:(t)=>w.bold(w.yellow(t)),hint:w.dim,name:(t)=>w.bold(w.cyan(t)),placeholder:w.magenta};function Uf(t){return`${V.name(t.name)} ${V.hint(t.version??eR)}`}function Kf(t,e){let n=`${V.name(t.name)}${t.version?` ${V.hint(`v${t.version}`)}`:""}`;return Vf([[n,...t.description?[V.desc(t.description)]:[]],Qe("Usage:",[` ${V.cmd(t.bin)} ${V.placeholder("[command]")} ${V.placeholder("[options]")}`]),Qe("Commands:",Wf(e)),Qe("Options:",qf(Se)),Qe("Exit codes:",Jf()),[`${V.hint("Run")} ${V.cmd(`${t.bin} <command> --help`)} ${V.hint("for command details.")}`]])}function Bf(t,e){let n=t.json?{...t.args,json:Se.json}:t.args,r=[...t.subcommands.length>0?[` ${V.cmd(e)} ${V.placeholder("<command>")} ${V.placeholder("[options]")}`]:[],...t.run?[` ${rR(t,e).join(" ")}`]:[],...t.prompts&&Object.keys(t.positionals).length>0?[` ${V.hint("Omit positional arguments to run interactively.")}`]:[],...t.passthrough?[` ${V.hint("Options end at the first argument; it and everything after it are passed on unchanged.")}`]:[]];return Vf([[V.name(e),V.desc(t.description)],Qe("Usage:",r),Qe("Commands:",Wf(t.subcommands)),Qe("Arguments:",sR(t.positionals)),Qe("Options:",qf(n)),Qe("Examples:",t.examples.map((o)=>` ${V.cmd(o)}`)),Qe("Exit codes:",Jf())])}function rR(t,e){let n=oR(t.positionals);return t.passthrough?[V.cmd(e),V.placeholder("[options]"),V.placeholder("[--]"),...n]:[V.cmd(e),...n,V.placeholder("[options]")]}function Qe(t,e){return e.length>0?[V.header(t),...e]:[]}function Vf(t){return t.filter((e)=>e.length>0).map((e)=>e.join(`
|
|
87
87
|
`)).join(`
|
|
88
88
|
|
|
89
|
-
`)}function
|
|
90
|
-
`:void 0}function
|
|
91
|
-
`}function
|
|
92
|
-
`}function
|
|
93
|
-
`}function
|
|
89
|
+
`)}function Wf(t){return ua(t.map((e)=>[` ${V.cmd(e.name)}`,V.desc(e.description)]))}function Jf(){return ua(Object.entries(Bi).map(([t,e])=>[` ${t}`,e]))}function Cu(t,e){return e.variadic?`${t}...`:t}function oR(t){return Object.entries(t).map(([e,n])=>n.required?V.arg(`<${Cu(e,n)}>`):V.arg(`[${Cu(e,n)}]`))}function sR(t){return ua(Object.entries(t).map(([e,n])=>[` ${V.arg(Cu(e,n))}`,`${V.desc(n.description??"")}${n.required?"":V.hint(" (optional)")}`]))}function qf(t){return ua(Object.entries(t).map(([e,n])=>{let r=n.alias?`${V.flag(`-${n.alias}`)}, `:" ",o=n.type==="boolean"?"":` ${V.placeholder(`<${n.type==="number"?"number":"value"}>`)}`,s=iR(n),i=s===void 0?"":` (default: ${V.default(s)})`;return[` ${r}${V.flag(`--${Me(e)}`)}${o}`,`${V.desc(n.description??"")}${i}`]}))}function iR(t){if(typeof t.displayDefault==="string")return t.displayDefault;if(t.default===void 0)return;if(t.type==="boolean"&&t.default===!1)return;if(t.type==="string")return`"${t.default}"`;return String(t.default)}function ua(t){let e=Math.max(0,...t.map(([n])=>Hf(n).length));return t.map(([n,r])=>`${n}${" ".repeat(e-Hf(n).length+tR)}${r}`)}function da(t){let e=!1;return{emitted:()=>e,json:t,result(n,r){if(e)throw Error("ctx.output.result was called more than once; a command emits one result");let o=aR(t,n,r);if(e=!0,o!==void 0)wn(o)}}}function aR(t,e,n){if(t)return Hn(e);return n?`${n(e)}
|
|
90
|
+
`:void 0}function pa(t,e,n){return{args:e.args,cli:t.info,config:t.config,interactive:e.interactive,json:e.json,output:n,positionals:e.positionals}}async function ga(t,e,n,r){let o=await Wm(n.json,async()=>{let s=await t.run?.(n);return typeof s==="number"?cR(e,s):zt});if(n.json&&!r.emitted())throw Error(`${e} finished in JSON mode without calling ctx.output.result`);return o}function cR(t,e){if(Ii(e))return e;throw Error(`${t} returned ${e}, which is not an exit code from ${zt} to ${xm}`)}var Ru="__exit__",Yf="__run__",lR="Back",uR="Return to previous menu";async function Xf(t,e){if(e)throw new v("Interactive mode cannot be combined with --json","Pass a command and its arguments instead");if(!ps())throw new v("Interactive mode requires a terminal","Pass a command and its arguments to run non-interactively");if(t.interactive.clearOnStart)console.clear();let n=t.info.version?` v${t.info.version}`:"";fr(w.bgCyan(w.black(` ${t.info.name}${n} `)));let r={commands:t.commands,message:t.interactive.promptMessage,path:t.info.bin,root:!0};return await zf(t,new Map,r),ce(t.interactive.goodbyeMessage),zt}async function zf(t,e,n){while(!0){let r=await dR(t,e,n);if(r===void 0)return;if(e.set(n.path,r),r===Yf&&n.owner){await Zf(t,n.owner,n.path);continue}let o=n.commands.find((s)=>s.name===r);if(o)await pR(t,e,o,`${n.path} ${r}`)}}async function dR(t,e,n){let r=n.root?{hint:t.interactive.exitHint,label:t.interactive.exitLabel,value:Ru}:{hint:uR,label:lR,value:Ru};try{let o=await gr({initialValue:e.get(n.path),message:n.message,options:[...n.owner?[{hint:n.owner.description,label:n.owner.name,value:Yf}]:[],...n.commands.map((s)=>({hint:s.description,label:s.name,value:s.name})),r]});return o===Ru?void 0:o}catch(o){if(o instanceof vt)return;throw o}}async function pR(t,e,n,r){if(n.subcommands.length===0)return Zf(t,n,r);return zf(t,e,{commands:n.subcommands,message:`${n.name}:`,path:r,root:!1,...n.run?{owner:n}:{}})}async function Zf(t,e,n){try{await gR(t,e,n)}catch(r){if(r instanceof vt)return;if(!(r instanceof m))throw r;Kn(r,{json:!1})}}async function gR(t,e,n){let{args:r}=us([],e.args),o=Mi([],e.positionals),s=e.prompts?null:ji(o,e.positionals);if(s)throw new v(s,`Run "${n} --help" for usage.`);let i=da(!1),a={args:Di(r,e.args),interactive:e.prompts,json:!1,positionals:o};await ga(e,n,pa(t,a,i),i)}var mR="--",fR=/^(?:--json(?:=true)?|-[^-=]*j[^-=]*(?:=true)?)$/,hR=/^(?:--no-(?:help|json)|(?:--(?:help|json)|-[hj]+)(?:=(?:true|false))?)$/;async function Iu(t,e){try{return await yR(t,e)}catch(n){return{code:Kn(n,{json:_u(e)}),menu:!1}}}function Ou(t,e){let{command:n,restArgs:r}=Ni(e,Se),o=n===void 0||n===dr?void 0:eh(t,n,r);if(!o||o instanceof v||!o.command.passthrough)return{operands:[],options:[...e]};let s=_m(o.tokens,{...o.command.args,...Qr}),i=s<0?[]:o.tokens.slice(s);return{operands:i,options:e.slice(0,e.length-i.length)}}async function yR(t,{options:e,operands:n}){let{command:r,flags:o,restArgs:s}=cu(e,Se,Qr),i=o.json===!0,a={code:zt,menu:!1};if(r===void 0){if(o.interactive&&!o.help&&!o.version)return{code:await Xf(t,i),menu:!0};return wn(o.version&&!o.help?wR(t,i):Qf(t,i)),a}let c=o.interactive?"--interactive":o.version?"--version":void 0;if(c)throw new v(`${c} cannot be combined with a command`,`Run "${t.info.bin} ${c}" on its own.`);if(r===dr)return wn(SR(t,s,i)),a;let l=vR(t,r,s);if(o.help)return wn(Pu(l.command,l.path,i)),a;return{code:await bR(t,l,n,i),menu:!1}}function _u({options:t}){let{before:e,restArgs:n}=Ni(t,Se);return[e,n].some((r)=>kR(r).some((o)=>fR.test(o)))}function kR(t){let e=t.indexOf(mR);return e<0?t:t.slice(0,e)}function wR({info:t},e){return e?Hn({name:t.name,bin:t.bin,version:t.version}):`${Uf(t)}
|
|
91
|
+
`}function Qf(t,e){return e?Hn(Ff(t.info,t.commands)):`${Kf(t.info,t.commands)}
|
|
92
|
+
`}function Pu(t,e,n){return n?Hn(la(t,e)):`${Bf(t,e)}
|
|
93
|
+
`}function SR(t,e,n){let{args:r,rawPositionals:o}=us(e,Qr);if(Pi(r,Qr,`Run "${t.info.bin} ${dr} [command]" for usage.`,e),o.length===0)return Qf(t,n);let{command:s,path:i}=th(t.commands,o,t.info.bin);return Pu(s,i,n)}function th(t,e,n){let[r="",...o]=e,s=t.find((a)=>a.name===r);if(!s)throw ca(r,Nu(t),n);let i=`${n} ${r}`;return o.length===0?{command:s,path:i}:th(s.subcommands,o,i)}function Nu(t){return t.map((e)=>e.name)}function vR(t,e,n){let r=eh(t,e,n);if(r instanceof v)throw r;return r}function eh(t,e,n){let r=t.commands.find((o)=>o.name===e);if(!r)return ca(e,Nu(t.commands),t.info.bin);return nh({command:r,path:`${t.info.bin} ${e}`,tokens:n})}function nh(t){let{command:e,path:n,tokens:r}=t;if(e.subcommands.length===0)return t;let o=r.findIndex((a)=>!hR.test(a)),s=r[o];if(s===void 0||s.startsWith("-"))return t;let i=e.subcommands.find((a)=>a.name===s);if(i)return nh({command:i,path:`${n} ${s}`,tokens:r.toSpliced(o,1)});if(e.run&&Object.keys(e.positionals).length>0)return t;return ca(s,Nu(e.subcommands),n)}async function bR(t,{command:e,path:n,tokens:r},o,s){let i=`Run "${n} --help" for usage.`,a={...e.args,...Qr},c=us(r,a),{args:l}=c,u=[...c.rawPositionals,...o];if(e.strict)Pi(l,a,i,r);if(s&&!e.json)throw new v(`${n} does not support --json`,i);let d=e.strict?Nm(u,e.positionals):void 0;if(d!==void 0)throw new v(`Unexpected argument: ${d}`,i);if(!e.run)return wn(Pu(e,n,s)),zt;let p=Mi(u,e.positionals),g=ji(p,e.positionals);if(g)throw new v(g,i);let f=e.prompts&&u.length===0&&ps()&&!s,y={args:Di(l,e.args),interactive:f,json:s,positionals:p},S=da(s);try{return await ga(e,n,pa(t,y,S),S)}catch(I){return Kn(I,{json:s&&!S.emitted()})}}var ER={clearOnStart:!0,exitHint:"Close the CLI",exitLabel:"Exit",goodbyeMessage:"Goodbye!",promptMessage:"What would you like to do?"};function Du(t){let e=`CLI "${t.name}"`;if(Gi(e,t.commands),t.commands.some((r)=>r.name===dr))throw Error(`${e} cannot define a command named "${dr}": the framework provides it`);let n={commands:t.commands,config:t.config,info:{bin:t.bin??t.name,description:t.description,name:t.name,version:t.version},interactive:{...ER,...t.interactive}};return{async main(r=process.argv.slice(2)){Vm();let o=Ou(n,r),s=Lf({json:_u(o)}),i=await Iu(n,o);if(s.settle(),i.code===zt&&!i.menu)return;await s.exit(i.code)},async run(r=process.argv.slice(2)){return(await Iu(n,Ou(n,r))).code}}}import tn from"fs";import Hu from"path";var hr=(t)=>(t.map=(e)=>hr((n)=>e(t(n))),t.or=(e)=>hr((n)=>{try{return t(n)}catch(r){return e(n)}}),t),ma=()=>"bad banditype"();var rh=()=>hr((t)=>t),oh=(t)=>hr((e)=>t.includes(e)?e:ma()),fa=(t)=>hr((e)=>typeof e===typeof t?e:ma()),X=()=>fa(""),yr=()=>fa(0),ha=()=>fa(!0);var Lu=()=>fa(),Bn=()=>hr((t)=>t===null?t:ma()),ws=(t)=>hr((e)=>e instanceof t?e:ma()),sh=(t)=>ws(Object).map((e)=>{let n={};for(let r in e){let o=t(e[r]);o!==void 0&&(n[r]=o)}return n}),Et=(t)=>ws(Object).map((e)=>{let n={};for(let r in t){let o=t[r](e[r]);o!==void 0&&(n[r]=o)}return n});var no=(t)=>ws(Array).map((e)=>e.map(t));import ro from"fs";var $R=".lock",TR=".break",ih=10,xR=1e4,AR=5000;function ah(t,e){let n=`${t}${$R}`,r=crypto.randomUUID();CR(n,r);try{return e()}finally{ch(n,r)}}function CR(t,e){let n=Date.now()+xR;while(!lh(t,e)){if(Date.now()>n)throw Error(`timed out waiting for ${t}, which another process holds`);if(Mu(t))RR(t,e);else Bun.sleepSync(ih)}}function ch(t,e){if(IR(t)===e)ro.rmSync(t,{force:!0})}function RR(t,e){let n=`${t}${TR}`;if(!lh(n,e)){if(Mu(n))ro.rmSync(n,{force:!0});else Bun.sleepSync(ih);return}try{if(Mu(t))ro.rmSync(t,{force:!0})}finally{ch(n,e)}}function lh(t,e){try{return ro.writeFileSync(t,e,{flag:"wx"}),!0}catch(n){if(uh(n)==="EEXIST")return!1;throw n}}function Mu(t){let e=ro.statSync(t,{throwIfNoEntry:!1})?.mtimeMs;return e!==void 0&&Date.now()-e>AR}function IR(t){try{return ro.readFileSync(t,"utf8")}catch(e){if(uh(e)==="ENOENT")return;throw e}}function uh(t){return t instanceof Error?Reflect.get(t,"code"):void 0}import ju from"fs";import kr from"path";var OR="..",_R=40;function ph(t){let{root:e}=kr.parse(kr.resolve(t)),n=dh(kr.resolve(t)),r=e,o=0;for(let s=n.shift();s!==void 0;s=n.shift()){if(s===OR){r=kr.dirname(ju.realpathSync(r));continue}let i=kr.join(r,s);if(!ju.lstatSync(i,{throwIfNoEntry:!1})?.isSymbolicLink()){r=i;continue}if(o+=1,o>_R)throw Error(`too many symbolic links in ${t}`);let a=ju.readlinkSync(i);if(kr.isAbsolute(a))r=e;n.unshift(...dh(a))}return r}function dh(t){return t.split(kr.sep).filter((e)=>e!==""&&e!==".")}function Gu(t,e){JSON.parse(t);let n=JSON.parse(JSON.stringify(e)),r=PR(t),o=t.match(/^[\t ]+(?=\S)/m)?.[0]??" ",s=t.includes(`\r
|
|
94
94
|
`)?`\r
|
|
95
95
|
`:`
|
|
96
96
|
`,i=/\s/.test(t[r.start+1]??"")||r.entries.some((l)=>/:\s+$/.test(t.slice(l.start,l.node.start)))?" ":"";function a(l,u){let d=t.slice(l.start,l.end);if(JSON.stringify(l.value)===JSON.stringify(u))return d;let p=Array.isArray(u);if(u===null||typeof u!=="object"||l.value===null||typeof l.value!=="object"||Array.isArray(l.value)!==p)return c(u,l.start,d.includes(`
|
|
97
|
-
`));let g=p?u.map((
|
|
98
|
-
`));let
|
|
99
|
-
`)?
|
|
100
|
-
`))});return`${p?"[":"{"}${
|
|
97
|
+
`));let g=p?u.map((R,B)=>String(B)):[...new Set([...l.entries.map((R)=>R.key).filter((R)=>Object.hasOwn(u,R)),...Object.keys(u)])];if(g.length===0)return p?"[]":"{}";let f=l.entries[0],y=l.entries.at(-1);if(!f||!y)return c(u,l.start,d.includes(`
|
|
98
|
+
`));let S=(R)=>p?u[Number(R)]:u[R];if(g.length===l.entries.length&&g.every((R,B)=>R===l.entries[B]?.key)){let R=l.start,B="";for(let _t of l.entries)B+=t.slice(R,_t.node.start)+a(_t.node,S(_t.key)),R=_t.node.end;return B+t.slice(R,l.end)}let I=t.slice(l.start+1,f.start),C=t.slice(y.node.end,l.end-1),q=l.entries[1],G=q?t.slice(f.node.end,q.start):`,${I.includes(`
|
|
99
|
+
`)?I:i}`,N=p?"":t.slice(f.start,f.node.start).match(/:\s*$/)?.[0]??": ",H=new Map(l.entries.map((R)=>[R.key,R])),A=g.map((R)=>{let B=H.get(R);if(B)return t.slice(B.start,B.node.start)+a(B.node,S(R));return(p?"":JSON.stringify(R)+N)+c(S(R),f.start,I.includes(`
|
|
100
|
+
`))});return`${p?"[":"{"}${I}${A.join(G)}${C}${p?"]":"}"}`}function c(l,u,d){if(!d)return Fu(l,i);let p=t.lastIndexOf(`
|
|
101
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
|
|
103
|
-
`;if(
|
|
104
|
-
`)}var
|
|
105
|
-
|
|
106
|
-
`)
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
`)
|
|
111
|
-
`)
|
|
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}
|
|
102
|
+
`,s+g)}return t.slice(0,r.start)+a(r,n)+t.slice(r.end)}function Fu(t,e){if(Array.isArray(t))return`[${t.map((o)=>Fu(o,e)).join(`,${e}`)}]`;if(t===null||typeof t!=="object")return JSON.stringify(t);let n=Object.entries(t);if(n.length===0)return"{}";let r=n.map(([o,s])=>`${JSON.stringify(o)}:${e}${Fu(s,e)}`);return`{${e}${r.join(`,${e}`)}${e}}`}function PR(t){let e=t.matchAll(/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g),n=e.next().value;function r(){if(!n)throw Error("Unexpected end of JSON");let s=n;return n=e.next().value,s}function o(){let s=r(),i=[],a=s[0]==="{";if(!a&&s[0]!=="[")return{end:s.index+s[0].length,entries:i,start:s.index,value:JSON.parse(s[0])};let c=a?"}":"]";while(n&&n[0]!==c){let u=n.index,d=a?JSON.parse(r()[0]):String(i.length);if(a)r();if(i.push({key:d,node:o(),start:u}),n?.[0]===",")r()}let l=r().index+1;return{end:l,entries:i,start:s.index,value:JSON.parse(t.slice(s.index,l))}}return o()}var NR=2,Uu="ConfigError",DR=ws(Object);class Ku{loaded;configPath;defaultConfig;options;constructor(t,e,n={}){this.configPath=Hu.resolve(t),this.defaultConfig=e,this.options=n}get path(){return this.configPath}get failure(){return this.state().failure}get(t){return this.current()[t]}set(t,e){let n=this.writable();this.update((r)=>({...r,[t]:e})),n.config={...n.config,[t]:e}}delete(t){let e=this.writable();this.update((n)=>(delete n[t],n)),delete e.config[t]}exists(){return tn.existsSync(this.configPath)}getAll(){return structuredClone(this.current())}save(t){let e=this.writable();if(t)e.config={...t};this.update(()=>e.config)}state(){return this.loaded??=this.load(),this.loaded}current(){let{config:t,failure:e}=this.state();if(e)throw e;return t}writable(){let t=this.state();if(t.failure)throw t.failure;if(t.error)throw this.unreadable(t.error);return t}unreadable(t){return new m(`Cannot overwrite unreadable config at ${this.configPath}`,"Repair the file and try again",void 0,{cause:t,tag:Uu})}readStored(){try{let t=this.readConfigFile();if(t===void 0)return structuredClone(this.defaultConfig);return ks(structuredClone(this.defaultConfig),gh(t))}catch(t){throw this.unreadable(t)}}update(t){try{let e=this.savePath();ah(e,()=>this.write(e,t(this.readStored())))}catch(e){throw e instanceof m?e:this.saveFailure(e)}}savePath(){let t=this.exists()?tn.realpathSync(this.configPath):ph(this.configPath);return tn.mkdirSync(Hu.dirname(t),{recursive:!0}),t}write(t,e){let n=`${t}.${crypto.randomUUID()}.tmp`;try{let r=this.exists()?tn.statSync(this.configPath).mode:void 0,o=this.exists()?Gu(tn.readFileSync(this.configPath,"utf-8"),e):`${JSON.stringify(e,null,NR)}
|
|
103
|
+
`;if(tn.writeFileSync(n,o,{flag:"wx",mode:r}),r!==void 0)tn.chmodSync(n,r);tn.renameSync(n,t)}finally{tn.rmSync(n,{force:!0})}}saveFailure(t){return new m(`Cannot save config at ${this.configPath}: ${mh(t)}`,`Check that ${Hu.dirname(this.configPath)} is writable and that no other process is saving the file`,void 0,{cause:t,tag:Uu})}load(){let{parse:t,strict:e}=this.options;try{let n=this.readConfigFile();if(n===void 0)return{config:structuredClone(this.defaultConfig)};let r=ks(structuredClone(this.defaultConfig),gh(n));return{config:t?t(r):r}}catch(n){if(e)return{config:structuredClone(this.defaultConfig),failure:this.loadFailure(n)};return bt.warn(w.yellow(`Config file corrupted at ${this.configPath}. Using defaults.`),{output:Ki()}),{config:structuredClone(this.defaultConfig),error:n}}}loadFailure(t){return new m(`Cannot read config at ${this.configPath}: ${mh(t)}`,"Repair the file and try again",void 0,{cause:t,tag:Uu})}readConfigFile(){try{return tn.readFileSync(this.configPath,"utf-8")}catch(t){if(t.code==="ENOENT")return;throw t}}}function gh(t){let e=JSON.parse(t);if(Array.isArray(e))throw Error("Config must be an object");return DR(e)}function mh(t){return t instanceof Error?t.message:String(t)}var ya="0.5.0";var E=Fi();var fh=new Map;function et(t,e){return e.some((n)=>jR(n).match(t))}function Bu(t){if(t.trim().length===0)return"is empty";if(t!==t.trim())return"has leading or trailing white space";if(t.includes("\x00"))return"contains a NUL character";if(t.startsWith("!"))return"must not be negated with a leading !";if(t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t))return"must be relative to the repository root";if(t.startsWith("./"))return"must not start with ./";if(t.split("/").includes(".."))return"must not contain a .. segment";return MR(t)}function wr(t){let e=Bu(t);if(e!==null)return e;if(t.endsWith("/"))return"ends with /, so it matches no file; use a pattern such as dir/**";return t.split("/").includes("")?"has an empty path segment, so it matches no file":null}function MR(t){let e=0,n=!1;for(let r=0;r<t.length;r++){let o=t[r];if(o==="\\"){if(r===t.length-1)return"ends with a lone backslash";r++;continue}if(n){n=o!=="]";continue}if(o==="[")n=!0;if(o==="{")e++;if(o==="}"){if(e===0)return"has an unmatched }";e--}}if(n)return"has an unclosed [";return e>0?"has an unclosed {":null}function jR(t){let e=fh.get(t);if(e)return e;let n=new Bun.Glob(t);return fh.set(t,n),n}class b extends Error{_tag="ValidationError"}var FR=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,GR=/^[A-Za-z_$][A-Za-z0-9_$]*$/,HR="must be lower-case letters and digits separated by single hyphens",UR=new Set(Object.getOwnPropertyNames(Object.prototype)),KR=X(),BR=ha(),ka=yr(),VR=no(rh()),WR=X().or(Bn());function At(t,e,n){try{return n()}catch(r){if(r instanceof b)throw new m(`Invalid ${t}: ${r.message}`,e);throw r}}function k(t,e){if(typeof e==="number")return`${t}[${e}]`;if(!GR.test(e))return`${t}[${JSON.stringify(e)}]`;return t.length===0?e:`${t}.${e}`}function T(t,e,n){let r=kh(t,e),o=Object.keys(r).find((s)=>!n.includes(s));if(o!==void 0)throw new b(`${e} has unknown key ${JSON.stringify(o)}; expected ${n.join(", ")}`);return r}function bn(t,e,n){return Object.entries(kh(t,e)).map(([r,o])=>{if(UR.has(r))throw new b(`${k(e,r)} uses a reserved name`);return[r,n(o,k(e,r),r)]})}function D(t,e,n){return t===void 0?e:n(t)}function lt(t,e,n){return t===void 0||t===null?e:n(t)}function ft(t,e,n){if(t===void 0||t===null)throw new b(`${e} is required`);return n(t,e)}function x(t,e){return En(KR,t,e,"must be a string")}function nt(t,e){let n=x(t,e);if(n.trim().length===0)throw new b(`${e} must not be empty`);return n}function Ct(t,e){return En(WR,t,e,"must be a string or null")}function je(t,e){let n=x(t,e);if(!FR.test(n))throw new b(`${e} ${HR}, got ${JSON.stringify(n)}`);return n}function $t(t,e){return En(BR,t,e,"must be true or false")}function Kt(t,e){let n=En(ka,t,e,"must be a positive integer");if(!Number.isInteger(n)||n<=0)throw new b(`${e} must be a positive integer`);return n}function ht(t,e){let n=En(ka,t,e,"must be a non-negative integer");if(!Number.isInteger(n)||n<0)throw new b(`${e} must be a non-negative integer`);return n}function Vn(t,e){let n=En(ka,t,e,"must be a positive number");if(!Number.isFinite(n)||n<=0)throw new b(`${e} must be a positive number`);return n}function Vu(t,e){let n=En(ka,t,e,"must be a number greater than 0 and at most 1");if(!(n>0&&n<=1))throw new b(`${e} must be a number greater than 0 and at most 1`);return n}function K(t,e,n){return En(oh(t),e,n,`must be one of ${t.join(", ")}`)}function L(t,e,n){return En(VR,t,e,"must be a list").map((o,s)=>n(o,k(e,s)))}function Dt(t,e){return L(t,e,x)}function wa(t,e){return L(t,e,(n,r)=>yh(n,r,Bu))}function hh(t,e){return L(t,e,(n,r)=>yh(n,r,wr))}function yh(t,e,n){let r=x(t,e),o=n(r);if(o!==null)throw new b(`${e} ${o}`);return r}function kh(t,e){if(typeof t!=="object"||t===null||Array.isArray(t))throw new b(`${e} must be an object`);return t}function En(t,e,n,r){try{return t(e)}catch{throw new b(`${n} ${r}`)}}var JR=["task","review"],Wu=["task"],Zt="{prompt}",vs="{model}",qR=["command","reviewCommand","model","modelFlag","env","inheritEnv","timeoutSeconds","roles"],YR=["default","stages","review"],XR=["agent","model"],zR=/^[A-Za-z_][A-Za-z0-9_]*$/,ZR=":",QR="-",Sa={default:null,review:null,stages:{}};function Sr(t){return t.roles??Wu}function Sh(t){let e=bn(t,"agents",tI);for(let[n]of e)je(n,"agent name");return Object.fromEntries(e)}function tI(t,e){let n=T(t,e,qR),r={command:wh(n.command,k(e,"command"))};if(n.reviewCommand!==void 0)r.reviewCommand=wh(n.reviewCommand,k(e,"reviewCommand"));if(n.model!==void 0)r.model=nt(n.model,k(e,"model"));if(n.modelFlag!==void 0)r.modelFlag=rI(n.modelFlag,k(e,"modelFlag"));if(n.env!==void 0)r.env=oI(n.env,k(e,"env"));if(n.inheritEnv!==void 0)r.inheritEnv=$t(n.inheritEnv,k(e,"inheritEnv"));if(r.inheritEnv===!0&&r.env!==void 0){let[o,s]=[k(e,"inheritEnv"),k(e,"env")];throw new b(`${o} and ${s} are alternatives; set only one of them`)}if(n.timeoutSeconds!==void 0)r.timeoutSeconds=Vn(n.timeoutSeconds,k(e,"timeoutSeconds"));if(n.roles!==void 0)r.roles=sI(n.roles,k(e,"roles"));return r}function vh(t){let e=T(t,"routing",YR);return{default:D(e.default,Sa.default,(n)=>Ss(n,"routing.default")),review:D(e.review,Sa.review,(n)=>Ss(n,"routing.review")),stages:Object.fromEntries(D(e.stages,[],(n)=>bn(n,"routing.stages",eI)))}}function Ss(t,e){if(t===null)return null;if(typeof t==="string")return nI(t,e);let n=T(t,e,XR),r=je(n.agent,k(e,"agent")),o=D(n.model,null,(s)=>nt(s,k(e,"model")));return{agent:r,model:o}}function eI(t,e){let n=Ss(t,e);if(n!==null)return n;throw new b(`${e} must name an agent; leave the stage out to use routing.default`)}function nI(t,e){let n=t.indexOf(ZR);if(n===-1)return{agent:je(t,e),model:null};let r=je(t.slice(0,n),`${e} (agent)`),o=nt(t.slice(n+1),`${e} (model)`);return{agent:r,model:o}}function bh(t){let{agents:e,review:n,routing:r}=t,o=[["routing.default",r.default,"task"],...Object.entries(r.stages).map(([s,i])=>[k("routing.stages",s),i,"task"]),["routing.review",r.review,"review"],["review.agent",n.agent===void 0?null:{agent:n.agent,model:null},"review"]];for(let[s,i,a]of o){if(i===null)continue;let c=e[i.agent];if(c===void 0)throw new b(`${s} names agent "${i.agent}", which agents does not define`);if(!Sr(c).includes(a))throw new b(`${s} names agent "${i.agent}", whose roles do not include "${a}"; add it to agents.${i.agent}.roles`)}}function wh(t,e){let n=L(t,e,nt);if(n.length===0)throw new b(`${e} must not be empty`);return n}function rI(t,e){let n=x(t,e);if(n.startsWith(QR)&&n.trim()===n&&n.length>1)return n;throw new b(`${e} must be an option such as "--model"`)}function oI(t,e){let n=L(t,e,(r,o)=>{let s=x(r,o);if(zR.test(s))return s;throw new b(`${o} must be an environment variable name, not a value`)});return Eh(n,e)}function sI(t,e){let n=Eh(L(t,e,(r,o)=>K(JR,r,o)),e);if(n.length===0)throw new b(`${e} must name at least one role`);return n}function Eh(t,e){let n=t.find((r,o)=>t.indexOf(r)!==o);if(n!==void 0)throw new b(`${e} repeats ${JSON.stringify(n)}`);return t}var iI=["GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_PREFIX","GIT_WORK_TREE"],Fe=Object.fromEntries(iI.map((t)=>[t,void 0]));var Ah={SIGHUP:129,SIGINT:130,SIGTERM:143},$h=Object.keys(Ah),Th={SIGHUP:()=>Ju("SIGHUP"),SIGINT:()=>Ju("SIGINT"),SIGTERM:()=>Ju("SIGTERM")},oo=[],qu={interrupted:!1};function Qt(t){if(oo.length===0)for(let e of $h)process.on(e,Th[e]);return oo.push(t),()=>{let e=oo.indexOf(t);if(e===-1)return;if(oo.splice(e,1),oo.length===0)for(let n of $h)process.off(n,Th[n])}}function Ch(){return qu.interrupted}function Ju(t){if(qu.interrupted)return;qu.interrupted=!0;let e=Ah[t],n=oo.toReversed().flatMap((r)=>aI(r)??[]);if(n.length===0)process.exit(e);Promise.all(n).finally(()=>process.exit(e))}function aI(t){try{let e=t();return e instanceof Promise?e.catch(xh):null}catch(e){return xh(e),null}}function xh(t){let e=t instanceof Error?t.message:String(t);process.stderr.write(`ari could not clean up after an interrupt: ${e}
|
|
104
|
+
`)}var cI=["ESRCH","EPERM"];function Ge(t,e){try{process.kill(-t,e)}catch(n){if(!cI.includes(n.code))throw n}}import{randomUUID as lI}from"crypto";import{existsSync as uI,mkdirSync as dI,readFileSync as pI,realpathSync as gI,renameSync as mI,rmSync as Rh,writeFileSync as fI}from"fs";import{homedir as hI}from"os";import{join as Ih}from"path";function Z(t){return new Bun.CryptoHasher("sha256").update(t).digest("hex")}var yI=".ari",kI="trust",wI=".json",SI=384,vI=Et({root:X(),sha256:X(),trustedAt:X()});function Oh(){let t=process.env.HOME;return Ih(t===void 0||t===""?hI():t,yI,kI)}function bs(t){try{return gI(t)}catch{return t}}function _h(t){let e=bs(t);try{let n=vI(JSON.parse(pI(Yu(e),"utf8")));return n.root===e?n:null}catch{return null}}function Ph(t,e,n=new Date){let r=bs(t),o={root:r,sha256:e,trustedAt:n.toISOString()},s=Yu(r),i=`${s}.${process.pid}.${lI()}.tmp`;dI(Oh(),{recursive:!0});try{fI(i,`${JSON.stringify(o,null,2)}
|
|
105
|
+
`,{mode:SI}),mI(i,s)}finally{Rh(i,{force:!0})}return o}function Nh(t){let e=Yu(bs(t));if(!uI(e))return!1;return Rh(e,{force:!0}),!0}function Yu(t){return Ih(Oh(),`${Z(t)}${wI}`)}import{existsSync as cN}from"fs";import{join as lN}from"path";function O(t,e){if(t<e)return-1;if(t>e)return 1;return 0}var bI=2;function pt(t){return`${JSON.stringify(t,EI,bI)}
|
|
106
|
+
`}function EI(t,e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;return Object.fromEntries(Object.entries(e).sort(([n],[r])=>O(n,r)))}var $I=["cached","run"],Dh="TYPESAFE_API_URL",TI=["TYPESAFE_API_KEY","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_TOKEN","CLOUDFLARE_AUTH_TOKEN"],xI=["argus"],AI="cached",CI=25,RI=6000,II=1000,OI=20000,_I=["config","command","mode","limit","maxBytes","timeoutSeconds","verdicts"];function Mh(t){let e=T(t,"review.argus",_I),n=D(e.timeoutSeconds,null,(o)=>Vn(o,"review.argus.timeoutSeconds")),r=D(e.verdicts,!1,(o)=>$t(o,"review.argus.verdicts"));return{command:D(e.command,[...xI],NI),config:ft(e.config,"review.argus.config",nt),limit:D(e.limit,CI,(o)=>Lh(o,"limit",II)),maxBytes:D(e.maxBytes,RI,(o)=>Lh(o,"maxBytes",OI)),mode:D(e.mode,AI,(o)=>K($I,o,"review.argus.mode")),...n===null?{}:{timeoutSeconds:n},...r?{verdicts:r}:{}}}function PI(t){return t==="run"?[Dh,...TI]:[Dh]}function va(t){let e=t.mode==="run";if(t.verdicts!==!0)return[e?"run":"check"];return e?["run","snapshot","import"]:["snapshot","import"]}function ba(t){return PI(t==="run"?"run":"cached")}function so(t,e,n){let{base:r,configPath:o,file:s,only:i}=n,a=["--config",o,"--base",r],c=i===null?[]:["--only",i],l=t.command;switch(e){case"check":return[...l,"check",...a,"--json"];case"run":return[...l,"run",...a,"--limit",String(t.limit),...c,"--json"];case"snapshot":return[...l,"report","create",...a,...c,"--json"];case"import":return[...l,"verify","--import",s??"",...a,"--json"]}}function NI(t){let e=L(t,"review.argus.command",nt);if(e.length===0)throw new b("review.argus.command must list at least the program to start");return e}function Lh(t,e,n){let r=`review.argus.${e}`,o=Kt(t,r);if(o>n)throw new b(`${r} must be at most ${n}`);return o}import{randomUUID as BP}from"crypto";import{appendFileSync as VP,existsSync as Cn,linkSync as WP,mkdirSync as Ly,readdirSync as JP,readFileSync as Rs,renameSync as My,rmSync as Ua,writeFileSync as jy}from"fs";import{basename as qP,dirname as Fy,join as Rt}from"path";function Es(t){if(typeof t!=="object"||t===null||Object.isFrozen(t))return t;for(let e of Object.values(t))Es(e);return Object.freeze(t)}var DI="basic",LI=300,MI=6000,jI=20,FI=2000,GI=!0,HI=1200,UI=60000,KI=25,BI=0.95,VI=0.75,WI=10,JI=!1,qI=!0,YI=25,XI=["**/*.test.*","**/*.spec.*","**/*_test.*","**/*-test.{js,cjs,mjs,ts,cts,mts}","**/test-*.{js,cjs,mjs,ts,cts,mts}","**/test.{js,cjs,mjs,ts,cts,mts}","**/test_*.py","**/test/**","**/tests/**","**/__tests__/**"],zI="Fix the reported value in .ari/config.json",ZI=["$schema","pack","requireTask","checkTimeoutSeconds","testGlobs","regression","review","context","knowledge","snapshots","hooks","agents","routing"],QI=["maxEntryBytes","maxBytes","decayAfterTasks","duplicateSimilarity","mergeSimilarity","rehearsalTasks","sleepOnStop"],Tt=Es({agents:{},checkTimeoutSeconds:LI,context:{briefBytes:FI,budget:MI,journalTail:jI},hooks:{brief:GI},knowledge:{decayAfterTasks:KI,duplicateSimilarity:BI,maxBytes:UI,maxEntryBytes:HI,mergeSimilarity:VI,rehearsalTasks:WI,sleepOnStop:JI},pack:DI,regression:{setup:[]},requireTask:!1,review:{command:null},routing:Sa,snapshots:{auto:qI,keep:YI},testGlobs:XI});function vr(t){return structuredClone(At("config",zI,()=>jh(t)))}function Ea(t){try{return jh(t),null}catch(e){if(e instanceof b)return e.message;throw e}}function jh(t){let e=T(t,"config",ZI);if(e.$schema!==void 0)x(e.$schema,"$schema");let n={agents:D(e.agents,Tt.agents,Sh),checkTimeoutSeconds:D(e.checkTimeoutSeconds,Tt.checkTimeoutSeconds,(r)=>Vn(r,"checkTimeoutSeconds")),context:D(e.context,Tt.context,tO),hooks:D(e.hooks,Tt.hooks,eO),knowledge:D(e.knowledge,Tt.knowledge,nO),pack:D(e.pack,Tt.pack,(r)=>je(r,"pack")),regression:D(e.regression,Tt.regression,oO),requireTask:D(e.requireTask,Tt.requireTask,(r)=>$t(r,"requireTask")),review:D(e.review,Tt.review,sO),routing:D(e.routing,Tt.routing,vh),snapshots:D(e.snapshots,Tt.snapshots,rO),testGlobs:D(e.testGlobs,Tt.testGlobs,(r)=>hh(r,"testGlobs"))};return bh(n),n}function tO(t){let e=T(t,"context",["budget","journalTail","briefBytes"]),n=Tt.context;return{briefBytes:D(e.briefBytes,n.briefBytes,(r)=>Kt(r,"context.briefBytes")),budget:D(e.budget,n.budget,(r)=>Kt(r,"context.budget")),journalTail:D(e.journalTail,n.journalTail,(r)=>ht(r,"context.journalTail"))}}function eO(t){let e=T(t,"hooks",["brief"]);return{brief:D(e.brief,Tt.hooks.brief,(n)=>$t(n,"hooks.brief"))}}function nO(t){let e=T(t,"knowledge",QI),n={decayAfterTasks:io(e,"decayAfterTasks",Kt),duplicateSimilarity:io(e,"duplicateSimilarity",Vu),maxBytes:io(e,"maxBytes",Kt),maxEntryBytes:io(e,"maxEntryBytes",Kt),mergeSimilarity:io(e,"mergeSimilarity",Vu),rehearsalTasks:io(e,"rehearsalTasks",ht),sleepOnStop:D(e.sleepOnStop,Tt.knowledge.sleepOnStop,(r)=>$t(r,"knowledge.sleepOnStop"))};if(n.mergeSimilarity>n.duplicateSimilarity)throw new b("knowledge.mergeSimilarity must not exceed knowledge.duplicateSimilarity");if(n.maxEntryBytes>n.maxBytes)throw new b("knowledge.maxEntryBytes must not exceed knowledge.maxBytes");return n}function rO(t){let e=T(t,"snapshots",["auto","keep"]),n=Tt.snapshots;return{auto:D(e.auto,n.auto,(r)=>$t(r,"snapshots.auto")),keep:D(e.keep,n.keep,(r)=>Kt(r,"snapshots.keep"))}}function io(t,e,n){return D(t[e],Tt.knowledge[e],(r)=>n(r,`knowledge.${e}`))}function oO(t){let e=T(t,"regression",["setup"]);return{setup:D(e.setup,Tt.regression.setup,(n)=>L(n,"regression.setup",nt))}}function sO(t){let e=T(t,"review",["command","agent","model","argus"]),n=D(e.command,Tt.review.command,(i)=>Ct(i,"review.command"));if(n!==null&&n.trim().length===0)throw new b("review.command must be a command or null");let r=D(e.agent,null,(i)=>i===null?null:je(i,"review.agent")),o=D(e.model,null,(i)=>i===null?null:nt(i,"review.model"));if(n!==null&&r!==null)throw new b("review.command and review.agent are alternatives; set only one of them");if(o!==null&&r===null)throw new b("review.model needs review.agent");let s=e.argus===void 0?null:Mh(e.argus);return{command:n,...r===null?{}:{agent:r},...o===null?{}:{model:o},...s===null?{}:{argus:s}}}var $s='writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys',iO=/"(?:[^"\\]|\\.)*"|'(?:[^']|'')*'/sy,aO=/(?:[^,[\]{}:#\n]|:(?![ \t\n,[\]{}]|$)|(?<![ \t\n])#)+/sy,cO=/(?:[ \t\n]|(?<=[ \t\n])#[^\n]*)+/sy,lO=/[&!*][^\s,[\]{}]*|\?(?=[ \t\n])/sy,uO=/[ \t\n,[\]{}]/;function zu(t){return`defines "${t}" twice`}function Zu(t,e){return $a(iO,t,e)}function Qu(t){return String(Bun.YAML.parse(t))}function Fh(t,e){let n=[],r=e,o=!1;while(r<t.length){let s=pO(t,r,o);if(r+=s.text.length,s.kind==="space")continue;let i=dO(s,n);if(i!==null)return{end:r,problem:i};if(n.length===0)return{end:r,problem:null};o=s.kind==="quoted"||s.kind==="close"}return{end:r,problem:null}}function dO(t,e){let n=e.at(-1),r=n?.keys!=null&&n.inKey;switch(t.kind){case"open":{if(r)return'writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys';let o=t.text==="{"?new Set:null;return e.push({inKey:o!==null,key:null,keys:o}),null}case"close":return e.pop(),r?Xu(n):null;case"comma":{let o=r?Xu(n):null;if(n!==void 0)Object.assign(n,{inKey:n.keys!==null,key:null});return o}case"colon":if(!r)return null;return n.inKey=!1,Xu(n);case"special":return r?'writes a key with a tag, an anchor, an alias, a "?" or a collection; use plain keys':null;case"quoted":case"plain":if(r)n.key=t.kind==="quoted"?Qu(t.text):t.text.trim();return null;case"space":return null}}function Xu(t){let{key:e,keys:n}=t;if(e===null||n===null)return null;if(n.has(e))return zu(e);return n.add(e),null}function pO(t,e,n){let r=t[e]??"";if(r==="{"||r==="[")return{kind:"open",text:r};if(r==="}"||r==="]")return{kind:"close",text:r};if(r===",")return{kind:"comma",text:r};if(r===":"&&(n||uO.test(t[e+1]??" ")))return{kind:"colon",text:r};let o=$a(cO,t,e);if(o!==null)return{kind:"space",text:o};let s=Zu(t,e);if(s!==null)return{kind:"quoted",text:s};let i=$a(lO,t,e);if(i!==null)return{kind:"special",text:i};return{kind:"plain",text:$a(aO,t,e)??r}}function $a(t,e,n){return t.lastIndex=n,t.exec(e)?.[0]??null}var gO=/^(?:---|\.\.\.)(?=[ \t]|$)/,mO=/^( *)((?:-(?: +|$))*)(.*)$/s,Gh=/^(?:[&!][^ \t]*(?:[ \t]+|$))+/,fO=/^#/,hO=/^[{[]/,yO=/^\?(?:[ \t]|$)/,kO=/^\*.*:(?:[ \t]|$)/s,Hh=/^[ \t]*:(?:[ \t]+|$)/,wO=/^([^\s|>%@`"'&*!#,[\]{}](?:(?![ \t]#).)*?)[ \t]*:(?:[ \t]+(.*))?$/s,Uh=-1;function Kh(t){let e=[],n=null,r=0,o=0;for(let s of t.split(`
|
|
107
|
+
`)){let i=o;if(o+=s.length+1,i<r)continue;let a=s.match(gO)?.[0];if(a!==void 0)e.length=0,n=null;let c=a===void 0?s:s.replace(a," ".repeat(a.length)),[,l="",u="",d=""]=c.match(mO)??[];if(n!==null&&l.length>n)continue;if(u===""&&Bh(d))continue;let p=l.length+u.length;EO(e,u===""?p:l.length);let g=SO(d);if(g===$s)return g;if(g!==null){let{keys:I}=$O(e,p);if(I.has(g.name))return zu(g.name);I.add(g.name)}let f=bO(g===null?d:g.value),y=u===""?e.at(-1)?.column??Uh:c.lastIndexOf("-",p-1);if(n=f.kind==="text"?g===null?y:p:null,f.kind!=="flow")continue;let S=Fh(t,i+c.length-f.text.length);if(S.problem!==null)return S.problem;if(r=S.end,g===null&&Hh.test(t.slice(S.end,o).trimEnd()))return $s}return null}function SO(t){if(yO.test(t)||kO.test(t))return $s;let e=t.replace(Gh,""),n=vO(e);return n!==null&&e!==t?$s:n}function vO(t){let e=Zu(t,0);if(e===null){let[,r,o=""]=t.match(wO)??[];return r===void 0?null:{name:r,value:o}}let n=t.slice(e.length).match(Hh)?.[0];return n===void 0?null:{name:Qu(e),value:t.slice(e.length+n.length)}}function bO(t){let e=t.replace(Gh,"");if(Bh(e))return{kind:"block",text:e};return{kind:hO.test(e)?"flow":"text",text:e}}function Bh(t){return t.trim()===""||fO.test(t)}function EO(t,e){while((t.at(-1)?.column??Uh)>e)t.pop()}function $O(t,e){let n=t.at(-1);if(n?.column===e)return n;let r={column:e,keys:new Set};return t.push(r),r}var ao="---",TO=/^\uFEFF+/,xO=/\r\n?/g;function co(t){return t.replace(TO,"").replace(xO,`
|
|
108
|
+
`)}function Ta(t){let e=co(t).split(`
|
|
109
|
+
`);if(e[0]?.trimEnd()!==ao)throw new b(`the file must start with a "${ao}" line that opens the front matter`);let n=e.findIndex((r,o)=>o>0&&r.trimEnd()===ao);if(n===-1)throw new b(`the front matter has no closing "${ao}" line`);return{body:e.slice(n+1).join(`
|
|
110
|
+
`),data:td(e.slice(1,n).join(`
|
|
111
|
+
`),"the front matter")}}function xa(t,e){return`${ao}
|
|
116
112
|
${t.join(`
|
|
117
113
|
`)}
|
|
118
|
-
${
|
|
119
|
-
${e}`}function
|
|
120
|
-
`)}function
|
|
121
|
-
`}function
|
|
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
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
`)
|
|
128
|
-
`
|
|
129
|
-
`)
|
|
130
|
-
|
|
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=`
|
|
114
|
+
${ao}
|
|
115
|
+
${e}`}function en(t){return JSON.stringify(t.toWellFormed())}function lo(t){return`[${t.map(en).join(", ")}]`}function td(t,e){let n=co(t),r=AO(n,e),o=Kh(n);if(o===null)return r;throw new b(`${e} ${o}`)}function AO(t,e){try{return Bun.YAML.parse(t)}catch(n){let r=n instanceof Error?n.message:String(n);throw new b(`${e} is not valid YAML (${r})`)}}var nd=3,Wh="spike",CO=/^[A-Za-z][A-Za-z0-9._-]*$/,RO=["pass","fail","regression"],IO={all:"check",criteria:"check bound to a criterion","expect:fail":"check with expect: fail","expect:pass":"check with expect: pass","expect:regression":"check with expect: regression"},OO=["title","pack","scope","lock","depends","criteria","checks","invariants","budget"],_O="AC-1",PO="Describe the change, its constraints and how a reviewer can verify it.";function Aa(t,e,n){return At(`contract "${t}"`,`Fix the front matter of .ari/tasks/${t}.md`,()=>NO(t,e,n))}function Bt(t){return Z(co(t))}function Jh(t,e){let n=e===Wh?["criteria: []"]:["criteria:",` - id: ${en(_O)}`,' text: ""'," checks: []"],r=[`title: ${en(t)}`,`pack: ${en(e)}`,"scope: []","lock: []","depends: []",...n,"checks: {}","invariants: []","budget:",` attempts: ${nd}`];return xa(r,`${PO}
|
|
116
|
+
`)}function uo(t,e){let n=e.find((o)=>o.name===t.pack),r=[...UO(t),...rd(t)];return[...jO(t),...FO(t,n,e,r.length>0),...Vh("scope",t.scope,!0),...Vh("lock",t.lock,!1),...HO(t),...r,...KO(t),...BO(t)]}function po(t,e){switch(e){case"all":return t.checks;case"criteria":{let n=new Set(t.criteria.flatMap((r)=>r.checks));return t.checks.filter((r)=>n.has(r.name))}case"expect:pass":return ed(t,"pass");case"expect:fail":return ed(t,"fail");case"expect:regression":return ed(t,"regression")}}function ed(t,e){return t.checks.filter((n)=>n.expect===e)}function rd(t){let e=new Set(t.checks.map((n)=>n.name));return t.criteria.flatMap((n)=>{if(n.checks.length===0)return[`criterion ${n.id} must name at least one check`];return n.checks.filter((r)=>!e.has(r)).map((r)=>`criterion ${n.id} names unknown check "${r}"`)})}function NO(t,e,n){let{body:r,data:o}=Ta(e),s=T(o,"front matter",OO);return{body:r.trim(),budget:lt(s.budget,{attempts:nd},DO),checks:lt(s.checks,[],(i)=>MO(i,n.checkTimeoutSeconds)),criteria:lt(s.criteria,[],(i)=>L(i,"criteria",LO)),depends:lt(s.depends,[],(i)=>Dt(i,"depends")),id:t,invariants:lt(s.invariants,[],(i)=>Dt(i,"invariants")),lock:lt(s.lock,[],(i)=>Dt(i,"lock")),pack:lt(s.pack,n.pack,(i)=>x(i,"pack")),scope:ft(s.scope,"scope",Dt),title:ft(s.title,"title",x)}}function DO(t){let e=T(t,"budget",["attempts"]);return{attempts:lt(e.attempts,nd,(n)=>Kt(n,"budget.attempts"))}}function LO(t,e){let n=T(t,e,["id","text","checks"]);return{checks:lt(n.checks,[],(r)=>Dt(r,k(e,"checks"))),id:ft(n.id,k(e,"id"),x),text:ft(n.text,k(e,"text"),x)}}function MO(t,e){return bn(t,"checks",(n,r,o)=>{if(!CO.test(o))throw new b(`${r} must be named with a letter followed by letters, digits, ".", "_" or "-"`);let s=T(n,r,["run","expect","timeout"]);return{expect:lt(s.expect,"pass",(i)=>K(RO,i,k(r,"expect"))),name:o,run:ft(s.run,k(r,"run"),x),timeoutSeconds:lt(s.timeout,e,(i)=>Vn(i,k(r,"timeout")))}}).map(([,n])=>n)}function jO(t){return t.title.trim().length===0?["title must not be empty"]:[]}function FO(t,e,n,r){if(!e){let s=n.map((i)=>i.name).join(", ");return[`pack "${t.pack}" is not a built-in or project pack (available: ${s})`]}return[...new Set(e.stages.flatMap((s)=>s.gates.flatMap(GO)))].filter((s)=>!r||s!=="all"&&s!=="criteria").filter((s)=>po(t,s).length===0).map((s)=>`pack "${e.name}" needs at least one ${IO[s]}`)}function GO(t){if(t.kind==="regression")return["expect:regression"];return t.kind==="checks"?[t.select]:[]}function Vh(t,e,n){let r=n&&e.length===0?[`${t} must list at least one glob`]:[],o=e.flatMap((s)=>{let i=wr(s);return i===null?[]:[`${t} glob ${JSON.stringify(s)} ${i}`]});return[...r,...o]}function HO(t){return t.depends.flatMap((e)=>{if(e.trim().length===0)return["depends must not contain an empty task id"];return e===t.id?[`depends must not name the task itself ("${t.id}")`]:[]})}function UO(t){let n=t.pack!==Wh&&t.criteria.length===0?[`criteria must list at least one criterion for pack "${t.pack}"`]:[],r=t.criteria.map((s)=>s.id),o=t.criteria.flatMap((s,i)=>{if(s.id.trim().length===0)return[`criteria[${i}] must have an id`];let a=r.indexOf(s.id)<i?[`criterion id "${s.id}" is used more than once`]:[],c=s.text.trim().length===0?[`criterion ${s.id} must have text`]:[];return[...a,...c]});return[...n,...o]}function KO(t){return t.checks.filter((e)=>e.run.trim().length===0).map((e)=>`check ${e.name} must have a run command`)}function BO(t){return t.invariants.some((e)=>e.trim().length===0)?["invariants must not contain an empty command"]:[]}var le=["fact","decision","constraint","pattern","gotcha"],VO=["active","archived"],WO=/^\d{4}-\d{2}-\d{2}$/,JO=/\s+/g,qO=["kind","scope","sources","status","supersedes","supersededBy","created"];function Ca(t,e){return At(`knowledge entry "${t}"`,`Restore .ari/knowledge/${t}.md from git`,()=>YO(t,e))}function br(t){let e=[`kind: ${en(t.kind)}`,`scope: ${lo(t.scope)}`,`sources: ${lo(t.sources)}`,`status: ${en(t.status)}`,`supersedes: ${lo(t.supersedes)}`,`supersededBy: ${t.supersededBy===null?"null":en(t.supersededBy)}`,`created: ${en(t.created)}`];return xa(e,`${t.text.trim()}
|
|
117
|
+
`)}function od(t){return t.normalize("NFC").toLowerCase().replace(JO," ").trim()}function YO(t,e){let{body:n,data:r}=Ta(e),o=T(r,"front matter",qO),s=ft(o.created,"created",x);if(!WO.test(s))throw new b(`created must be a YYYY-MM-DD date, got "${s}"`);let i=n.trim();if(i.length===0)throw new b("the entry text is empty");return{created:s,id:t,kind:ft(o.kind,"kind",(a,c)=>K(le,a,c)),scope:lt(o.scope,[],(a)=>wa(a,"scope")),sources:lt(o.sources,[],(a)=>Dt(a,"sources")),status:lt(o.status,"active",(a)=>K(VO,a,"status")),supersededBy:lt(o.supersededBy,null,(a)=>Ct(a,"supersededBy")),supersedes:lt(o.supersedes,[],(a)=>Dt(a,"supersedes")),text:i}}var qh="<!--",Yh="-->",go="`",Xh=2,XO=/^ {0,3}(`{3,}|~{3,})(.*)$/,zO=/^ {0,3}(`{3,}|~{3,})[ \t]*$/,ZO=/^ {0,3}(#{1,6})(?:[ \t]+(.*))?$/,QO=/(?:^|[ \t]+)#+[ \t]*$/,t_=/\s+/g;function nn(t){return t.replace(t_," ").trim().toLowerCase()}function Zh(t){let{unclosedComment:e,visible:n}=o_(co(t).split(`
|
|
118
|
+
`)),r=[],o=null;for(let s of n){let i=s.fenced?null:r_(s.text);if(i!==null&&i.level<=Xh){if(o=i.level===Xh?e_(i.text,s.line):null,o!==null)r.push(o);continue}o?.lines.push(s)}return{sections:r.map(n_),unclosedComment:e}}function e_(t,e){return{lines:[],section:{body:"",heading:t,key:nn(t),line:e,prose:[]}}}function n_({lines:t,section:e}){return{...e,body:t.map((n)=>n.text).join(`
|
|
119
|
+
`),prose:t.filter((n)=>!n.fenced).map((n)=>n.text)}}function r_(t){let e=ZO.exec(t);if(e===null)return null;return{level:(e[1]??"").length,text:(e[2]??"").replace(QO,"").trim()}}function o_(t){let e=[],n=null,r=null;for(let[o,s]of t.entries()){let i=o+1;if(n!==null){e.push({fenced:!0,line:i,text:s}),n=i_(s,n)?null:n;continue}let a=r===null?s_(s):null;if(a!==null){n=a,e.push({fenced:!0,line:i,text:s});continue}let c=a_(s,r!==null);r=c.inside?c.fresh?i:r:null,e.push({fenced:!1,line:i,text:c.text})}return{unclosedComment:r,visible:e}}function s_(t){let e=XO.exec(t),n=e?.[1];if(n===void 0)return null;let r=n.slice(0,1);if(r===go&&(e?.[2]??"").includes(go))return null;return{length:n.length,marker:r}}function i_(t,e){let n=zO.exec(t)?.[1];return n?.startsWith(e.marker)===!0&&n.length>=e.length}function a_(t,e){let n=e,r=!1,o="",s=0;while(s<t.length){if(n){let a=t.indexOf(Yh,s);if(a===-1)return{fresh:r,inside:!0,text:o};n=!1,r=!1,s=a+Yh.length;continue}if(t.startsWith(qh,s)){n=!0,r=!0,s+=qh.length;continue}let i=t[s]===go?c_(t,s):s+1;o+=t.slice(s,i),s=i}return{fresh:r,inside:n,text:o}}function c_(t,e){let n=zh(t,e),r=t.indexOf(go,e+n);while(r!==-1){let o=zh(t,r);if(o===n)return r+o;r=t.indexOf(go,r+o)}return e+n}function zh(t,e){let n=e;while(t[n]===go)n++;return n-e}var sd="TODO(ari): write this section",$n="Acceptance criteria",Ra=["Problem","Context","Options","Decision",$n,"Scope","Risks and open questions"],l_={Context:["What already exists that this design has to respect.","List the knowledge entries you consulted by id, one per line: - <id>: why it matters (find them with ari knowledge search <query>)."],Decision:["The option you chose, and why it beats the others."],Options:["Two or more ways to solve the problem, each with what it costs."],Problem:["What is wrong or missing, for whom, and what happens today."],"Risks and open questions":["What could go wrong and what you could not settle; write None if nothing."],Scope:["The files and areas the change touches and what it leaves alone; keep it inside the contract's scope."],[$n]:["One line per criterion of the contract, written as - AC-1: what must be true.","The ids must be exactly the ids of the contract's criteria."]},u_=["Fill this section."],d_=/\s+/g,p_=/<!--|-->/g,g_=/^[-*+][ \t]+([^\s:]+):(?=\s|$)/;function Qh(t,e=[]){let n=new Set(Ra.map(nn)),r=e.filter((i)=>!n.has(nn(i))),o=[...Ra,...r].map(m_);return`# ${t.replace(p_,"").replace(d_," ").trim()}
|
|
120
|
+
|
|
121
|
+
${o.join(`
|
|
122
|
+
|
|
123
|
+
`)}
|
|
124
|
+
`}function ty(t){let{requirements:e}=t,{sections:n,unclosedComment:r}=Zh(t.text),o=r===null?[]:[`Close the HTML comment that starts at line ${r} of ${t.path} with -->`],s=e.sections.flatMap((a)=>f_(a,n,t.path)),i=e.traceable?h_(n,t):{ids:0,problems:[]};return{filled:e.sections.length-s.length,problems:[...o,...s,...i.problems],traced:i.ids}}function m_(t){let e=(l_[t]??u_).join(`
|
|
125
|
+
`);return`## ${t}
|
|
126
|
+
<!--
|
|
127
|
+
${e}
|
|
128
|
+
-->
|
|
129
|
+
${sd}`}function f_(t,e,n){let r=e.filter((s)=>s.key===nn(t));if(r.length===0)return[`Add the section '${t}' to ${n}`];if(r.length>1)return[`The section '${t}' appears ${r.length} times in ${n}; keep one and merge the rest`];let o=r[0]?.body??"";if(o.includes(sd))return[`Fill the section '${t}' in ${n}: replace the placeholder '${sd}'`];return o.trim().length===0?[`Fill the section '${t}' in ${n}`]:[]}function h_(t,e){let n=nn($n),r=t.filter((g)=>g.key===n).flatMap((g)=>g.prose.flatMap(y_)),{contractPath:o,criteria:s,path:i}=e,a=new Set(s),c=new Set(r),l=s.filter((g)=>!c.has(g)),u=[...c].filter((g)=>!a.has(g)),d=[...c].filter((g)=>r.filter((f)=>f===g).length>1),p=[...l.map((g)=>`Add '- ${g}: <what must be true>' under '${$n}' in ${i}; the contract has ${g}`),...u.map((g)=>`Remove ${g} from '${$n}' in ${i}, or add it to the criteria of ${o}; the contract lacks ${g}`),...d.map((g)=>`Keep one line for ${g} under '${$n}' in ${i}; it appears more than once`)];return{ids:s.length-l.length,problems:p}}function y_(t){let e=g_.exec(t)?.[1];return e===void 0?[]:[e]}var ry=200,k_=".ari/designs/{id}.md",w_=/\{id\}/g,S_=/[\r\n]/,v_="Fix the pack file; see the packs section of the Ariadne design",b_=["all","criteria","expect:pass","expect:fail","expect:regression"],E_=["pass","fail"],$_=["kind","path","minBytes","sections","traceable"],T_="The design in .ari/designs/{id}.md is the work item: fill in every section (list the knowledge entries you consulted by id under Context), make 'Acceptance criteria' list exactly the ids of the contract's criteria, then ask a human to approve it. Do not change code in this stage.",Ts={kind:"criteria"},rn={kind:"invariants"},te={kind:"scope"},He={kind:"locked"},id={kind:"tests-unchanged"},x_={kind:"regression"},ad={kind:"approval"},ey={kind:"review"};function ue(t,e){return{expect:e,kind:"checks",select:t}}function cd(t,e={}){return{kind:"artifact",minBytes:ry,path:t,...e}}var ny=Es([{description:"Implement the contract and prove it with its checks",name:"basic",stages:[{gates:[Ts,ue("criteria","pass"),rn,te,He],instruction:"Implement the change inside the scope until every criterion's checks pass.",name:"implement"}]},{description:"Approved design, implementation, then review",name:"sdlc",stages:[{gates:[cd(".ari/designs/{id}.md"),ad],instruction:"Write the design to .ari/designs/{id}.md, then ask a human to approve it.",name:"design"},{gates:[Ts,ue("all","pass"),rn,te,He],instruction:"Implement the approved design inside the scope until every check passes.",name:"implement"},{gates:[ey,ue("all","pass"),rn,te,He],instruction:"Get the change reviewed: run the review command or ask a human to approve it.",name:"review"}]},{description:"Red, green, refactor with frozen tests",name:"tdd",stages:[{gates:[Ts,ue("criteria","fail"),te],instruction:"Write failing tests for every criterion. Do not implement the change yet.",name:"red"},{gates:[ue("all","pass"),id,rn,te,He],instruction:"Make every check pass with the smallest change. Do not edit the tests.",name:"green"},{gates:[ue("all","pass"),id,rn,te,He],instruction:"Improve the code while every check stays green. Do not edit the tests.",name:"refactor"}]},{description:"Reproduce the bug with a regression check, then fix it",name:"bugfix",stages:[{gates:[ue("expect:regression","fail"),te],instruction:"Write a regression check that fails because of the bug. Do not fix it yet.",name:"reproduce"},{gates:[x_,ue("all","pass"),rn,te,He],instruction:"Fix the bug so the regression check passes here and still fails on the base commit.",name:"fix"}]},{description:"Approved specification, then implementation",name:"spec-driven",stages:[{gates:[Ts,ad],instruction:"Specify the criteria and their checks in the contract, run ari amend, then ask a human to approve.",name:"specify"},{gates:[ue("all","pass"),rn,te,He],instruction:"Implement the approved specification inside the scope until every check passes.",name:"implement"}]},{description:"Change the structure without changing behaviour",name:"refactor",stages:[{gates:[id,ue("all","pass"),rn,te,He],instruction:"Restructure the code without changing behaviour. Keep the tests unchanged and every check green.",name:"refactor"}]},{description:"Exploration that ends in written findings",name:"spike",stages:[{gates:[cd(".ari/designs/{id}.md"),te,He],instruction:"Explore inside the scope and write the findings to .ari/designs/{id}.md.",name:"explore"}]},{description:"Structured design traced to the criteria, approval, implementation, then review",name:"feature",stages:[{gates:[cd(k_,{sections:[...Ra],traceable:!0}),ad,te],instruction:T_,name:"design"},{gates:[Ts,ue("all","pass"),rn,te,He],instruction:"Implement the approved design inside the scope until every check passes.",name:"implement"},{gates:[ey,ue("all","pass"),rn,te,He],instruction:"Get the change reviewed: run the review command or ask a human to approve it.",name:"review"}]}]),oy={approval:(t,e)=>Wn(t,e,"approval"),artifact:__,checks:O_,command:(t,e)=>{let n=T(t,e,["kind","run"]);return{kind:"command",run:nt(n.run,k(e,"run"))}},criteria:(t,e)=>Wn(t,e,"criteria"),invariants:(t,e)=>Wn(t,e,"invariants"),locked:(t,e)=>Wn(t,e,"locked"),regression:(t,e)=>Wn(t,e,"regression"),review:(t,e)=>Wn(t,e,"review"),scope:(t,e)=>Wn(t,e,"scope"),"tests-unchanged":(t,e)=>Wn(t,e,"tests-unchanged")},A_=Object.keys(oy);function Ia(t,e="pack"){return At(e,v_,()=>C_(td(t,"the pack file")))}function Tn(t){let e=new Map(t.map((s)=>[s.name,s])),n=ny.map((s)=>e.get(s.name)??s),r=new Set(ny.map((s)=>s.name)),o=t.filter((s)=>!r.has(s.name)).sort((s,i)=>O(s.name,i.name));return[...n,...o]}function Ue(t,e){let n=Tn(e),r=n.find((s)=>s.name===t);if(r)return r;let o=n.map((s)=>s.name).join(", ");throw new m(`Unknown pack "${t}"`,`Use one of ${o}, or add .ari/packs/${t}.yaml`)}function Oa(t,e){let{agents:n,regression:r,review:o,testGlobs:s}=e,i=t.stages.map(({gates:c,name:l})=>({gates:c,name:l})),a=o.agent===void 0?{}:{reviewer:n[o.agent]??null};return Z(pt({regression:r,review:o,stages:i,testGlobs:s,...a}))}function mo(t,e){return t.instruction.replace(w_,e)}function C_(t){let e=T(t,"pack",["name","description","stages"]),n=L(e.stages,"stages",R_);if(n.length===0)throw new b("stages must list at least one stage");let r=new Set;for(let[o,s]of n.entries()){if(r.has(s.name))throw new b(`stages[${o}].name repeats "${s.name}"`);r.add(s.name)}return{description:lt(e.description,"",(o)=>x(o,"description")),name:je(e.name,"name"),stages:n}}function R_(t,e){let n=T(t,e,["name","instruction","gates"]),r=L(n.gates,k(e,"gates"),I_);if(r.length===0)throw new b(`${k(e,"gates")} must list at least one gate`);let o=new Set(r.map((s)=>s.kind));if(o.has("tests-unchanged")&&!o.has("scope"))throw new b(`${k(e,"gates")} has tests-unchanged without scope; tests-unchanged covers the test files inside the scope and relies on the scope gate for the rest`);return{gates:r,instruction:nt(n.instruction,k(e,"instruction")),name:je(n.name,k(e,"name"))}}function I_(t,e){let n=T(t,e,["kind","select","expect","path","minBytes","sections","traceable","run"]),r=K(A_,n.kind,k(e,"kind"));return oy[r](n,e)}function Wn(t,e,n){return T(t,e,["kind"]),{kind:n}}function O_(t,e){let n=T(t,e,["kind","select","expect"]);return ue(lt(n.select,"all",(r)=>K(b_,r,k(e,"select"))),lt(n.expect,"pass",(r)=>K(E_,r,k(e,"expect"))))}function __(t,e){let n=T(t,e,$_),r=nt(n.path,k(e,"path"));if(r.startsWith("/")||r.split("/").includes(".."))throw new b(`${k(e,"path")} must stay inside the repository`);let s=lt(n.sections,void 0,(a)=>P_(a,k(e,"sections"))),i=lt(n.traceable,!1,(a)=>$t(a,k(e,"traceable")));if(i&&!(s??[]).some((a)=>nn(a)===nn($n)))throw new b(`${k(e,"traceable")} needs "${$n}" in ${k(e,"sections")}`);return{kind:"artifact",minBytes:lt(n.minBytes,ry,(a)=>ht(a,k(e,"minBytes"))),path:r,...s===void 0?{}:{sections:s},...i?{traceable:i}:{}}}function P_(t,e){let n=L(t,e,(o,s)=>{let i=nt(o,s).trim();if(S_.test(i)||i.startsWith("#"))throw new b(`${s} must be the text of a heading on one line, without leading hashes`);return i});if(n.length===0)throw new b(`${e} must list at least one section`);let r=new Set;for(let[o,s]of n.entries()){let i=nn(s);if(r.has(i))throw new b(`${k(e,o)} repeats "${s}"`);r.add(i)}return n}var sy="attempt budget exhausted",iy="failedAttempts",N_={active:()=>"Run 'ari done' to finish the current stage",blocked:(t)=>`Run 'ari resolve ${t} --answer <text>'`,done:()=>`Done tasks are final; create a follow-up with 'ari new "<title>"'`,draft:(t)=>`Complete the contract, then run 'ari ready ${t}'`,ready:(t)=>`Run 'ari start ${t}'`};function on(t,e,n={}){return{at:e,by:n.by??null,detail:n.detail??null,stage:n.stage??null,type:t}}function ld(t,e){return{approvals:[],attempts:0,base:null,contractHash:null,evidence:[],gatesHash:null,history:[on("created",e)],id:t,journalStats:null,knowledgeUsed:[],lastFailure:null,lockHashes:{},notes:[],question:null,stage:0,stageTestHashes:{},status:"draft"}}function cy(t){let e=t.history[0]?.at??"";return pt(t)===pt(ld(t.id,e))}function ud(t,e){return xn(t,["draft"],"mark ready"),{...t,history:[...t.history,on("ready",e)],status:"ready"}}function ly(t,e,n,r){return xn(t,["ready"],"start"),{...t,attempts:0,...ky(n),base:e,history:[...t.history,on("started",r,{detail:e})],stage:0,status:"active"}}function uy(t,e,n,r){if(xn(t,["active"],"record a passed stage for"),!Number.isInteger(n)||t.stage>=n)throw Error(`Stage ${t.stage} of task "${t.id}" is outside a pack of ${n} stages`);let o=t.stage+1>=n,s=on(o?"done":"advanced",e.at,{stage:e.stage});return{...t,evidence:[...t.evidence,e],history:[...t.history,s],lastFailure:null,stage:o?t.stage:t.stage+1,stageTestHashes:{...r},status:o?"done":"active"}}function dy(t,e,n){if(xn(t,["active"],"record a failed attempt for"),!Number.isInteger(n)||n<=0)throw Error(`Attempt budget must be a positive integer: ${n}`);let r=t.attempts+1,o=e.gates.filter((c)=>!c.ok).map((c)=>c.gate),s=on("failed",e.at,{detail:`attempt ${r} of ${n}: ${o.join(", ")||"no failing gate recorded"}`,stage:e.stage}),i=r>=n,a=on("blocked",e.at,{detail:sy,stage:e.stage});return{...t,attempts:r,history:i?[...t.history,s,a]:[...t.history,s],lastFailure:e,question:i?sy:t.question,status:i?"blocked":"active"}}function dd(t,e,n){xn(t,["draft","ready","active","blocked"],"amend");let r=xs(e.reason,"Amending a task needs a reason","Pass --reason <text>"),o=e.base!==null&&e.base!==t.base;if(o)xn(t,["active","blocked"],"move the base of");let s=o?e.base:t.base,i=`gates ${e.gatesHash}, locks ${ay(e.lockHashes)}, tests ${ay(e.stageTestHashes)}`,a=o?`, base ${t.base} -> ${s}`:"",c=`${r} (contract ${e.contractHash}, ${i}${a})`;return{...t,...ky(e),approvals:t.approvals.filter((l)=>l.stage!==e.stage),base:s,history:[...t.history,on("amended",n,{detail:c})]}}function py(t,e,n){xn(t,["active"],"block");let r=xs(e,"Blocking a task needs a question for a human","Pass --reason <text>");return{...t,history:[...t.history,on("blocked",n,{detail:r})],question:r,status:"blocked"}}function pd(t,e,n){xn(t,["blocked"],"resolve");let r=xs(e,"Resolving a task needs an answer","Pass --answer <text>");return{...t,attempts:0,history:[...t.history,on("resolved",n,{detail:r})],notes:[...t.notes,{at:n,promoted:!1,text:r}],question:null,status:"active"}}function gy(t,e,n){xn(t,["active"],"approve");let{artifactHashes:r,stage:o,treeHash:s}=e,i=xs(e.by,"An approval needs the approver's name","Set git user.name so the approval records who gave it");return{...t,approvals:[...t.approvals,{artifactHashes:{...r},at:n,by:i,stage:o,treeHash:s}],history:[...t.history,on("approved",n,{by:i,stage:o})]}}function my(t,e,n){let r=xs(e,"A note needs text","Pass the note text as an argument");return{...t,notes:[...t.notes,{at:n,promoted:!1,text:r}]}}function _a(t,e){let n=new Map(Object.entries(t.journalStats??{}).filter(([o])=>o!==iy));for(let o of e)n.set(o.type,(n.get(o.type)??0)+1);let r=t.history.filter((o)=>o.type==="failed").length;return{...t,journalStats:{...Object.fromEntries(n),[iy]:r}}}function fy(t,e){let n=[...new Set([...t.knowledgeUsed,...e])].sort(O);return{...t,knowledgeUsed:n}}function hy(t,e){let n=`Run 'ari sleep' to list the unpromoted notes of "${t.id}"`;for(let o of e){let s=t.notes[o];if(s===void 0)throw new m(`Task "${t.id}" has no note ${o}`,n);if(s.promoted)throw new m(`Note ${o} of task "${t.id}" is already promoted`,n)}let r=new Set(e);return{...t,notes:t.notes.map((o,s)=>r.has(s)?{...o,promoted:!0}:o)}}function yy(t,e){let n=new Set(e);return{...t,notes:t.notes.map((r,o)=>n.has(o)?{...r,promoted:!1}:r)}}function ky({contractHash:t,gatesHash:e,lockHashes:n,stageTestHashes:r}){return{contractHash:t,gatesHash:e,lockHashes:{...n},stageTestHashes:{...r}}}function ay(t){return Z(pt(t))}function xn(t,e,n){if(e.includes(t.status))return;throw new m(`Cannot ${n} task "${t.id}": it is ${t.status}, not ${e.join(" or ")}`,N_[t.status](t.id))}function xs(t,e,n){let r=t.trim();if(r.length===0)throw new m(e,n);return r}import{mkdirSync as D_,readFileSync as L_,rmSync as Pa,statSync as M_,writeFileSync as j_}from"fs";import{dirname as F_}from"path";var G_="EEXIST",H_="ENOENT",U_="ESRCH",K_=".break",B_=20,V_=1e4,W_=1000,J_=10,q_=0;function md(t,e,n){return As(t,`task "${e}"`,n)}function As(t,e,n){Y_(t,e);try{return n()}finally{Pa(t,{force:!0})}}function Y_(t,e){D_(F_(t),{recursive:!0});let n=Date.now()+V_;while(!wy(t)){if(gd(t))X_(t);if(Date.now()>=n)throw new m(`Another ari process is still changing ${e}`,`Run the command again once it finishes; if no ari process is running, delete ${t}`);Bun.sleepSync(B_)}}function X_(t){let e=`${t}${K_}`;if(!wy(e)){if(gd(e))Pa(e,{force:!0});return}try{if(gd(t))Pa(t,{force:!0})}finally{Pa(e,{force:!0})}}function wy(t){try{return j_(t,`${process.pid}`,{flag:"wx"}),!0}catch(e){if(fd(e)===G_)return!1;throw e}}function gd(t){let e=z_(t);if(e===null)return!1;if(Number.isNaN(e.pid))return Date.now()-e.modifiedMs>W_;return!Z_(e.pid)}function z_(t){try{return{modifiedMs:M_(t).mtimeMs,pid:Number.parseInt(L_(t,"utf8"),J_)}}catch(e){if(fd(e)===H_)return null;throw e}}function Z_(t){try{return process.kill(t,q_),!0}catch(e){return fd(e)!==U_}}function fd(t){return t.code}var hd=["draft","ready","active","blocked","done"],Q_=["pass","fail"],tP=["criteria","checks","invariants","scope","locked","tests-unchanged","regression","artifact","approval","review","command"],eP=["created","ready","started","advanced","done","failed","amended","blocked","resolved","approved"],nP=["edit","shell","tool","check","done","context","note","stop","compact","session"],rP=["approvals","attempts","base","contractHash","evidence","gatesHash","history","id","journalStats","knowledgeUsed","lastFailure","lockHashes","notes","question","stage","stageTestHashes","status"],oP=["command","durationMs","exitCode","expect","name","ok","outputSha256","outputTail","timedOut"];function Sy(t,e){return At(`task record "${t}"`,`Restore .ari/tasks/${t}.json from git; only ari writes it`,()=>{let n=sP(e);if(n.id!==t)throw new b(`id is "${n.id}" but the file belongs to task "${t}"`);return n})}function Da(t){let e=T(t,"event",["at","detail","task","type"]);return{at:x(e.at,"at"),detail:Object.fromEntries(bn(e.detail,"detail",pP)),task:x(e.task,"task"),type:K(nP,e.type,"type")}}function sP(t){let e=T(t,"record",rP);return{approvals:L(e.approvals,"approvals",iP),attempts:ht(e.attempts,"attempts"),base:Ct(e.base,"base"),contractHash:Ct(e.contractHash,"contractHash"),evidence:L(e.evidence,"evidence",cP),gatesHash:D(e.gatesHash,null,(n)=>Ct(n,"gatesHash")),history:L(e.history,"history",aP),id:x(e.id,"id"),journalStats:e.journalStats===null?null:dP(e.journalStats,"journalStats"),knowledgeUsed:Dt(e.knowledgeUsed,"knowledgeUsed"),lastFailure:e.lastFailure===null?null:lP(e.lastFailure,"lastFailure"),lockHashes:Na(e.lockHashes,"lockHashes"),notes:L(e.notes,"notes",yd),question:Ct(e.question,"question"),stage:ht(e.stage,"stage"),stageTestHashes:Na(e.stageTestHashes,"stageTestHashes"),status:K(hd,e.status,"status")}}function iP(t,e){let n=T(t,e,["artifactHashes","at","by","stage","treeHash"]);return{artifactHashes:D(n.artifactHashes,{},(r)=>Na(r,k(e,"artifactHashes"))),at:x(n.at,k(e,"at")),by:x(n.by,k(e,"by")),stage:x(n.stage,k(e,"stage")),treeHash:D(n.treeHash,null,(r)=>Ct(r,k(e,"treeHash")))}}function yd(t,e){let n=T(t,e,["at","promoted","text"]);return{at:x(n.at,k(e,"at")),promoted:$t(n.promoted,k(e,"promoted")),text:x(n.text,k(e,"text"))}}function aP(t,e){let n=T(t,e,["at","by","detail","stage","type"]);return{at:x(n.at,k(e,"at")),by:Ct(n.by,k(e,"by")),detail:Ct(n.detail,k(e,"detail")),stage:Ct(n.stage,k(e,"stage")),type:K(eP,n.type,k(e,"type"))}}function cP(t,e){let n=T(t,e,["at","gates","stage","testHashes","treeHash"]);return{at:x(n.at,k(e,"at")),gates:L(n.gates,k(e,"gates"),vy),stage:x(n.stage,k(e,"stage")),testHashes:Na(n.testHashes,k(e,"testHashes")),treeHash:x(n.treeHash,k(e,"treeHash"))}}function lP(t,e){let n=T(t,e,["at","gates","stage","treeHash"]);return{at:x(n.at,k(e,"at")),gates:L(n.gates,k(e,"gates"),vy),stage:x(n.stage,k(e,"stage")),treeHash:x(n.treeHash,k(e,"treeHash"))}}function vy(t,e){let n=T(t,e,["checks","details","gate","ok","summary"]);return{checks:L(n.checks,k(e,"checks"),uP),details:Dt(n.details,k(e,"details")),gate:K(tP,n.gate,k(e,"gate")),ok:$t(n.ok,k(e,"ok")),summary:x(n.summary,k(e,"summary"))}}function uP(t,e){let n=T(t,e,oP),r=k(e,"exitCode");return{command:x(n.command,k(e,"command")),durationMs:ht(n.durationMs,k(e,"durationMs")),exitCode:n.exitCode===null?null:ht(n.exitCode,r),expect:K(Q_,n.expect,k(e,"expect")),name:x(n.name,k(e,"name")),ok:$t(n.ok,k(e,"ok")),outputSha256:x(n.outputSha256,k(e,"outputSha256")),outputTail:x(n.outputTail,k(e,"outputTail")),timedOut:$t(n.timedOut,k(e,"timedOut"))}}function Na(t,e){return Object.fromEntries(bn(t,e,x))}function dP(t,e){return Object.fromEntries(bn(t,e,ht))}function pP(t,e){if(typeof t==="string"||typeof t==="boolean")return t;if(typeof t==="number"&&Number.isFinite(t))return t;return Dt(t,e)}import{copyFileSync as bP,existsSync as EP,mkdtempSync as $P,readFileSync as TP,readlinkSync as xP,rmSync as AP,utimesSync as CP}from"fs";import{tmpdir as RP}from"os";import{join as Ma,resolve as IP}from"path";import{lstatSync as gP,statSync as mP}from"fs";import{dirname as fP,join as hP}from"path";var yP=["ENOENT","ENOTDIR","ELOOP"];function $e(t){return by(()=>gP(t))}function kd(t){return by(()=>mP(t))}function Te(t,e,n=new Map){let r=fP(e);if(r===".")return!1;let o=n.get(r);if(o!==void 0)return o;let s=$e(hP(t,r))?.isSymbolicLink()===!0||Te(t,r,n);return n.set(r,s),s}function by(t){try{return t()}catch(e){if(yP.includes(e.code))return null;throw e}}import{realpathSync as kP}from"fs";var Cs="ari-base-",wd="ari-index-",Ey="ari-verdicts-",wP=12;function La(t){return`${wd}${SP(t)}-`}function SP(t){return Z(vP(t)).slice(0,wP)}function vP(t){try{return kP(t)}catch{return t}}var ja="\x00",ee=0,OP=128,_P=128,Ry=1,Iy=1,PP=1,Sd=["diff","--name-only","--no-renames","--ignore-submodules=untracked","-z"],NP=["git","--no-optional-locks","--no-replace-objects",...["core.fsmonitor=false","core.untrackedCache=false","core.trustctime=true","core.checkStat=default"].flatMap((t)=>["-c",t])],$y=1,DP=/^(?:[a-z]|S) /,Ty=/^s/i,LP=2,MP="symlink:",jP=["--no-assume-unchanged","--no-skip-worktree"],xy="worktree ",FP="bare",GP="prunable",Ay=/^(?:error|fatal): /;async function F(t,e,n={}){let r=[...NP,...e],o=KP(r,t,n),[s,i,a]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if((n.allowedExitCodes??[ee]).includes(a))return{exitCode:a,stderr:i,stdout:s};let l=i.trim()||s.trim()||"no output";throw Error(`git ${e.join(" ")} failed in ${t} with exit code ${a}: ${l}`)}async function Jn(t){let e=await F(t,["rev-parse","--show-toplevel"],{allowedExitCodes:[ee,OP]});if(e.exitCode!==ee)throw new m(`${t} is not inside a git working tree`,"Run ari from inside a git repository");return e.stdout.trim()}async function sn(t,e){let n=await F(t,["rev-parse","--git-path",e]);return IP(t,n.stdout.trim())}async function Fa(t){let e=await F(t,["rev-parse","--verify","--quiet","HEAD^{commit}"],{allowedExitCodes:[ee,Ry]});if(e.exitCode!==ee)throw new m("The repository has no commits yet","Make a first commit, then run the command again");return e.stdout.trim()}async function Oy(t){let e=await F(t,["config","user.name"],{allowedExitCodes:[ee,Iy]}),n=e.stdout.trim();return e.exitCode===ee&&n.length>0?n:null}async function xe(t,e){let n=await Dy(t,async(s)=>(await Ny(t,await Ha(t),s),F(t,[...Sd,e,"--"],{env:s}))),r=await F(t,[...Sd,"--cached",e,"--"]),o=await F(t,["ls-files","--others","--exclude-standard","-z"]);return bd([n,r,o].flatMap((s)=>Ke(s.stdout)))}async function Ga(t,e,n){let r=await F(t,[...Sd,e,n,"--"]);return bd(Ke(r.stdout))}async function fo(t,e){let n=await F(t,["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],{allowedExitCodes:[ee,Ry]});if(n.exitCode!==ee)throw new m(`"${e}" does not name a commit`,"Pass a branch, tag or commit that this repository has");return n.stdout.trim()}async function _y(t,e,n){let r=await F(t,["merge-base",e,n],{allowedExitCodes:[ee,PP]});if(r.exitCode!==ee)throw new m(`${e} and ${n} share no history`,"Pass a ref that the current branch was integrated with");return r.stdout.trim()}async function Py(t){let e=await F(t,["worktree","list","--porcelain","-z"]),n=[],r=null;for(let o of[...e.stdout.split(ja),""])if(o.startsWith(xy))r=o.slice(xy.length);else if(o===FP||o.startsWith(GP))r=null;else if(o===""&&r!==null)n.push(r),r=null;return n}async function Ae(t,e){return Dy(t,async(n)=>{await Ny(t,await Ha(t),n);let r=await F(t,["add","--all","--sparse","--","."],{allowedExitCodes:[ee,_P],env:n});if(r.exitCode!==ee)throw new m(`git cannot hash the working tree: ${vd(r.stderr)}`,"Commit, remove or ignore those paths (an embedded repository needs a commit), then run the command again");if(e.length>0){let s=e.map((i)=>`:(glob)${i}`);await F(t,["rm","--cached","-r","-q","--sparse","--ignore-unmatch","--",...s],{env:n})}return(await F(t,["write-tree"],{env:n})).stdout.trim()})}async function An(t,e){if(e.length===0)return{};let n=await F(t,["ls-files","--cached","--others","--exclude-standard","-z"]),r=new Map,o=bd(Ke(n.stdout)).filter((s)=>et(s,e)&&!Te(t,s,r));return Object.fromEntries(o.flatMap((s)=>{let i=UP(Ma(t,s));return i===null?[]:[[s,i]]}))}function vd(t){let e=t.split(`
|
|
130
|
+
`).map((r)=>r.trim()).filter((r)=>r.length>0),n=e.filter((r)=>Ay.test(r)).map((r)=>r.replace(Ay,""));return(n.length>0?n:e).join("; ")||"no output"}async function Ha(t){let e=await F(t,["ls-files","-v","-z"]),n=Ke(e.stdout).filter((o)=>DP.test(o)),r=n.some((o)=>Ty.test(o))&&await HP(t);return n.filter((o)=>!(r&&Ty.test(o))||$e(Ma(t,Cy(o)))!==null).map(Cy)}async function HP(t){return(await F(t,["config","--type=bool","core.sparseCheckout"],{allowedExitCodes:[ee,Iy]})).stdout.trim()==="true"}function Cy(t){return t.slice(LP)}async function Ny(t,e,n){if(e.length===0)return;let r=`${e.join(ja)}${ja}`;for(let o of jP)await F(t,["update-index",o,"-z","--stdin"],{env:n,stdin:r})}async function Dy(t,e){let n=$P(Ma(RP(),La(t))),r=Ma(n,"index"),o=()=>AP(n,{force:!0,recursive:!0}),s=Qt(o);try{let i=await sn(t,"index");if(EP(i))bP(i,r),CP(r,$y,$y);return await e({GIT_INDEX_FILE:r})}finally{o(),s()}}function UP(t){let e=$e(t);if(e?.isSymbolicLink())return`${MP}${Z(xP(t))}`;return e?.isFile()?Z(TP(t)):null}function KP(t,e,n){try{return Bun.spawn(t,{cwd:e,env:n.env?{...process.env,...n.env}:process.env,stderr:"pipe",stdin:n.stdin===void 0?"ignore":new TextEncoder().encode(n.stdin),stdout:"pipe"})}catch(r){throw Error(`Could not run ${t.join(" ")} in ${e}`,{cause:r})}}function Ke(t){return t.split(ja).filter((e)=>e.length>0)}function bd(t){return[...new Set(t)].sort(O)}var J=".ari",Er=".ari/tasks/*.json",Gy=".ari/tasks/*.md",rt=".ari/config.json",ho="ids",YP=`${J}/`,Ka="tasks",Hy="knowledge",Uy="packs",XP="ari",$d="active.json",zP="journal",Ky=".md",By=".json",Vy=".md",Ed=".yaml",ZP=".jsonl",Td=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Wy=`
|
|
131
|
+
`,QP=".ari-",tN=".tmp",eN="ENOENT",Jy="EEXIST",nN=new Set(["EPERM","ENOTSUP","ENOSYS","EXDEV"]),rN="locks",oN=".lock";function yo(t){return t===J||t.startsWith(YP)}function ne(t){return t.filter((e)=>!yo(e))}function ko(t){if(Cn(Rt(t,J)))return;throw new m("Ariadne is not initialised in this repository","Run 'ari init'")}function qy(){return pt(Tt)}function M(t){ko(t);let e=Rt(t,rt);if(!Cn(e))return vr({});return vr(Id(e,rt,"Fix the JSON syntax of .ari/config.json"))}function xd(t){return Td.test(t)}function qn(t){if(xd(t))return t;throw new m(`"${t}" is not a task id`,"Task ids are lower-case words joined by hyphens; run 'ari list'")}function It(t){return`${J}/${Ka}/${qn(t)}${Ky}`}function Rn(t){return`${J}/${Ka}/${qn(t)}${By}`}function Ad(t){return`${J}/${Uy}/${t}${Ed}`}function de(t){return ko(t),Wa(Rt(t,J,Ka),Ky)}function In(t){return ko(t),Wa(Rt(t,J,Ka),By)}function it(t,e,n){ko(t);let r=Rt(t,It(e));if(!Cn(r))throw new m(`Task "${e}" does not exist`,"Run 'ari list' to see the tasks of this repository");let o=Rs(r,"utf8");return{contractText:o,task:{contract:Aa(e,o,n),record:On(t,e)}}}function Pt(t,e){let n={invalid:[],tasks:[]};for(let r of de(t))try{n.tasks.push(it(t,r,e).task)}catch(o){if(!(o instanceof m))throw o;n.invalid.push({hint:o.hint??"",id:r,problem:o.message})}return n}function Yy(t,e,n,r){let{id:o}=n,s=It(o),i=()=>new m(`Task "${o}" already exists at ${s}`,"Run 'ari list'");md(ek(e,o),o,()=>{if(Cn(Rt(t,s))||!tk(t,o))throw i();zy(t,n),Yn(Rt(t,s),r,i)})}function Xy(t){let e=de(t);return[...e,...In(t).filter((n)=>!e.includes(n)&&!tk(t,n))]}function zy(t,e){Tr(Rt(t,Rn(e.id)),pt(e))}function Vt(t,e,n,r){return md(ek(e,n),n,()=>{let o=r(On(t,n));return zy(t,o),o})}function Gt(t){ko(t);let e=Rt(t,J,Uy);return Wa(e,Ed).map((n)=>{let r=Ad(n),o=Ia(Rs(Rt(t,r),"utf8"),r);if(o.name===n)return o;throw new m(`${r} declares the pack "${o.name}"`,`Rename the file to ${o.name}${Ed} or fix its name`)})}function an(t){return ko(t),Wa(Rt(t,J,Hy),Vy)}function pe(t){return an(t).map((e)=>Ca(e,Rs(nk(t,e),"utf8")))}function Ba(t,e){if(!Td.test(e.id))throw Error(`Knowledge entry id "${e.id}" is not a slug`);let n=nk(t,e.id);Yn(n,br(e),()=>Error(`Knowledge entry ${n} already exists`))}async function P(t){return sn(t,XP)}function gt(t){let e=Rt(t,$d);if(!Cn(e))return null;let n=`Delete ${e}, then run 'ari next', which offers to adopt the task again`,r=Id(e,e,n);return At("active task pointer",n,()=>{let o=T(r,"pointer",["since","task"]);return{since:x(o.since,"since"),task:x(o.task,"task")}})}function Cd(t,e){Tr(Rt(t,$d),pt(e))}function Zy(t){Ua(Rt(t,$d),{force:!0})}function $r(t,e){let n=Rd(t,e.task);Ly(Fy(n),{recursive:!0});let r=JSON.stringify(JSON.parse(pt(e)));VP(n,`${r}${Wy}`)}function Va(t,e){Ua(Rd(t,e),{force:!0})}function Qy(t,e){let n=Rd(t,e);if(!Cn(n))return[];return Rs(n,"utf8").split(Wy).flatMap((r)=>{if(r.trim().length===0)return[];let o=sN(r);return o===null||o.task!==e?[]:[o]})}function sN(t){try{return Da(JSON.parse(t))}catch(e){if(e instanceof SyntaxError||e instanceof b)return null;throw e}}function Rd(t,e){return Rt(t,zP,`${qn(e)}${ZP}`)}function On(t,e){let n=Rn(e),r=Rt(t,n);if(!Cn(r))throw new m(`Task "${e}" has a contract but no record at ${n}`,`Restore ${n} from git; only ari writes it`);return Sy(e,Id(r,n,`Restore ${n} from git; only ari writes it`))}function tk(t,e){if(!Cn(Rt(t,Rn(e))))return!0;try{return cy(On(t,e))}catch(n){if(n instanceof m)return!1;throw n}}function ek(t,e){return Rt(t,rN,`${qn(e)}${oN}`)}function nk(t,e){return Rt(t,J,Hy,`${e}${Vy}`)}function Id(t,e,n){let r=Rs(t,"utf8");try{return JSON.parse(r)}catch(o){let s=o instanceof Error?o.message:String(o);throw new m(`${e} is not valid JSON (${s})`,n)}}function Wa(t,e){return iN(t).filter((r)=>r.endsWith(e)).map((r)=>qP(r,e)).filter((r)=>Td.test(r)).sort(O)}function iN(t){try{return JP(t)}catch(e){if(e.code===eN)return[];throw e}}function Tr(t,e){let n=rk(t);try{jy(n,e),My(n,t)}catch(r){throw Ua(n,{force:!0}),r}}function Yn(t,e,n){let r=rk(t);try{jy(r,e),aN(r,t)}catch(o){if(o.code===Jy)throw n();throw o}finally{Ua(r,{force:!0})}}function aN(t,e){try{WP(t,e)}catch(n){if(!nN.has(n.code??""))throw n;if(Cn(e))throw Object.assign(Error(`${e} already exists`),{code:Jy});My(t,e)}}function rk(t){let e=Fy(t);return Ly(e,{recursive:!0}),Rt(e,`${QP}${BP()}${tN}`)}var uN=1,dN=/^[\w@%+=:,./{}-]+$/,Od="the base set of variables only",pN="the whole environment, with every token in it",gN="{base}",mN="{changed-files}",fN="{verdicts-file}",hN="argus sends the source of the changed files to the model endpoint";function ok(t,e){let n=yN(t),r={agents:e.agents,packCommands:n,regressionSetup:e.regression.setup,reviewCommand:e.review.command,...e.review.argus===void 0?{}:{reviewArgus:e.review.argus},version:uN};return{commands:kN(e,n),sha256:Z(pt(r))}}function yN(t){if(!cN(lN(t,J)))return[];return Gt(t).sort((e,n)=>O(e.name,n.name)).flatMap((e)=>e.stages.flatMap((n)=>n.gates.flatMap((r)=>r.kind==="command"?[{pack:e.name,run:r.run,stage:n.name}]:[])))}function kN(t,e){let n=Object.entries(t.agents).flatMap(([a,c])=>wN(a,c)),r=t.review.command===null?[]:[wo("review.command",t.review.command)],o=SN(t.review.argus),s=t.regression.setup.map((a,c)=>wo(`regression.setup[${c}]`,a)),i=e.map(({pack:a,run:c,stage:l})=>wo(`.ari/packs/${a}: stage ${l}, command gate`,c));return[...n,...r,...o,...s,...i]}function wN(t,e){let n=vN(e),r=e.reviewCommand===void 0?[]:[wo(`agents.${t}.reviewCommand`,_d(e.reviewCommand),n)];return[wo(`agents.${t}.command`,_d(e.command),n),...r]}function SN(t){if(t===void 0)return[];let e={base:gN,configPath:t.config,file:fN,only:mN};return va(t).map((n)=>{let r=`${Od} and ${ba(n).join(", ")}, when set`,o=n==="run"?`${r}; ${hN}`:r;return wo("review.argus.command",_d(so(t,n,e)),o)})}function vN(t){if(t.inheritEnv===!0)return pN;return t.env===void 0||t.env.length===0?Od:`${Od} and ${t.env.join(", ")}`}function wo(t,e,n=null){return{command:e,environment:n,source:t}}function _d(t){return t.map((e)=>dN.test(e)?e:JSON.stringify(e)).join(" ")}var xr="ARI_TRUST_CONFIG",bN="1";function So(){return process.env[xr]===bN}function Be(t,e){let n=ok(t,e),r=_h(t),o=EN(n.commands.length,n.sha256,r?.sha256??null);return{commands:n.commands,root:bs(t),sha256:n.sha256,state:o,trustedAt:r?.trustedAt??null,trustedSha256:r?.sha256??null}}function _n(t){return t.state==="untrusted"||t.state==="changed"}function vo(t,e){let n=Be(t,e);if(n.state==="not-required")return n;let r=Ph(t,n.sha256);return{...n,state:"trusted",trustedAt:r.trustedAt,trustedSha256:r.sha256}}function sk(t){return Nh(t)}function EN(t,e,n){if(t===0)return"not-required";if(n===null)return"untrusted";return n===e?"trusted":"changed"}var $N=1,TN="Commands that ari would run for this repository";async function Xn({config:t,root:e},n){if(So())return;let r=Be(e,t);if(!_n(r))return;if(ur()&&await Nd(r.root,r.commands)){vo(e,t);return}let o=r.state==="changed"?"the commands in .ari changed since you trusted them":"nobody has trusted the commands in .ari on this machine";throw new m(`Cannot ${n}: ${o}`,`Review them with 'ari trust', trust them with 'ari trust --yes', or set ${xr}=1 where the repository is already trusted, such as in CI`,$N,{tag:"ConfigNotTrusted"})}function Pd(t){return t.flatMap(({command:e,environment:n,source:r})=>[`${r}: ${e}`,...n===null?[]:[` environment: ${n}`]])}async function Nd(t,e){Nt(Pd(e).join(`
|
|
132
|
+
`),TN);try{return await Ee({initialValue:!1,message:`Trust these commands in ${t}?`})}catch(n){if(n instanceof vt)return!1;throw n}}var xN=2,Ar=1,AN=5000,CN=1000,RN=2147483647,IN=1048576,ON=["HOME","PATH","USER","LOGNAME","SHELL","TERM","TMPDIR","TZ","LANG","LC_ALL","LC_CTYPE","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_CACHE_HOME","XDG_STATE_HOME"];function Cr(t,e){let n=e.agent??e.route?.agent;if(n===void 0)throw new m(`No ${e.role} agent is chosen`,e.role==="task"?"Pass --agent <name>, or set routing.default in .ari/config.json":"Pass --agent <name>, or set routing.review or review.agent in .ari/config.json",Ar,{tag:"NoAgentChosen"});let r=t.agents[n];if(r===void 0)throw new m(`No agent "${n}" is configured`,`Run 'ari agents add <preset> --name ${n}', or add "agents": { "${n}": { "command": ["<binary>", "<non-interactive flag>", "{prompt}"] } } to .ari/config.json`,Ar,{tag:"AgentNotConfigured"});if(!Sr(r).includes(e.role))throw new m(`Agent "${n}" is not configured as a ${e.role} agent`,`Add "${e.role}" to agents.${n}.roles in .ari/config.json`,Ar,{tag:"AgentRoleMismatch"});let o=e.agent===void 0?e.route?.model:void 0,s=e.model??o??r.model??null,i={config:r,model:s,name:n,role:e.role};return Ja(i,""),i}function Ja(t,e){let{config:n,model:r,name:o,role:s}=t,i=s==="review"&&n.reviewCommand!==void 0?"reviewCommand":"command",a=n[i]??n.command,c=`agents.${o}.${i}`;if(!a.some((p)=>p.includes(Zt)))throw new m(`The command of agent "${o}" has no ${Zt} argument`,`Put ${Zt} where the agent takes its prompt in ${c}`,Ar,{tag:"AgentCommandInvalid"});let l=a.some((p)=>p.includes(vs));if(l&&r===null)throw new m(`Agent "${o}" needs a model for ${vs} in ${c}`,`Set agents.${o}.model, give a model in routing, or pass --model`,Ar,{tag:"AgentCommandInvalid"});if(!l&&r!==null&&n.modelFlag===void 0)throw new m(`Agent "${o}" has no way to take the model "${r}"`,`Put ${vs} in ${c}, or set agents.${o}.modelFlag`,Ar,{tag:"AgentCommandInvalid"});let u=a.map((p)=>p.replaceAll(Zt,()=>e).replaceAll(vs,()=>r??"")),d=!l&&r!==null&&n.modelFlag!==void 0?[n.modelFlag,r]:[];return[...u,...d]}function qa(t){if(t.inheritEnv===!0)return{...process.env,...Fe};return Is(t.env??[])}function Is(t){let e=[...ON,...t].filter((n)=>!(n in Fe));return Object.fromEntries(e.flatMap((n)=>process.env[n]===void 0?[]:[[n,process.env[n]]]))}async function Ya(t,e,n){let r=Ja(t,e),{name:o}=t;return Dd(r,{...n,action:`start the agent "${o}"`,maxCaptureBytes:IN,reapGroup:t.role==="review",startFailure:(s,i)=>new m(`Agent "${o}" could not start: ${s}`,`Fix agents.${o}.command in .ari/config.json`,Ar,{cause:i,tag:"AgentStartFailed"}),timeoutSeconds:n.timeoutSeconds??t.config.timeoutSeconds})}async function Dd(t,e){await Xn(e.trust,e.action);let n=_N(t,e),r=Qt(()=>ik(n)),o={timedOut:!1},s=e.timeoutSeconds,i=s===void 0?void 0:setTimeout(()=>{o.timedOut=!0,ik(n)},Math.min(s*CN,RN)),a=e.stdout==="capture"?PN(n,e.maxCaptureBytes):Promise.resolve({overflowed:!1,text:""}),c=await n.exited;if(clearTimeout(i),Ch())await new Promise(()=>{return});if(e.reapGroup)Ge(n.pid,"SIGKILL");r();let{overflowed:l,text:u}=await a;return{exitCode:c,overflowed:l,stdout:u,timedOut:o.timedOut}}function _N(t,e){let n=e.stdout==="inherit"?"inherit":e.stdout==="capture"?"pipe":xN;try{return Bun.spawn(t,{cwd:e.cwd,detached:!0,env:e.environment,stderr:"inherit",stdin:"ignore",stdout:n})}catch(r){throw e.startFailure(t[0]??"",r)}}async function PN(t,e){let n=t.stdout;if(!(n instanceof ReadableStream))return{overflowed:!1,text:""};let r=[],o=0,s=!1;for await(let i of n){if(o+i.length>e){s=!0,Ge(t.pid,"SIGKILL");break}r.push(i),o+=i.length}return{overflowed:s,text:new TextDecoder().decode(Buffer.concat(r))}}async function ik(t){Ge(t.pid,"SIGTERM"),await Promise.race([t.exited,Bun.sleep(AN)]),Ge(t.pid,"SIGKILL")}var bo=["task","review","both"],Ld="--model",Ve=[{binary:"claude",command:["claude","-p",Zt,"--permission-mode","acceptEdits"],label:"Claude Code",modelFlag:Ld,name:"claude",reviewCommand:["claude","-p",Zt,"--tools","Read,Grep,Glob","--permission-mode","dontAsk"]},{binary:"codex",command:["codex","exec","--sandbox","workspace-write",Zt],label:"Codex CLI",modelFlag:Ld,name:"codex",reviewCommand:["codex","exec","--sandbox","read-only",Zt]},{binary:"gemini",command:["gemini","--approval-mode","auto_edit","-p",Zt],label:"Gemini CLI",modelFlag:Ld,name:"gemini",reviewCommand:["gemini","--approval-mode","plan","-p",Zt]}];function ak(t){let e=Ve.find((n)=>n.name===t);if(e!==void 0)return e;throw new v(`ari has no agent preset "${t}"`,`Choose one of: ${Ve.map((n)=>n.name).join(", ")}, or add the agent to .ari/config.json yourself`)}function ck(t){let e=t??"task",n=bo.find((r)=>r===e);if(n!==void 0)return n;throw new v(`Unknown role "${e}"`,`Choose one of: ${bo.join(", ")}`)}function Eo(t,e,n){let r=n===void 0?{}:{model:n};switch(e){case"task":return{command:t.command,...r,modelFlag:t.modelFlag,roles:["task"]};case"review":return{command:t.reviewCommand,...r,modelFlag:t.modelFlag,roles:["review"]};case"both":return{command:t.command,reviewCommand:t.reviewCommand,...r,modelFlag:t.modelFlag,roles:["task","review"]}}}var NN="--version",DN=5000,LN=200;async function lk(){return Promise.all(Ve.map(MN))}async function MN(t){return{...await Os([t.binary]),label:t.label,preset:t.name}}async function Os(t){for(let e of t){let n=Bun.which(e);if(n!==null)return{binary:e,path:n,version:await jN(n)}}return{binary:t[0]??"",path:null,version:null}}async function jN(t){let e;try{e=Bun.spawn([t,NN],{detached:!0,env:{...Is([]),...Fe},stderr:"ignore",stdin:"ignore",stdout:"pipe"})}catch{return null}let n=()=>Ge(e.pid,"SIGKILL"),r=Qt(n),o=setTimeout(n,DN),[s,i]=await Promise.all([new Response(e.stdout).text(),e.exited]);clearTimeout(o),n(),r();let a=s.split(`
|
|
133
|
+
`).map((c)=>c.trim()).find((c)=>c.length>0);return i===0&&a!==void 0?a.slice(0,LN):null}import{isDeepStrictEqual as S0}from"util";import{randomUUID as u0}from"crypto";import{chmodSync as d0,existsSync as Ud,mkdirSync as p0,readFileSync as vk,renameSync as g0,rmSync as m0,statSync as f0,writeFileSync as h0}from"fs";import{basename as y0,dirname as Sk,join as Kd}from"path";import{isDeepStrictEqual as dk}from"util";var FN=/"(?:[^"\\]|\\.)*"|[^\s{}[\],:]+|[{}[\],:]/g,GN=/"(?:[^"\\\n]|\\.)*"|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,HN=/[^\r\n]/g,UN=/(?:^|\n)([\t ]*)[^\n]*$/,KN=/^[\t ]*\r?\n/,BN=/^[\t ]+(?=\S)/m,VN=" ",_s=",";function Md(t){return t.replace(GN,(e)=>e.startsWith('"')?e:e.replace(HN," "))}function Xa(t,e){let n=BN.exec(t)?.[0]??VN,r=t.includes(`\r
|
|
134
|
+
`)?`\r
|
|
135
|
+
`:`
|
|
136
|
+
`,o=(i,a)=>{let c=t.slice(i.start,i.end);if(dk(i.value,a))return c;let l=r+(UN.exec(t.slice(0,i.start))?.[1]??""),u=(A,R)=>JSON.stringify(A,null,n).replaceAll(`
|
|
137
|
+
`,R);if(!uk(i.value)||!uk(a)||Array.isArray(i.value)!==Array.isArray(a))return u(a,l);let d=WN(i,a),p=[],g="",f=i.start+1,y=(A)=>{let R=t.slice(f,A);return g+(g.length===0||KN.test(R)?"":r)+R};for(let A of i.entries){let R=y(A.start),B=d.get(A);if(g="",B!==void 0){let _t=o(A.node,a[B]);p.push(R+t.slice(A.start,A.node.start)+_t+t.slice(A.node.end,A.end))}else if(R.trim().length>0)g=R.trimEnd();f=t[A.end]===_s?A.end+1:A.end}let S=new Set(d.values()),I=l+n,C=Object.keys(a).filter((A)=>!S.has(A)).map((A)=>{let R=Array.isArray(a)?"":`${JSON.stringify(A)}: `;return I+R+u(a[A],I)}),q=y(i.end-1),G=q.trimEnd(),N=C.length===0?q.slice(G.length):l,H=p.length>0&&C.length>0?_s:"";return c[0]+p.join(_s)+H+G+C.join(_s)+N+c.at(-1)},s=JN(Md(t));return t.slice(0,s.start)+o(s,JSON.parse(JSON.stringify(e)))+t.slice(s.end)}function WN({entries:t},e){let n=Array.isArray(e)&&e.length<t.length,r=new Map;for(let o of t){let s=n?String(r.size):o.key;if((!n||dk(o.node.value,e[s]))&&Object.hasOwn(e,s))r.set(o,s)}return r}function uk(t){return typeof t==="object"&&t!==null}function JN(t){let e=[...t.matchAll(FN)],n=0,r=()=>{let s=e[n];if(s===void 0)throw Error("Unexpected end of JSON");return n+=1,s},o=()=>{let s=r(),i=s[0];if(i!=="{"&&i!=="[")return{end:s.index+i.length,entries:[],start:s.index,value:JSON.parse(i)};let a=i==="{"?"}":"]",c=[];while(e[n]!==void 0&&e[n]?.[0]!==a){let u=e[n]?.index??0,d=i==="{"?JSON.parse(r()[0]):String(c.length);if(i==="{")r();let p=o(),g=e[n]?.[0]===_s?r().index:p.end;c.push({end:g,key:d,node:p,start:u})}let l=r().index+1;return{end:l,entries:c,start:s.index,value:JSON.parse(t.slice(s.index,l))}};return o()}import{existsSync as gk,readlinkSync as XN,realpathSync as zN,statSync as ZN}from"fs";import{basename as QN,dirname as Ps,isAbsolute as t0,join as Za,relative as e0,resolve as mk,sep as n0}from"path";async function za(t){let e=M(t),n=await P(t),r={config:e,drift:null,root:t,state:n,task:null},o=gt(n)?.task??null;if(o===null)return r;if(!de(t).includes(o)){if(In(t).includes(o)&&pk(On(t,o)))throw qN(o);return r}let{contractText:s,task:i}=it(t,o,e);if(!pk(i.record))return r;return{...r,drift:YN(i,s),task:i}}function pk({status:t}){return t==="active"||t==="blocked"}function qN(t){return new m(`the contract of the active task "${t}" is missing`,`Restore ${It(t)}`)}function YN({contract:t,record:e},n){if(e.contractHash===null||Bt(n)===e.contractHash)return null;return`the contract of task "${t.id}" changed after its approval; run 'ari amend ${t.id} --reason <text>' or restore ${It(t.id)}`}var fk=".git",r0="..",Qa=0,o0=1,hk=128,s0=40,i0=["rev-parse","--show-toplevel","--absolute-git-dir","--git-common-dir"];function yk(){let t=new Map,e=new Map,n=new Map,r=[],o=(c)=>jd(t,c,()=>a0(c)),s=(c)=>jd(e,c.root,async()=>{let l=await l0(c);return r.push(l),l}),i=async(c)=>{let l=[],u=null;for(let d of kk(c).filter((p)=>gk(Za(p,fk)))){let p=await o(d);if(p===null)continue;if(u!==null&&await c0(u,p))break;if(u=p,gk(Za(d,J)))l.push(await s(p))}return l},a=(c)=>{let l=wk(Ht(c));return jd(n,l,()=>i(l))};return{at:async(c)=>(await a(c))[0]??null,governing:a,opened:()=>r}}function Ht(t,e=s0){let n=Gd(()=>zN(t));if(n!==null)return n;let r=Ps(t);if(r===t)return t;let o=Za(Ht(r,e),QN(t)),s=e>0?Fd(o):null;return s===null?o:Ht(mk(Ps(o),s),e-1)}function Fd(t){return Gd(()=>XN(t))}function tc(t){return Gd(()=>ZN(t).isDirectory())??!1}function cn(t,e){let n=e0(t,e),r=n.split(n0);return r[0]===r0||t0(n)?null:r.join("/")}function Gd(t){try{return t()}catch{return null}}function jd(t,e,n){let r=t.get(e);if(r!==void 0)return r;let o=n();return t.set(e,o),o}function kk(t){let e=Ps(t);return e===t?[t]:[t,...kk(e)]}function wk(t){return tc(t)||Ps(t)===t?t:wk(Ps(t))}async function a0(t){let e=await F(t,i0,{allowedExitCodes:[Qa,hk]});if(e.exitCode!==Qa)return{fault:`git cannot read the repository at ${t}`,gitDirectories:[Za(t,fk)],root:t};let[n="",r="",o=""]=e.stdout.split(`
|
|
138
|
+
`);if(Ht(n)!==t)return null;let s=[r,mk(t,o)].map((i)=>Ht(i));return{fault:null,gitDirectories:[...new Set(s)],root:t}}async function c0(t,e){if(t.fault===null&&t.gitDirectories.at(-1)===e.gitDirectories.at(-1))return!0;if(e.fault!==null)return!1;return(await F(e.root,["check-ignore","-q","--",t.root],{allowedExitCodes:[Qa,o0,hk]})).exitCode===Qa}async function l0({fault:t,gitDirectories:e,root:n}){if(t!==null)return{fault:t,gitDirectories:e,root:n,workspace:null};try{return{fault:null,gitDirectories:e,root:n,workspace:await za(n)}}catch(r){if(!(r instanceof m))throw r;return{fault:Hd(r),gitDirectories:e,root:n,workspace:null}}}function Hd({hint:t,message:e}){return t===void 0?e:`${e} (${t})`}var k0=2;function ec(t,e){let n=W(t,e);return n===null?null:re(e,n)}function W(t,e){let n=Kd(t,e);return Ud(n)?vk(n,"utf8"):null}function re(t,e){let n;try{n=JSON.parse(Md(e))}catch(r){let o=r instanceof Error?r.message:String(r);throw new m(`${t} is not valid JSON (${o})`,`Fix ${t}, then run the command again`)}if(z(n))return n;throw new m(`${t} does not hold a JSON object`,`Fix ${t}, then run the command again`)}function nc(t,e,n){if(!Ud(t))return n;try{return e(JSON.parse(vk(t,"utf8")))}catch{return n}}function Bd(t,e,n){return Ce(t,e,zn(W(t,e),n))}function zn(t,e){return t===null?`${JSON.stringify(e,null,k0)}
|
|
139
|
+
`:Xa(t,e)}function Ce(t,e,n){let r=Kd(t,e),o=W(t,e),s=Ns(o,n);if(s!=="unchanged")Rr(r,n,w0(r));return s}function Ns(t,e){if(t===e)return"unchanged";return t===null?"created":"updated"}function Rr(t,e,n){let r=Ht(t);p0(Sk(r),{recursive:!0});let o=Kd(Sk(r),`.${y0(r)}.${process.pid}.${u0()}.tmp`);try{if(h0(o,e),n!==void 0)d0(o,n);g0(o,r)}finally{m0(o,{force:!0})}}function w0(t){return Ud(t)?f0(t).mode:void 0}function z(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}var Vd="agents",bk=1;function Ek(t,e){let n=ak(e.preset),r=e.name??n.name,o=Eo(n,e.role,e.model),{agents:s,settings:i}=xk(t),a=s[r];if(a!==void 0&&S0(a,o))return{action:"unchanged",entry:o,name:r,preset:n.name};if(a!==void 0)throw new m(`agents.${r} already exists with other settings`,`Choose another name with --name, or run 'ari agents remove ${r}' first`,bk,{tag:"AgentExists"});let c={...i,[Vd]:{...s,[r]:o}};return Ak(c,`ari cannot add agent "${r}"`,"Choose another name with --name"),{action:Bd(t,rt,c),entry:o,name:r,preset:n.name}}function $k(t,e){let{agents:n,settings:r}=xk(t);if(n[e]===void 0)return{action:"unchanged",name:e};let{[e]:o,...s}=n,i={...r,[Vd]:s};return Ak(i,`ari cannot remove agent "${e}"`,`Change the routing and review settings that name "${e}" in ${rt} first`),Bd(t,rt,i),{action:"removed",name:e}}function Tk(t){let e=M(t);return{agents:Object.entries(e.agents).sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>({command:o.command,env:o.env??[],inheritEnv:o.inheritEnv===!0,model:o.model??null,modelFlag:o.modelFlag??null,name:r,reviewCommand:o.reviewCommand??null,roles:Sr(o),timeoutSeconds:o.timeoutSeconds??null})),routing:e.routing}}function rc(t){if(t===null)return"none";return t.model===null?t.agent:`${t.agent} (${t.model})`}function xk(t){M(t);let e=ec(t,rt)??{},n=e[Vd]??{};return{agents:z(n)?n:{},settings:e}}function Ak(t,e,n){let r=Ea(t);if(r!==null)throw new m(`${e}: ${r}`,n,bk,{tag:"InvalidConfig"})}import{existsSync as v0}from"fs";import{join as b0}from"path";async function Ir(t,e){let n=E0(t),r=await e();if(n)$0(t);return r}function E0(t){if(!v0(b0(t,J)))return!0;try{return!_n(Be(t,M(t)))}catch(e){if(e instanceof m)return!1;throw e}}function $0(t){try{let e=M(t);if(_n(Be(t,e)))vo(t,e)}catch(e){if(!(e instanceof m))throw e}}var T0=" ";async function _(){return Jn(process.cwd())}function We(t){if(t===void 0)return[];return t.split(",").map((e)=>e.trim()).filter((e)=>e.length>0)}function ln(t,e,n){if(t!==void 0&&t.trim().length>0)return t;throw new v(`${e} is required`,`Run ${n}`)}function Re(t,e){if(t===void 0||t.trim().length>0)return t;throw new v(`${e} must not be empty`,`Leave ${e} out, or give it a value`)}function oc(t){return t.flatMap((e)=>x0(e)).join(`
|
|
140
|
+
`)}function x0(t){let e=`${t.ok?"pass":"FAIL"} ${t.gate}: ${t.summary}`;if(t.ok)return[e];let n=t.details.map((o)=>` - ${o}`),r=t.checks.filter((o)=>!o.ok&&o.outputTail.length>0).flatMap((o)=>[` ${o.name} (${o.command}) output:`,...o.outputTail.trimEnd().split(`
|
|
141
|
+
`).map((s)=>`${T0}${s}`)]);return[e,...n,...r]}var A0=Ve.map((t)=>t.name).join(", "),C0=E({description:"List the configured agents, their roles and the routing; environment values are never shown",examples:["ari agents list --json"],json:!0,name:"list",run:async(t)=>{t.output.result(Tk(await _()),_0)}}),R0=E({args:j({model:{description:"Model the agent uses unless the routing or --model says otherwise",type:"string"},name:{description:"Name in config.agents (default: the preset's name)",type:"string"},role:{description:`What the agent does: ${bo.join(", ")} (default: task)`,type:"string"}}),description:"Add an agent from a preset with least-privilege, non-interactive flags to .ari/config.json",examples:["ari agents add claude","ari agents add codex --name codex-review --role review --model gpt-5.5","ari agents add gemini --role both"],json:!0,name:"add",positionals:st({preset:{description:`Preset: ${A0}`,required:!0}}),run:async(t)=>{let e=await _(),n=await Ir(e,()=>Ek(e,{model:Re(t.args.model,"--model"),name:Re(t.args.name,"--name"),preset:t.positionals.preset,role:ck(t.args.role)}));t.output.result(n,Rk)}}),I0=E({description:"Remove an agent from .ari/config.json unless the routing or the review gate still names it",examples:["ari agents remove codex-review"],json:!0,name:"remove",positionals:st({name:{description:"Agent name in config.agents",required:!0}}),run:async(t)=>{let e=await _();t.output.result(await Ir(e,()=>$k(e,t.positionals.name)),Rk)}}),O0=E({description:"Find the preset agents' binaries on PATH and their versions, running only '<binary> --version'",examples:["ari agents detect --json"],json:!0,name:"detect",run:async(t)=>{t.output.result({agents:await lk()},({agents:e})=>e.map(P0).join(`
|
|
142
|
+
`))}}),Ck=E({description:"Configure the agents that 'ari run' and 'ari review' start",name:"agents",subcommands:[C0,R0,I0,O0]});function _0(t){let e=t.agents.map((a)=>{let c=a.model===null?"":`, model ${a.model}`,l=a.inheritEnv?", inherits the whole environment":"";return`${a.name} ${a.roles.join("+")}${c}${l}: ${a.command.join(" ")}`}),{default:n,review:r,stages:o}=t.routing,s=Object.entries(o).map(([a,c])=>` stage ${a}: ${rc(c)}`),i=[`routing default: ${rc(n)}`,...s,`routing review: ${rc(r)}`];return[...e.length===0?["No agents are configured; run 'ari agents add <preset>'"]:e,...i].join(`
|
|
143
|
+
`)}function Rk(t){return`Agent "${t.name}" ${t.action} in .ari/config.json`}function P0(t){if(t.path===null)return`${t.preset} not found on PATH`;return`${t.preset} ${t.path} ${t.version??"version unknown"}`}import{existsSync as CH}from"fs";import{join as RH}from"path";import{resolve as L0}from"path";var N0=/^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)/,D0=/\r?\n/;function Ds(t,e){return typeof t==="object"&&t!==null?t[e]:void 0}function Wt(t,e){let n=Ds(t,e);return typeof n==="string"?n:null}function sc(t,e){return Wt(t,"cwd")??e}function Ik(t){return t.split(D0).flatMap((e)=>N0.exec(e.trim())?.[1]?.trim()??[])}function Ls(t,e,n){return{command:n.command??null,cwd:e,event:t,paths:n.paths??[],tool:n.tool??null}}var Wd=["before-edit","before-shell","after-tool","stop","pre-compact","session-start"],Pn=new Set(["before-edit","before-shell"]);function Ok(t){return Wd.includes(t)}var M0=30,j0=120,F0=new Set(["stop","pre-compact"]),G0=1000,H0="apply_patch",_k="run_shell_command";function mt(t,e,n=null){let r=F0.has(t)?j0:M0;return{agentEvent:e,event:t,matcher:n,timeoutSeconds:r}}var Pk=[mt("stop","Stop"),mt("pre-compact","PreCompact","manual|auto"),mt("session-start","SessionStart","startup|resume|clear|compact|fork")];function qd(t){return{decision:"block",reason:t}}function Jd(t){return(e)=>({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t,permissionDecisionReason:e}})}function Nk(t,e,n){let r=Ds(e,"tool_input"),o=Wt(r,"file_path")??Wt(r,"notebook_path"),s=Wt(r,"command"),i=Wt(e,"tool_name"),a=i===_k?Wt(r,"dir_path"):null;return Ls(t,L0(sc(e,n),a??""),{command:s,paths:o===null?[]:[o],tool:i})}function U0(t,e,n){let r=Wt(e,"tool_name"),o=Wt(Ds(e,"tool_input"),"command"),s=r===H0?{paths:Ik(o??"")}:{command:o};return Ls(t,sc(e,n),{...s,tool:r})}function K0(t,e,n){let r=Wt(e,"cwd")??Wt(Ds(e,"workspace_roots"),"0")??n,o=Wt(e,"file_path");return Ls(t,r,{command:Wt(e,"command"),paths:t==="after-tool"&&o!==null?[o]:[]})}function B0(t,e,n){return Ls(t,sc(e,n),{command:Wt(V0(e),"command"),tool:Wt(e,"toolName")})}function V0({toolArgs:t}){if(typeof t!=="string")return t;try{return JSON.parse(t)}catch{return null}}function Yd({answers:t},e,n){let r=W0(t,e,n);return typeof r==="string"?r:JSON.stringify(r)}function W0(t,e,n){switch(n.kind){case"allow":return t.allow?.(e)??"";case"context":return t.context(n.text);case"ask":return(t.ask??t.deny)(n.reason);case"block":return t.block(n.reason);case"deny":return t.deny(n.reason)}}var J0={answers:{ask:Jd("ask"),block:qd,context:(t)=>t,deny:Jd("deny")},file:".claude/settings.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,...Pn.has(e)?{onFailure:"block"}:{},timeout:n,type:"command"}),label:"Claude Code",layout:"grouped",name:"claude",parse:Nk,registrations:[mt("before-edit","PreToolUse","Edit|Write|NotebookEdit"),mt("before-shell","PreToolUse","Bash|PowerShell|Monitor"),mt("after-tool","PostToolUse","Edit|Write|NotebookEdit|Bash|PowerShell|Monitor"),...Pk],support:"verified"},q0={answers:{allow:(t)=>t==="stop"?{}:"",block:qd,context:(t)=>t,deny:Jd("deny")},file:".codex/hooks.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,statusMessage:`ari ${e}`,timeout:n,type:"command"}),label:"Codex CLI",layout:"grouped",name:"codex",parse:U0,registrations:[mt("before-edit","PreToolUse","^apply_patch$"),mt("before-shell","PreToolUse","^Bash$"),mt("after-tool","PostToolUse","^(Bash|apply_patch)$"),...Pk],support:"verified"},Y0={answers:{block:(t)=>({decision:"deny",reason:t}),context:(t)=>({hookSpecificOutput:{additionalContext:t}}),deny:(t)=>({decision:"deny",reason:t})},file:".gemini/settings.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,name:`ari-${e}`,timeout:n*G0,type:"command"}),label:"Gemini CLI",layout:"grouped",name:"gemini",parse:Nk,registrations:[mt("before-edit","BeforeTool","write_file|replace"),mt("before-shell","BeforeTool",_k),mt("after-tool","AfterTool","write_file|replace|run_shell_command"),mt("stop","AfterAgent","*"),mt("pre-compact","PreCompress","*"),mt("session-start","SessionStart","*")],support:"verified"},X0={answers:{allow:(t)=>Pn.has(t)?{permission:"allow"}:{},block:(t)=>({followup_message:t}),context:(t)=>({additional_context:t}),deny:(t)=>({agent_message:t,permission:"deny",user_message:t})},file:".cursor/hooks.json",handler:(t,{event:e,timeoutSeconds:n})=>({command:t,...Pn.has(e)?{failClosed:!0}:{},timeout:n}),label:"Cursor",layout:"flat",name:"cursor",parse:K0,registrations:[mt("before-shell","beforeShellExecution"),mt("after-tool","afterFileEdit"),mt("stop","stop"),mt("pre-compact","preCompact"),mt("session-start","sessionStart")],support:"partial"},z0={answers:{allow:(t)=>Pn.has(t)?{permissionDecision:"allow"}:"",block:qd,context:(t)=>({additionalContext:t}),deny:(t)=>({permissionDecision:"deny",permissionDecisionReason:t})},file:".github/hooks/ari.json",handler:(t,{matcher:e,timeoutSeconds:n})=>({bash:t,...e===null?{}:{matcher:e},powershell:t,timeoutSec:n,type:"command"}),label:"GitHub Copilot CLI",layout:"flat",name:"copilot",parse:B0,registrations:[mt("before-shell","preToolUse","bash|powershell"),mt("stop","agentStop"),mt("pre-compact","preCompact"),mt("session-start","sessionStart")],support:"partial"},Ie=[J0,q0,Y0,X0,z0];import{existsSync as Ms,readFileSync as jk,rmSync as Z0,statSync as Q0}from"fs";import{join as js,relative as zd}from"path";var Fk="# ari:managed",tD=493,eD=64,nD=1,Dk=0,$o=[{command:"ari scope --staged",name:"pre-commit"},{command:"ari verify",name:"pre-push"}],rD=["","."].flatMap((t)=>["yml","yaml","json","toml"].map((e)=>`${t}lefthook.${e}`)),Lk=".husky",Mk=/\.ya?ml$/,Gk=$o.map((t)=>t.name);async function To(t){let e=await sn(t,"hooks");return $o.every(({name:n})=>{let r=js(e,n);return Zd(r)&&Uk(r)})}async function ac(t){let e=await Fs(t);for(let n of e)if(n.action!=="unchanged")Rr(n.target,n.script,tD);return{agent:"git",files:e.map(({action:n,hook:r,path:o})=>({action:n,hook:r,path:o}))}}async function Fs(t){let e=await Qd(t);if(e!==null)throw new m(`This repository manages git hooks with ${e.name}; ari will not write hooks beside it`,e.hint);let n=await sn(t,"hooks"),r=$o.map((s)=>({hook:s,path:js(n,s.name),script:oD(s)})),o=r.filter(({path:s})=>Ms(s)&&!Zd(s));if(o.length>0){let s=o.map(({hook:i})=>i.name).join(", ");throw new m(`Unmanaged git hooks already exist: ${s}`,`Add the lines yourself: ${ic("").join("; ")}`)}return r.map(({hook:s,path:i,script:a})=>{let c=Ms(i);return{action:c&&jk(i,"utf8")===a&&Uk(i)?"unchanged":c?"updated":"created",hook:s.name,path:zd(t,i),script:a,target:i}})}async function Hk(t){return zd(t,await sn(t,"hooks"))}async function Gs(t){let e=await sn(t,"hooks");return $o.map(({name:n})=>{let r=js(e,n);return{action:Zd(r)?"removed":"unchanged",hook:n,path:zd(t,r),target:r}})}async function cc(t){let e=await Gs(t);for(let n of e)if(n.action==="removed")Z0(n.target);return{agent:"git",files:e.map(({action:n,hook:r,path:o})=>({action:n,hook:r,path:o}))}}function Zd(t){return Ms(t)&&jk(t,"utf8").includes(Fk)}function Uk(t){return(Q0(t).mode&eD)!==0}function oD(t){return["#!/bin/sh",Fk,"if ! command -v ari >/dev/null 2>&1; then",` echo "ari is not on PATH; install @r5n/ariadne or remove .git/hooks/${t.name}" >&2`," exit 1","fi",`exec ${t.command}`,""].join(`
|
|
144
|
+
`)}async function Qd(t){let e=await F(t,["config","--get","core.hooksPath"],{allowedExitCodes:[Dk,nD]}),n=e.stdout.trim();if(e.exitCode===Dk&&n.length>0)return Xd(`core.hooksPath (${n})`,ic(`${n}/`),"Add the lines yourself: ");let r=rD.find((o)=>Ms(js(t,o)));if(r!==void 0){let o=Mk.test(r)?sD():ic("lefthook ");return Xd(`lefthook (${r})`,o,Mk.test(r)?`Add to ${r}:
|
|
145
|
+
`:"Add the lines yourself: ")}if(Ms(js(t,Lk)))return Xd("husky",ic(`${Lk}/`),"Add the lines yourself: ");return null}function ic(t){return $o.map((e)=>`${t}${e.name}: ${e.command}`)}function Xd(t,e,n){let r=n.endsWith(`
|
|
146
|
+
`)?`
|
|
147
|
+
`:"; ";return{hint:`${n}${e.join(r)}`,lines:e,name:t}}function sD(){return $o.flatMap((t)=>[`${t.name}:`," commands:",` ari-${t.name}:`,` run: ${t.command}`])}import{realpathSync as iD,rmSync as aD}from"fs";import{join as lc}from"path";var uc={read:W,remove:(t,e)=>{aD(iD(lc(t,e)))},write:(t,e,n)=>{Ce(t,e,n)}};function tp(){let t=new Map;return{read:(e,n)=>{let r=lc(e,n);return t.has(r)?t.get(r)??null:W(e,n)},remove:(e,n)=>{t.set(lc(e,n),null)},write:(e,n,r)=>{t.set(lc(e,n),r)}}}var Hs={kind:"none"},Us={kind:"delete"};function xo(t,e){return{exact:e,kind:"write",text:t}}function dc(t,e,n,r){switch(n.kind){case"none":return{action:"unchanged",restored:null};case"delete":return r.remove(t,e),{action:"removed",restored:null};case"write":{let o=Ns(r.read(t,e),n.text);if(o!=="unchanged")r.write(t,e,n.text);return{action:o,restored:n.exact?"original":"entries"}}}}import{existsSync as cD,readFileSync as lD}from"fs";import{join as ep}from"path";var np="hooks.json",uD=384,Kk=sh(Et({installed:X(),original:X().or(Bn())}));function Bk(t,e=np){let n=ep(t,e);if(!cD(n))return{state:"absent"};try{return{path:n,receipts:Kk(JSON.parse(lD(n,"utf8"))),state:"readable"}}catch{return{path:n,state:"unreadable"}}}function Ao(t,e,n=np){return Vk(t,n)[e]??null}function Co(t,e,n,r=np){let{[e]:o,...s}=Vk(t,r);if(n===null&&o===void 0)return;let i=n===null?s:{...s,[e]:n};Rr(ep(t,r),`${JSON.stringify(i)}
|
|
148
|
+
`,uD)}function Vk(t,e){return nc(ep(t,e),Kk,{})}var dD="ari hook",pD=1;function rp(t,e){return`${dD} ${t} ${e}`}function qk(t,e,n){let{file:r,name:o}=e,s=W(t,r),i=s===null?{}:re(r,s),a=Ao(n,r),c=sp(i,e)?void 0:s,l=a?.installed===s?a?.original:c,u=Ce(t,r,Ks(e,s)),d=W(t,r)??"";return Co(n,r,l===void 0?null:{installed:d,original:l}),{action:u,agent:o,events:Bs(e),file:r}}function Ks(t,e){let n=e===null?{}:re(t.file,e);return zn(e,Yk(n,t,t.registrations))}function pc(t,e,n){let{action:r}=op(t,e,{forget:!0,state:n,view:uc});return{action:r,agent:e.name,file:e.file}}function gD(t,e,n){if(e===null)return Hs;let r=re(t.file,e);if(!sp(r,t))return Hs;if(n?.installed!==e)return xo(zn(e,Yk(r,t,[])),!1);return n.original===null?Us:xo(n.original,!0)}function op(t,e,n){let{file:r}=e,{forget:o,state:s,view:i}=n,a=Ao(s,r),c=dc(t,r,gD(e,i.read(t,r),a),i);if(o)Co(s,r,null);return c}function un(t,e){let n=ec(t,e.file);return n!==null&&sp(n,e)}function Bs(t){return[...new Set(t.registrations.map((e)=>e.event))]}function sp({hooks:t},e){if(!z(t))return!1;return Object.values(t).flat().some((n)=>Xk(n,e).length>0)}function Yk({hooks:t={},...e},n,r){if(!z(t))throw Wk(n,'"hooks" value that is not an object');let s=[...new Set([...Object.keys(t),...r.map(({agentEvent:a})=>a)])].flatMap((a)=>{let c=t[a]??[];if(!Array.isArray(c))throw Wk(n,`hooks.${a} that is not a list`);let l=mD(c,n,r.filter(({agentEvent:u})=>u===a));return l.length===0&&c.length>0?[]:[[a,l]]}),i=n.layout==="flat"?{version:e.version??pD}:{};return{...e,...i,...s.length===0?{}:{hooks:Object.fromEntries(s)}}}function Wk({file:t},e){return new m(`${t} has a ${e}`,`Fix ${t}`)}function mD(t,e,n){let r=new Set(n);return[...t.flatMap((s)=>{let i=Xk(s,e),a=[...r].filter(({event:c})=>i.includes(rp(e.name,c)));for(let c of a)r.delete(c);return[...fD(s,e),...a.map((c)=>Jk(e,c))]}),...[...r].map((s)=>Jk(e,s))]}function Jk(t,e){let n=t.handler(rp(t.name,e.event),e);if(t.layout==="flat")return n;return e.matcher===null?{hooks:[n]}:{hooks:[n],matcher:e.matcher}}function fD(t,e){let n=zk(t,e),r=n.filter((o)=>Zk(o,e).length===0);if(r.length===n.length)return[t];return r.length>0&&z(t)?[{...t,hooks:r}]:[]}function Xk(t,e){return zk(t,e).flatMap((n)=>Zk(n,e))}function zk(t,{layout:e}){if(e==="flat")return[t];return z(t)&&Array.isArray(t.hooks)?t.hooks:[]}function Zk(t,{name:e}){let n=z(t)?Object.values(t):[],r=rp(e,"");return n.filter((o)=>typeof o==="string"&&o.startsWith(r))}import{join as G1,resolve as jv}from"path";var Qk=1.2,tw=0.75,ew=0.5,hD=/[\p{Variation_Selector}\p{Me}]/gu,yD=/[\p{L}\p{N}][\p{L}\p{M}\p{N}]*/gu;function nw(t){return t.normalize("NFC").toLowerCase().replace(hD,"").match(yD)??[]}function gc(t,e){let n=[...new Set(nw(t))].sort(O),r=e.map(kD),o=r.reduce((a,c)=>a+c.length,0),s=r.length===0?0:o/r.length,i=new Map(n.map((a)=>[a,wD(a,r)]));return r.map((a)=>({id:a.id,score:SD(a,n,i,s)})).sort((a,c)=>c.score-a.score||O(a.id,c.id))}function kD(t){let e=nw(t.text),n=new Map;for(let r of e)n.set(r,(n.get(r)??0)+1);return{frequencies:n,id:t.id,length:e.length}}function wD(t,e){let n=e.filter((r)=>r.frequencies.has(t)).length;return Math.log(1+(e.length-n+ew)/(n+ew))}function SD(t,e,n,r){let o=r===0?1:t.length/r,s=Qk*(1-tw+tw*o);return e.reduce((i,a)=>{let c=t.frequencies.get(a)??0,l=n.get(a)??0;return i+l*c*(Qk+1)/(c+s)},0)}function yt(t){return Buffer.byteLength(t,"utf8")}function ip(t){return Math.ceil(yt(t)/4)}import{readFileSync as tS}from"fs";import{join as eS}from"path";var vD=1000,bD=2147483647,ED=60,iw=8192,aw=iw*2,$D=1000,TD=`exec 2>&1
|
|
149
|
+
`,xD=192,AD=128,rw=`
|
|
150
|
+
`,CD=[126,127],ow=128,RD=31;async function cw(t,e){let n=performance.now(),r=Bun.spawn(["sh","-c",`${TD}${t}`],{cwd:e.cwd,detached:!0,env:{...process.env,...Fe},stderr:"pipe",stdin:"ignore",stdout:"pipe"}),o=Qt(()=>ap(r.pid));try{return await ID(r,t,e,n)}finally{o()}}async function ID(t,e,n,r){let o={hasher:new Bun.CryptoHasher("sha256"),window:new Uint8Array},s=[t.stdout.getReader(),t.stderr.getReader()],i=Promise.all(s.map((u)=>OD(u,o))),a={timedOut:!1},c=setTimeout(()=>{a.timedOut=!0,ap(t.pid)},Math.min(n.timeoutSeconds*vD,bD));await t.exited,clearTimeout(c);let l=await _D(i,$D);if(ap(t.pid),!l)await Promise.all(s.map((u)=>u.cancel()));return{command:e,durationMs:Math.round(performance.now()-r),exitCode:t.exitCode,outputSha256:o.hasher.digest("hex"),outputTail:pw(o.window),timedOut:a.timedOut}}function lw(t){return t.exitCode===0&&!t.timedOut}function uw(t){return t.exitCode!==0&&!t.timedOut&&!cp(t)&&!lp(t)}function cp(t){let{exitCode:e}=t;return e===null||e>ow&&e<=ow+RD}function lp(t){return t.exitCode!==null&&!t.timedOut&&CD.includes(t.exitCode)}async function OD(t,e){for(;;){let{done:n,value:r}=await t.read();if(n)return;e.hasher.update(r),e.window=up(PD(e.window,r),aw)}}async function _D(t,e){let n,r=new Promise((s)=>{n=setTimeout(()=>s(!1),e)}),o=await Promise.race([t.then(()=>!0),r]);return clearTimeout(n),o}function ap(t){Ge(t,"SIGKILL")}function dw(t){return pw(up(new TextEncoder().encode(t),aw))}function pw(t){let n=new TextDecoder().decode(sw(t)).split(rw);if(n.at(-1)==="")n.pop();let r=new TextEncoder().encode(n.slice(-ED).join(rw));return new TextDecoder().decode(sw(up(r,iw)))}function sw(t){let e=0;while(e<t.length&&((t[e]??0)&xD)===AD)e++;return t.subarray(e)}function up(t,e){return t.length<=e?t:t.subarray(t.length-e)}function PD(t,e){let n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function kt(t,e,n,r=[],o=[]){return{checks:[...o],details:[...r],gate:t,ok:e,summary:n}}async function Je(t,e,n){let r=[];for(let o of t){let s=await cw(o.run,{cwd:n,timeoutSeconds:o.timeoutSeconds});r.push(ND(o.name,e,s))}return r}async function Vs(t,e,n,r,o){return await Xn(t,e),Je(n,r,o)}function ND(t,e,n){let r=e==="pass"?lw(n):uw(n);return{...n,expect:e,name:t,ok:r}}function dp(t){return`${t.name} should ${t.expect} but ${DD(t)}`}function Or(t){return t.filter((e)=>!e.ok).map(dp)}function wt(t,e,n){return t===1?e:n}function DD(t){if(t.timedOut)return`timed out after ${t.durationMs} ms`;if(lp(t))return`could not run (exit code ${t.exitCode})`;if(!cp(t))return`exited with ${t.exitCode}`;return t.exitCode===null?"was killed by a signal":`was killed by a signal (exit code ${t.exitCode})`}import{copyFileSync as VD,mkdirSync as WD,readlinkSync as JD,rmSync as gp,symlinkSync as qD}from"fs";import{dirname as YD,join as fc}from"path";import{existsSync as LD,mkdtempSync as MD,readFileSync as jD,realpathSync as FD,rmSync as gw}from"fs";import{tmpdir as GD}from"os";import{join as pp}from"path";var Ws=0,mw=128,HD="gitdir",UD=".git",KD=["-c","core.hooksPath=/dev/null"];async function mc(t,e,n){let r=FD(MD(pp(GD(),Cs))),o={admin:null,directory:r},s=Qt(()=>fw(t,o));try{return await BD(t,e,o),await n(r)}finally{fw(t,o),s()}}async function BD(t,e,n){let{directory:r}=n,o=await F(t,[...KD,"worktree","add","--detach",r,e],{allowedExitCodes:[Ws,mw],env:{GIT_INDEX_FILE:void 0}});if(o.exitCode!==Ws)throw Error(`git worktree add ${r} ${e} failed in ${t}: ${vd(o.stderr)}`);let s=await F(r,["rev-parse","--absolute-git-dir"],{allowedExitCodes:[Ws,mw],env:Fe}),i=s.stdout.trim();if(s.exitCode===Ws&&hw(i,r))n.admin=i}function fw(t,e){let{admin:n,directory:r}=e,o=Bun.spawnSync(["git","worktree","remove","--force",r],{cwd:t,env:{...process.env,GIT_INDEX_FILE:void 0},stderr:"ignore",stdin:"ignore",stdout:"ignore"});if(gw(r,{force:!0,recursive:!0}),o.exitCode===Ws||n===null)return;if(hw(n,r))gw(n,{force:!0,recursive:!0})}function hw(t,e){let n=pp(t,HD);return LD(n)&&jD(n,"utf8").trim()===pp(e,UD)}var XD="@base",zD=12;async function yw(t){let e=t.contract.checks.filter((p)=>p.expect==="regression");if(e.length===0)return kt("regression",!1,"the contract has no check with expect: regression");let n=t.base.slice(0,zD),r=ne(t.changedFiles).filter((p)=>et(p,t.config.testGlobs)),o=await mc(t.root,t.base,(p)=>ZD(t,e,r,p)),s=await Je(e,"pass",t.root),i=[...o.setup,...o.checks,...s],c=o.setup.some((p)=>!p.ok)?[`regression checks did not run on ${n} because its setup failed`]:[],l=[...Or(i),...c],u=l.length===0,d=u?`every regression check fails on ${n} and passes on the working tree`:`${l.length} regression ${wt(l.length,"problem","problems")} against ${n}`;return kt("regression",u,d,l,i)}async function ZD(t,e,n,r){for(let a of n)tL(t.root,r,a);let o=QD(t.config),s=o.length===0?[]:await Vs({config:t.config,root:t.root},"run regression.setup",o,"pass",r);if(s.some((a)=>!a.ok))return{checks:[],setup:s};let i=e.map((a)=>({...a,name:`${a.name}${XD}`}));return{checks:await Je(i,"fail",r),setup:s}}function QD(t){return t.regression.setup.map((e,n)=>({name:`setup[${n}]`,run:e,timeoutSeconds:t.checkTimeoutSeconds}))}function tL(t,e,n){let r=fc(t,n),o=fc(e,n),s=Te(t,n)?null:$e(r);if(s===null){eL(e,n);return}if(!s.isFile()&&!s.isSymbolicLink())return;if(kw(e,n),gp(o,{force:!0,recursive:!0}),s.isFile())VD(r,o);else qD(JD(r),o)}function eL(t,e){let n=fc(t,e);if(Te(t,e)||$e(n)?.isDirectory()!==!1)return;gp(n,{force:!0})}function kw(t,e){let n=YD(e);if(n===".")return;kw(t,n);let r=fc(t,n),o=$e(r);if(o?.isDirectory())return;if(o!==null)gp(r,{force:!0});WD(r)}import{readFileSync as TM}from"fs";import{join as xM}from"path";var Zn="candidates",nL=["confirmed","false_positive","deferred","uncertain"],rL=["id","verdict","rationale"],mp="argus verdicts: ";function ww(t,e){if(t===void 0)return{answers:[],warnings:[]};if(!Array.isArray(t))return sL(`${Zn} must be a list, so no answer was sent`);let n=[],r=[];for(let[i,a]of t.entries())try{r.push(oL(a,k(Zn,i),e))}catch(c){if(!(c instanceof b))throw c;n.push(`${mp}${c.message}; dropped`)}let o=new Map;for(let i of r)o.set(i.id,(o.get(i.id)??0)+1);for(let[i,a]of o)if(a>1)n.push(`${mp}candidate ${i} was answered more than once; none of its answers was sent`);return{answers:r.filter((i)=>o.get(i.id)===1).map(({rationale:i,reviewId:a,verdict:c})=>({rationale:i,reviewId:a,verdict:c})),warnings:n}}function oL(t,e,n){let r=T(t,e,rL),o=nt(r.id,k(e,"id")),s=n.get(o);if(s===void 0)throw new b(`${e}.id ${JSON.stringify(o)} is not a candidate of this review`);return{id:o,rationale:nt(r.rationale,k(e,"rationale")),reviewId:s,verdict:K(nL,r.verdict,k(e,"verdict"))}}function sL(t){return{answers:[],warnings:[`${mp}${t}`]}}import{realpathSync as Pw}from"fs";import{readFileSync as iL,realpathSync as aL}from"fs";import{join as cL,sep as lL}from"path";var uL="reviews",Sw=8,dL=/^[a-f0-9]{64}$/,pL=Et({reviewer:Et({promptVersion:X()}),snapshotId:X(),verdicts:no(Et({reviewId:X()}))});function vw(t,e,n){let r=cL(n.stateDirectory,uL),o;try{let l=aL(t.verdictFile);if(!l.startsWith(`${r}${lL}`))return`its verdict template ${t.verdictFile} is not in ${r}`;o=pL(JSON.parse(iL(l,"utf8")))}catch{return`its verdict template ${t.verdictFile} cannot be read`}if(o.snapshotId!==t.id)return"its verdict template belongs to another snapshot";let s=o.verdicts.map((l)=>l.reviewId),i=new Set(s.filter((l)=>dL.test(l))),a=e.filter((l)=>i.has(l.reviewId)),c=gL(a.map((l)=>l.reviewId));return{candidates:a.map((l)=>({...l,id:l.reviewId.slice(0,c)})),offer:{configPath:n.configPath,promptVersion:o.reviewer.promptVersion,reviewIds:s,snapshotId:t.id}}}function gL(t){let e=Math.max(Sw,...t.map((n)=>n.length));for(let n=Sw;n<e;n+=1)if(new Set(t.map((r)=>r.slice(0,n))).size===t.length)return n;return e}function bw(t,e){return new Map(t.slice(0,e).flatMap((n)=>n.id===void 0?[]:[[n.id,n.reviewId]]))}var Ew="ArgusStartFailed",fp=16777216,mL=1;async function hc(t,e,n,r){try{return await Dd(n,{action:e==="import"?"start argus to import review verdicts":"start argus to collect review evidence",cwd:t.root,environment:Is(ba(e)),maxCaptureBytes:fp,reapGroup:!0,startFailure:(o,s)=>new m(`argus could not start: ${o}`,"Install argus or fix review.argus.command",mL,{cause:s,tag:Ew}),stdout:"capture",timeoutSeconds:r,trust:{config:t.config,root:t.root}})}catch(o){if(o instanceof m&&o._tag===Ew)return o.message;throw o}}var fL=1,hL=300,$w="...",yL=/\p{Cc}+/gu,kL=Et({choice:X(),confidence:yr()}),wL=Et({evaluation:Et({answer:kL}).or(Bn()),flagged:ha(),line:yr(),path:X(),question:X(),reviewId:X(),status:X(),target:X()}),SL=Et({results:no(wL),root:X(),snapshotId:X().or(Bn()).or(Lu()),verdictFile:X().or(Bn()).or(Lu())}),vL=Et({error:Et({message:X()})});function xw(t,e){let n;try{n=JSON.parse(t)}catch{return{kind:"invalid"}}let r=Tw(()=>SL(n));if(r!==null)return bL(r,e);let o=Tw(()=>vL(n));if(o===null)return{kind:"invalid"};return{kind:"failure",message:Js(o.error.message,hL)}}function bL(t,e){let n=t.results.filter((s)=>e.has(s.path)),r=n.flatMap((s)=>{let i=s.evaluation?.answer;if(s.status!=="checked"||!s.flagged||i===void 0)return[];if(!Number.isInteger(s.line)||s.line<fL)return[];let{line:a,path:c,question:l,reviewId:u,target:d}=s;return[{answer:i.choice,confidence:i.confidence,line:a,path:c,question:l,reviewId:u,target:d}]}),o=(s)=>n.filter((i)=>i.status===s).length;return{candidates:r.sort($L),counts:{blocked:o("blocked"),checked:o("checked"),pending:o("pending")},kind:"report",root:t.root,snapshot:EL(t)}}function EL(t){let{snapshotId:e,verdictFile:n}=t;return typeof e==="string"&&typeof n==="string"?{id:e,verdictFile:n}:null}function $L(t,e){return e.confidence-t.confidence||O(t.path,e.path)||t.line-e.line||O(t.question,e.question)}function Js(t,e){let n=t.replace(yL," ").trim();return n.length>e?`${n.slice(0,e-$w.length)}${$w}`:n}function Tw(t){try{return t()}catch{return null}}import{existsSync as TL,realpathSync as Cw}from"fs";import{dirname as xL,join as AL,relative as CL,resolve as RL,sep as Rw}from"path";var IL=["cache","reports","reviews","verifications"],OL="ari-probe",Iw=1,Aw=0,_L=1;function Ow(t,e){let n=RL(t,e);if(!TL(n))return{location:null,problem:`the argus config ${e} does not exist`};try{return{location:{configPath:n,stateDirectory:Cw(xL(n))},problem:null}}catch{return{location:null,problem:`the directory of the argus config ${e} cannot be read`}}}async function _w(t,e){let n=Cw(t);for(let r of IL){let o=AL(e.stateDirectory,r);if(!PL(n,o))continue;let s=CL(n,o).split(Rw).join("/");if(await NL(t,`${s}/${OL}`))continue;throw new m(`Cannot run argus: its state directory ${s} is inside the repository and git does not ignore it, so running argus would change the working tree that the review hashes`,`Keep the argus config outside the repository, for example 'argus init --root . --config <directory outside the repository>/config.json', or add ${s}/ to .gitignore. Pass --no-argus to review without it`,Iw,{tag:"ArgusStateInRepository"})}}async function yc(t,e,n="collected evidence"){if(await Ae(t,[])===e)return;throw new m(`The working tree changed while argus ${n}, so the review stops`,"Keep the state of the argus config outside the repository or ignored by git, make sure that the argus command only reads the project, and leave the files alone while the review runs",Iw,{tag:"ArgusChangedTree"})}function PL(t,e){return e===t||e.startsWith(`${t}${Rw}`)}async function NL(t,e){try{return(await F(t,["check-ignore","--quiet","--",e],{allowedExitCodes:[Aw,_L]})).exitCode===Aw}catch{return!1}}var DL=1,LL=500,Nw={blocked:0,checked:0,pending:0},ML=/[\\*?[\]{}()!@+,#]/g,jL="argus (run) was allowed to send the source of the changed files to its model endpoint",FL=0,GL=1;async function Dw(t){let{argus:e,changedFiles:n,root:r}=t,o=e.mode==="run"||e.verdicts===!0,s=o?BL(n):{files:[],warnings:[]};if(o?s.files.length===0:n.length===0)return wc(e.mode,!0,[],Nw,[]);let a=Ow(r,e.config);if(a.location===null)return kc(t,a.problem);await _w(r,a.location);let c={base:t.base,configPath:a.location.configPath,only:s.files.map(VL).join(`
|
|
151
|
+
`)};if(e.mode==="run")t.notify?.(JL(e.limit));let l=await HL(t,c);if(typeof l==="string")return kc(t,l);if(e.verdicts!==!0)return wc(e.mode,!0,l.candidates,l.counts,s.warnings);if(l.snapshot===null)return kc(t,"argus report create saved no snapshot");let u=vw(l.snapshot,l.candidates,a.location);if(typeof u==="string")return kc(t,u);return{...wc(e.mode,!0,u.candidates,l.counts,s.warnings),offer:u.offer}}function Lw(t,e,n){let r=e?.included??0;return{blocked:t.counts.blocked,candidates:t.candidates.length,checked:t.counts.checked,included:r,mode:t.mode,modelRequestsAllowed:t.used&&t.mode==="run",omitted:t.candidates.length-r,pending:t.counts.pending,used:t.used,warnings:[...t.warnings,...n?.warnings??[]],...n===void 0?{}:{verdicts:n.verdicts}}}async function HL(t,e){let n="argus was not asked anything";for(let r of va(t.argus).filter((o)=>o!=="import"))if(n=await UL(t,r,e),typeof n==="string")return n;return n}async function UL(t,e,n){let r=t.argus.timeoutSeconds??t.config.checkTimeoutSeconds,o=await hc(t,e,so(t.argus,e,n),r);if(typeof o==="string")return o;if(o.timedOut)return`argus did not finish within ${r} seconds`;if(o.overflowed)return`argus printed more than ${fp} bytes`;let s=xw(o.stdout,new Set(t.changedFiles));if(s.kind==="failure")return`argus failed: ${s.message}`;if(s.kind==="invalid"||![FL,GL].includes(o.exitCode))return`argus exited with ${o.exitCode} and did not print its JSON report`;if(!WL(s.root,t.root))return`its project root ${s.root} is not the root of this repository`;return s}function Sc(t){let{candidates:e,checked:n,included:r,mode:o,omitted:s,pending:i,blocked:a}=t;if(!t.used)return t.warnings;let c=s===0?`${r} added to the prompt`:`${r} added to the prompt, ${s} left out`,l=`${n} checks answered, ${i} without an answer, ${a} blocked`,u=t.modelRequestsAllowed?[jL]:[];return[`argus (${o}): ${e} candidates in the changed files, ${c}; ${l}`,...u,...t.verdicts===void 0?[]:[KL(t.verdicts)],...t.warnings]}function KL({answered:t,offered:e,saved:n,sent:r}){return`argus verdicts: ${e} candidates offered to the reviewer, ${t} answered, ${r} sent to argus, ${n} saved`}function kc(t,e){if(!t.explicit&&t.verdictsExplicit!==!0)return wc(t.argus.mode,!1,[],Nw,[`argus gave no evidence: ${e}`]);let n=t.verdictsExplicit===!0?"--argus-verdicts":"--argus";throw new m(`argus was requested with ${n}, but ${e}`,`Fix review.argus in .ari/config.json, run the argus command yourself to see why it fails, or leave out ${n} to review without it`,DL,{tag:"ArgusUnavailable"})}function wc(t,e,n,r,o){return{candidates:n,counts:r,mode:t,offer:null,used:e,warnings:o}}function BL(t){let e=t.filter((s)=>!s.includes(`
|
|
152
|
+
`)),n=e.slice(0,LL),r=e.length-n.length,o=`argus was asked about the first ${n.length} changed files; ${r} more were left out`;return{files:n,warnings:r>0?[o]:[]}}function VL(t){return t.replace(ML,"\\$&")}function WL(t,e){try{return Pw(t)===Pw(e)}catch{return t===e}}function JL(t){return`argus (mode run) may send the source of the changed files to its model endpoint, in at most ${t} requests`}import{mkdtempSync as qL,rmSync as YL,writeFileSync as XL}from"fs";import{tmpdir as zL}from"os";import{join as Mw}from"path";var ZL="verdicts.json",QL=384,tM=2,eM=300,jw="argus verdicts: ",nM=Et({imported:yr()}).or(Et({error:Et({message:X()})}));async function Fw(t){let{answers:e}=t;if(e.length===0)return{saved:0,sent:0,warnings:[]};let n=qL(Mw(zL(),Ey)),r=()=>YL(n,{force:!0,recursive:!0}),o=Qt(r);try{let s=Mw(n,ZL);return XL(s,`${JSON.stringify(oM(t),null,tM)}
|
|
153
|
+
`,{mode:QL}),await rM(t,s)}finally{r(),o()}}async function rM(t,e){let{answers:n,base:r,context:o,offer:s,seconds:i}=t,a=so(o.argus,"import",{base:r,configPath:s.configPath,file:e,only:null}),c=n.length,l=await hc(o,"import",a,i);if(typeof l==="string")return vc(c,l);if(l.timedOut)return vc(c,`argus did not finish importing within ${i} seconds`);let u=sM(l.stdout);if(u===null)return vc(c,`argus exited with ${l.exitCode} and did not print its JSON result`);if("error"in u)return vc(c,`argus rejected the verdicts: ${Js(u.error.message,eM)}`);let d=u.imported<c?[`${jw}argus saved ${u.imported} of ${c} verdicts`]:[];return{saved:u.imported,sent:c,warnings:d}}function oM({answers:t,model:e,offer:n}){let r=new Map(t.map((o)=>[o.reviewId,o]));return{snapshotId:n.snapshotId,verdicts:n.reviewIds.map((o)=>{let s=r.get(o);return{evidence:[],rationale:s?.rationale??"",reviewId:o,verdict:s?.verdict??""}}),version:2,...e===null?{}:{reviewer:{model:e,promptVersion:n.promptVersion}}}}function sM(t){try{return nM(JSON.parse(t))}catch{return null}}function vc(t,e){return{saved:0,sent:t,warnings:[`${jw}${e}; nothing was saved, and the review is not affected`]}}var iM="argus verdicts: the review did not finish cleanly, so no answer was sent";async function Gw(t){let{before:e,clean:n,found:r,input:o,model:s,offered:i,written:a}=t,{offer:c}=r;if(c===null)return null;let l=ww(a,i),u={answered:l.answers.length,offered:i.size,saved:0,sent:0,snapshotId:c.snapshotId};if(!n)return{verdicts:u,warnings:[...l.warnings,...l.answers.length===0?[]:[iM]]};let d=o.argus.timeoutSeconds??o.config.checkTimeoutSeconds,p=await Fw({answers:l.answers,base:o.base,context:o,model:s,offer:c,seconds:d});if(p.sent>0)await yc(o.root,e,"imported the verdicts");return{verdicts:{...u,saved:p.saved,sent:p.sent},warnings:[...l.warnings,...p.warnings]}}var aM=120,cM=2,_r=`
|
|
154
|
+
`,lM="## Candidates from a decision model (not verified defects)",Hw=["A decision model answered review questions about the files that this change touches, and flagged the answers below.","Each line is a lead, not a finding: the model can be wrong, and a file without a lead is not thereby clean.","Check a lead against the code before you report it, and judge the change by the contract, as above."].join(_r),uM=[`Each lead has an ID in square brackets. You may answer a lead that you checked against the code, in the same JSON object, under an optional "${Zn}" key:`,`"${Zn}":[{"id":"<ID>","verdict":"confirmed","rationale":"<why, citing the code>"}]`,"A verdict is confirmed (a real problem), false_positive (not a problem), deferred (real, but fine to leave in this change) or uncertain (you cannot tell).","Answer only the leads that you checked and leave the others out; a lead that you leave out stays unreviewed. These answers are stored with the decision model's candidates and never change your own verdict or findings."].join(_r);function Kw(t,e){let r=t.some((a)=>a.id!==void 0)?`${Hw}${_r}${uM}`:Hw,o=`${lM}${_r}${_r}${r}${_r}`,s=[];for(let a of t){let c=[...s,dM(a)],l=Uw(o,c,t.length-c.length,e);if(Buffer.byteLength(l)>e)break;s=c}if(s.length===0)return null;let i=t.length-s.length;return{included:s.length,omitted:i,text:Uw(o,s,i,e)}}function Uw(t,e,n,r){let o=n===0?[]:[pM(n,r)];return[t,...e,...o].join(_r)}function dM(t){let e=`${bc(t.path)}:${t.line}`,n=t.confidence.toFixed(cM);return`- ${t.id===void 0?"":`[${t.id}] `}${e} ${bc(t.target)}: question "${bc(t.question)}", answer "${bc(t.answer)}", confidence ${n}`}function pM(t,e){return`(${t} more candidate${t===1?"":"s"} left out to stay within ${e} bytes)`}function bc(t){return Js(t.replaceAll('"',"'"),aM)}var hp=["critical","major","minor","info"],gM=["critical","major"],mM=["pass","fail"],fM=["verdict","findings"],Bw=["severity","file","line","summary"],hM=/^```(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n```$/;function Vw(t,e=[]){let n=t.trim();if(n.length===0)return{extras:{},problem:"the review agent printed nothing",verdict:null};let r=hM.exec(n)?.[1]??n,o;try{o=JSON.parse(r)}catch{return{extras:{},problem:"the review agent's answer is not one JSON object",verdict:null}}try{let s=T(o,"verdict object",[...fM,...e]);return{extras:Object.fromEntries(e.filter((a)=>(a in s)).map((a)=>[a,s[a]])),problem:null,verdict:yM(s)}}catch(s){if(s instanceof b)return{extras:{},problem:`the review agent's answer: ${s.message}`,verdict:null};throw s}}function Ww(t){return t.findings.filter((e)=>gM.includes(e.severity))}function Ec(t){let e=t.file===null?"":` ${t.file}${t.line===null?"":`:${t.line}`}`;return`${t.severity}${e}: ${t.summary}`}function yM(t){let e=K(mM,t.verdict,"verdict");return{findings:L(t.findings,"findings",kM),verdict:e}}function kM(t,e){let n=T(t,e,Bw);for(let r of Bw)if(!(r in n))throw new b(`${k(e,r)} is required`);return{file:n.file===null?null:nt(n.file,k(e,"file")),line:n.line===null?null:Kt(n.line,k(e,"line")),severity:K(hp,n.severity,k(e,"severity")),summary:nt(n.summary,k(e,"summary"))}}var qw=120000,wM=20000,SM=3,vM=12,qs=`
|
|
132
155
|
|
|
133
|
-
`,
|
|
134
|
-
`),["Answer with exactly one JSON object and nothing else, for example:",
|
|
156
|
+
`,Jw="```",bM='{"verdict":"fail","findings":[{"severity":"major","file":"src/a.ts","line":12,"summary":"\u2026"}]}';function Yw(t){let{contract:e,stage:n}=t,r=[[`You review a change for the Ariadne task "${e.id}" (${e.title}), at stage ${n}.`,"You run in a temporary copy of the repository. Read any file you need, but change nothing: a changed file fails the review.","Judge the change against the task's contract: does it meet every acceptance criterion, stay inside the scope, and avoid bugs, regressions and risky code?"].join(`
|
|
157
|
+
`),["Answer with exactly one JSON object and nothing else, for example:",bM,'- "verdict" is "pass" when the change meets the contract and has no critical or major problem, otherwise "fail".',`- "severity" is one of ${hp.join(", ")}; "file" and "line" may be null; "findings" may be empty.`].join(`
|
|
135
158
|
`),`## Contract (${t.contractPath})
|
|
136
159
|
|
|
137
|
-
${t.contractText.trim()}`,[`## Files changed since ${t.base.slice(0,
|
|
138
|
-
`)].join(
|
|
160
|
+
${t.contractText.trim()}`,[`## Files changed since ${t.base.slice(0,vM)}`,"",...t.changedFiles.length===0?["(none)"]:t.changedFiles.map((c)=>`- ${c}`)].join(`
|
|
161
|
+
`)].join(qs),o=EM(t,r),s=o===null?r:[r,o.text].join(qs),i=qw-Buffer.byteLength(s)-qs.length*2,a=[s,`## Diff
|
|
139
162
|
|
|
140
|
-
${
|
|
141
|
-
${$
|
|
142
|
-
${
|
|
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=`
|
|
163
|
+
${Jw}diff
|
|
164
|
+
${$M(t.diff,i)}
|
|
165
|
+
${Jw}`].join(qs);return{argus:o,prompt:a}}function EM(t,e){if(t.argus===void 0)return null;let n=qw-Buffer.byteLength(e)-qs.length*SM;return Kw(t.argus.candidates,Math.max(0,Math.min(t.argus.maxBytes,n-wM)))}function $M(t,e){let n=Buffer.from(t.trimEnd());if(n.length<=e)return n.toString();let r=`
|
|
166
|
+
[diff truncated after ${e} bytes; read the changed files in the copy]`;return`${n.subarray(0,Math.max(0,e-Buffer.byteLength(r))).toString().replace(/\uFFFD$/,"")}${r}`}var AM={GIT_AUTHOR_DATE:"@0 +0000",GIT_AUTHOR_EMAIL:"ari@localhost",GIT_AUTHOR_NAME:"ari",GIT_COMMITTER_DATE:"@0 +0000",GIT_COMMITTER_EMAIL:"ari@localhost",GIT_COMMITTER_NAME:"ari"},Xw=["--no-color","--no-ext-diff","--no-textconv","--no-renames"],zw=[":(glob,exclude).ari/tasks/*.json",":(glob,exclude).ari/knowledge/**"],CM="review:",RM=1;async function Zw(t){let{config:e,root:n,task:r}=t,{agent:o,model:s}=e.review,i=Cr(e,{agent:o,model:s,role:"review",route:null}),a=TM(xM(n,It(r.contract.id)),"utf8"),{argus:c}=e.review,l=await yp({...t,contractText:a,...c===void 0?{}:{argus:{argus:c,explicit:!1}}},i),u=l.ok?"passed":"failed",d=[...l.problems,...l.findings.map(Ec),...l.argus===void 0?[]:Sc(l.argus)],p=`the review agent ${l.agent} ${u} the change`;return kt("review",l.ok,p,d,[l.evidence])}async function yp(t,e){let{config:n,root:r,task:o}=t,s=OM(o);await Xn({config:n,root:r},`start the agent "${e.name}"`);let i=await Ae(r,[]),a=await IM(r,i,s,o.contract.id),c=Ke((await F(r,["diff","--name-only","-z",...Xw,s,a,"--",".",...zw])).stdout),l=t.argus===void 0?null:await Dw({...t.argus,base:s,changedFiles:c,config:n,root:r});if(l!==null)await yc(r,i);let u=(await F(r,["diff",...Xw,s,a,"--",".",...zw])).stdout,{argus:d,prompt:p}=Yw({...l===null||t.argus===void 0?{}:{argus:{candidates:l.candidates,maxBytes:t.argus.argus.maxBytes}},base:s,changedFiles:c,contract:o.contract,contractPath:It(o.contract.id),contractText:t.contractText,diff:u,stage:t.stage}),g=e.config.timeoutSeconds??n.checkTimeoutSeconds,f=performance.now(),y=await mc(r,a,async(Q)=>{let Xr=await Ya(e,p,{cwd:Q,environment:qa(e.config),stdout:"capture",timeoutSeconds:g,trust:{config:n,root:r}});return{copyChanged:await Ae(Q,[])!==i,ran:Xr}}),S=Math.round(performance.now()-f),I=await Ae(r,[])!==i,{ran:C}=y,q=d===null||l===null?new Map:bw(l.candidates,d.included),G=Vw(C.stdout,q.size===0?[]:[Zn]),N=G.verdict===null?[]:Ww(G.verdict),H=[...C.timedOut?[`the review agent did not finish within ${g} seconds`]:[],...!C.timedOut&&C.exitCode!==0?[`the review agent exited with ${C.exitCode}`]:[],...C.overflowed?["the review agent printed more than 1 MiB"]:[],...y.copyChanged?["the review agent changed files in its copy of the repository"]:[],...I?["the working tree changed while the review ran"]:[]],A=[...H,...G.problem===null?[]:[G.problem],...G.verdict?.verdict==="pass"&&N.length>0?[`the verdict is pass, but ${N.length} finding(s) are critical or major`]:[]],R=A.length===0&&G.verdict?.verdict==="pass",B={command:Ja(e,Zt).join(" "),durationMs:S,exitCode:C.timedOut?null:C.exitCode,expect:"pass",name:`${CM}${e.name}`,ok:R,outputSha256:Z(C.stdout),outputTail:dw(C.stdout),timedOut:C.timedOut},_t=l===null||t.argus===void 0?null:await Gw({before:i,clean:G.verdict!==null&&H.length===0,found:l,input:{argus:t.argus.argus,base:s,config:n,root:r},model:e.model,offered:q,written:G.extras[Zn]});return{agent:e.name,...l===null?{}:{argus:Lw(l,d,_t??void 0)},durationMs:S,evidence:B,exitCode:C.exitCode,findings:G.verdict?.findings??[],model:e.model,ok:R,problems:A,timedOut:C.timedOut,verdict:G.verdict?.verdict??null}}async function IM(t,e,n,r){let o=`ari review snapshot of ${r}`;return(await F(t,["commit-tree","--no-gpg-sign",e,"-p",n,"-m",o],{env:AM})).stdout.trim()}function OM(t){if(t.record.base!==null)return t.record.base;throw new m(`Task "${t.contract.id}" has not started, so it has no change to review`,`Run 'ari start ${t.contract.id}' first`,RM,{tag:"TaskNotStarted"})}var _M="{id}",PM=[".ari/tasks/**",".ari/knowledge/**"];async function wp(t){let e=Nn(t.task,t.pack),r={...t,changedFiles:()=>xe(t.root,rS(t.task)),stage:e},o=[],s=[];for(let[i,a]of e.gates.entries()){let c=await NM(a,r);if(o.push(c),c.ok&&UM(a)&&i<e.gates.length-1)s.push({index:i,result:await KM(a.kind,c,r)})}for(let i of s)o[i.index]=await i.result();return o}function Nn(t,e){let n=e.stages[t.record.stage];if(n)return n;throw new m(`Task "${t.contract.id}" is at stage ${t.record.stage}, but pack "${e.name}" has ${e.stages.length}`,`Restore the stages of pack "${e.name}", or amend the task's pack`)}async function Ys(t,e,n){let r=await An(t,e.testGlobs);return Object.fromEntries(Object.entries(r).filter(([o])=>!yo(o)&&et(o,n.scope)))}async function Sp(t,e,n){let o=e.gates.flatMap((s)=>s.kind==="artifact"?[Ro(s.path,n)]:[]).flatMap((s)=>{let i=eS(t,s);return kd(i)?.isFile()?[[s,Z(tS(i))]]:[]});return{artifactHashes:Object.fromEntries(o),treeHash:await Ae(t,PM)}}function Xs(t,e){return[...new Set([...Object.keys(t),...Object.keys(e)])].sort(O).flatMap((r)=>{let o=t[r],s=e[r];if(o===s)return[];if(o===void 0)return[`added ${r}`];return s===void 0?[`deleted ${r}`]:[`changed ${r}`]})}async function NM(t,e){switch(t.kind){case"criteria":return DM(e.task.contract);case"checks":return LM(t.select,t.expect,e);case"invariants":return MM(e);case"scope":return jM(e);case"locked":return FM(e);case"tests-unchanged":return GM(e);case"regression":return yw({base:rS(e.task),changedFiles:await e.changedFiles(),config:e.config,contract:e.task.contract,root:e.root});case"artifact":return HM(t,e);case"approval":return vp("approval",e);case"review":return BM(e);case"command":return VM(t.run,e)}}function DM(t){let e=rd(t),n=e.length===0?`${t.criteria.length} ${wt(t.criteria.length,"criterion","criteria")} bound to existing checks`:`${e.length} criteria ${wt(e.length,"problem","problems")}`;return kt("criteria",e.length===0,n,e)}async function LM(t,e,n){let r=po(n.task.contract,t);if(r.length===0)return kt("checks",!1,`no check matches the selection "${t}"`);let o=await Je(r,e,n.root),s=Or(o),i=e==="pass"?"passed":"failed as expected",a=`${o.length-s.length} of ${o.length} ${wt(o.length,"check","checks")} ${i}`;return kt("checks",s.length===0,a,s,o)}async function MM(t){let e=t.task.contract.invariants.map((s,i)=>({name:`invariants[${i}]`,run:s,timeoutSeconds:t.config.checkTimeoutSeconds})),n=await Je(e,"pass",t.root),r=Or(n),o=`${n.length-r.length} of ${n.length} ${wt(n.length,"invariant","invariants")} passed`;return kt("invariants",r.length===0,o,r,n)}async function jM(t){let e=ne(await t.changedFiles()),n=e.filter((o)=>!et(o,t.task.contract.scope)),r=n.length===0?`${e.length} changed ${wt(e.length,"file","files")} inside the scope`:`${n.length} of ${e.length} changed ${wt(e.length,"file","files")} outside the scope`;return kt("scope",n.length===0,r,n)}async function FM(t){let e=await An(t.root,t.task.contract.lock),n=Xs(t.task.record.lockHashes,e),r=Object.keys(t.task.record.lockHashes).length,o=n.length===0?`${r} locked ${wt(r,"file","files")} unchanged`:`${n.length} locked ${wt(n.length,"file","files")} changed`;return kt("locked",n.length===0,o,n)}async function GM(t){let e=await Ys(t.root,t.config,t.task.contract),n=Xs(t.task.record.stageTestHashes,e),r=Object.keys(t.task.record.stageTestHashes).length,o=n.length===0?`${r} test ${wt(r,"file","files")} unchanged since the stage started`:`${n.length} test ${wt(n.length,"file","files")} changed since the stage started`;return kt("tests-unchanged",n.length===0,o,n)}function HM(t,e){let{contract:n}=e.task,r=Ro(t.path,n.id),o=eS(e.root,r),s=kd(o),i=t.sections!==void 0||t.traceable===!0;if(!s?.isFile()){let g=t.sections===void 0?[]:[`Write ${r} with the sections: ${t.sections.join(", ")}`];return kt("artifact",!1,`${r} does not exist`,g)}let a=`${r} has ${s.size} bytes`,c=s.size<t.minBytes?`${a}; it needs at least ${t.minBytes}`:null;if(!i)return kt("artifact",c===null,c??a);let l=ty({contractPath:It(n.id),criteria:n.criteria.map((g)=>g.id),path:r,requirements:{sections:t.sections??[],traceable:t.traceable===!0},text:tS(o,"utf8")}),u=c===null?l.problems:[c,...l.problems];if(u.length>0)return kt("artifact",!1,`${r} has ${u.length} ${wt(u.length,"problem","problems")}`,u);let d=`${l.filled} required ${wt(l.filled,"section","sections")} filled`,p=t.traceable===!0?`, ${l.traced} ${wt(l.traced,"criterion","criteria")} traced`:"";return kt("artifact",!0,`${a}, ${d}${p}`)}function Ro(t,e){return t.replaceAll(_M,e)}function UM(t){return t.kind==="approval"||t.kind==="review"}async function KM(t,e,n){let{agent:r,command:o}=n.config.review;if(t==="approval"||o===null&&r===void 0)return()=>vp(t,n);let s=await kp(n);return async()=>{if(nS(s,await kp(n)))return e;return kt(t,!1,"the working tree changed while the gates after the review ran",[],e.checks)}}function kp(t){return Sp(t.root,t.stage,t.task.contract.id)}function nS(t,e){return t.treeHash===e.treeHash&&Xs(t.artifactHashes,e.artifactHashes).length===0}async function vp(t,e){let n=e.stage.name,r=`a human runs 'ari approve ${e.task.contract.id}'`,o=e.task.record.approvals.filter((c)=>c.stage===n);if(o.length===0)return kt(t,!1,`stage ${n} has no approval; ${r}`);let s=await kp(e),i=o.filter((c)=>nS(c,s));if(i.length>0)return kt(t,!0,`stage ${n} approved by ${Qw(i)}`);let a=`the working tree changed after ${Qw(o)} approved stage ${n}`;return kt(t,!1,`${a}; ${r} again`)}function Qw(t){return[...new Set(t.map((e)=>e.by))].join(", ")}async function BM(t){let{agent:e,command:n}=t.config.review;if(e!==void 0){let{config:c,root:l,stage:u,task:d}=t;return Zw({config:c,root:l,stage:u.name,task:d})}if(n===null)return vp("review",t);let r={name:"review",run:n,timeoutSeconds:t.config.checkTimeoutSeconds},o={config:t.config,root:t.root},s=await Vs(o,"run review.command",[r],"pass",t.root),i=Or(s),a=i.length===0?"the review command passed":"the review command failed";return kt("review",i.length===0,a,i,s)}async function VM(t,e){let n={name:"command",run:t,timeoutSeconds:e.config.checkTimeoutSeconds},r={config:e.config,root:e.root},o=await Vs(r,"run a command gate of a project pack",[n],"pass",e.root),s=Or(o),i=s.length===0?`${t} passed`:`${t} failed`;return kt("command",s.length===0,i,s,o)}function rS(t){if(t.record.base!==null)return t.record.base;throw Error(`Task "${t.contract.id}" has no base commit; gates run only after 'ari start'`)}import{closeSync as WM,existsSync as JM,fstatSync as qM,openSync as YM,readSync as XM}from"fs";import{join as zM}from"path";var ZM="journal",QM=".jsonl",oS=65536,tj=1000,$c=10;function Tc(t,e,n){let r=[];if(n===0)return r;for(let o of nj(iS(t,e))){let s=aS(o,e);if(s!==null)r.push(s);if(r.length===n)break}return r.reverse()}function*sS(t,e){let n=[];for(let r of ej(iS(t,e))){let o=aS(r,e);if(o===null)continue;if(n.push(o),n.length<tj)continue;yield n,n=[]}if(n.length>0)yield n}function iS(t,e){return zM(t,ZM,`${qn(e)}${QM}`)}function aS(t,e){try{let n=Da(JSON.parse(t.toString("utf8")));return n.task===e?n:null}catch(n){if(n instanceof SyntaxError||n instanceof b)return null;throw n}}function*ej(t){let e=[];for(let n of cS(t,!1)){let r=0;for(let o=n.indexOf($c);o!==-1;o=n.indexOf($c,r))yield Buffer.concat([...e,n.subarray(r,o)]),e=[],r=o+1;e.push(n.subarray(r))}yield Buffer.concat(e)}function*nj(t){let e=[];for(let n of cS(t,!0)){let r=n.length;for(let o=n.lastIndexOf($c);o!==-1;o=o===0?-1:n.lastIndexOf($c,o-1))yield Buffer.concat([n.subarray(o+1,r),...e]),e=[],r=o;e.unshift(n.subarray(0,r))}yield Buffer.concat(e)}function*cS(t,e){if(!JM(t))return;let n=YM(t,"r");try{let{size:r}=qM(n);for(let o=0;o<r;o+=oS){let s=Math.min(oS,r-o),i=Buffer.alloc(s),a=XM(n,i,0,s,e?r-o-s:o);yield i.subarray(0,a)}}finally{WM(n)}}import{randomUUID as cj}from"crypto";import{mkdirSync as lj,readFileSync as uj,renameSync as dj,rmSync as pj,writeFileSync as gj}from"fs";import{basename as mj,dirname as lS,join as uS}from"path";var rj=/\p{M}+/gu,oj=/[\u00DF\u00E6\u0111\u00F0\u0127\u0131\u0142\u0153\u00F8\u00FE]/g,sj=/[^a-z0-9]+/,ij={\u{e6}:"ae",\u{f0}:"d",\u{111}:"d",\u{127}:"h",\u{131}:"i",\u{142}:"l",\u{f8}:"o",\u{153}:"oe",\u{df}:"ss",\u{fe}:"th"};function zs(t,e){if(!Number.isInteger(e)||e<=0)throw Error(`slugify needs a positive maxWords, got ${e}`);let r=t.toLowerCase().normalize("NFKD").replace(rj,"").replace(oj,(o)=>ij[o]??"").split(sj).filter((o)=>o.length>0).slice(0,e).join("-");return aj(r)}function aj(t){if(t.length<=64)return t;let e=t.lastIndexOf("-",64);return e>0?t.slice(0,e):t.slice(0,64)}function Zs(t,e){if(t.length===0)throw Error("uniqueId needs a non-empty base");let n=new Set(e);if(!n.has(t))return t;let r=2;while(n.has(`${t}-${r}`))r++;return`${t}-${r}`}var fj=["constraint","decision"],hj=6,yj=10,kj="knowledge",wj=".md",Sj=4,vj="\x00",bj=",",Ej={"[":"]","{":"}"},$j="\\",Tj=()=>new Date().toISOString();function bp(t,e,n){let r=nt(t.text,`${e}.text`).trim(),o=yt(r);if(o>n)throw new b(`${e}.text is ${o} bytes, but a knowledge entry holds at most ${n}`);return{kind:K(le,t.kind,`${e}.kind`),scope:wa(t.scope,`${e}.scope`),text:r}}function dS(t){return le.includes(t)}function Qs(t,e){return{created:e.created,id:e.id,kind:t.kind,scope:[...t.scope],sources:[...e.sources],status:"active",supersededBy:null,supersedes:[...e.supersedes],text:t.text}}function Ep(t,e){let n=zs(t.text,hj),r=Zs(n.length>0?n:t.kind,e);return e.add(r),r}function $p(t,e,n,r){for(;;){let o=Qs(e,{...n,id:Ep(e,r)});try{return Ba(t,o),o}catch(s){if(!an(t).includes(o.id))throw s}}}function dn(t,e){return{...t,status:"archived",supersededBy:e}}function pn(t){return fj.includes(t.kind)}function Io(t){return t.slice(0,yj)}function ti(t,e){let n=Oe(t,e.id),r=uS(lS(n),`.${mj(n)}.${process.pid}.${cj()}.tmp`);lj(lS(n),{recursive:!0});try{gj(r,br(e)),dj(r,n)}catch(o){throw pj(r,{force:!0}),o}}function xj(t){let e=new Map;for(let n of t){if(n.record.status!=="done")continue;for(let r of n.record.knowledgeUsed)e.set(r,(e.get(r)??0)+1)}return e}async function Oo(t){let e=await F(t,["ls-files","--cached","--others","--exclude-standard","-z"]);return ne([...new Set(e.stdout.split(vj).filter((n)=>n.length>0))])}function xc(t,e,n){if(t.length===0||e.length===0)return!0;return t.some((o)=>e.some((s)=>o===s||et(o,[s])||et(s,[o])))||n.some((o)=>et(o,t)&&et(o,e))}function pS(t){let e=[],n=[],r="";for(let o=0;o<t.length;o++){let s=t[o]??"";if(s===$j){r+=t.slice(o,o+2),o++;continue}let i=Ej[s];if(i!==void 0)n.push(i);else if(s===n.at(-1))n.pop();if(s===bj&&n.length===0){e.push(r.trim()),r="";continue}r+=s}return e.push(r.trim()),e.filter((o)=>o.length>0)}function Aj(t,e,n={}){let r=M(t),o=At("note","Shorten the text or fix the --kind and --scope values",()=>bp(e,"note",r.knowledge.maxEntryBytes)),i={created:Io((n.clock??Tj)()),sources:[...n.sources??[]],supersedes:[]};return $p(t,o,i,new Set(an(t)))}async function gS(t,e,n={}){M(t);let r=gt(await P(t))?.task,o=r!==void 0&&de(t).includes(r)?[r]:[];return Aj(t,e,{...n,sources:o})}function Tp(t,e={}){return M(t),{entries:pe(t).filter((r)=>e.all===!0||r.status==="active")}}function mS(t,e,n={}){let{entries:r}=Tp(t,n),o=new Map(r.map((a)=>[a.id,a]));return{matches:gc(e,r.map((a)=>({id:a.id,text:a.text}))).flatMap(({id:a,score:c})=>{let l=o.get(a);return l===void 0||c<=0?[]:[{entry:l,score:Cj(c)}]}),query:e}}function fS(t,e,n){return{entry:ei(t,e),uses:xj(n).get(e)??0}}function hS(t,e,n={}){let r=ei(t,e);if(r.status==="archived")throw new m(`Knowledge entry "${e}" is already archived`,"Run 'ari knowledge list' to see the active entries");if(pn(r)&&n.force!==!0)throw new m(`Knowledge entry "${e}" is a ${r.kind}; ${r.kind} entries are archived only on purpose`,`Run 'ari knowledge archive ${e} --force' if it no longer holds`);let o=dn(r,null);return ti(t,o),o}function ei(t,e){if(M(t),an(t).includes(e))return Ca(e,uj(Oe(t,e),"utf8"));throw new m(`Knowledge entry "${e}" does not exist`,"Run 'ari knowledge list --all' to see every entry")}function Oe(t,e){return uS(t,J,kj,`${e}${wj}`)}function Cj(t){let e=10**Sj;return Math.round(t*e)/e}var Rj=4,_e=`
|
|
144
167
|
|
|
145
|
-
`,
|
|
146
|
-
`,
|
|
147
|
-
`,
|
|
148
|
-
`)){if(a-=
|
|
149
|
-
`).trim(),i].filter((d)=>d.length>0).join(
|
|
150
|
-
`)}function
|
|
151
|
-
`)}}function
|
|
152
|
-
`)}]}function
|
|
153
|
-
`);return
|
|
154
|
-
${t.replace(
|
|
155
|
-
${e}`}function
|
|
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=`
|
|
168
|
+
`,bS=`
|
|
169
|
+
`,Ij=3,Oj=/`+/g,_j=/^ {0,3}(?:```|~~~)/,Pj=/\n+$/,Nj=/\n/g,ES=`
|
|
170
|
+
`,Rp="none",yS={constraint:0,decision:1},Ip={contract:{title:"Contract",unit:"contract"},failure:{title:"Last failed attempt",unit:"failed attempt"},journal:{title:"Journal tail",unit:"journal event"},knowledge:{title:"Knowledge",unit:"knowledge entry"},notes:{title:"Task notes",unit:"task note"},rules:{title:"Constraints and decisions",unit:"constraint or decision entry"},task:{title:"Task",unit:"task header"}},Dj=["failure","rules","notes","knowledge","journal"],Lj=/y$/,Mj=()=>new Date().toISOString();async function tr(t,e={}){let n=M(t),r=await P(t),o=e.id??jj(r),s=e.budget??n.context.budget,{task:i}=it(t,o,n),a=pe(t).filter((g)=>g.status==="active"),c=(await Oo(t)).filter((g)=>et(g,i.contract.scope)),l=Hj(t,i),u=Uj(i),d=[...Kj(i.record.lastFailure,e.commandOutput!==!1),...Bj(i,a,c),...Vj(i.record.notes),...Wj(i,a,c),...Jj(Tc(r,o,n.context.journalTail))],p=Fj(o,s,l,u,d);if(i.record.status!=="done"&&e.journal!==!1){let g=(e.clock??Mj)(),f={[ho]:p.knowledge,tokens:p.estimatedTokens};$r(r,{at:g,detail:f,task:o,type:"context"})}return p}function jj(t){let e=gt(t);if(e!==null)return e.task;throw new m("No task is active in this worktree","Pass a task id: ari context <id>")}function Fj(t,e,n,r,o){let s=e*Rj,i=[n,Ac(r.fields,r.body)],a=kS(o,yt(i.join(_e)),Number.POSITIVE_INFINITY),c=yt(wS(i,a.sections,null))<=s,l=yt(`${_e}${vS(e,SS(o))}`),u=c?i:[n,Gj(t,n,r,s-l)],d=u.join(_e),p=c?a:kS(o,yt(d)+l,s),g=SS(p.omitted),f=wS(u,p.sections,g.length===0?null:vS(e,g)),y=[xp("task",u[0]??"",1),xp("contract",u[1]??"",1),...p.sections.map((S)=>xp(S.name,$S(S),S.items.length))];return{budget:e,estimatedTokens:ip(f),knowledge:p.sections.flatMap((S)=>S.knowledge),omitted:g,sections:y,sha256:Z(f),task:t,text:f}}function Gj(t,e,{body:n,fields:r},o){let s=Ac(r,n);if(yt([e,s].join(_e))<=o)return s;let i=`_The contract body is shortened to fit the budget; read ${It(t)}._`,a=o-yt([e,Ac(r,i)].join(_e))-_e.length,c=[];for(let d of n.split(`
|
|
171
|
+
`)){if(a-=yt(d)+1,a<0)break;c.push(d)}let l=c.flatMap((d,p)=>_j.test(d)?[p]:[]),u=l.length%2===0?c:c.slice(0,l.at(-1));return Ac(r,[u.join(`
|
|
172
|
+
`).trim(),i].filter((d)=>d.length>0).join(_e))}function Ac(t,e){return e.length===0?t:`${t}${_e}${e}`}function kS(t,e,n){let r=[],o=[],s=e;for(let i of t){let a=r.at(-1),c=a?.name===i.section,l=c?bS:`${_e}${Op(i.section)}${_e}`,u=yt(l)+yt(i.text);if(s+u>n){o.push(i);continue}s+=u;let d=c&&a?a:{items:[],knowledge:[],name:i.section};if(d!==a)r.push(d);if(d.items.push(i.text),i.knowledgeId!==null)d.knowledge.push(i.knowledgeId)}return{omitted:o,sections:r}}function wS(t,e,n){return[...[...t,...e.map($S)],...n===null?[]:[n]].join(_e)}function $S(t){return`${Op(t.name)}${_e}${t.items.join(bS)}`}function Op(t){return`## ${Ip[t].title}`}function xp(t,e,n){return{estimatedTokens:ip(e),items:n,name:t,text:e,title:Ip[t].title}}function SS(t){return Dj.flatMap((e)=>{let n=t.filter((r)=>r.section===e).length;return n===0?[]:[{count:n,section:e}]})}function vS(t,e){let n=e.map(({count:r,section:o})=>{let{unit:s}=Ip[o];return`${r} ${r===1?s:`${s.replace(Lj,"ie")}s`}`});return`_Omitted to fit the budget of ${t} tokens: ${n.join(", ")}._`}function Hj(t,e){let{contract:n,record:r}=e,o=Ue(n.pack,Gt(t)),s=Nn(e,o);return[`# ${n.id}: ${n.title}`,"",`- Status: ${r.status}`,`- Pack: ${o.name}`,`- Stage: ${s.name} (${r.stage+1} of ${o.stages.length})`,`- Instruction: ${Qn(mo(s,n.id))}`,...r.question===null?[]:[`- Question: ${Qn(r.question)}`]].join(`
|
|
173
|
+
`)}function Uj(t){let{contract:e}=t,n=e.criteria.map((i)=>{let a=i.checks.length===0?Rp:i.checks.join(", ");return`- ${i.id}: ${Qn(i.text)} (checks: ${a})`}),r=e.checks.map((i)=>`- ${i.name} (expect ${i.expect}, timeout ${i.timeoutSeconds}s): ${Cc(i.run)}`),o=e.invariants.map((i)=>`- ${Cc(i)}`),s=[Op("contract"),"",`Scope: ${Cp(e.scope)}`,`Lock: ${Cp(e.lock)}`,...Ap("Criteria:",n),...Ap("Checks:",r),...Ap("Invariants:",o)];return{body:e.body.trim(),fields:s.join(`
|
|
174
|
+
`)}}function Ap(t,e){return e.length===0?[`${t} ${Rp}`]:[t,...e]}function Kj(t,e){if(t===null)return[];let n=t.gates.filter((o)=>!o.ok).flatMap((o)=>[`- ${o.gate}: ${Qn(o.summary)}`,...o.details.map((s)=>` - ${Qn(s)}`),...o.checks.filter((s)=>e&&!s.ok&&s.outputTail.length>0).map((s)=>` ${s.name} output:${ES}${Qn(qj(s.outputTail))}`)]);return[{knowledgeId:null,section:"failure",text:[`Stage ${t.stage} at ${t.at}:`,...n].join(`
|
|
175
|
+
`)}]}function Bj(t,e,n){return TS(t,e,n).sort((r,o)=>(yS[r.kind]??0)-(yS[o.kind]??0)).map((r)=>xS("rules",r))}function TS(t,e,n){return e.filter((r)=>pn(r)&&xc(r.scope,t.contract.scope,n))}function Vj(t){return t.map((e,n)=>({index:n,note:e})).sort((e,n)=>O(n.note.at,e.note.at)||n.index-e.index).map(({note:e})=>({knowledgeId:null,section:"notes",text:`- ${e.at}: ${Qn(e.text)}`}))}function Wj(t,e,n){let r=new Set(TS(t,e,n).map((l)=>l.id)),o=e.filter((l)=>!r.has(l.id)),s=new Map(o.map((l)=>[l.id,l])),{contract:i}=t,a=[i.title,i.body,...i.criteria.map((l)=>l.text)].join(`
|
|
176
|
+
`);return gc(a,o.map((l)=>({id:l.id,text:l.text}))).flatMap(({id:l})=>{let u=s.get(l);return u===void 0?[]:[xS("knowledge",u)]})}function xS(t,e){let n=e.scope.length===0?"":` (scope: ${Cp(e.scope)})`;return{knowledgeId:e.id,section:t,text:`- ${e.kind} ${Cc(e.id)}${n}: ${Qn(e.text)}`}}function Jj(t){return t.map((e)=>({knowledgeId:null,section:"journal",text:`- ${e.at} ${e.type} ${JSON.stringify(JSON.parse(pt(e.detail)))}`}))}function Cp(t){return t.length===0?Rp:t.map(Cc).join(", ")}function Cc(t){let e="`".repeat(AS(t)+1),n=t.startsWith("`")||t.endsWith("`")?" ":"";return`${e}${n}${t}${n}${e}`}function qj(t){let e="`".repeat(Math.max(Ij,AS(t)+1));return`${e}
|
|
177
|
+
${t.replace(Pj,"")}
|
|
178
|
+
${e}`}function AS(t){return Math.max(0,...[...t.matchAll(Oj)].map((e)=>e[0].length))}function Qn(t){return t.replace(Nj,ES)}function CS(t,e){let n=Math.max(t.length,e.length);return n===0?1:1-Au(t,e)/n}var Yj=3;function _p(t,e,n,r){return{clusters:Xj(t,r),decisions:Zj(t,n),notes:zj(e)}}function Pp(t,e,n){let r=od(t),o=od(e),s=Math.max(r.length,o.length);if(s>0&&Math.min(r.length,o.length)/s<n)return 0;return CS(r,o)}function Xj(t,e){let n=new Map(t.map((i)=>[i.id,i.id])),r=new Map,o=(i)=>{let a=n.get(i)??i;return a===i?i:o(a)};t.forEach((i,a)=>{for(let c of t.slice(a+1)){let l=Pp(i.text,c.text,e.knowledge.mergeSimilarity);if(l<e.knowledge.mergeSimilarity)continue;let[u,d]=[o(i.id),o(c.id)].sort(O);n.set(d,u),r.set(u,Math.max(r.get(u)??0,r.get(d)??0,l))}});let s=new Map;for(let i of t){let a=o(i.id);s.set(a,[...s.get(a)??[],i.id])}return[...s.entries()].filter(([,i])=>i.length>1).map(([i,a])=>({ids:a,similarity:Qj(r.get(i)??0)})).sort((i,a)=>O(i.ids[0]??"",a.ids[0]??""))}function zj(t){return t.filter((e)=>e.record.status==="done").flatMap((e)=>e.record.notes.flatMap((n,r)=>n.promoted?[]:[{at:n.at,note:r,task:e.contract.id,text:n.text}]))}function Zj(t,e){let n=t.filter((r)=>r.kind==="decision");return n.flatMap((r,o)=>n.slice(o+1).filter((s)=>xc(r.scope,s.scope,e)).map((s)=>({ids:[r.id,s.id]})))}function Qj(t){let e=10**Yj;return Math.round(t*e)/e}import{existsSync as kF,readFileSync as BS}from"fs";function Np(t,e){let n=RS(t),r=RS(e),o=tF(n,r),s=[],i=0,a=0;while(i<n.length&&a<r.length)if(n[i]===r[a])i++,a++;else if(ni(o,i+1,a)>=ni(o,i,a+1))s.push(`-${n[i]}`),i++;else s.push(`+${r[a]}`),a++;for(let c of n.slice(i))s.push(`-${c}`);for(let c of r.slice(a))s.push(`+${c}`);return s}function RS(t){if(t.length===0)return[];let e=t.split(`
|
|
179
|
+
`);if(e.at(-1)==="")e.pop();return e}function tF(t,e){let n=Array.from({length:t.length+1},()=>Array(e.length+1).fill(0));for(let r=t.length-1;r>=0;r--){let o=n[r]??[];for(let s=e.length-1;s>=0;s--)o[s]=t[r]===e[s]?ni(n,r+1,s+1)+1:Math.max(ni(n,r+1,s),ni(n,r,s+1))}return n}function ni(t,e,n){return t[e]?.[n]??0}import{existsSync as US,mkdirSync as gF,readFileSync as KS}from"fs";import{join as si}from"path";import{existsSync as eF,readdirSync as nF}from"fs";var gn=".json",PS=/^(\d{8}T\d{9}Z)(?:-(\d+))?$/,rF=/[^0-9TZ]/g,IS=10,Rc=1;function ri(t){return PS.test(t)}function Ic(t,e){let n=t.replace(rF,""),r=Rc;while(e(OS(n,r)))r++;return OS(n,r)}function _o(t){if(!eF(t))return[];return nF(t).filter((e)=>e.endsWith(gn)&&ri(e.slice(0,-gn.length)))}function Pr(t,e){let[n="",r=`${Rc}`]=_S(t),[o="",s=`${Rc}`]=_S(e);return O(n,o)||Number.parseInt(r,IS)-Number.parseInt(s,IS)}function OS(t,e){return e===Rc?t:`${t}-${e}`}function _S(t){return PS.exec(t)?.slice(1).filter((e)=>e!==void 0)??[t]}var oi=1,NS=["pass","apply","undo"];var oF=/^[0-9a-f]{64}$/,FS=["version","id","at","kind"],DS=[...FS,"forced","reason","proposal","pruned","archived","created","promoted"],LS=[...FS,"undoes","restored","removed","unpromoted"],sF=["duplicate","decay","budget","merge","proposal"],iF=["merge","promotion"],aF=["utf8","base64"];function GS(t,e,n){return At(`sleep ledger entry ${e}`,n,()=>cF(t))}function cF(t){let e=T(t,"entry",LS.concat(DS)),n=K(NS,e.kind,"kind"),r=ht(e.version,"version");if(r!==oi)throw new b(`version ${r} is not supported`);let o={at:x(e.at,"at"),id:x(e.id,"id"),version:oi};if(n==="undo"){let i=T(t,"entry",LS);return{...o,kind:n,removed:L(i.removed,"removed",MS),restored:L(i.restored,"restored",MS),undoes:x(i.undoes,"undoes"),unpromoted:L(i.unpromoted,"unpromoted",jS)}}let s=T(t,"entry",DS);return{...o,archived:L(s.archived,"archived",lF),created:L(s.created,"created",uF),forced:$t(s.forced,"forced"),kind:n,promoted:L(s.promoted,"promoted",jS),proposal:s.proposal===null?null:pF(s.proposal),pruned:L(s.pruned,"pruned",dF),reason:Ct(s.reason,"reason")}}function lF(t,e){let n=T(t,e,["id","reason","supersededBy","original","sha256"]);return{id:x(n.id,`${e}.id`),original:ft(n.original,`${e}.original`,Oc),reason:K(sF,n.reason,`${e}.reason`),sha256:Dn(n.sha256,`${e}.sha256`),supersededBy:Ct(n.supersededBy,`${e}.supersededBy`)}}function uF(t,e){let n=T(t,e,["id","kind","origin","replaces","task","notes","sha256"]);return{id:x(n.id,`${e}.id`),kind:K(le,n.kind,`${e}.kind`),notes:L(n.notes,`${e}.notes`,ht),origin:K(iF,n.origin,`${e}.origin`),replaces:Dt(n.replaces,`${e}.replaces`),sha256:Dn(n.sha256,`${e}.sha256`),task:Ct(n.task,`${e}.task`)}}function Oc(t,e){let n=T(t,e,["sha256","encoding","content"]);return{content:x(n.content,`${e}.content`),encoding:K(aF,n.encoding,`${e}.encoding`),sha256:Dn(n.sha256,`${e}.sha256`)}}function MS(t,e){let n=T(t,e,["id","sha256"]);return{id:x(n.id,`${e}.id`),sha256:Dn(n.sha256,`${e}.sha256`)}}function jS(t,e){let n=T(t,e,["task","notes"]);return{notes:L(n.notes,`${e}.notes`,ht),task:x(n.task,`${e}.task`)}}function dF(t,e){let n=T(t,e,["task","events"]);return{events:ht(n.events,`${e}.events`),task:x(n.task,`${e}.task`)}}function pF(t){let e=T(t,"proposal",["sha256"]);return{sha256:Dn(e.sha256,"proposal.sha256")}}function Dn(t,e){let n=x(t,e);if(!oF.test(n))throw new b(`${e} must be a SHA-256 hex digest`);return n}var mF="sleep",fF=si("locks","sleep.ledger.lock"),hF="the sleep ledger",Dp="Restore the file from a backup, or delete it to drop that entry from the sleep history";function Lp(t){return si(t,mF)}function Nr(t,e){return As(si(t,fF),hF,e)}function Po(t){return t.kind!=="undo"}function No(t,e,n){let r=Lp(t);gF(r,{recursive:!0});let o=Ic(e,(i)=>US(HS(t,i))),s={...n,at:e,id:o,version:oi};return Yn(HS(t,o),pt(s),()=>Error(`The sleep ledger entry ${o} already exists`)),s}function ii(t){let e=Lp(t);return _o(e).map((n)=>yF(si(e,n),n)).sort((n,r)=>Pr(n.id,r.id))}function ai(t){let e=new Map;for(let n of t)if(n.kind==="undo")e.set(n.undoes,n.id);return e}function Do(t){let e=Buffer.from(t),n=e.toString("utf8"),r=Buffer.from(n,"utf8").equals(e);return{content:r?n:e.toString("base64"),encoding:r?"utf8":"base64",sha256:Z(t)}}function Dr(t){return Buffer.from(t.content,t.encoding==="utf8"?"utf8":"base64")}function Lo(t){return Z(KS(t))}function Mp(t){return US(t)?Lo(t):null}function HS(t,e){return si(Lp(t),`${e}${gn}`)}function yF(t,e){let n;try{n=JSON.parse(KS(t,"utf8"))}catch(o){let s=o instanceof Error?o.message:String(o);throw new m(`The sleep ledger entry ${t} is not valid JSON (${s})`,Dp)}let r=GS(n,t,Dp);if(`${r.id}${gn}`===e)return r;throw new m(`The sleep ledger entry ${t} declares the id "${r.id}"`,Dp)}function _c(t,e){return e.map(({after:n,reason:r})=>{let o=Oe(t,n.id),s=Do(BS(o));return ti(t,n),{id:n.id,original:s,reason:r,sha256:Lo(o),supersededBy:n.supersededBy}})}function VS(t,e){return e.map(({entry:n,notes:r,origin:o,replaces:s,task:i})=>({id:n.id,kind:n.kind,notes:r,origin:o,replaces:s,sha256:Lo(Oe(t,n.id)),task:i}))}function Pc(t,e,n){let r=n.map(({entry:s,origin:i})=>({change:"created",diff:Np("",br(s)),id:s.id,reason:i,supersededBy:null})),o=e.map(({after:s,reason:i})=>({change:i==="merge"?"replaced":"archived",diff:Np(wF(t,s.id),br(s)),id:s.id,reason:i,supersededBy:s.supersededBy}));return[...r,...o]}function wF(t,e){let n=Oe(t,e);return kF(n)?BS(n,"utf8"):""}function er(t){let{activeBytes:e,clusters:n,decisions:r,journaled:o,maxBytes:s,notes:i}=t,a=[...o.length>0?["journals"]:[],...e>s?["budget"]:[],...n+i+r>0?["candidates"]:[]];return{activeBytes:e,candidates:{clusters:n,decisions:r,notes:i},due:a.length>0,journaled:[...o],maxBytes:s,reasons:a}}function Lr(t){let e=(n)=>n.record.history.findLast((r)=>r.type==="done")?.at??n.record.history.at(-1)?.at??"";return t.filter((n)=>n.record.status==="done").sort((n,r)=>O(e(r),e(n))||O(n.contract.id,r.contract.id))}function jp(t,e){return[...new Set(t.record.knowledgeUsed.map((n)=>SF(n,e)))]}function Fp(t){let e=vF(t);return(n)=>{let r=new Set,o=[n];for(let s=o.pop();s!==void 0;s=o.pop()){if(r.has(s))continue;r.add(s);let i=t.get(s);if(i===void 0)continue;if(i.status==="active")return i;if(i.supersededBy!==null)o.push(i.supersededBy);o.push(...e.get(s)??[])}return null}}function SF(t,e){let n=new Set([t]),r=t;for(;;){let o=e.get(r)?.supersededBy??null;if(o===null||n.has(o)||!e.has(o))return r;n.add(o),r=o}}function vF(t){let e=new Map;for(let n of t.values())for(let r of n.supersedes)e.set(r,[...e.get(r)??[],n.id]);return e}var bF=["fact","pattern","gotcha"],EF=()=>new Date().toISOString();async function Mr(t,e={}){let n=M(t),r=await P(t),o=await Oo(t),s=(e.clock??EF)();return Nr(r,()=>{let{retirements:i,...a}=qS(t,r,n,o,!0),c=No(r,s,{archived:_c(t,i),created:[],forced:!1,kind:"pass",promoted:[],proposal:null,pruned:a.pruned,reason:null});return{...a,ledger:c.id}})}async function WS(t){let e=M(t),n=await P(t),r=await Oo(t),{retirements:o,...s}=qS(t,n,e,r,!1);return{...s,changes:Pc(t,o,[]),dryRun:!0}}async function jr(t,e={}){let n=M(t),r=await P(t),{tasks:o}=Pt(t,n),s=Mo(new Map(pe(t).map((a)=>[a.id,a]))),i=e.candidates===!1?{clusters:[],decisions:[],notes:[]}:_p(s,o,await Oo(t),n);return{activeBytes:Gp(s),clusters:i.clusters.length,decisions:i.decisions.length,journaled:o.filter((a)=>YS(r,a)).map((a)=>a.contract.id).sort(O),maxBytes:n.knowledge.maxBytes,notes:i.notes.length}}async function JS(t){return er(await jr(t,{candidates:!1})).due?Mr(t):null}function qS(t,e,n,r,o){let{tasks:s}=Pt(t,n),{pruned:i,tasks:a}=$F(t,e,s,o),c=new Map(pe(t).map((p)=>[p.id,p])),l=[...AF(c,n),...CF(c,a,n),...RF(c,a,n)],u=l.flatMap(({id:p,reason:g})=>{let f=c.get(p);return f===void 0?[]:[{after:f,reason:g}]}),d=Mo(c);return{activeBytes:Gp(d),archived:l,candidates:_p(d,a,r,n),maxBytes:n.knowledge.maxBytes,pruned:i,retirements:u}}function $F(t,e,n,r){let o=[],s=n.map((i)=>{let{id:a}=i.contract;if(!YS(e,i))return i;let c=0,l=(d)=>{let p=TF(d,e,a);return c=p.events,p.record},u=r?Vt(t,e,a,l):l(i.record);if(r)Va(e,a);return o.push({events:c,task:a}),{contract:i.contract,record:u}});return{pruned:o,tasks:s}}function YS(t,e){return e.record.status==="done"&&Tc(t,e.contract.id,1).length>0}function TF(t,e,n){let r=t,o=0;for(let s of sS(e,n))r=xF(r,s),o+=s.length;return{events:o,record:r}}function xF(t,e){let n=e.flatMap((r)=>{let o=r.detail[ho];return r.type==="context"&&Array.isArray(o)?o:[]});return _a(fy(t,n),e)}function Mo(t){return[...t.values()].filter((e)=>e.status==="active").sort((e,n)=>O(e.id,n.id))}function Gp(t){return t.reduce((e,n)=>e+yt(n.text),0)}function XS(t,e){return O(t.created,e.created)||O(t.id,e.id)}function AF(t,e){let n=[],r=[];for(let o of Mo(t).filter((s)=>!pn(s)).sort(XS)){let s=n.find((i)=>i.kind===o.kind&&Pp(i.text,o.text,e.knowledge.duplicateSimilarity)>=e.knowledge.duplicateSimilarity);if(s===void 0){n.push(o);continue}t.set(o.id,dn(o,s.id)),r.push({id:o.id,reason:"duplicate",supersededBy:s.id})}return r}function CF(t,e,n){let r=Lr(e).slice(0,n.knowledge.decayAfterTasks);if(r.length<n.knowledge.decayAfterTasks)return[];let o=new Set(r.flatMap((i)=>jp(i,t))),s=r.map((i)=>Io(i.record.history[0]?.at??"")).sort(O)[0]??"";return Mo(t).flatMap((i)=>{if(!bF.includes(i.kind)||o.has(i.id))return[];if(O(i.created,s)>=0)return[];return t.set(i.id,dn(i,null)),[{id:i.id,reason:"decay",supersededBy:null}]})}function RF(t,e,n){let r=new Map;for(let a of Lr(e).flatMap((c)=>jp(c,t)))r.set(a,(r.get(a)??0)+1);let o=Mo(t).filter((a)=>!pn(a)).sort((a,c)=>(r.get(a.id)??0)-(r.get(c.id)??0)||XS(a,c)),s=[],i=Gp(Mo(t));for(let a of o){if(i<=n.knowledge.maxBytes)break;t.set(a.id,dn(a,null)),i-=yt(a.text),s.push({id:a.id,reason:"budget",supersededBy:null})}return s}import{readFileSync as IF}from"fs";import{join as zS}from"path";var ZS=1048576,OF=".ari/designs/";function Nc(t,e){let n=t.stages.flatMap((r)=>r.gates.flatMap((o)=>o.kind==="artifact"?[Ro(o.path,e)]:[]));return[...new Set(n)].sort(O)}function Up(t){return t.startsWith(OF)}function QS(t,e){let n=$e(zS(t,e));if(n===null)return{artifact:null,warning:null};if(n.isSymbolicLink()||Te(t,e))return Hp(e,"it is a symbolic link or lies behind one");if(!n.isFile())return Hp(e,"it is not a regular file");if(n.size>ZS)return Hp(e,`it is larger than ${ZS} bytes`);return{artifact:{file:Do(IF(zS(t,e))),path:e},warning:null}}function Hp(t,e){return{artifact:null,warning:`${t} was not captured: ${e}`}}async function tv(t,e,n){let{contractText:r,task:o}=it(t,e,n),s=Ue(o.contract.pack,Gt(t)),i=Nc(s,e).map((u)=>QS(t,u)),a=await tr(t,{commandOutput:!1,id:e,journal:!1}),{record:c}=o;return{plan:{artifacts:i.flatMap(({artifact:u})=>u===null?[]:[u]),context:{budget:a.budget,estimatedTokens:a.estimatedTokens,knowledge:a.knowledge,sha256:a.sha256,text:a.text},contract:{sha256:Bt(r),text:r},notes:c.notes.map((u)=>({...u})),record:{pack:s.name,stage:c.stage,stageName:s.stages[c.stage]?.name??null,status:c.status}},warnings:i.flatMap(({warning:u})=>u===null?[]:[u])}}function Kp(t){return pt({artifacts:t.artifacts.map(({file:e,path:n})=>[n,e.sha256]),context:t.context.sha256,contract:t.contract.sha256,notes:t.notes,record:t.record})}import{existsSync as lv,mkdirSync as GF,readFileSync as HF,rmSync as UF}from"fs";import{join as Dc}from"path";var ci=1,ev=["manual","pre-compact","approve","stage"],nv=["save","restore"];var iv=["version","id","at","kind","task","pruned"],rv=[...iv,"trigger","reason","contract","record","artifacts","notes","context"],ov=[...iv,"restores","written"],sv="/",_F="..",PF=/[\\\0]/;function av(t,e,n){return At(`snapshot entry ${e}`,n,()=>NF(t))}function NF(t){let e=T(t,"entry",rv.concat(ov)),n=K(nv,e.kind,"kind"),r=ht(e.version,"version");if(r!==ci)throw new b(`version ${r} is not supported`);let o={at:x(e.at,"at"),id:x(e.id,"id"),pruned:Dt(e.pruned,"pruned"),task:x(e.task,"task"),version:ci};if(n==="restore"){let i=T(t,"entry",ov);return{...o,kind:n,restores:x(i.restores,"restores"),written:L(i.written,"written",FF)}}let s=T(t,"entry",rv);return{...o,artifacts:L(s.artifacts,"artifacts",MF),context:ft(s.context,"context",jF),contract:ft(s.contract,"contract",DF),kind:n,notes:L(s.notes,"notes",yd),reason:Ct(s.reason,"reason"),record:ft(s.record,"record",LF),trigger:K(ev,s.trigger,"trigger")}}function DF(t,e){let n=T(t,e,["sha256","text"]);return{sha256:Dn(n.sha256,k(e,"sha256")),text:x(n.text,k(e,"text"))}}function LF(t,e){let n=T(t,e,["pack","stage","stageName","status"]);return{pack:x(n.pack,k(e,"pack")),stage:ht(n.stage,k(e,"stage")),stageName:Ct(n.stageName,k(e,"stageName")),status:K(hd,n.status,k(e,"status"))}}function MF(t,e){let n=T(t,e,["path","file"]);return{file:ft(n.file,k(e,"file"),Oc),path:cv(n.path,k(e,"path"))}}function jF(t,e){let n=T(t,e,["budget","estimatedTokens","knowledge","sha256","text"]);return{budget:ht(n.budget,k(e,"budget")),estimatedTokens:ht(n.estimatedTokens,k(e,"estimatedTokens")),knowledge:Dt(n.knowledge,k(e,"knowledge")),sha256:Dn(n.sha256,k(e,"sha256")),text:x(n.text,k(e,"text"))}}function FF(t,e){let n=T(t,e,["path","before","sha256"]);return{before:n.before===null?null:Oc(n.before,k(e,"before")),path:cv(n.path,k(e,"path")),sha256:Dn(n.sha256,k(e,"sha256"))}}function cv(t,e){let n=x(t,e);if(n.length===0||n.startsWith(sv)||n.split(sv).includes(_F)||PF.test(n))throw new b(`${e} must be a path inside the repository, got ${JSON.stringify(n)}`);return n}var KF="snapshots",BF=Dc("locks","snapshots.lock"),VF="the snapshots",Bp="Restore the file from a backup, or delete it to drop that entry from the snapshot history";function Fr(t){return Dc(t,KF)}function Lc(t,e){return As(Dc(t,BF),VF,e)}function Mc(t,e,n){GF(Fr(t),{recursive:!0});let r=Ic(e,(s)=>lv(nr(t,s))),o={...n,at:e,id:r,version:ci};return Yn(nr(t,r),pt(o),()=>Error(`The snapshot entry ${r} already exists`)),o}function Ln(t){let e=[],n=[];for(let r of _o(Fr(t))){let o=r.slice(0,-gn.length);try{e.push(uv(t,o))}catch(s){n.push({id:o,problem:WF(s)})}}return{entries:e.sort((r,o)=>Pr(r.id,o.id)),unreadable:n.sort((r,o)=>Pr(r.id,o.id))}}function jo(t,e){if(ri(e)&&lv(nr(t,e)))return uv(t,e);let n=Ln(t),r=[...n.entries.map((o)=>o.id),...n.unreadable.map((o)=>o.id)];throw new m(`The snapshot history has no entry "${e}"`,r.length===0?"Run 'ari snapshot' to save the first one":`Known entries: ${r.join(", ")}`)}function jc(t,e){for(let n of e)UF(nr(t,n),{force:!0})}function nr(t,e){return Dc(Fr(t),`${e}${gn}`)}function uv(t,e){let n=nr(t,e),r;try{r=JSON.parse(HF(n,"utf8"))}catch(s){let i=s instanceof Error?s.message:String(s);throw new m(`The snapshot entry ${n} cannot be read (${i})`,Bp)}let o=av(r,n,Bp);if(o.id===e)return o;throw new m(`The snapshot entry ${n} declares the id "${o.id}"`,Bp)}function WF(t){if(t instanceof m)return t.message;return t instanceof Error?t.message:String(t)}var JF=()=>new Date().toISOString(),qF={id:null,warning:null};async function Vp(t,e={}){let n=M(t),r=await P(t),o=e.task??YF(r),{plan:s,warnings:i}=await tv(t,o,n),a=(e.clock??JF)();return Lc(r,()=>{let c=Ln(r).entries.filter((p)=>p.task===o),l=c.findLast(Wp);if(l!==void 0&&Kp(l)===Kp(s))return dv(l.id,o,s,[],i,!1);let u=c.slice(0,Math.max(0,c.length+1-n.snapshots.keep)).map((p)=>p.id),d=Mc(r,a,{...s,kind:"save",pruned:u,reason:e.reason??null,task:o,trigger:e.trigger??"manual"});return jc(r,u),dv(d.id,o,s,u,i,!0)})}async function Fo(t,e,n,r={}){try{if(!M(t).snapshots.auto)return qF;let o=await Vp(t,{clock:r.clock,task:e,trigger:n});return{id:o.saved?o.id:null,warning:o.warnings.length===0?null:o.warnings.join("; ")}}catch(o){let s=o instanceof Error?o.message:String(o);return{id:null,warning:`ari could not save a snapshot of task "${e}" (${s})`}}}function Wp(t){return t.kind==="save"}function YF(t){let e=gt(t);if(e!==null)return e.task;throw new m("No task is active in this worktree","Pass --task <id>, or run 'ari next' to see what to do")}function dv(t,e,n,r,o,s){let{artifacts:i,context:a,record:c}=n;return{artifacts:i.map((l)=>l.path),context:{estimatedTokens:a.estimatedTokens,knowledge:a.knowledge,sha256:a.sha256},id:t,pack:c.pack,pruned:r,saved:s,stage:c.stageName,status:c.status,task:e,warnings:o}}var yv=`
|
|
180
|
+
|
|
181
|
+
`,pv=`
|
|
182
|
+
`,XF=/\s+/g,gv=60,zF=40,mv="...",kv=["tasks","snapshot","rules"],ZF={rules:"Constraints and decisions:",snapshot:null,tasks:"Tasks:"},fv={active:0,ready:1},QF=`No Ariadne tasks yet. Create one with 'ari new "<title>"'.`,tG="Ariadne could not list the tasks of this repository. Run 'ari next' to see why.",eG="No task is active in this worktree and none is ready to start. Run 'ari next'.",nG="No task is active in this worktree. Run 'ari next' for the next action.";function wv(t){let e=[],{root:n,state:r}=t,o=Jp(e,"tasks",()=>Pt(n,t.config),null),s=Jp(e,"knowledge",()=>pe(n),[]),i=o?.tasks??[],a=i.filter((g)=>g.record.status==="active"),c=oG(i,a).map(sG),l=Jp(e,"snapshots",()=>lG(r,a),null),u=s.filter(iG).sort(aG).map(cG),d=rG(o===null?null:i.length+o.invalid.length,c.length),p=[...c.map((g)=>({part:"tasks",text:g})),...l===null?[]:[{part:"snapshot",text:l}],...u.map((g)=>({part:"rules",text:g}))];return{text:dG(d,p,t.config.context.briefBytes),warnings:e}}function rG(t,e){if(t===null)return tG;if(t===0)return QF;return e===0?eG:nG}function Jp(t,e,n,r){try{return n()}catch(o){let s=o instanceof Error?o.message:String(o);return t.push(`ari left the ${e} out of the session brief (${s})`),r}}function oG(t,e){let n=new Set(t.filter((o)=>o.record.status==="done").map((o)=>o.contract.id)),r=t.filter((o)=>o.record.status==="ready"&&o.contract.depends.every((s)=>n.has(s)));return[...e,...r].sort((o,s)=>(fv[o.record.status]??0)-(fv[s.record.status]??0)||O(o.contract.id,s.contract.id))}function sG({contract:t,record:e}){return`- ${t.id}: ${Xp(t.title)} (${t.pack}, ${e.status})`}function iG(t){return t.status==="active"&&pn(t)&&t.scope.length===0}function aG(t,e){return O(t.id,e.id)}function cG(t){return`- ${t.kind} \`${t.id}\`: ${Xp(t.text)}`}function lG(t,e){let n=new Set(e.map((s)=>s.contract.id));if(n.size===0)return null;let o=_o(Fr(t)).map((s)=>s.slice(0,-gn.length)).sort((s,i)=>Pr(i,s));for(let s of o.slice(0,zF)){let i=uG(t,s);if(i===null||i.kind!=="save"||!n.has(i.task))continue;let a=Xp(i.reason??i.trigger),c=a.length>gv?`${a.slice(0,gv-mv.length)}${mv}`:a;return`Latest snapshot of an active task: ${s} of "${i.task}" (${c}); 'ari snapshot show ${s}' prints what it saved.`}return null}function uG(t,e){try{return jo(t,e)}catch{return null}}function dG(t,e,n){let r=Yp(t,qp(e),null);if(yt(r)<=n)return r;let o=yt(`${yv}${hv(e.length)}`),s=[];for(let a of kv.flatMap((c)=>e.filter((l)=>l.part===c))){let c=[...s,a];if(yt(Yp(t,qp(c),null))+o<=n)s.push(a)}let i=e.length-s.length;return pG(Yp(t,qp(s),i===0?null:hv(i)),n)}function qp(t){let e={rules:[],snapshot:[],tasks:[]};for(let{part:n,text:r}of t)e[n].push(r);return e}function Yp(t,e,n){let r=kv.flatMap((o)=>{let s=e[o];if(s.length===0)return[];let i=ZF[o];return[i===null?s.join(pv):[i,...s].join(pv)]});return[t,...r,...n===null?[]:[n]].join(yv)}function hv(t){return`Left out to fit context.briefBytes: ${t} ${t===1?"item":"items"}. 'ari list' and 'ari knowledge list' show everything.`}function Xp(t){return t.replace(XF," ").trim()}function pG(t,e){let n=0,r=0;for(let o of t){if(n+=yt(o),n>e)break;r+=o.length}return t.slice(0,r)}import{resolve as Dv}from"path";var Sv=new RegExp([/\\\n/,/\\(?<escaped>[\s\S])/,/(?<![^ \t\r\n;&|()])#[^\n]*/,/'(?<single>[^']*)'?/,/"(?<double>(?:[^"\\$]+|\\[\s\S]|\$\(cat <<-?[ \t]*["']?(?<mark>\w+)[^\n]*\n[\s\S]*?\n[ \t]*\k<mark>\n\s*\)|\$)*)"?/,/\(\((?<arithmetic>(?:[^()\n]|\([^()\n]*\))*)\)\)/,/<<(?!<)(?<tabs>-?)[ \t]*(?<delimiter>(?:'[^'\n]*'|"[^"\n]*"|\\.|[^ \t\r\n'"\\`;&|()<>])+)/,/(?:(?<![^ \t\r\n;&|()<>])\d+)?[<>]&[ \t]*(?:\d+-?|-)(?![^ \t\r\n;&|()<>])/,/(?<output>(?:&|(?<![^ \t\r\n;&|()<>])\d+)?>(?!\()[>|&]?)/,/(?<input><<<|(?:(?<![^ \t\r\n;&|()<>])\d+)?<(?!\()>?)/,/(?<separator>&&|\|\||\|&|;;|[<>]?\(|[;&|)\n`])/,/(?<blank>[ \t\r]+)/,/(?<plain>[^ \t\r\n'"\\`;&|()<>#]+|[\s\S])/].map(({source:t})=>t).join("|"),"y"),gG=/[ \t\r\n]/,mG=/\$\(cat <<-?[ \t]*(["'])(\w+)\1\n[\s\S]*?\n[ \t]*\2\n\s*\)/g,fG=/\\[\s\S]/g,hG=/\\([$`"\\\n])/g,yG=/[$`]/,kG=/[$*?[]|\{./;var wG=/['"\\]/g,SG=/^\t+/;var vG=/[(`]/,bG=new Set(["-C","-c","--config-env","--exec-path","--git-dir","--namespace","--work-tree"]);function zp(t){let e=[],n=[],r=vv(""),o="words",s=null,i=0,a=(u,d)=>{s=(s??"")+u,r.literal&&=d},c=(u="words")=>{if(s!==null)r[o].push(s);s=null,o=u},l=(u)=>{if(c(),r.literal&&=!vG.test(u),r.words.length+r.inputs.length+r.outputs.length>0)e.push(r);r=vv(u)};while(i<t.length){Sv.lastIndex=i;let u=Sv.exec(t);if(u===null)break;let{arithmetic:d,blank:p,delimiter:g,double:f,escaped:y,input:S,output:I,plain:C,separator:q,single:G,tabs:N}=u.groups??{};if(i+=u[0].length,y!==void 0)a(y,!0);else if(G!==void 0)a(G,!0);else if(f!==void 0)a($G(f),EG(f));else if(d!==void 0)a(d,!1);else if(C!==void 0)a(C,!kG.test(C)&&(s!==null||!C.startsWith("~")));else if(p!==void 0&&s!==null)c();else if(I!==void 0)c("outputs");else if(S!==void 0)c("inputs");else if(g!==void 0)c(),n.push({delimiter:g.replace(wG,""),tabs:N!==""});else if(q!==void 0){if(q===`
|
|
183
|
+
`)for(let H of n.splice(0)){let{body:A,end:R}=TG(t,i,H);r.inputs.push(A),i=R}l(q)}}return l(""),e}function Zp(t){return zp(t).flatMap((e)=>[e,...[...e.words,...e.inputs].filter((n)=>gG.test(n)).flatMap(Zp)])}function Fc(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n]??"";if(!r.startsWith("-"))return{args:t.slice(n+1),directories:e,subcommand:r};if(bG.has(r))n+=1;if(r==="-C")e.push(t[n]??"")}return null}function Gr(t){return t.slice(t.lastIndexOf("/")+1)}function vv(t){return{before:t,inputs:[],literal:!0,outputs:[],words:[]}}function EG(t){return!yG.test(t.replace(mG,"").replace(fG,""))}function $G(t){return t.replace(hG,(e,n)=>n===`
|
|
184
|
+
`?"":n)}function TG(t,e,{delimiter:n,tabs:r}){for(let o=e;o<t.length;){let s=t.indexOf(`
|
|
185
|
+
`,o),i=s===-1?t.length:s,a=t.slice(o,i);if((r?a.replace(SG,""):a)===n)return{body:t.slice(e,o),end:i};o=i+1}return{body:t.slice(e),end:t.length}}import{basename as xG,isAbsolute as AG,join as CG,resolve as Hc}from"path";var RG=/^[A-Za-z_]\w*\+?=/,IG=new Set("! { builtin command do elif else env exec if nohup sudo then time until while".split(" ")),OG=new Map([["mkdir",["created","m mode"]],["rm",["removed",""]],["rmdir",["removed",""]],["tee",["written",""]],["touch",["written","A d r t date reference"]],["truncate",["written","r s reference size"]]]),_G=new Set("ari ariadne cat cd diff echo egrep file gh grep head jq ls popd printf pushd rg tail test wc".split(" ")),PG=new Set("add blame branch commit diff fetch grep log ls-files push show status tag".split(" ")),NG=new Set(["cd","popd","pushd"]),bv=new Set(["","&&",";",`
|
|
186
|
+
`]),DG="S suffix",LG=/^(?:-[a-z0-9E]*i|--in-place)/,MG=/^(?:-[a-zA-Z0-9]*[ef]|--expression|--file)/,jG="e f l expression file line-length",FG=/^-[a-zA-Z0-9]*[eE]/,GG="e E",HG=/^-\w+$/,UG=/^\.\w+$/,KG=/^(?:-[a-zA-Z]*t$|--target-directory)/,BG=/^(?:--staged|-[A-Za-z]*S)/,VG=/^(?:--worktree|-[A-Za-z]*W)/,Ev="of=",tg="--",Qp=".";function Tv(t,e){let n=e,r=e,o=!0,s=t.map((i,a)=>{let c=JG(i,n),[l="",u="-",...d]=Uc(i);if(!NG.has(l))return o=!1,c;return o&&=l==="cd"&&i.literal&&!u.startsWith("-")&&d.length===0,o&&=bv.has(i.before)&&bv.has(t[a+1]?.before??""),r=o?Hc(r,u):r,n=o?r:null,c});return{directory:r,steps:s}}function Uc({words:t}){let e=t.findIndex((n)=>!RG.test(n)&&!IG.has(n));return e===-1?[]:[Gr(t[e]??""),...t.slice(e+1)]}function Kc(t,e=""){let n=new Set(e.split(" ")),r=t.indexOf(tg),o=[],s=r===-1?t:t.slice(0,r);for(let i=0;i<s.length;i+=1){let a=s[i]??"";if(!a.startsWith("-"))o.push(a);else if(n.has(WG(a)))i+=1}return[...o,...r===-1?[]:t.slice(r+1)].filter((i)=>i.length>0)}function WG(t){if(t.startsWith("--"))return t.slice(2);return HG.test(t)?t.slice(-1):""}function JG(t,e){if(!t.literal)return{command:t,resolved:!1,targets:[]};let[n="",...r]=Uc(t),o=n==="git"?Fc(r):null,s=e===null?null:Hc(e,...o?.directories??[]),i=o===null?xv(n,r,e):qG(o.subcommand,o.args,s),a=[...Gc(e,"file",t.outputs),...Gc(s,"file",i?.written),...Gc(s,"directory",i?.created),...Gc(s,"removed",i?.removed)],c=a.filter((l)=>l!==null);return{command:t,resolved:i!==null&&c.length===a.length,targets:c}}function Gc(t,e,n=[]){return n.flatMap((r)=>{if(t===null&&!AG(r))return null;let o=Hc(t??r,r),s=e!=="removed"&&tc(o);if(s&&e==="directory")return[];return{kind:s?"directory":e,path:o}})}function xv(t,e,n){let[r,o]=OG.get(t)??[];if(r!==void 0)return{[r]:Kc(e,o)};switch(t){case"dd":return{written:e.filter((s)=>s.startsWith(Ev)).map((s)=>s.slice(Ev.length))};case"cp":case"ln":case"mv":return YG(t,e,n);case"sed":return{written:$v(e,jG,MG)??[]};case"perl":{let s=$v(e,GG,FG);return s===null?null:{written:s}}default:return _G.has(t)?{}:null}}function qG(t,e,n){switch(t){case"checkout":return e.includes(tg)?{removed:e.slice(e.indexOf(tg)+1)}:null;case"restore":return e.some((o)=>BG.test(o))&&!e.some((o)=>VG.test(o))?{}:{removed:Kc(e,"s source pathspec-from-file")};case"rm":case"mv":return xv(t,e,n);default:return PG.has(t)?{}:null}}function YG(t,e,n){if(e.some((a)=>KG.test(a)))return null;let r=Kc(e,DG),[o=Qp,s]=r.length<2?[Qp,r]:[r.at(-1),r.slice(0,-1)],i=o.endsWith("/")||tc(Hc(n??Qp,o));return{removed:t==="mv"?s:[],written:i?s.map((a)=>CG(o,xG(a))):[o]}}function $v(t,e,n){if(!t.some((s)=>LG.test(s)))return null;let r=Kc(t,e),o=r.length>1&&UG.test(r[0]??"")?r.slice(1):r;return t.some((s)=>n.test(s))?o:o.slice(1)}import{basename as Av,dirname as XG,join as Cv}from"path";var zG=[`${J}/tasks/*.md`,`${J}/designs/**`],ZG="x",QG=/\*\*.*/,t1=".git",e1=[/^(?:ari|hooks|info)(?:\/|$)/,/^(?:HEAD|commondir|config(?:\.worktree)?|gitdir|objects|packed-refs|refs|worktrees)$/,/^(?:objects|refs|worktrees)\/(?!.*\.lock$)/],n1="; pass the paths to change instead of their directory",r1="\x00",Bc=0,o1=1,Rv=128;async function Iv(t,e){let n=Ht(e),r=await t.governing(n),o=Pv(t.opened(),n);if(o!==null)return o;return r.flatMap((i)=>{let a=cn(i.root,n);return a===null||a.length===0?[]:li(i,a)??[]})[0]??null}async function Ov(t,e){let n=[],r=new Map;for(let{kind:o,path:s}of e){let a=o==="removed"&&Fd(s)!==null?Cv(Ht(XG(s)),Av(s)):Ht(s),c=await t.governing(a),l=Pv(t.opened(),a);if(l!==null)n.push(l);let u=o==="removed"?t.opened().filter(({root:d})=>cn(a,d)!==null):[];for(let d of new Set([...c,...u])){let p=r.get(d)??[];r.set(d,[...p,{file:cn(d.root,a)??"",kind:o}])}}for(let[o,s]of r)n.push(...await s1(o,s));return n}async function s1(t,e){let n=e.filter(({kind:a})=>a==="removed").map(({file:a})=>a),r=n.length===0?[]:await l1(t,n),o=n.flatMap((a)=>r.filter((u)=>a.length===0||u===a||u.startsWith(`${a}/`)).flatMap((u)=>{let d=li(t,u);return d===null?[]:`${d}${u===a?"":n1}`}).slice(0,1)),s=e.flatMap(({file:a,kind:c})=>{if(c==="removed"||a.length===0)return[];let l=c==="file"?li(t,a):i1(t,a),u=c==="file"?a:`${a}/`;return l===null?[]:[{guarded:_v(t,a)!==null,name:u,reason:l}]}),i=await u1(t.root,s.filter(({guarded:a})=>!a).map(({name:a})=>a));return[...o,...s.filter(({name:a})=>!i.has(a)).map(({reason:a})=>a)]}function _v(t,e){if(yo(e)&&!et(e,zG))return`${e} is written only by ari; use ari commands instead of editing it`;let n=t.workspace?.task??null;if(n===null)return null;return Object.hasOwn(n.record.lockHashes,e)||et(e,n.contract.lock)?`${e} is locked by task "${n.contract.id}" and must stay unchanged`:null}function li(t,e,n=et){let r=_v(t,e);if(r!==null||yo(e))return r;let o=t.fault??t.workspace?.drift??null;if(o!==null)return`ari cannot check ${e}: ${o}`;let s=t.workspace?.task??null;if(s===null||n(e,s.contract.scope))return null;let{id:i,scope:a}=s.contract;return`${e} is outside the scope of task "${i}" (${a.join(", ")}); change the scope with a contract edit and 'ari amend ${i} --reason <text>', or ask a human`}function i1(t,e){return li(t,`${e}/${ZG}`)===null?null:li(t,e,a1)}function a1(t,e){let n=t.split("/").length,r=e.map((o)=>o.replace(QG,"**").split("/").slice(0,n).join("/"));return et(t,r)}function Pv(t,e){return t.some(({gitDirectories:r,root:o})=>cn(Cv(o,t1),e)===""||r.some((s)=>c1(s,e)))?`${Av(e)} belongs to git and to ari's own state; use git and ari commands instead`:null}function c1(t,e){let n=cn(t,e);return n!==null&&e1.some((r)=>r.test(n))}async function l1({root:t,workspace:e},n){let r=await F(t,["--literal-pathspecs","ls-files","-z","-co","--exclude-standard","--",...n.map((s)=>s.length===0?".":s)],{allowedExitCodes:[Bc,Rv]}),o=r.exitCode===Bc?Ke(r.stdout):n;return[...Object.keys(e?.task?.record.lockHashes??{}),J,...o]}async function u1(t,e){if(e.length===0)return new Set;let n=await F(t,["check-ignore","-z","--stdin"],{allowedExitCodes:[Bc,o1,Rv],stdin:[...new Set(e)].join(r1)});return new Set(n.exitCode===Bc?Ke(n.stdout):[])}var d1="'ari approve' records a human approval; ask a person to run it, and pass text that contains these words in a file, as in 'git commit -F <file>'",p1="'ari trust' records that a person has read the commands in .ari/config.json; ask a person to run it, and to run 'ari trust' without --yes to read them first",g1="'ari uninstall' and 'ari hooks uninstall' remove the hooks that guard this repository; ask a person to run them",m1="'git commit --no-verify' skips ari's pre-commit scope check; commit without --no-verify, -n or core.hooksPath, and fix what the check reports",f1="run it as a plain command with literal paths, or ask a person to run it",h1=/(?:^|\/)(?:ari|ariadne)(?:@[^/]*)?$/,y1="approve",k1="trust",Nv="uninstall",w1="hooks",S1="git",v1="commit",b1="config",E1=/^core\.hookspath$/i,$1=/^(?:--config-env=)?core\.hookspath=|^GIT_CONFIG_KEY_\d+=core\.hookspath$/i,T1=/^(?:--)?unset/,x1=/^(?:--no-veri(?:f|fy)?|-[^-\smFcCtSu]*n\S*)$/,A1=/(?<![\w-])\.ari(?![\w.-])/,eg=/[\s'"`;&|()<>=,]+/,C1=[[/^(?:cp|dd|eval|ln|mkdir|mv|rm|rmdir|tee|touch|truncate|xargs)$/,null],[/^find$/,/^-(?:delete|exec(?:dir)?|ok(?:dir)?)$/],[/^git$/,/^(?:checkout|restore)$/],[/^sed$/,/^(?:-[a-zA-Z]*i|--in-place)/]],R1=/^(?:ba|da|fi|k|z)?sh$/,I1=/^-[a-z]*c$/,O1=/^(?:bun|deno|node|perl|php|python|ruby)[\d.]*$/,_1=/^(?:-[a-zA-Z]*[ceEip]|--eval|--print)$/;async function Lv(t,e,n){let{directory:r,steps:o}=Tv(zp(e),n),s=[...new Set([...await t.governing(n),...await t.governing(r)])],i=P1(Zp(e));if(i!==null&&(s.length>0||await N1(t,e,n)))return{kind:"deny",reason:i};let a=await Ov(t,o.flatMap(({targets:d})=>d));if(a.length>0)return{kind:"deny",reason:[...new Set(a)].join("; ")};let c=o.filter(({resolved:d})=>!d).flatMap((d)=>M1(d)??[])[0],l=s.filter(({fault:d,workspace:p})=>d!==null||p?.task!=null),u=c===void 0?null:F1(l,e,[n,r]);if(u===null)return{kind:"allow"};return{kind:"ask",reason:`the command mentions ${u}, which ari protects, and ari does not resolve what its '${c}' writes; ${f1}`}}function P1(t){if(t.some((e)=>Vc(e,y1)))return d1;if(t.some((e)=>Vc(e,k1)))return p1;if(t.some((e)=>Vc(e,Nv)||Vc(e,w1,Nv)))return g1;return t.some(D1)?m1:null}async function N1(t,e,n){for(let r of new Set(e.split(eg)))if((await t.governing(Dv(n,r))).length>0)return!0;return!1}function Vc({words:t},e,n){return t.some((r,o)=>{if(!h1.test(r))return!1;let[s,...i]=t.slice(o+1).filter((a)=>!a.startsWith("-"));return s===e&&(n===void 0||i.includes(n))})}function D1({words:t}){if(t.some((e)=>$1.test(e)))return!0;return t.some((e,n)=>{let r=Gr(e)===S1?Fc(t.slice(n+1)):null;if(r?.subcommand===b1)return L1(r.args);return r?.subcommand===v1&&r.args.some((o)=>x1.test(o))})}function L1(t){let e=t.findIndex((n)=>E1.test(n));return e!==-1&&(e<t.length-1||t.some((n)=>T1.test(n)))}function M1({command:t}){let[e]=Uc(t),n=t.words.flatMap((o)=>o.split(eg)).filter((o)=>o.length>0);return n.map(Gr).find((o,s)=>j1(o,e,n,s+1))??(!t.literal&&t.outputs.length>0?">":null)}function j1(t,e,n,r){let o=C1.find(([c])=>c.test(t))?.[1];if(o===null)return!0;if(o!==void 0)return n.slice(r).some((c)=>o.test(c));let s=R1.test(t);if(!s&&!O1.test(t))return!1;let i=n.slice(r),a=i.findIndex((c)=>!c.startsWith("-"));if(a===-1&&t===e)return!0;return s?i.some((c)=>I1.test(c)):i.slice(0,a===-1?i.length:a).some((c)=>_1.test(c))}function F1(t,e,n){if(t.length>0&&A1.test(e))return J;let r=new Set(e.split(eg));for(let{root:o,workspace:s}of t){let i=Object.keys(s?.task?.record.lockHashes??{}),a=new Set(i.map(Gr));for(let c of[...r].filter((l)=>a.has(Gr(l)))){let u=[o,...n].map((d)=>cn(o,Ht(Dv(d,c)))).find((d)=>d!==null&&i.includes(d));if(u!==void 0)return u}}return null}var H1="stop.json",U1=500,K1=20000,ge={kind:"allow"},B1={decision:{kind:"ask",reason:"ari could not check this in time; write a simpler command, or ask a person to run it"},expired:!0,warning:"ari hook ran out of time"},V1=Et({task:X(),tree:X()});async function Fv(t){let e=yk();if(Pn.has(t.event))return W1(J1(e,t));let n=await e.at(t.cwd);if(n===null)return Wc(ge);if(n.workspace===null)return Mv(t,n.fault??"");try{let r=[],o=await Y1(t,n.workspace,r);return{...Wc(o),warning:r.length===0?null:r.join("; ")}}catch(r){if(!(r instanceof m))throw r;return Mv(t,Hd(r))}}function Mv({event:t},e){return{...Wc(ge),warning:`ari hook skipped ${t}: ${e}`}}async function W1(t){let e=Promise.withResolvers(),n=setTimeout(e.resolve,K1,B1);try{return await Promise.race([e.promise,t.then(Wc)])}finally{clearTimeout(n)}}function Wc(t){return{decision:t,expired:!1,warning:null}}async function J1(t,e){let{command:n,cwd:r,event:o,paths:s}=e,i=await t.at(r);if(o==="before-shell"&&n!==null)return Lv(t,n,r);if(o==="before-edit"&&s.length>0)return q1(t,e);if(i===null)return ge;return{kind:"ask",reason:`ari found no ${o==="before-edit"?"path":"command"} in the hook payload`}}async function q1(t,e){let n=[];for(let r of e.paths){let o=await Iv(t,jv(e.cwd,r));if(o!==null)n.push(o)}return n.length===0?ge:{kind:"deny",reason:n.join("; ")}}async function Y1(t,e,n){switch(t.event){case"before-edit":case"before-shell":return ge;case"after-tool":return Jc(e,X1(t,e)),ge;case"stop":{let r=await z1(e);if(r.kind==="allow"&&e.config.knowledge.sleepOnStop)await Q1(e.root);return r}case"pre-compact":{let r=await Z1(e);if(r!==null)n.push(r);return Jc(e,{detail:{},type:"compact"}),await Mr(e.root),ge}case"session-start":return eH(e,n)}}function X1(t,e){let n=Ht(e.root),r=t.paths.flatMap((o)=>cn(n,Ht(jv(t.cwd,o)))??[]);if(r.length>0)return{detail:{paths:r},type:"edit"};if(t.command!==null)return{detail:{command:t.command.slice(0,U1)},type:"shell"};return{detail:t.tool===null?{}:{tool:t.tool},type:"tool"}}async function z1(t){let{task:e}=t;if(e===null||e.record.status!=="active")return ge;let n=e.contract.id,r=await Ae(t.root,[Er]);if(e.record.evidence.at(-1)?.treeHash===r)return ge;let o=G1(t.state,H1),s=nc(o,V1,null);if(s?.task===n&&s.tree===r)return ge;return Rr(o,`${JSON.stringify({task:n,tree:r})}
|
|
187
|
+
`),Jc(t,{detail:{blocked:!0},type:"stop"}),{kind:"block",reason:`Task "${n}" has changes that no gate has passed yet. Run 'ari check', fix what it reports, then 'ari done'. If you are stuck, run 'ari block ${n} --reason <question>' for a human.`}}async function Z1(t){if(t.task===null)return null;return(await Fo(t.root,t.task.contract.id,"pre-compact")).warning}async function Q1(t){try{await JS(t)}catch(e){let n=e instanceof Error?e.message:String(e);throw new m(`the sleep pass at stop failed (${n})`,"Run 'ari sleep' to see the failure, or set knowledge.sleepOnStop to false")}}function tH(t,e){if(!t.config.hooks.brief)return ge;try{let n=wv(t);return e.push(...n.warnings),{kind:"context",text:n.text}}catch(n){let r=n instanceof Error?n.message:String(n);return e.push(`ari could not build the session brief (${r})`),ge}}async function eH(t,e){if(t.task===null)return tH(t,e);Jc(t,{detail:{},type:"session"});let{text:n}=await tr(t.root,{id:t.task.contract.id});return n.trim().length===0?ge:{kind:"context",text:n}}function Jc(t,e){if(t.task===null)return;$r(t.state,{...e,at:new Date().toISOString(),task:t.task.contract.id})}var Go="git",nH={amp:"Amp",opencode:"OpenCode"},rH=".git/hooks";function ng(){return[...Ie.map((t)=>t.name),Go]}function Pe(t){let e=Ie.find((r)=>r.name===t);if(e!==void 0)return e;if(t===Go)throw new v("git hooks run 'ari scope --staged' and 'ari verify' directly","Run 'ari hooks install --agent git'");let n=nH[t];if(n!==void 0)throw new m(`${n} hooks run only as in-process plugins, which ari does not ship`,"Rely on the AGENTS.md block from 'ari init', 'ari hooks install --agent git' and 'ari verify' in CI");throw new v(`Unknown agent "${t}"`,`Choose one of: ${ng().join(", ")}`)}function Gv(t){if(t!==Go)Pe(t)}async function Ho(t,e){if(e===Go)return ac(t);return qk(t,Pe(e),await P(t))}async function Hv(t,e){if(e===Go)return cc(t);return pc(t,Pe(e),await P(t))}async function Uv(t){return[...Ie.map((n)=>({agent:n.name,events:Bs(n),file:n.file,installed:un(t,n),label:n.label,support:n.support})),{agent:Go,events:[...Gk],file:rH,installed:await To(t),label:"git",support:"git"}]}async function Kv(t,e,n,r){let o=Pe(t),s=oH(o,e);try{let{decision:i,expired:a,warning:c}=await Fv(o.parse(s,sH(n),r));return{expired:a,stdout:Yd(o,s,i),warning:c}}catch(i){if(!Pn.has(s))throw i;let a=`ari could not check this ${s} event: ${i instanceof Error?i.message:String(i)}`;return{expired:!1,stdout:Yd(o,s,{kind:"deny",reason:a}),warning:a}}}function oH(t,e){if(!Ok(e))throw new v(`Unknown hook event "${e}"`,`Choose one of: ${Wd.join(", ")}`);if(Bs(t).includes(e))return e;throw new v(`${t.label} has no ari adapter for "${e}"`,`Its adapter handles: ${Bs(t).join(", ")}`)}function sH(t){if(t.trim().length===0)return{};let e=null;try{e=JSON.parse(t)}catch{}if(z(e))return e;throw new m("The hook payload on stdin is not a JSON object","Agents call 'ari hook' with a JSON object")}import{homedir as Bv}from"os";import{join as iH}from"path";var Mn=["project","user"],aH=".ari",cH="receipts",lH="~/";function rr(t){let e=t??"project",n=Mn.find((r)=>r===e);if(n!==void 0)return n;throw new v(`Unknown scope "${e}"`,`Choose one of: ${Mn.join(", ")}`)}async function xt(t,e){if(t==="user")return{base:Bv(),receipts:iH(Bv(),aH,cH),scope:t};let n=await Jn(e);return{base:n,receipts:await P(n),scope:t}}function oe(t,e){return t==="user"?`${lH}${e}`:e}function ui(t,e,n){let r=t.find((o)=>o.agent===e);if(r!==void 0)return r;throw new v(`ari has no ${n} integration for "${e}"`,`Choose one of: ${t.map((o)=>o.agent).join(", ")}`)}function rg(t,e,n){return[...new Set(e)].map((r)=>ui(t,r,n))}import{isDeepStrictEqual as hH}from"util";function qc(t){let{base:e,file:n,receipts:r}=t,o=W(e,n),s=t.install(o),i=Ao(r.directory,n,r.store),a=t.managed(o)?void 0:o,c=i?.installed===o?i.original:a,l=Ce(e,n,s),u=W(e,n)??"";return Co(r.directory,n,c===void 0?null:{installed:u,original:c},r.store),l}function uH(t,e,n){if(e===null||!t.managed(e))return Hs;if(n?.installed!==e){let r=t.remove(e);return r===null?Us:xo(r,!1)}return n.original===null?Us:xo(n.original,!0)}function Yc(t,e,n){let{base:r,file:o,receipts:s}=t,i=Ao(s.directory,o,s.store),a=dc(r,o,uH(t,e.read(r,o),i),e);if(n)Co(s.directory,o,null,s.store);return a}function Xc(t){return Yc(t,uc,!0).action}function mn(t){return t.managed(W(t.base,t.file))}import{isDeepStrictEqual as dH}from"util";var Uo="# ari:begin",di="# ari:end",pi=`\r
|
|
188
|
+
`,fn=`
|
|
189
|
+
`,pH=1,gH=/^\r?\n/,mH=/\r$/;function Wv(t){return(t??"").split(fn).some((e)=>sg(e,Uo))}function Jv(t,e){let n=t??"";og(e.file,n);let r=n.includes(pi)?pi:fn,o=[`${Uo} managed by 'ari mcp install'; 'ari mcp uninstall' removes it`,...e.lines,di].join(r),s=Yv(e.file,n);if(s===null&&Vv(og(e.file,n),e.table)!==void 0)throw new m(`${e.file} already defines [${e.table.join(".")}] outside ari's managed block`,`Remove that table from ${e.file}, or keep it and do not install ari's`);let i=s===null?fH(n,o,r):n.slice(0,s.start)+o+n.slice(s.end),a;try{a=og(e.file,i)}catch(c){throw new m(`ari cannot add [${e.table.join(".")}] to ${e.file} without breaking it`,`Add the table yourself:
|
|
190
|
+
${e.lines.join(fn)}`,pH,{cause:c})}if(dH(Vv(a,e.table),e.value))return i;throw new m(`ari cannot add [${e.table.join(".")}] to ${e.file}: the file defines it in another way`,`Add the table yourself:
|
|
191
|
+
${e.lines.join(fn)}`)}function qv(t,e){let n=Yv(t,e);if(n===null)return e;let r=e.slice(0,n.start),o=e.slice(n.end).replace(gH,""),i=(r.endsWith(`${pi}${pi}`)?r.slice(0,-pi.length):r.endsWith(`${fn}${fn}`)?r.slice(0,-fn.length):r)+o;return i.trim().length===0?null:i}function fH(t,e,n){if(t.length===0)return`${e}${n}`;return`${t.endsWith(fn)?t:`${t}${n}`}${n}${e}${n}`}function Yv(t,e){let n=[],r=0;for(let i of e.split(fn)){let a=r+i.replace(mH,"").length;if(sg(i,Uo))n.push({end:a,kind:Uo,start:r});else if(sg(i,di))n.push({end:a,kind:di,start:r});r+=i.length+fn.length}let[o,s]=n;if(o===void 0)return null;if(n.length!==2||o.kind!==Uo||s?.kind!==di)throw new m(`${t} has a damaged ari block: expect one '${Uo}' line followed by one '${di}' line`,`Remove the ari marker lines and the lines between them from ${t}, then run the command again`);return{end:s.end,start:o.start}}function sg(t,e){let n=t.trim();return n===e||n.startsWith(`${e} `)}function og(t,e){try{return Bun.TOML.parse(e)}catch(n){let r=n instanceof Error?n.message:String(n);throw new m(`${t} is not valid TOML (${r})`,`Fix ${t}, then run the command again`)}}function Vv(t,e){return e.reduce((n,r)=>typeof n==="object"&&n!==null?n[r]:void 0,t)}var hn="ari",ig="ari",Zc=["mcp","serve"],gi="mcpServers",yH="mcp.json",Xv=900,kH=1000,wH=2,zc={command:ig,args:Zc},se=[{agent:"claude",entry:zc,format:"json",label:"Claude Code",project:".mcp.json",user:null,userHint:`Claude Code keeps user-scope servers in its own state file; run 'claude mcp add --scope user ${hn} -- ${ig} ${Zc.join(" ")}'`},{agent:"codex",entry:{...zc,tool_timeout_sec:Xv},format:"toml",label:"Codex CLI",project:".codex/config.toml",user:".codex/config.toml",userHint:null},{agent:"gemini",entry:{...zc,timeout:Xv*kH},format:"json",label:"Gemini CLI",project:".gemini/settings.json",user:".gemini/settings.json",userHint:null},{agent:"cursor",entry:{type:"stdio",...zc},format:"json",label:"Cursor",project:".cursor/mcp.json",user:".cursor/mcp.json",userHint:null}];function me(t){return ui(se,t,"MCP")}function Ne(t,e){return tl(t,e)}function Ko(t,e){let n=tl(t,e);return{...Qv(t,e,n.file),action:qc(n)}}function Qc(t,e){let n=tl(t,e);return{...Qv(t,e,n.file),action:Xc(n)}}function Zv(t,e){return se.map((n)=>({agent:n.agent,files:[t,e].flatMap((r)=>{let o=n[r.scope];if(o===null)return[];let s=mn(tl(n,r));return[{file:oe(r.scope,o),installed:s,scope:r.scope}]}),label:n.label}))}function Qv(t,e,n){return{agent:t.agent,file:oe(e.scope,n),scope:e.scope,server:hn}}function tl(t,e){let n=t[e.scope];if(n===null)throw new m(`ari does not write ${t.label}'s ${e.scope}-scope MCP configuration`,t.userHint??"");let r={directory:e.receipts,store:yH},o={base:e.base,file:n,receipts:r};return t.format==="toml"?{...o,...SH(t,n)}:{...o,...vH(t,n)}}function SH(t,e){let n={file:e,lines:[`[mcp_servers.${hn}]`,...bH(t.entry)],table:["mcp_servers",hn],value:t.entry};return{install:(r)=>Jv(r,n),managed:Wv,remove:(r)=>qv(e,r)}}function vH(t,e){let n=(o)=>{let s=o[gi]??{};if(z(s))return s;throw new m(`${e} has a "${gi}" value that is not an object`,`Fix ${e}`)},r=(o,s)=>o===null?`${JSON.stringify(s,null,wH)}
|
|
192
|
+
`:Xa(o,s);return{install:(o)=>{let s=o===null?{}:re(e,o),i=n(s),a=i[hn];if(a!==void 0&&!zv(a))throw new m(`${e} already has an MCP server named "${hn}" that ari did not write`,`Rename or remove mcpServers.${hn} in ${e}, then run the command again`);let c={...z(a)?a:{},...t.entry};return r(o,{...s,[gi]:{...i,[hn]:c}})},managed:(o)=>o!==null&&zv(n(re(e,o))[hn]),remove:(o)=>{let{[gi]:s,...i}=re(e,o),{[hn]:a,...c}=n(re(e,o));return r(o,Object.keys(c).length===0?i:{...i,[gi]:c})}}}function bH(t){let{args:e,command:n,...r}=t;return Object.entries({command:n,args:e,...r}).map(([o,s])=>`${o} = ${tb(s)}`)}function tb(t){if(Array.isArray(t))return`[${t.map(tb).join(", ")}]`;return typeof t==="number"?String(t):JSON.stringify(t)}function zv(t){if(!z(t)||t.command!==ig||!Array.isArray(t.args))return!1;return hH(t.args.slice(0,Zc.length),Zc)}import{existsSync as $H,readdirSync as TH,rmdirSync as xH}from"fs";import{dirname as ub,join as db}from"path";var ag="```",EH=["`ari approve`, `ari amend`, `ari resolve` and `ari trust` are for people. Never run them; ask instead.","`ari snapshot restore` is a person's decision when it would replace an approved design: an approval does not survive a changed design."];function yn(t=[]){return["## What only people do","",...[...EH,...t].map((e)=>`- ${e}`)].join(`
|
|
193
|
+
`)}function De(...t){return t.map((e)=>typeof e==="string"?e:e.join(`
|
|
194
|
+
`)).join(`
|
|
195
|
+
|
|
196
|
+
`)}var eb={body:De(["# Ariadne","",'This repository tracks work as Ariadne tasks. A task\'s contract (`.ari/tasks/<id>.md`) says what "done" means, and `ari` runs its checks. Never call a task finished on your own word: only `ari done` finishes a stage.'],["## The loop","","1. Run `ari next` and follow the one action it prints.","2. Change only files inside the task's `scope`. Locked files stay byte-identical.","3. Run `ari check` to evaluate the stage's gates. It records nothing.","4. Run `ari done`. It records the evidence and advances, or prints every failing gate and exits 1.","","A failed `ari done` spends an attempt (3 by default), and a spent budget blocks the task for a person, so run `ari check` first. The MCP tools `ari_next`, `ari_check` and `ari_done` return the same JSON as the commands.","","Also: `ariadne-design`, `ariadne-contract`, `ariadne-implement`, `ariadne-review`, `ariadne-memory`."],["## What the gates mean","","| Gate | Passes when |","| --- | --- |","| `criteria` | each criterion names an existing check |","| `checks` | each selected check exits as expected |","| `invariants` | every invariant exits 0 |","| `scope` | every changed file is in scope |","| `locked` | locked files are unchanged |","| `tests-unchanged` | test files in scope are unchanged in the stage |","| `regression` | a regression check fails on the base commit, passes now |","| `artifact` | the file has enough bytes; `sections`: each listed `##` section has a body; `traceable`: its `AC-n` ids are the contract's |","| `approval` | a person approved, and nothing changed since |","| `review` | the reviewer passed the change |","| `command` | the pack's command exits 0 |","","`contractChanged` or `gatesChanged` in `ari check` means the frozen contract or gates differ and `ari done` refuses: ask a person to amend."],["## What only people do","","- `ari approve`, `ari amend`, `ari resolve` and `ari trust` are for people: ask instead. So is `ari snapshot restore` over an approved design.","- On `ConfigNotTrusted`, ask a person to run `ari trust`; never set `ARI_TRUST_CONFIG`.",'- Stuck, or the contract is wrong: `ari block <id> --reason "<question>"`, then stop.',"- Never edit `.ari/config.json`, `.ari/tasks/*.json` or `.ari/knowledge/**`, and never use `git commit --no-verify`."]),description:"Work through this repository's Ariadne (ari) tasks, whose contracts and gates the ari CLI keeps. Use it whenever the repository has an .ari/ directory, before changing code there, and to pick up, check or finish a task.",name:"ariadne"};var nb={body:De(["# Write the contract","",'The contract (`.ari/tasks/<id>.md`) is what `ari` judges the work by, so write it with the person. Take the criteria from their request; never invent one. `ari new "<title>" --pack <pack> --scope "<globs>"` creates the draft. Choose the pack by the work:'],["| Work | Pack |","| --- | --- |","| a new feature | `feature` |","| a defect | `bugfix` |","| a change that keeps behaviour | `refactor` |","| unknown territory, findings first | `spike` |","| a quick, known change | `basic` |","| tests first | `tdd` |","| a specification to approve first | `spec-driven` |","| a design and a review without the structured design | `sdlc` |"],["Then complete the front matter:","",`${ag}markdown`,"---","title: Add profile inheritance","pack: feature","scope: [src/profiles/**]","lock: [src/profiles/inheritance.test.ts]","criteria:"," - id: AC-1"," text: A child profile's values override its parent's"," checks: [inheritance]","checks:"," inheritance:"," run: bun test src/profiles/inheritance.test.ts"," expect: pass","invariants: [bun run lint]","---",ag],["- Criterion ids are `AC-1`, `AC-2` and so on. The design's Acceptance criteria must list exactly these ids.","- Bind every criterion to at least one check, a shell command run from the repository root. Write it so that it fails before the change and passes after; `expect: regression` makes ari prove the failure on the base commit.","- `scope` lists globs: write `src/**`, never `src/`. `lock` keeps the files that define the work, such as tests, unchanged from the start."],["Run `ari ready <id>`; it lists every problem in the contract. `ari start <id>` then needs a clean working tree outside `.ari/`. After the start a changed contract needs a person to run `ari amend`."],yn()),description:"Use when a request has to become an ari task contract. Covers choosing the pack, writing scope, lock, criteria and checks, marking the task ready and starting it, and fixing a draft that ari ready rejects.",name:"ariadne-contract"};var rb={body:De(["# Design a feature","","Use this when a feature needs a design, or when `ari next` says the task is in its design stage. The design is `.ari/designs/<id>.md`. `ari check` reads its structure, never its meaning, so the meaning is your job."],["## Steps","","1. Search before you design: `ari knowledge search <query>`. Note the id of every entry that matters.",'2. With no task yet, run `ari new "<title>" --pack feature`, write the contract with the person (`ariadne-contract`), then `ari ready <id>` and `ari start <id>`. The contract comes first because the design must trace to its criteria `AC-1`, `AC-2` and so on.',"3. Fill the sections of the design in order. Problem. Context: one `- <knowledge id>: why it matters` line for each entry you consulted. Options: at least two, each with its cost. Decision: the option, and why it beats the others. Acceptance criteria: one `- AC-n: text` line for each criterion of the contract, no more and no fewer. Scope. Risks and open questions (`None` if there are none). Replace every placeholder.","4. When a choice is the person's (a trade-off, a missing requirement, a risk to accept), ask one question at a time and wait. Never invent requirements.","5. Run `ari check` until the artifact gate passes. It lists every empty or missing section and every criterion id that differs.",'6. Run `ari snapshot --reason "design ready"`, then stop and ask the person to run `ari approve <id>`. Editing the design after approval voids it.','7. After approval, run `ari done`, and record the decision: `ari note --global --kind decision "<what was decided and why>"`.'],["A criterion the design needs but the contract lacks is a change to the contract: ask a person to run `ari amend`. When ari's MCP server is connected, `ari_check`, `ari_snapshot`, `ari_note` and `ari_done` do the same and return the same documents."],yn()),description:"Use when asked to design, plan or scope a feature, or when an ari task is in a design stage (the feature or sdlc pack). Fills .ari/designs/<id>.md section by section until ari check passes, then asks a person to approve it.",name:"ariadne-design"};var ob={body:De(["# Implement the task","","Run `ari next` and obey the one action it prints; `ari show <id>` prints the stage and its instruction. Change only files inside the contract's `scope`, and never a locked one."],["| Pack and stage | What to do |","| --- | --- |","| `basic` implement | make the checks of every criterion pass |","| `tdd` red | write failing tests for each criterion, and do not implement |","| `tdd` green | the smallest change that passes; do not edit the tests |","| `tdd` refactor | improve the code, checks green, tests unchanged |","| `bugfix` reproduce | write a regression check that fails because of the bug; do not fix it |","| `bugfix` fix | fix it: the check passes here and still fails on the base commit |","| `refactor` refactor | restructure without changing behaviour; tests unchanged |","| `feature` or `sdlc` implement | implement the approved design until every check passes |"],['1. Work in small steps. Before you change the plan or the design, run `ari snapshot --reason "<why>"`; it saves the plan and the context pack, not code.',"2. Run `ari check` after each step. It runs the stage's gates and records nothing; fix what it reports.","3. Run `ari done` only when `ari check` passes. A failed `ari done` spends one of the task's attempts (3 by default), and the task blocks when they run out.",'4. When you are stuck, or the contract looks wrong, run `ari block <id> --reason "<question>"` and stop. Do not widen the scope, edit a locked file or weaken a check to pass a gate.','5. A surprise that cost you time is worth a line: `ari note "<text>"`, or `ari note --global --kind gotcha "<text>"` for the project.',"6. The last stage of `feature` and `sdlc` is review: load `ariadne-review`."],yn()),description:"Use when an ari task is in an implement stage, or runs the basic, tdd, bugfix or refactor pack. Covers following ari next, staying in scope, running ari check before ari done, and blocking the task instead of weakening a gate.",name:"ariadne-implement"};var sb={body:De(["# Memory","","Memory is files that ari keeps: task notes, the journal, `.ari/knowledge/*.md` and the ledgers under the git directory. Use the commands; never edit `.ari/knowledge/**`, `.ari/tasks/*.json` or a ledger."],["## Read","","- Before you design or decide: `ari knowledge search <query>`, and `ari knowledge show <id>` for one entry.","- After your context was reset or compacted: `ari context` prints the active task's contract, notes and relevant knowledge within a token budget (`--budget <tokens>` changes it). `ari snapshot list` then `ari snapshot show <id>` print the plan and context pack as last saved."],["## Write","",'- `ari note "<text>"` adds a note to the active task: progress, a finding, a dead end.','- `ari note --global --kind <kind> "<text>"` adds project knowledge that outlives the task. The kinds are `fact` (how things are), `decision` (what was chosen, and why), `constraint` (a rule that must hold), `pattern` (how it is done here) and `gotcha` (a trap that cost time). One idea per entry, in plain words. `--scope "<globs>"` ties it to files.',"- Never write a secret, a token or a credential into a note."],["## Housekeeping","","`ari sleep --if-due` consolidates memory when it is due and does nothing otherwise; every pass is logged and `ari sleep --undo` reverses the last one. `ari snapshot` saves the plan before a risky change, and identical state writes nothing."],yn()),description:"Use when you learn something worth keeping, before you design or decide, and after your context was reset or compacted. Covers ari note and its kinds, ari knowledge search, ari context, ari snapshot show and ari sleep.",name:"ariadne-memory"};var ib={body:De(["# Review the change","","`ari review` has the configured review agent judge the change in a temporary copy and prints its verdict and findings. It changes and records nothing. `ari done` in a review stage runs the review gate: it passes when the review command exits 0 or the review agent answers `pass`, and with neither configured a person approves."],["1. Run `ari check` first; review a change whose gates already pass.","2. Run `ari review`. Exit 1 means it failed, and any doubt fails it (an unreadable answer, a timeout, a changed file).","3. Fix every `critical` and `major` finding, which block, then run `ari review` again. Fix a `minor` one when it is cheap, otherwise say why you left it in `ari note`. An `info` finding needs no action.",'4. Never edit the contract or the review configuration to get a pass. When the review is wrong, say so with `ari block <id> --reason "<question>"`.',"5. When it passes, run `ari done`."],["## Argus candidates","","With `review.argus` configured, or `ari review --argus`, the review prompt lists candidates from a decision model. They are leads, never findings: check each against the code before you act. With `ari review --argus-verdicts` (or `review.argus.verdicts`) a reviewer may answer a lead in an optional `candidates` array of `{ id, verdict, rationale }`, where verdict is `confirmed`, `false_positive`, `deferred` or `uncertain`. Answer only a lead you checked against the code and reached a verdict on. A guess is worse than silence, because the answer is stored."],yn(["With no review command or agent configured, `ari approve` on the review stage is the person's review."])),description:"Use when an ari task reaches its review stage, when asked to review a change, or when ari review or the review gate reports findings. Covers ari review, what each severity means, the review gate and the optional Argus candidates and answers.",name:"ariadne-review"};var ab="SKILL.md",el="<!-- ari:managed by 'ari skills install'; 'ari skills uninstall' removes it -->";function cb({body:t,description:e,name:n}){let r=["---",`name: ${n}`,`description: ${e}`,"---","<!-- ari:managed by 'ari skills install'; 'ari skills uninstall' removes it -->",""].join(`
|
|
197
|
+
`);return{description:e,name:n,text:`${r}
|
|
198
|
+
${t}
|
|
199
|
+
`}}var ot=[eb,rb,nb,ob,ib,sb].map(cb);function lb(t){if(t.length===0)return ot;let e=ot.map((r)=>r.name),n=t.find((r)=>!e.includes(r));if(n!==void 0)throw new v(`ari has no skill named "${n}"`,`Choose one of: ${e.join(", ")}`);return ot.filter((r)=>t.includes(r.name))}var AH="skills.json",fe=[{agent:"claude",label:"Claude Code",project:".claude/skills",user:".claude/skills"},{agent:"codex",label:"Codex CLI",project:".agents/skills",user:".agents/skills"},{agent:"gemini",label:"Gemini CLI",project:".gemini/skills",user:".gemini/skills"},{agent:"cursor",label:"Cursor",project:".cursor/skills",user:".cursor/skills"}];function Jt(t){return ui(fe,t,"skill")}function mi(t,e,n){return db(t[e],n,ab)}function ie(t,e,n){return ug(t,e,n)}function pb(t,e){for(let n of fe){let r=ot.find((o)=>mi(n,t.scope,o.name)===e);if(r!==void 0)return{skill:r,target:n}}return null}function Bo(t,e,n=ot){return n.map((r)=>{let o=ug(t,e,r),s=W(o.base,o.file);if(s!==null&&!o.managed(s))return{...cg(t,e,r),action:"refused",reason:mb(e,o.file)};return{...cg(t,e,r),action:qc(o)}})}function nl(t,e,n=ot){return n.map((r)=>{let o=ug(t,e,r),s=Xc(o);if(s==="removed")fb(e.base,ub(o.file));return{...cg(t,e,r),action:s}})}function rl(t,e){let n=t.filter((s)=>s.action==="refused"),[r]=n;if(r===void 0)return;let o=n.length===1?r.reason??"":`${n.length} skills exist and ari did not write them: ${n.map((s)=>s.file).join(", ")}`;throw new m(o,ol(n.length,e))}function ol(t,e){return`Move or remove ${t===1?"that skill":"those skills"}, then run 'ari skills install --agent ${e}' again`}function lg(t){if(t.every((e)=>e==="unchanged"))return"unchanged";if(t.every((e)=>e==="created"))return"created";if(t.every((e)=>e==="removed"))return"removed";return"updated"}function gb(t){let e=t.filter((r)=>r.action!=="unchanged");if(e.length===0)return{action:"unchanged",restored:null};let n=e.map((r)=>r.restored);return{action:e.every((r)=>r.action==="removed")?"removed":"updated",restored:n.find((r)=>r==="original")??n.find((r)=>r!==null)??null}}function cg(t,e,n){let r=oe(e.scope,mi(t,e.scope,n.name));return{agent:t.agent,file:r,scope:e.scope,skill:n.name}}function mb(t,e){return`${oe(t.scope,e)} exists and ari did not write it`}function ug(t,e,n){let r=mi(t,e.scope,n.name),o=(s)=>(s??"").includes(el);return{base:e.base,file:r,install:(s)=>{if(s===null||o(s))return n.text;throw new m(mb(e,r),ol(1,t.agent))},managed:o,receipts:{directory:e.receipts,store:AH},remove:()=>null}}function fb(t,e){let n=db(t,e);if(e==="."||!$H(n)||TH(n).length>0)return;xH(n),fb(t,ub(e))}var jt="AGENTS.md",dg="<!-- ari:begin -->",sl="<!-- ari:end -->",IH=/^ {0,3}(<!-- ari:(?:begin|end) -->)\s*$/,OH=/^ {0,3}(`{3,}(?=[^`]*$)|~{3,})/,_H=/^ {0,3}(`{3,}|~{3,})[ \t]*\r?$/,pg=`${J}/config.json`,PH="git",hb=`\r
|
|
200
|
+
`,gg=`
|
|
201
|
+
`,NH=[dg,"## Ariadne","","This repository tracks work as Ariadne (`ari`) tasks. Work in this loop:","","1. Run `ari next` and follow the one action it prints.","2. Change only files inside the active task's `scope`.","3. Run `ari check` to evaluate the current stage's gates.","4. Run `ari done`; it records evidence and advances. Fix what it reports and run it again.","",'Record learnings with `ari note "<text>"` and reload context with `ari context`. If you are stuck, ask a human with `ari block <id> --reason "<question>"`.',"When the task's pack starts with a design stage (the `feature` and `sdlc` packs), the design in `.ari/designs/<id>.md` comes first and a person approves it: run `ari snapshot` before you ask, and never run `ari approve` yourself.","Skills for designing, writing contracts, implementing, reviewing and memory (`ariadne`, `ariadne-design`, `ariadne-contract`, `ariadne-implement`, `ariadne-review`, `ariadne-memory`) load on demand from `.claude/skills`, `.agents/skills`, `.gemini/skills` or `.cursor/skills`; `ari skills list` shows them.","Edit task contracts (`.ari/tasks/*.md`) and designs, never other files under `.ari/`: ari writes them. `ari --help --json` describes every command.",sl];function mg(t){let e=fi(W(t,jt));return{action:Ce(t,jt,e),path:jt}}function fg(t,e){return Ce(t,pg,hg(W(t,pg),e))}function hg(t,e){let n=t??qy();if(e===null)return n;let r=re(pg,n);if(vr(r).pack===e)return n;return zn(n,{...r,pack:e})}async function yb(t,e={}){let n=[...e.agents??[],...e.gitHooks===!0?[PH]:[]],r=[...new Set(n)];for(let f of r)Gv(f);let o=rg(se,e.mcp??[],"MCP"),s=rg(fe,e.skills??[],"skill"),i=CH(RH(t,J))?Gt(t):[],a=e.pack===void 0?null:Ue(e.pack,i).name,c=fg(t,a),l=mg(t),u=[];for(let f of r)u.push(await Ho(t,f));let d={base:t,receipts:await P(t),scope:"project"},p=o.map((f)=>Ko(f,d)),g=s.flatMap((f)=>{let y=Bo(f,d);return rl(y,f.agent),y});return{agentsMd:l,config:c,hooks:u,mcp:p,pack:M(t).pack,root:t,skills:g}}function fi(t){let e=t??"",n=e.includes(hb)?hb:gg,r=NH.join(n),o=DH(e),[s,i]=o;if(s===void 0){let a=e.length===0?"":e.endsWith(n)?n:`${n}${n}`;return`${e}${a}${r}${n}`}if(o.length!==2||s.marker!==dg||i?.marker!==sl)throw new m(`${jt} has a damaged ari block: expect one ${dg} followed by one ${sl}`,`Remove the ari markers and the lines between them from ${jt}, then run 'ari init' again`);return`${e.slice(0,s.start)}${r}${e.slice(i.start+sl.length)}`}function DH(t){let e=[],n=null,r=0;for(let o of t.split(gg)){let s=OH.exec(o)?.[1];if(n===null&&s!==void 0)n={mark:s,markers:e.length};else if(n!==null&&LH(o,n.mark))e.length=n.markers,n=null;let i=IH.exec(o)?.[1];if(i!==void 0)e.push({marker:i,start:r+o.indexOf(i)});r+=o.length+gg.length}return e}function LH(t,e){return _H.exec(t)?.[1]?.startsWith(e)===!0}function Hr(t){return t.kind==="config"?"ari init":Sb("install",t)}function wb(t){return Sb("uninstall",t)}function Sb(t,{agent:e,kind:n,scope:r}){switch(n){case"hooks":return e===null?null:`ari hooks ${t} --agent ${e}`;case"git":return`ari hooks ${t} --agent git`;case"mcp":return e===null?null:`ari mcp ${t} --agent ${e}${kb(r)}`;case"skill":return e===null?null:`ari skills ${t} --agent ${e}${kb(r)}`;case"config":case"routing":return null}}function kb(t){return t==="user"?" --scope user":""}var bb=5000,MH=new Set(["created","updated","unchanged"]),jH="2025-11-25",Eb=2,FH="ari_next",GH=new Set(["hooks","mcp","skill","git"]),HH="<!-- ari:begin -->",$b=".ari/config.json",UH=".git/hooks",Tb="Install ari globally (bun add -g @r5n/ariadne), then run 'ari install' again";async function yg(t,e,n={}){let r=e.filter((a)=>MH.has(a.action)),o=await Promise.all(KH(r).map((a)=>BH(t,a)));if(!r.some((a)=>GH.has(a.kind)))return o;let s=n.ari===void 0?Bun.which("ari"):n.ari,i=s!==null&&r.some((a)=>a.kind==="mcp")?[await wg(s,t,n.timeoutMs??bb)]:[];return[kg(s),...i,...o]}function kg(t){return t===null?Vo("ari on PATH","ari is not on PATH, so agents cannot start it",Tb):Sg("ari on PATH",t)}function wg(t,e,n=bb){return qH(t,e,n)}function KH(t){let e=new Set;return t.filter((n)=>{let r=n.kind==="git"?"git":n.kind==="routing"?"config:.ari/config.json":`${n.kind}:${n.file}`;if(e.has(r))return!1;return e.add(r),!0})}async function BH(t,e){let n=il(e),r=e.kind==="routing"?$b:e.kind==="git"?UH:e.file??"";try{let o=await WH(t,e);return o===null?Sg(n,JH(e,r)):Vo(n,`${r}: ${o}`,VH(e))}catch(o){if(!(o instanceof Error))throw o;let s=o instanceof m&&o.hint!==void 0?o.hint:`Fix ${r}`;return Vo(n,o.message,s)}}function VH(t){let e=Hr(t);return e===null?"Run 'ari install' again to repair it":`Run '${e}' to repair it`}function il(t){switch(t.kind){case"hooks":return`${t.agent} hooks`;case"mcp":return`${t.agent} MCP server`;case"skill":return`${t.agent} skill`;case"git":return"git hooks";case"config":return t.file===jt?"AGENTS.md block":"configuration";case"routing":return"configuration"}}async function WH(t,e){let n=e.agent??"";switch(e.kind){case"hooks":return un(t,Pe(n))?null:"has no ari hook entries";case"mcp":{let r=Ne(me(n),await vb(t,e.scope));return r.managed(W(r.base,r.file))?null:"does not register the ari server"}case"skill":{let[r,o]=[Jt(n),await vb(t,e.scope)],s=ot.filter((i)=>{let a=ie(r,o,i),c=W(a.base,a.file)??"";return!(c.startsWith(`---
|
|
202
|
+
name: ${i.name}
|
|
203
|
+
`)&&c.includes(el))}).map((i)=>i.name);if(s.length===0)return null;return s.length===1?`${s.join("")} is not ari's skill`:`${s.join(", ")} are not ari's skills`}case"git":return await To(t)?null:"pre-commit and pre-push do not both run ari";case"config":if(e.file===jt)return(W(t,jt)??"").includes(HH)?null:"has no ari block";return M(t),null;case"routing":return M(t),null}}function JH(t,e){switch(t.kind){case"hooks":case"mcp":return e;case"skill":return`${e} (${ot.length} skills)`;case"git":return"pre-commit and pre-push run ari";case"config":case"routing":return t.file===jt?"AGENTS.md has the ari block":`${$b} is valid`}}async function vb(t,e){return xt(e,t)}async function qH(t,e,n){let o=Bun.spawn([t,"mcp","serve"],{cwd:e,detached:!0,env:{...process.env,...Fe},stderr:"pipe",stdin:"pipe",stdout:"pipe"}),s=()=>Ge(o.pid,"SIGKILL"),i=Qt(s),a=setTimeout(s,n);try{o.stdin.write(YH()),await o.stdin.flush();let c=await XH(o.stdout);return await o.stdin.end(),ZH("ari mcp serve",c,n,await new Response(o.stderr).text())}catch(c){return Vo("ari mcp serve",`'ari mcp serve' failed: ${c instanceof Error?c.message:String(c)}`,Tb)}finally{clearTimeout(a),s(),i()}}function YH(){return[{id:1,jsonrpc:"2.0",method:"initialize",params:{capabilities:{},clientInfo:{name:"ari-install",version:"1"},protocolVersion:jH}},{jsonrpc:"2.0",method:"notifications/initialized"},{id:Eb,jsonrpc:"2.0",method:"tools/list"}].map((e)=>`${JSON.stringify(e)}
|
|
204
|
+
`).join("")}async function XH(t){let e=new TextDecoder,n="";for await(let r of t){n+=e.decode(r,{stream:!0});let o=n.split(`
|
|
205
|
+
`);n=o.pop()??"";for(let s of o){let i=zH(s);if(i!==null&&i.id===Eb)return i}}return null}function zH(t){try{let e=JSON.parse(t);return z(e)?e:null}catch{return null}}function ZH(t,e,n,r){if(e===null){let s=r.trim().split(`
|
|
206
|
+
`).at(-1)??"",i=s.length>0?`stopped without answering: ${s}`:`did not answer within ${n} ms`;return Vo(t,i,"Run 'ari mcp serve' in this repository to see why")}let o=QH(e);if(!o.includes(FH))return Vo(t,"answered tools/list without ari's tools","Make sure 'ari' on PATH is @r5n/ariadne");return Sg(t,`answers, with ${o.length} tools`)}function QH(t){let e=t.result;if(!z(e)||!Array.isArray(e.tools))return[];return e.tools.flatMap((n)=>z(n)&&typeof n.name==="string"?[n.name]:[])}function Sg(t,e){return{detail:e,hint:null,name:t,ok:!0}}function Vo(t,e,n){return{detail:e,hint:n,name:t,ok:!1}}import{existsSync as Lb}from"fs";import{join as Mb}from"path";function vg(t,e,n=ot){return n.map((r)=>{let o=ie(t,e,r),s=mn(o);return{current:s&&W(o.base,o.file)===r.text,file:oe(e.scope,mi(t,e.scope,r.name)),installed:s,scope:e.scope,skill:r.name}})}function xb(t,e){return fe.map((n)=>({agent:n.agent,files:[t,e].flatMap((r)=>vg(n,r)),label:n.label}))}var at=["claude","codex","gemini","cursor","copilot"],or=["hooks","mcp","skill"],Ye={hooks:"hooks",mcp:"MCP server",skill:"skill"},$g="config",sr="agents-md",qe="git",cl="claude mcp add --scope user ari -- ari mcp serve",bg=".ari/config.json",tU="AGENTS.md",Ab=".claude/settings.json",Cb=["cursor","copilot"],Rb={cursor:["claude","codex"],gemini:["codex"]},eU=["claude","codex","gemini"],nU=":";function Ot(t,e){return`${t}${nU}${e}`}function ll(t){return at.includes(t)}function Ft(t,e){let n=t.agents.find((r)=>r.agent===e);if(n!==void 0)return n;throw Error(`No detected state for agent ${e}`)}function ul(t){let e=new Set(t.targets.filter(Ag).map((n)=>n.agent));return at.filter((n)=>Ft(t,n).path!==null||e.has(n))}function Ur(t,e,n,r){let o=t.initialised&&!r?[Pb(t,sr,"project")]:[],s=or.flatMap((i)=>at.filter((a)=>e.includes(a)).map((a)=>dU(t,a,i,n)));return[...o,...s,pU(t)]}function rU(t,e,n,r){let s=Ur(t,e,n,r).filter((a)=>a.skip===null&&a.problem===null).map((a)=>a.id),i=new Set(Wo(t,s).map(({id:a})=>a));return s.filter((a)=>!i.has(a))}function Ib(t,e,n,r){return Ur(t,e,n,r).map((o)=>o.id)}function Ob(t,e,n,r){let o=Ur(t,e,n,r),s=new Set(o.filter((i)=>i.status!=="current"&&i.elsewhere===null).map((i)=>i.id));return rU(t,e,n,r).filter((i)=>s.has(i))}function _b(t,e){let n=t.configured.map((s)=>({...s,configured:!0})),r=new Set(n.map((s)=>s.name)),o=e.filter((s)=>Ft(t,s).preset&&!r.has(s)).map((s)=>({configured:!1,model:null,name:s,roles:[]}));return[...n,...o]}function Tg(t,e){if(e.pack!==null&&!t.packs.some((d)=>d.name===e.pack))throw new v(`Unknown pack "${e.pack}"`,`Choose one of: ${t.packs.map((d)=>d.name).join(", ")}`);if(e.routing!==null)uU(t,e.routing,e.init);let n=e.init,r=Ur(t,e.agents,e.scope,n),o=new Set(e.targets),s=e.recommended?Wo(t,e.targets):[],i=new Map(s.map(({id:d,reason:p})=>[d,p])),a=n?[al($g,null,"config","project",bg,null),al(sr,null,"config","project",tU,null)]:[],c=new Set(r.filter((d)=>o.has(d.id)).map((d)=>d.kind)),l=r.flatMap((d)=>{if(!(o.has(d.id)||d.skip!==null&&c.has(d.kind)))return[];let g=e.recommended&&d.problem!==null?gU(d.problem):null,f=d.skip??i.get(d.id)??g;return[al(d.id,d.agent,d.kind,d.scope,d.file,f)]}),u=e.routing===null?[]:[al("routing",null,"routing","project",bg,null)];return{init:n,pack:e.pack,routing:e.routing,scope:e.scope,targets:[...a,...l,...u],warnings:dl(t,{...e,targets:e.targets.filter((d)=>!i.has(d))})}}function dl(t,e){let n=Ur(t,e.agents,e.scope,e.init),r=new Set(e.targets),o=new Set(n.filter((c)=>c.skip===null).map((c)=>c.id)),s=Nb(t),i=new Set([...[...r].filter((c)=>o.has(c)),...s]),a={answers:e,effective:i,installed:s,requested:r,state:t};return[...oU(a),...sU(a),...iU(a),...aU(a),...cU(a),...lU(a,n)]}function oU({answers:t,state:e}){return t.agents.flatMap((n)=>{let r=Ft(e,n);if(r.path!==null)return[];return[Jo("agent-not-found",`${r.label} was not found on PATH (looked for ${r.binaries.join(", ")})`,`ari writes its files anyway; they take effect once ${r.label} is installed`)]})}function sU({answers:t,requested:e}){if(t.scope!=="user"||!e.has(Ot("mcp","claude")))return[];return[Jo("claude-user-mcp","Claude Code keeps user-scope MCP servers in its own state file, which ari does not edit",`Run: ${cl}`)]}function iU({requested:t,state:e}){let n=e.hookManager;if(n===null||!t.has(qe))return[];return[Jo("git-hooks-managed",Db(n.name),n.hint)]}function aU({effective:t,installed:e,requested:n,state:r}){let o=Ot("hooks","claude");if(!t.has(o))return[];return Cb.flatMap((s)=>{let i=Ot("hooks",s);if(!t.has(i)||!(n.has(i)||n.has(o)))return[];let a=Ft(r,s).label,c=n.has(i)&&!e.has(i)?[i]:[],l=c.length>0?`Leave out ${a}'s hooks; it runs Claude Code's`:`Run 'ari hooks uninstall --agent ${s}', or leave out Claude Code's hooks`,u=`${a} also runs Claude Code's hooks from ${Ab}, so every ari hook would run twice there`;return[Jo("hooks-twice",u,l,c)]})}function cU({answers:t,effective:e,installed:n,requested:r,state:o}){return at.flatMap((s)=>{let i=Rb[s];if(i===void 0||!t.agents.includes(s))return[];let a=[s,...i].filter((y)=>e.has(Ot("skill",y)));if(a.length<2||!a.some((y)=>r.has(Ot("skill",y))))return[];let c=Ft(o,s).label,l=Ot("skill",s),u=r.has(l)&&!n.has(l)&&a.includes(s)?[l]:[],d=a.map((y)=>Eg(o,y)),p=a.filter((y)=>y!==s).map((y)=>Eg(o,y)),g=u.length>0?`Leave out ${c}'s own skill; it reads the copy in ${p.join(" and ")}`:a.includes(s)?`Run 'ari skills uninstall --agent ${s}'; ${c} reads the copy in ${p.join(" and ")}`:`The copies are identical; keep both while ${a.map((y)=>Ft(o,y).label).join(" and ")} need them`,f=`${c} reads ${d.join(" and ")}, so it would load the ariadne skills ${mU(a.length)}`;return[Jo("skill-twice",f,g,u)]})}function lU({requested:t},e){return e.flatMap((n)=>{if(n.problem===null||n.skip!==null||!t.has(n.id))return[];return[Jo("target-blocked",n.problem.message,n.problem.hint)]})}function Wo(t,e){let n=new Set(e),r=Nb(t),o=new Set([...n,...r]),s=o.has(Ot("hooks","claude")),i=Cb.flatMap((c)=>{let l=Ot("hooks",c);if(!s||!n.has(l)||r.has(l))return[];let u=`${Ft(t,c).label} runs Claude Code's hooks from ${Ab}`;return[{id:l,reason:u}]}),a=at.flatMap((c)=>{let l=Ot("skill",c),u=(Rb[c]??[]).find((g)=>o.has(Ot("skill",g)));if(u===void 0||!n.has(l)||r.has(l))return[];let d=Eg(t,u),p=`${Ft(t,c).label} also reads ${d}, where ${Ft(t,u).label}'s copy is`;return[{id:l,reason:p}]});return[...i,...a]}function uU(t,e,n){if(!t.initialised&&!n)throw new v("Routing needs .ari/config.json, which does not exist yet","Pass --init to create it in the same run, or run 'ari init' first");let r=new Set([...t.configured.map((s)=>s.name),...eU]);for(let[s,i]of[["--task-agent",e.task],["--review-agent",e.review]]){if(r.has(i.agent))continue;throw new v(`${s} names "${i.agent}", which is neither a configured agent nor a preset`,`Choose one of: ${[...r].join(", ")}`)}let o=t.routing.reviewCommand;if(o===null)return;throw new m(`review.command (${o}) runs the review gate, so ari cannot also set review.agent`,`Remove review.command from ${bg}, or leave the review agent out`,1,{tag:"ReviewCommandSet"})}function dU(t,e,n,r){let o=Ft(t,e),s=Ot(n,e),i=n==="hooks"?"project":r,a={agent:e,elsewhere:null,file:null,id:s,kind:n,problem:null,scope:i,status:null};if(!o.kinds.includes(n))return{...a,skip:`ari has no ${Ye[n]} integration for ${o.label}`};if(i==="user"&&!o.userScope.includes(n))return{...a,skip:`${o.label} keeps user-scope MCP servers itself; run '${cl}'`};let c=xg(t,s,i),l=i==="user"?"project":"user",u=n==="hooks"?void 0:t.targets.find((p)=>p.id===s&&p.scope===l),d=u!==void 0&&Ag(u)?u.scope:null;return{...a,elsewhere:d,file:c.file,problem:c.problem,skip:null,status:c.status}}function pU(t){let e=t.hookManager,n={agent:null,elsewhere:null,id:qe,kind:"git",scope:"project"};if(e!==null)return{...n,file:t.gitHooksDirectory,problem:null,skip:Db(e.name),status:null};return Pb(t,qe,"project")}function Pb(t,e,n){let r=xg(t,e,n),{agent:o,file:s,kind:i,problem:a,status:c}=r;return{agent:o,elsewhere:null,file:s,id:e,kind:i,problem:a,scope:n,skip:null,status:c}}function xg(t,e,n){let r=t.targets.find((o)=>o.id===e&&o.scope===n);if(r!==void 0)return r;throw Error(`No detected state for ${e} in the ${n} scope`)}function Nb(t){return new Set(t.targets.filter(Ag).map((e)=>e.id))}function Ag(t){return t.status!=="missing"&&t.agent!==null}function Eg(t,e){return xg(t,Ot("skill",e),"project").file}function Db(t){return`${t} manages this repository's git hooks, so ari leaves them alone`}function gU(t){return t.hint.length===0?t.message:`${t.message}. ${t.hint}`}function al(t,e,n,r,o,s){return{agent:e,file:o,id:t,kind:n,scope:r,skip:s}}function Jo(t,e,n,r=[]){return{code:t,drop:r,fix:n,message:e}}function mU(t){return t===2?"twice":`${t} times`}var fU={claude:["claude"],codex:["codex"],copilot:["copilot"],cursor:["cursor-agent","cursor"],gemini:["gemini"]},hU="<!-- ari:begin -->",yU=new Set(["EACCES","EISDIR","ELOOP","ENOTDIR","EPERM"]);async function yi(t,e){let n=Lb(Mb(t,rt)),r=e!==void 0?e:n?M(t):null,o=Lb(Mb(t,J))?Gt(t):[],s={project:await TU(t),user:await xt("user",t)},[i,a,c]=await Promise.all([Promise.all(at.map(kU)),Qd(t),Hk(t)]),l=[...n?[bU(t)]:[],...Ie.map((u)=>Rg(Ot("hooks",Cg(u.name)),Cg(u.name),"hooks","project",u.file,()=>un(t,u),()=>Ks(u,W(t,u.file))===W(t,u.file))),...pl("mcp",s),...pl("skill",s),...a===null?[await EU(t,c)]:[]];return{agents:i,configured:$U(r),gitHooksDirectory:c,hookManager:a,initialised:n,pack:r?.pack??null,packs:Tn(o).map(({description:u,name:d})=>({description:u,name:d})),root:t,routing:{review:r?.review.agent===void 0?null:{agent:r.review.agent,model:r.review.model??null},reviewCommand:r?.review.command??null,task:r?.routing.default??null},targets:l}}async function jb(t){let e={user:await xt("user",t)};return[...pl("mcp",e),...pl("skill",e)]}async function kU(t){let e=Ie.find((c)=>c.name===t),n=se.find((c)=>c.agent===t),r=fe.find((c)=>c.agent===t),o=fU[t],s=await Os(o),i=[...e===void 0?[]:["hooks"],...n===void 0?[]:["mcp"],...r===void 0?[]:["skill"]],a=[...n?.user==null?[]:["mcp"],...r?.user==null?[]:["skill"]];return{agent:t,binaries:o,kinds:i,label:e?.label??t,path:s.path,preset:Ve.some((c)=>c.name===t),support:e?.support??"partial",userScope:a,version:s.version}}function pl(t,e){return(t==="mcp"?se:fe).flatMap((r)=>Mn.flatMap((o)=>{let s=e[o];if(r[o]===null||s===void 0)return[];let i=Cg(r.agent);return[t==="mcp"?wU(i,o,s):SU(i,o,s)]}))}function wU(t,e,n){let r=se.find((i)=>i.agent===t);if(r===void 0)throw Error(`ari has no mcp target for ${t}`);let o=Ne(r,n),s=()=>o.install(W(o.base,o.file))===W(o.base,o.file);return Rg(Ot("mcp",t),t,"mcp",e,o.file,()=>mn(o),s)}function SU(t,e,n){let r=Jt(t),o=ot.map((c)=>ie(r,n,c)),s=()=>o.some((c)=>mn(c)),i=()=>o.map((c)=>{let l=W(c.base,c.file);return c.install(l)===l}).every(Boolean);return{...Rg(Ot("skill",t),t,"skill",e,r[e],s,i),parts:vU(t,n)}}function vU(t,e){return(hi(()=>vg(Jt(t),e),"").value??[]).map((r)=>({name:r.skill,status:gl(r.installed,r.current)}))}function Rg(t,e,n,r,o,s,i){let a={agent:e,file:oe(r,o),id:t,kind:n,scope:r},c=hi(s,a.file);if(c.problem!==null)return{...a,problem:c.problem,status:"outdated"};let l=c.value===!0,u=hi(i,a.file);if(u.problem!==null)return{...a,problem:u.problem,status:l?"outdated":"missing"};return{...a,problem:null,status:gl(l,u.value===!0)}}function bU(t){let e={agent:null,file:jt,id:sr,kind:"config",scope:"project"},n=hi(()=>W(t,jt),jt);if(n.problem!==null)return{...e,problem:n.problem,status:"outdated"};let r=n.value,o=(r??"").includes(hU),s=hi(()=>fi(r)===r,jt);if(s.problem!==null)return{...e,problem:s.problem,status:"outdated"};return{...e,problem:null,status:gl(o,s.value===!0)}}async function EU(t,e){let n={agent:null,file:e,id:qe,kind:"git",scope:"project"},r=await xU(()=>To(t),e);if(r.problem!==null)return{...n,problem:r.problem,status:"outdated"};let o=r.value===!0;try{let s=await Fs(t);return{...n,problem:null,status:gl(o,s.every((i)=>i.action==="unchanged"))}}catch(s){return{...n,problem:Ig(s,e),status:o?"outdated":"missing"}}}function $U(t){if(t===null)return[];return Object.entries(t.agents).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>({model:n.model??null,name:e,roles:Sr(n)}))}async function TU(t){return{base:t,receipts:await P(t),scope:"project"}}function gl(t,e){if(!t)return"missing";return e?"current":"outdated"}function hi(t,e){try{return{problem:null,value:t()}}catch(n){return{problem:Ig(n,e),value:null}}}async function xU(t,e){try{return{problem:null,value:await t()}}catch(n){return{problem:Ig(n,e),value:null}}}function Ig(t,e){if(t instanceof m)return{hint:t.hint??"",message:t.message};let n=t.code;if(t instanceof Error&&typeof n==="string"&&yU.has(n))return{hint:`Check that ${e} is a readable file, then run the command again`,message:`${e} cannot be read (${n})`};throw t}function Cg(t){let e=at.find((n)=>n===t);if(e!==void 0)return e;throw Error(`ari has no install support for ${t}`)}function Y(t,e){return{detail:e,hint:null,name:t,status:"ok"}}function ct(t,e,n){return{detail:e,hint:n,name:t,status:"warn"}}function St(t,e,n){return{detail:e,hint:n,name:t,status:"fail"}}function Fb(t){return{fail:t.filter((e)=>e.status==="fail").length,ok:t.filter((e)=>e.status==="ok").length,warn:t.filter((e)=>e.status==="warn").length}}function Xe(t){return`'${t.replaceAll("'","'\\''")}'`}function ml(t,e){return t.ok?Y(t.name,t.detail):St(t.name,t.detail,t.hint??e)}var AU="agent binaries",CU="ari agents detect";function Gb(t){let e=Object.keys(t.agents).sort(O);if(e.length===0)return[Y(AU,"none configured; 'ari agents add <preset>' adds one for ari run and ari review")];let n=IU(t);return e.map((r)=>RU(r,t.agents[r],n.has(r)))}function RU(t,e,n){let r=`agent ${t}`,s=[...new Set([e?.command[0],e?.reviewCommand?.[0]].filter((l)=>l!==void 0))].map((l)=>({binary:l,path:Bun.which(l)})),i=s.filter((l)=>l.path===null).map((l)=>l.binary);if(i.length===0)return Y(r,s.map((l)=>`${l.binary} at ${l.path}`).join("; "));let a=`${i.join(", ")} not found on PATH${n?", and the routing or review gate uses this agent":""}`,c=`Install ${i.join(" and ")} and put it on PATH, then run '${CU}'`;return n?St(r,a,c):ct(r,a,c)}function IU(t){let{review:e,routing:n}=t,o=[n.default,n.review,...Object.values(n.stages)].flatMap((s)=>s===null?[]:[s.agent]);return new Set([...o,...e.agent===void 0?[]:[e.agent]])}import{existsSync as Hb}from"fs";import{join as Ub}from"path";var fl="configuration",hl="trust",Kb="ari init",OU="ari doctor",_U=12;function Bb(t){if(!Hb(Ub(t,J)))return{check:St(fl,"ari is not set up in this repository: .ari/ does not exist",Kb),config:null,skipReason:"ari is not set up in this repository"};try{let e=M(t);if(!Hb(Ub(t,rt)))return{check:ct(fl,`${rt} is missing, so the defaults apply`,Kb),config:e,skipReason:null};return{check:Y(fl,`${rt} is valid (pack ${e.pack})`),config:e,skipReason:null}}catch(e){if(!(e instanceof m))throw e;return{check:St(fl,e.message,`Fix ${rt} by hand, then run '${OU}' again`),config:null,skipReason:"the configuration is not valid"}}}function Vb(t,e){let n=Be(t,e),r=So();switch(n.state){case"not-required":return Y(hl,"the configuration starts no commands, so nothing needs trust");case"trusted":return Y(hl,`trusted since ${n.trustedAt} (configuration ${n.sha256.slice(0,_U)})`);case"untrusted":case"changed":{let o=n.state==="changed"?`the commands changed since ${n.trustedAt}`:"nobody has trusted them on this machine";if(r)return Y(hl,`${o}, but ${xr}=1 lets ari run them`);return ct(hl,`${n.commands.length} configured command(s) are not trusted: ${o}, so ari run, ari review and command gates refuse to start them`,"ari trust")}}}var yl="ari on PATH",PU=/\d+(?:\.\d+)+[\w.+-]*/,Wb="bun add -g @r5n/ariadne";async function Jb(t){let e=kg(Bun.which("ari"));if(!e.ok)return St(yl,e.detail,Wb);let n=await Os(["ari"]),r=n.path??e.detail;if(n.version===null)return ct(yl,`${r} did not report a version`,`${r} --version`);let o=PU.exec(n.version)?.[0]??n.version;if(o===t)return Y(yl,`${r} (Ariadne ${o})`);return ct(yl,`${r} is Ariadne ${o}, but this is Ariadne ${t}`,`${Wb}@${t}`)}var NU="ari doctor",qb="git hooks",DU="agents",LU="ari hooks install --agent git",Og="ari install";function _g(t){return t.flatMap((e)=>{let n=FU(e);if(e.problem!==null)return[UU(n,e)];if(e.status==="missing")return e.kind==="config"?[KU(n,e)]:[];if(e.status==="current")return[Y(n,GU(e))];return[ct(n,HU(e),Xb(e))]})}function Yb(t){let e=at.filter((r)=>t.targets.some((o)=>o.agent===r&&o.status!=="missing"));return[...e.length===0?[ct(DU,"no agent is set up here: no hooks, MCP server or skill is installed",Og)]:e.flatMap((r)=>MU(t,r)),...jU(t)]}function MU(t,e){let n=t.agents.find((r)=>r.agent===e);if(n===void 0)return[];return n.kinds.flatMap((r)=>{if(t.targets.some((c)=>c.agent===e&&c.kind===r&&c.status!=="missing"))return[];let s=il({agent:e,file:null,kind:r}),i=Wo(t,[Ot(r,e)])[0];if(i!==void 0)return[Y(s,`not needed: ${i.reason}`)];let a=Hr({agent:e,kind:r,scope:"project"})??Og;return[ct(s,`${n.label} has no ${Ye[r]} installed`,a)]})}function jU(t){if(t.hookManager!==null)return[Y(qb,`${t.hookManager.name} manages them, so ari leaves them alone`)];let e=t.targets.find((n)=>n.id==="git");if(e===void 0||e.status!=="missing"||e.problem!==null)return[];return[ct(qb,"not installed: commits and pushes are not checked against the task's scope",LU)]}function FU(t){let e=il(t);return t.scope==="user"?`${e} (user)`:e}function GU(t){if(t.kind==="git")return"pre-commit and pre-push run ari";if(t.kind==="skill")return`${t.file}: ${t.parts?.length??0} skills`;return t.kind==="config"?`${t.file} has the ari block`:t.file}function HU(t){let e=t.kind==="skill"?t.parts??[]:[],n=e.filter((s)=>s.status==="missing").map((s)=>s.name),r=e.filter((s)=>s.status==="outdated").map((s)=>s.name);if(n.length+r.length===0)return`${t.file} is not what this ari installs now`;let o=[...n.length===0?[]:[`${n.join(", ")} ${n.length===1?"is":"are"} missing`],...r.length===0?[]:[`${r.join(", ")} ${r.length===1?"is":"are"} outdated`]];return`${t.file}: ${o.join("; ")}`}function UU(t,e){let n=e.problem?.message??"",r=e.kind==="skill"?e.problem?.hint??"":"";if(r.length>0)return St(t,n,r);return St(t,n,`Make ${e.file} a valid, readable file by hand, then run '${NU}' again`)}function KU(t,e){return ct(t,`${e.file} has no ari block, so agents are not told the loop`,Xb(e))}function Xb(t){return Hr(t)??Og}import{existsSync as BU,readdirSync as VU,readFileSync as WU,realpathSync as JU,statSync as qU}from"fs";import{tmpdir as YU}from"os";import{join as Qb,resolve as XU,sep as zU}from"path";var ZU=3600,QU=1000,tE=ZU*QU,zb="temporary files",tK=".git",Zb="gitdir:",eK="git worktree prune";async function eE(t,e=Date.now()){let n=await nK(t,e);if(n.length===0)return Y(zb,"no leftover ari-base-* or ari-index-* directory older than one hour");let r=n.map((i)=>`${i.path} (${i.kind}, ${aK(i.ageMs)} old)`),o=n.map((i)=>i.kind==="base worktree"?`git worktree remove --force ${Xe(i.path)}`:`rm -r ${Xe(i.path)}`),s=n.some((i)=>i.kind==="base worktree")?[eK]:[];return ct(zb,`${n.length} directory(ies) left behind by an interrupted run: ${r.join("; ")}`,[...o,...s].join(" && "))}async function nK(t,e){let n=YU(),r=La(t),o=await rK(t);return sK(n).flatMap((s)=>{let i=Qb(n,s),a=iK(i,e);if(a===null||a<tE)return[];if(s.startsWith(r))return[{ageMs:a,kind:"temporary index",path:i}];return s.startsWith(Cs)&&oK(i,o)?[{ageMs:a,kind:"base worktree",path:i}]:[]})}async function rK(t){try{return nE(await sn(t,"worktrees"))}catch{return null}}function oK(t,e){if(e===null)return!1;try{let n=WU(Qb(t,tK),"utf8").trim();if(!n.startsWith(Zb))return!1;return nE(XU(n.slice(Zb.length).trim())).startsWith(`${e}${zU}`)}catch{return!1}}function sK(t){try{return VU(t).filter((e)=>e.startsWith(Cs)||e.startsWith(wd))}catch{return[]}}function iK(t,e){try{let n=qU(t);return n.isDirectory()?e-n.mtimeMs:null}catch{return null}}function nE(t){return BU(t)?JU(t):t}function aK(t){let e=Math.floor(t/tE);return e<1?"under an hour":e===1?"1 hour":`${e} hours`}var rE="knowledge size",oE="sleep",sE="ari sleep",cK="ari doctor";async function iE(t){try{let e=er(await jr(t));return[lK(e),uK(e)]}catch(e){if(!(e instanceof m))throw e;let n=e.hint===void 0||e.hint.length===0?"Fix it by hand":e.hint.replace(/\.$/,"");return[St("knowledge",e.message,`${n}, then run '${cK}' again`)]}}function lK({activeBytes:t,maxBytes:e}){let n=`${t} of ${e} bytes of active knowledge`;if(t<=e)return Y(rE,n);return ct(rE,`${n}: over the budget`,sE)}function uK(t){if(!t.due)return Y(oE,"nothing to consolidate");let e=t.reasons.map((n)=>dK(n,t));return ct(oE,`sleep is due: ${e.join("; ")}`,sE)}function dK(t,e){switch(t){case"journals":return`journals of done tasks remain (${e.journaled.join(", ")})`;case"budget":return`active knowledge exceeds ${e.maxBytes} bytes`;case"candidates":{let{clusters:n,decisions:r,notes:o}=e.candidates;return`${n} cluster(s), ${o} note(s) and ${r} decision(s) are waiting for a proposal`}}}var Pg="receipts",pK=[{kind:"hooks",name:"hooks.json"},{kind:"mcp",name:"mcp.json"},{kind:"skill",name:"skills.json"}],gK="ari install";function Ng(t){let e={edited:0,fixes:[],matches:0,problems:[]};for(let o of t)for(let s of pK){if(s.kind==="hooks"&&o.scope==="user")continue;mK(o,s,e)}if(e.problems.length>0)return ct(Pg,`${e.problems.join("; ")}; uninstall would remove only ari's entries instead of restoring files byte for byte`,[...new Set(e.fixes)].join("; "));let n=e.matches+e.edited;if(n===0)return Y(Pg,"no receipts: nothing was installed through ari here");let r=e.edited===0?"":`; ${e.edited} edited since install, which uninstall keeps`;return Y(Pg,`${e.matches} of ${n} match their files${r}`)}function mK(t,e,n){let r=Bk(t.receipts,e.name);if(r.state==="absent")return;if(r.state==="unreadable"){n.problems.push(`${r.path} cannot be read`),n.fixes.push(`rm ${Xe(r.path)}`);return}for(let[o,s]of Object.entries(r.receipts))fK(t,e.kind,o,s,n)}function fK(t,e,n,r,o){let s=hK(t,e,n);if(s===null)return;let i=yK(t,n);if(i===void 0)return;let a=kK(s,t,i);if(a===null)return;if(i===null||!a){o.problems.push(`the receipt for ${n} (${t.scope}) names ari entries that are no longer there`),o.fixes.push(wK(e,s.agent,t.scope));return}if(i===r.installed)o.matches++;else o.edited++}function hK(t,e,n){if(e==="hooks"){let o=Ie.find((s)=>s.file===n);return o===void 0?null:{agent:o.name,hooks:o}}if(e==="mcp"){let o=se.find((s)=>s[t.scope]===n);return o===void 0?null:{agent:o.agent,managed:Ne(o,t)}}let r=pb(t,n);return r===null?null:{agent:r.target.agent,managed:ie(r.target,t,r.skill)}}function yK(t,e){try{return W(t.base,e)}catch{return}}function kK(t,e,n){try{if(t.hooks!==void 0)return un(e.base,t.hooks);return t.managed===void 0?null:t.managed.managed(n)}catch{return null}}function wK(t,e,n){return Hr({agent:e,kind:t,scope:n})??gK}import{accessSync as SK,constants as vK,existsSync as bK}from"fs";import{dirname as cE}from"path";function qo(t){if(t.kind==="restore")return t.written.flatMap(({before:o,path:s})=>o===null?[]:aE(s,o));let{artifacts:e,context:n,contract:r}=t;return[...Bt(r.text)===r.sha256?[]:["the contract text does not match its SHA-256"],...e.flatMap(({file:o,path:s})=>aE(s,o)),...Z(n.text)===n.sha256?[]:["the context pack does not match its SHA-256"]]}function aE(t,e){return Z(Dr(e))===e.sha256?[]:[`${t} does not match its SHA-256`]}var lE="snapshots";async function uE(t){let e=await P(t),n=Fr(e),r=Ln(e),o=r.unreadable.map(({id:c,problem:l})=>({detail:`${c} cannot be read (${l})`,fix:`rm ${Xe(nr(e,c))}`})),s=r.entries.flatMap((c)=>{let l=qo(c);if(l.length===0)return[];return[{detail:`${c.id} is not intact (${l.join("; ")})`,fix:`rm ${Xe(nr(e,c.id))}`}]}),i=$K(n),a=[...o,...s,...i===null?[]:[{detail:`${i} is not writable, so automatic snapshots can only warn`,fix:`chmod u+w ${Xe(i)}`}]];if(a.length===0)return Y(lE,EK(r.entries.length,new Set(r.entries.map((c)=>c.task)).size));return ct(lE,a.map((c)=>c.detail).join("; "),a.map((c)=>c.fix).join(" && "))}function EK(t,e){if(t===0)return"no snapshots yet; the directory can be written";return`${t} ${t===1?"entry":"entries"} for ${e} ${e===1?"task":"tasks"}, all intact; the directory can be written`}function $K(t){let e=TK(t);try{return SK(e,vK.W_OK),null}catch{return e}}function TK(t){let e=t;while(!bK(e)&&cE(e)!==e)e=cE(e);return e}import{join as xK}from"path";var Yo="active task",dE="tasks",AK="active.json",CK=10,RK=new Set(["active","blocked"]),pE="ari list",IK="then run 'ari doctor' again";async function gE(t,e){let n=await P(t);return[OK(t,e,n),...NK(t,e)]}function OK(t,e,n){let r=`rm ${Xe(xK(n,AK))}`,o=mE(()=>gt(n));if(o.failure!==null)return St(Yo,`the pointer of this worktree cannot be read: ${o.failure.message}`,r);if(o.value===null)return Y(Yo,"no task is active in this worktree");return _K(t,e,o.value,r)}function _K(t,e,n,r){let{task:o}=n;if(!de(t).includes(o)){let i=In(t).includes(o)?"its contract is missing":"no such task exists";return ct(Yo,`the pointer of this worktree names "${o}", but ${i}`,r)}let s=mE(()=>it(t,o,e).task);if(s.failure!==null||s.value===null){let i=s.failure??new m(`task "${o}" cannot be read`);return St(Yo,`the pointer of this worktree names "${o}", which cannot be read: ${i.message}`,DK(i))}return PK(s.value,r)}function PK({contract:t,record:e},n){let r=t.id;if(RK.has(e.status))return Y(Yo,`${r} (${e.status}, stage ${e.stage})`);return ct(Yo,`the pointer of this worktree names "${r}", which is ${e.status}`,n)}function NK(t,e){let{invalid:n,tasks:r}=Pt(t,e);if(n.length===0)return[Y(dE,`${r.length} task(s), every contract and record is readable`)];let o=n.slice(0,CK).map((i)=>St(`task ${i.id}`,i.problem,fE(i.hint))),s=n.length-o.length;return s>0?[...o,St(dE,`${s} more task(s) cannot be read`,pE)]:o}function mE(t){try{return{failure:null,value:t()}}catch(e){if(e instanceof m)return{failure:e,value:null};throw e}}function DK(t){return fE(t.hint??"")}function fE(t){return t.length===0?pE:`${t.replace(/\.$/,"")}, ${IK}`}var hE="git on PATH",LK="ari mcp serve",MK=5000,jK="ari doctor --json",FK="not inside a git working tree",GK="git is not on PATH",HK=["configuration","trust","project integrations","git hooks","agent binaries","tasks","temporary files","sleep and knowledge size","snapshots"],UK=["trust","agent binaries","tasks","sleep and knowledge size","snapshots"];async function yE({cwd:t,version:e}){let n=Bun.which("git"),r=n===null?null:await KK(t),o=[...await ze("ari on PATH",async()=>[await Jb(e)]),n===null?St(hE,"git is not on PATH, so ari cannot read any repository","Install git"):Y(hE,n)],s=r===null?await BK(t,n===null?GK:FK):await VK(r),i=[...o,...s.checks],a=Fb(i);return{checks:i,ok:a.fail===0,root:r,skipped:s.skipped,summary:a,version:e}}async function KK(t){try{return await Jn(t)}catch(e){if(e instanceof m)return null;throw e}}async function BK(t,e){let n=await jb(t),r=await xt("user",t);return{checks:[..._g(n),...await ze("ari mcp serve",()=>kE(t,n)),...await ze("receipts",()=>[Ng([r])])],skipped:HK.map((s)=>({name:s,reason:e}))}}async function VK(t){let e=Bb(t),{config:n}=e,r=await ze("integrations",async()=>{let c=await yi(t,n);return[..._g(c.targets),...Yb(c),...await kE(t,c.targets)]}),o=await ze("receipts",async()=>[Ng(await JK(t))]),s=await ze("temporary files",async()=>[await eE(t)]),i=n===null?{first:[],last:[]}:await WK(t,n),a=e.skipReason;return{checks:[e.check,...i.first,...r,...o,...i.last,...s],skipped:n===null&&a!==null?UK.map((c)=>({name:c,reason:a})):[]}}async function WK(t,e){let n=await ze("trust",()=>[Vb(t,e)]),r=await ze("agent binaries",()=>Gb(e)),o=await ze("tasks",()=>gE(t,e)),s=await ze("sleep",()=>iE(t)),i=await ze("snapshots",async()=>[await uE(t)]);return{first:n,last:[...r,...o,...s,...i]}}async function JK(t){return[await xt("project",t),await xt("user",t)]}async function kE(t,e){let n=e.some((o)=>o.kind==="mcp"&&o.status!=="missing"),r=Bun.which("ari");if(!n||r===null)return[];return[ml(await wg(r,t,MK),LK)]}async function ze(t,e){try{return await e()}catch(n){return[qK(t,n)]}}function qK(t,e){if(e instanceof m){let r=e.hint===void 0||e.hint.length===0?"Fix it by hand":e.hint.replace(/\.$/,"");return St(t,e.message,`${r}, then run 'ari doctor' again`)}let n=e instanceof Error?e.message:String(e);return St(t,`the check stopped unexpectedly: ${n}`,jK)}var YK=26,SE=6,XK=" ".repeat(SE),zK={fail:"FAIL",ok:"ok",warn:"warn"};function Dg(t){return t.flatMap((e)=>{let n=`${ZK(e.status,wE(zK[e.status],SE))}${wE(e.name,YK)}${e.detail}`;return e.hint===null||e.status==="ok"?[n]:[n,`${XK}fix: ${e.hint}`]})}function vE(t){let{fail:e,ok:n,warn:r}=t.summary,o=t.skipped.length===0?[]:["",...t.skipped.map((i)=>`skipped ${i.name}: ${i.reason}`)],s=`${n} ok, ${r} warning(s), ${e} failure(s)`;return[...Dg(t.checks),...o,"",s].join(`
|
|
207
|
+
`)}function ZK(t,e){switch(t){case"ok":return w.green(e);case"warn":return w.yellow(e);case"fail":return w.red(e)}}function wE(t,e){let n=Bun.stringWidth(t);return n>=e?`${t} `:`${t}${" ".repeat(e-n)}`}var QK=1,bE=E({description:"Check the setup without changing anything: ari, configuration, trust, integrations, tasks and memory",examples:["ari doctor","ari doctor --json"],json:!0,name:"doctor",run:async(t)=>{let e=await yE({cwd:process.cwd(),version:t.cli.version??""});return t.output.result(e,vE),e.ok?void 0:QK}});function kl(t,e){let n=new Set,r=(o,s)=>{for(let i of e(o)){if(i===t)return[...s,t];if(n.has(i))continue;n.add(i);let a=r(i,[...s,i]);if(a)return a}return null};return r(t,[t])}function wl(t){return`depends forms a cycle: ${t.join(" -> ")}`}var tB=["ari check","ari done"],eB=["ari next"],nB='ari new "<title>"',EE=["active","blocked"];function Lg(t){let e=[...t.tasks].sort((u,d)=>O(u.contract.id,d.contract.id)),n=t.active?e.find((u)=>u.contract.id===t.active?.task):void 0;if(n?.record.status==="active")return rB(n,t.packs);if(n?.record.status==="blocked")return oB(n,t.packs);let r=e.filter((u)=>!t.claimed.has(u.contract.id)),s=r.filter((u)=>EE.includes(u.record.status)).find((u)=>jg(u,t.packs)===null);if(s)return sB(s,t.packs);let i=lB(r,t),a=dB(e,r.filter((u)=>!i.has(u.contract.id)));if(a)return aB(a,t.packs);let c=uB(e,r,t,i);if(c)return iB(c);let l=e.find((u)=>u.record.status==="draft");if(l)return cB(l);return{action:"new",commands:[nB],instruction:"Create a task and write its contract: scope, criteria and checks.",stage:null,task:null}}function rB(t,e){let n=Mg(t,e);return{action:"continue",commands:[...tB],instruction:mo(n,t.contract.id),stage:n.name,task:t.contract.id}}function oB(t,e){let n=t.record.question??"the task was blocked without a recorded question";return{action:"resolve",commands:[`ari resolve ${t.contract.id} --answer "<answer>"`],instruction:`A human must answer: ${n}`,stage:Mg(t,e).name,task:t.contract.id}}function sB(t,e){return{action:"start",commands:[`ari start ${t.contract.id}`],instruction:`Task "${t.contract.title}" is ${t.record.status}, but no worktree holds it; adopt it here.`,stage:Mg(t,e).name,task:t.contract.id}}function iB(t){return{action:"fix",commands:[...eB],instruction:t.instruction,stage:null,task:t.id}}function aB(t,e){let n=e.find((r)=>r.name===t.contract.pack)?.stages[0];return{action:"start",commands:[`ari start ${t.contract.id}`],instruction:`Start "${t.contract.title}".`,stage:n?.name??null,task:t.contract.id}}function cB(t){return{action:"ready",commands:[`ari ready ${t.contract.id}`],instruction:`Complete the contract of "${t.contract.title}", then mark it ready.`,stage:null,task:t.contract.id}}function Mg(t,e){let n=jg(t,e);if(n!==null)throw new m(n.message,n.hint);let r=e.find((o)=>o.name===t.contract.pack)?.stages[t.record.stage];if(r)return r;throw Error(`Task "${t.contract.id}" has no stage ${t.record.stage}`)}function jg(t,e){let n=e.find((r)=>r.name===t.contract.pack);if(!n)return{hint:"Fix the contract's pack",message:`Unknown pack "${t.contract.pack}" in task "${t.contract.id}"`};if(t.record.stage<n.stages.length)return null;return{hint:`Restore the stages of pack "${n.name}" in .ari/packs/${n.name}.yaml`,message:`Task "${t.contract.id}" is at stage ${t.record.stage}, but pack "${n.name}" has ${n.stages.length}`}}function lB(t,{packs:e,uncoveredLocks:n}){let o=t.filter((s)=>s.record.status==="ready").map((s)=>{let i=n.get(s.contract.id),a=i===void 0?[]:[`lock glob ${JSON.stringify(i)} matches no file that git tracks or would track`];return[s.contract.id,[...uo(s.contract,e),...a]]});return new Map(o.filter(([,s])=>s.length>0))}function uB(t,e,{invalid:n,packs:r},o){let s=new Map(t.map((p)=>[p.contract.id,p])),i=new Set(n.map((p)=>p.id)),a=(p)=>s.get(p)?.contract.depends??[],c=e.filter((p)=>p.record.status==="ready").flatMap((p)=>{let g=p.contract.id,f=p.contract.depends.find((S)=>!s.has(S)&&!i.has(S));if(f!==void 0)return[{id:g,instruction:`depends names the unknown task "${f}". Fix the depends of .ari/tasks/${g}.md`}];let y=kl(g,a);return y?[{id:g,instruction:`${wl(y)}. Remove one of these dependencies`}]:[]}),l=[...o].map(([p,g])=>({id:p,instruction:`The contract can no longer start: ${g.join("; ")}. Fix .ari/tasks/${p}.md`})),u=e.filter((p)=>EE.includes(p.record.status)).flatMap((p)=>{let g=jg(p,r);return g===null?[]:[{id:p.contract.id,instruction:`${g.message}. ${g.hint}`}]});return[...n.map((p)=>({id:p.id,instruction:`${p.problem}. ${p.hint}`})),...u,...l,...c].sort((p,g)=>O(p.id,g.id))[0]}function dB(t,e){let n=new Map(t.map((i)=>[i.contract.id,i])),r=new Map,o=(i,a)=>{let c=r.get(i);if(c!==void 0)return c;let l=n.get(i);if(!l||a.has(i))return 0;let u=new Set([...a,i]),d=Math.max(-1,...l.contract.depends.map((p)=>o(p,u)))+1;return r.set(i,d),d};for(let i of t)o(i.contract.id,new Set);let s=(i)=>i.contract.depends.every((a)=>n.get(a)?.record.status==="done");return e.filter((i)=>i.record.status==="ready"&&s(i)).sort((i,a)=>(r.get(i.contract.id)??0)-(r.get(a.contract.id)??0)||O(i.contract.id,a.contract.id))[0]}import{join as pB}from"path";var $E=Error("the design already exists");function TE(t,e,n,r){let o=new Set;return gB(e).flatMap((s)=>{let i=Ro(s.path,n);if(o.has(i))return[];return o.add(i),[{created:mB(t,i,Qh(r,s.sections??[])),path:i}]})}function gB(t){return t.stages.flatMap((e)=>e.gates.flatMap((n)=>n.kind==="artifact"&&n.sections!==void 0?[n]:[]))}function mB(t,e,n){if(Te(t,e))throw new m(`Cannot write the design template to ${e}: a directory on its way is a symbolic link`,"Replace the link with a real directory, or write the design by hand");try{return Yn(pB(t,e),n,()=>$E),!0}catch(r){if(r===$E)return!1;let o=r instanceof Error?r.message:String(r);throw new m(`The task was created, but the design template could not be written to ${e} (${o})`,`Write ${e} by hand with the sections of the pack`)}}import{realpathSync as fB}from"fs";import{resolve as hB}from"path";var yB="ENOENT";async function ki(t){let e=xE(t),n=new Map;for(let r of await Py(t)){if(xE(r)===e)continue;let o=kB(await P(r));if(o!==null&&!n.has(o.task))n.set(o.task,r)}return n}function kB(t){try{return gt(t)}catch(e){if(e instanceof m)return null;throw e}}function xE(t){try{return fB(t)}catch(e){if(e.code===yB)return hB(t);throw e}}var wB=8,SB=6,vB=10,AE=`
|
|
158
208
|
scope: []
|
|
159
|
-
`,
|
|
160
|
-
scope: ${
|
|
161
|
-
`)}function
|
|
162
|
-
`);throw new
|
|
163
|
-
${r}`,n)}function
|
|
209
|
+
`,bB="decision",Fg=10,RE={active:(t)=>`Finish it with 'ari done', or block it with 'ari block ${t} --reason <text>'`,blocked:(t)=>`A human answers it with 'ari resolve ${t} --answer <text>'`},EB=()=>new Date().toISOString();async function IE(t,e,n={}){let r=await he(t),o=e.trim(),s=zs(o,wB);if(s.length===0)throw new m(`The title "${e}" has no letters or digits to build a task id from`,'Run ari new "<title>"');let i=Ue(n.pack??r.config.pack,r.projectPacks),a=[...n.scope??[]],c=a.find((f)=>wr(f)!==null);if(c!==void 0)throw new m(`Scope glob ${JSON.stringify(c)} ${wr(c)}`,"Pass globs relative to the root");let l=Zs(s,Xy(t)),u=$B(Jh(o,i.name),a),d=ld(l,kn(n)());Yy(t,r.state,d,u);let p=TE(t,i,l,o),g={contract:Aa(l,u,r.config),record:d};return{contractPath:It(l),designs:p,id:l,task:g}}async function OE(t,e,n={}){let r=await he(t),{task:o}=it(t,e,r.config),s=kn(n)();ud(o.record,s);let i=[...uo(o.contract,r.packs),...OB(o.contract,t),...Ug(r,o.contract)];Gg(e,i,`Fix ${It(e)}, then run 'ari ready ${e}'`);let a=Vt(t,r.state,e,(c)=>ud(c,s));return{contract:o.contract,record:a}}async function Xo(t,e,n={}){let r=await he(t),{contractText:o,task:s}=it(t,e,r.config),{contract:i}=s,a=kn(n)();if(PB(r,e),await AB(r,e),Hg(s.record.status))return xB(r,s,a);let c=await Fa(t),l=await An(t,i.lock),u=await Ys(t,r.config,i),d={contractHash:Bt(o),gatesHash:bl(r,i),lockHashes:l,stageTestHashes:u},p=(y)=>ly(y,c,d,a);p(s.record),Gg(e,uo(i,r.packs),`Fix ${It(e)}, then start it again`),_B(r,i),await CB(t,e),GE(i,l);let g=Vt(t,r.state,e,p);Cd(r.state,{since:a,task:e});let f={contract:i,record:g};return{...El(f,ir(r,i)),task:f}}async function _E(t,e={}){let n=await he(t),{contractText:r,task:o}=UE(n),s=ir(n,o.contract),i=Nn(o,s),a=await wp({config:n.config,pack:s,root:t,task:o}),c=a.every((d)=>d.ok);$r(n.state,BE("check",o,i,a,kn(e)()));let l=Bt(r)!==o.record.contractHash,u=bl(n,o.contract)!==o.record.gatesHash;return{contractChanged:l,gates:a,gatesChanged:u,ok:c,stage:i.name,task:o}}async function PE(t,e={}){let n=await he(t),r=UE(n),{task:o}=r,{contract:s}=o;KE(n,r);let i=ir(n,s),a=Nn(o,i),c=await Ae(t,[Er]),l=await wp({config:n.config,pack:i,root:t,task:o}),u=kn(e)();$r(n.state,BE("done",o,a,l,u));let d=s.budget.attempts,p={budget:d,gates:l,stage:a.name},g=Qy(n.state,s.id),f=(N)=>Vt(t,n.state,s.id,(H)=>(DB(o.record,H),N({...H,knowledgeUsed:LB(H.knowledgeUsed,g)})));if(!l.every((N)=>N.ok)){let N=f((A)=>dy(A,{at:u,gates:l,stage:a.name,treeHash:c},d)),H=N.status==="blocked"?"blocked":"failed";return{...p,attempts:N.attempts,next:null,outcome:H,task:{contract:s,record:N}}}let y=await Ys(t,n.config,s),S={at:u,gates:l,stage:a.name,testHashes:y,treeHash:c},I=f((N)=>{let H=uy(N,S,i.stages.length,y);return H.status==="done"?_a(H,g):H}),C=I.status==="done",q={contract:s,record:I};if(C)return Zy(n.state),Va(n.state,s.id),{...p,attempts:I.attempts,next:null,outcome:"done",task:q};let G=El(q,i);return{...p,attempts:I.attempts,next:G,outcome:"advanced",task:q}}async function NE(t,e,n,r={}){let o=await he(t),{contractText:s,task:i}=it(t,e,o.config),{contract:a,record:c}=i,l=Hg(c.status);if(r.onto!==void 0&&!l)throw new m(`Task "${e}" is ${c.status}; only an active or blocked task has a base to move`,`Run 'ari amend ${e} --reason <text>' without --onto`);let u=await An(t,a.lock),d=c.status!=="draft"&&c.status!=="done";if(d){let I=[...uo(a,o.packs),...Ug(o,a)];Gg(e,I,`Fix ${It(e)}, then run 'ari amend ${e}' again`)}if(l)RB(i,ir(o,a));let p=d?Nn(i,ir(o,a)).name:null;if(l)GE(a,u);let g=l?await Ys(t,o.config,a):{...c.stageTestHashes},y={base:r.onto===void 0?null:await _y(t,"HEAD",await fo(t,r.onto)),contractHash:Bt(s),gatesHash:bl(o,a),lockHashes:u,reason:n,stage:p,stageTestHashes:g},S=kn(r)();return dd(c,y,S),{contract:a,record:Vt(t,o.state,e,(I)=>dd(I,y,S))}}async function DE(t,e,n,r={}){let o=await he(t),{task:s}=it(t,e,o.config),i=kn(r)(),a=Vt(t,o.state,e,(c)=>py(c,n,i));return{contract:s.contract,record:a}}async function LE(t,e,n,r={}){let o=await he(t),{task:s}=it(t,e,o.config),i=kn(r)();pd(s.record,n,i);let a=n.trim(),c=o.config.knowledge.maxEntryBytes,l=yt(a);if(l>c)throw new m(`The answer is ${l} bytes, but a knowledge entry holds at most ${c}`,"Shorten the answer, or raise knowledge.maxEntryBytes in .ari/config.json");let u=zs(a,SB),d=Zs(u.length>0?u:bB,an(t));Ba(t,{created:i.slice(0,vB),id:d,kind:"decision",scope:[...s.contract.scope],sources:[e],status:"active",supersededBy:null,supersedes:[],text:a});let p=Vt(t,o.state,e,(g)=>pd(g,n,i));return{knowledgeId:d,task:{contract:s.contract,record:p}}}async function ME(t,e,n,r={}){let o=await he(t),s=it(t,e,o.config),{contract:i,record:a}=s.task,c=ir(o,i);if(a.status==="active")KE(o,s);let l=Nn(s.task,c),u=await Sp(t,l,e),d=kn(r)(),p=Vt(t,o.state,e,(g)=>(NB(a,g),gy(g,{...u,by:n,stage:l.name},d)));return{contract:i,record:p}}async function jE(t,e,n={}){let r=await he(t),o=n.task??HE(r),{task:s}=it(t,o,r.config),i=kn(n)(),a=Vt(t,r.state,o,(c)=>my(c,e,i));return{contract:s.contract,record:a}}async function Sl(t){let e=await he(t),n=gt(e.state),r=n===null?null:TB(e,n.task);if(r!==null&&Hg(r.record.status))return Lg({...{claimed:new Set,invalid:[],uncoveredLocks:new Map},active:n,packs:e.packs,tasks:[r]});let{invalid:o,tasks:s}=Pt(t,e.config),i=new Set((await ki(t)).keys()),a=await IB(t,s);return Lg({active:n,claimed:i,invalid:o,packs:e.packs,tasks:s,uncoveredLocks:a})}async function vl(t,e={}){let n=await he(t),r=Pt(t,n.config),{statuses:o}=e;if(o===void 0)return r;return{invalid:r.invalid,tasks:r.tasks.filter((s)=>o.includes(s.record.status))}}async function jn(t,e){let n=await he(t),{task:r}=it(t,e,n.config),s=r.record.status==="active"||r.record.status==="blocked"?El(r,ir(n,r.contract)):null;return{active:gt(n.state)?.task===e,instruction:s?.instruction??null,stage:s?.stage??null,task:r}}async function he(t){let e=M(t),n=Gt(t);return{config:e,packs:Tn(n),projectPacks:n,root:t,state:await P(t)}}function kn(t){return t.clock??EB}function bl(t,e){let n=t.packs.find((r)=>r.name===e.pack);return n===void 0?null:Oa(n,t.config)}function ir(t,e){return Ue(e.pack,t.projectPacks)}function El(t,e){let n=Nn(t,e);return{instruction:mo(n,t.contract.id),stage:n.name}}function $B(t,e){if(e.length===0)return t;if(!t.includes(AE))throw Error("The contract template has no empty scope line");return t.replace(AE,()=>`
|
|
210
|
+
scope: ${lo(e)}
|
|
211
|
+
`)}function Gg(t,e,n){if(e.length===0)return;let r=e.map((o)=>` - ${o}`).join(`
|
|
212
|
+
`);throw new m(`The contract of "${t}" has ${e.length} problem(s):
|
|
213
|
+
${r}`,n)}function Hg(t){return t==="active"||t==="blocked"}function TB(t,e){return de(t.root).includes(e)?it(t.root,e,t.config).task:null}function xB(t,e,n){let r=e.contract.id;if(gt(t.state)?.task!==r)Cd(t.state,{since:n,task:r});return{...El(e,ir(t,e.contract)),task:e}}async function AB(t,e){let n=(await ki(t.root)).get(e);if(n===void 0)return;throw new m(`Task "${e}" is already held by the worktree at ${n}`,"Continue it there, or run 'ari next' here for other work")}async function CB(t,e){let n=ne(await xe(t,"HEAD"));if(n.length===0)return;let r=n.length-Fg,o=r>0?` and ${r} more`:"",s=(await Ha(t)).filter((a)=>n.includes(a)),i=s.length===0?"":`; git hides ${s.slice(0,Fg).join(", ")} until you run 'git update-index --no-skip-worktree <path>' or 'git update-index --no-assume-unchanged <path>', so keep local settings in an ignored file instead`;throw new m(`Task "${e}" cannot start with uncommitted changes outside .ari: ${n.slice(0,Fg).join(", ")}${o}`,`Commit, stash or ignore them, then run 'ari start ${e}'; the scope gate counts every change since the start commit${i}`)}function RB(t,e){let{evidence:n,id:r}=t.record,o=n.findIndex((i,a)=>i.stage!==e.stages[a]?.name),s=n[o];if(s===void 0)return;throw new m(`Task "${r}" passed stage "${s.stage}", which pack "${e.name}" does not have as stage ${o+1}`,"Keep the pack that the passed stages belong to, or create a follow-up with 'ari new'")}async function IB(t,e){let n=e.filter((s)=>s.record.status==="ready"&&s.contract.lock.length>0),r=n.flatMap((s)=>s.contract.lock),o=Object.keys(await An(t,r));return new Map(n.flatMap((s)=>{let i=FE(s.contract,o);return i===void 0?[]:[[s.contract.id,i]]}))}function FE(t,e){return t.lock.find((n)=>!e.some((r)=>et(r,[n])))}function GE(t,e){let n=FE(t,Object.keys(e));if(n===void 0)return;throw new m(`Lock glob ${JSON.stringify(n)} of task "${t.id}" matches no file that git tracks or would track`,`Fix the lock list in ${It(t.id)}: escape [ ] { } * ? with a backslash, and lock only files that are not ignored`)}function Ug(t,e){let{tasks:n}=Pt(t.root,t.config),r=new Map(n.map((s)=>[s.contract.id,s.contract.depends]));r.set(e.id,e.depends.filter((s)=>s!==e.id));let o=kl(e.id,(s)=>r.get(s)??[]);return o===null?[]:[wl(o)]}function OB(t,e){let n=new Set(de(e));return t.depends.filter((r)=>r.trim().length>0&&r!==t.id&&!n.has(r)).map((r)=>`depends names the unknown task "${r}"`)}function _B(t,e){let n=new Set(de(t.root)),r=e.depends.filter((s)=>!n.has(s)||it(t.root,s,t.config).task.record.status!=="done");if(r.length===0)return;let o=Ug(t,e).map((s)=>`; ${s}`);throw new m(`Task "${e.id}" depends on unfinished tasks: ${r.join(", ")}${o.join("")}`,"Finish those tasks first; 'ari next' shows the order")}function PB(t,e){let n=gt(t.state);if(n===null||n.task===e||!de(t.root).includes(n.task))return;let{status:r}=it(t.root,n.task,t.config).task.record;if(r!=="active"&&r!=="blocked")return;throw new m(`Task "${n.task}" is already ${r} in this worktree; one task runs per worktree`,RE[r](n.task))}function HE(t){let e=gt(t.state);if(e!==null)return e.task;throw new m("No task is active in this worktree","Run 'ari next' to see what to do")}function UE(t){let e=HE(t),n=it(t.root,e,t.config),{question:r,status:o}=n.task.record;if(o==="active")return n;if(o==="blocked")throw new m(`Task "${e}" is blocked: ${r??"no question was recorded"}`,RE.blocked(e));throw new m(`Task "${e}" is ${o}, not active`,"Run 'ari next' to see what to do")}function KE(t,{contractText:e,task:n}){let{contract:r}=n;if(Bt(e)!==n.record.contractHash)throw new m(`The contract of "${r.id}" changed after it was frozen`,`Run 'ari amend ${r.id} --reason <text>' to accept the change`);if(bl(t,r)!==n.record.gatesHash)throw new m(`The gates of "${r.id}" changed after they were frozen: its pack, or the test globs, regression setup or review command of .ari/config.json`,`Run 'ari amend ${r.id} --reason <text>' to accept the change`)}function NB(t,e){if(t.stage===e.stage)return;throw new m(`Task "${e.id}" moved to another stage while its approval was recorded`,`Review the current stage, then run 'ari approve ${e.id}' again`)}function DB(t,e){if(pt(CE(t))===pt(CE(e)))return;throw new m(`Task "${e.id}" changed while its gates ran, so their result no longer applies`,"Run 'ari done' again; another ari command changed its status, stage, approvals, contract or frozen hashes")}function CE(t){let{approvals:e,attempts:n,base:r,contractHash:o,gatesHash:s,lockHashes:i,stage:a,stageTestHashes:c,status:l}=t,u=t.evidence.length;return{approvals:e,attempts:n,base:r,contractHash:o,gatesHash:s,lockHashes:i,stage:a,stageTestHashes:c,stages:u,status:l}}function LB(t,e){let n=e.flatMap((r)=>{let o=r.detail[ho];return r.type==="context"&&Array.isArray(o)?o:[]});return[...new Set([...t,...n])].sort(O)}function BE(t,e,n,r,o){let s=r.filter((i)=>!i.ok).map((i)=>i.gate);return{at:o,detail:{failing:s,ok:s.length===0,stage:n.name},task:e.contract.id,type:t}}var MB=20,jB=`
|
|
164
214
|
|
|
165
|
-
`,
|
|
166
|
-
`),a=n===null?[]:[
|
|
167
|
-
`)}function
|
|
168
|
-
${r.outputTail}`);return[`- ${t.gate}: ${t.summary}`,...e,...n]}var
|
|
169
|
-
`)}),e.failed?
|
|
170
|
-
`)
|
|
171
|
-
`)
|
|
172
|
-
`)}
|
|
173
|
-
`)
|
|
174
|
-
`)}
|
|
175
|
-
|
|
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}
|
|
215
|
+
`,FB=["advanced","done","failed"];async function Kg(t,e={}){let n=await PE(t,e),r=n.outcome==="done"?await Mr(t):null,o=n.outcome==="advanced"?await Fo(t,n.task.contract.id,"stage",e):{id:null,warning:null};return{...n,sleep:r,snapshot:o.id,snapshotWarning:o.warning}}async function VE(t,e){let n=M(t),r=(a)=>Cr(n,{agent:e.agent,model:e.model,role:"task",route:GB(n,a)});for(let a of HB(n,e))Cr(n,{agent:e.agent,model:e.model,role:"task",route:a});await Xn({config:n,root:t},"run an agent");let o=await BB(t,e),s=[],i=null;for(;;){let a=await jn(t,o),c=r(a.stage??""),l=await WB(t,o,i),u=a.task.record.history.length,d=await Ya(c,l,{cwd:t,environment:qa(c.config),stdout:e.output??"inherit",trust:{config:n,root:t}}),p=await UB(t,o,u)??await Kg(t,{clock:e.clock}),g=p.gates.filter((f)=>!f.ok).map((f)=>f.gate);if(s.push({agent:c.name,agentExitCode:d.exitCode,failing:g,model:c.model,outcome:p.outcome,stage:p.stage,timedOut:d.timedOut}),p.outcome==="done"||p.outcome==="blocked")return{agent:e.agent??null,outcome:p.outcome,task:o,turns:s};i=p.outcome==="failed"?p:null}}function GB(t,e){return t.routing.stages[e]??t.routing.default}function HB(t,e){if(e.agent!==void 0)return[null];let n=[t.routing.default,...Object.values(t.routing.stages)].filter((r)=>r!==null);return n.length===0?[null]:n}async function UB(t,e,n){let r=await jn(t,e),{contract:o,record:s}=r.task,i=s.history.slice(n).findLast((c)=>FB.includes(c.type)),a=KB(s.status,i?.type);if(a===null)return null;return{attempts:s.attempts,budget:o.budget.attempts,gates:i?.type==="failed"?s.lastFailure?.gates??[]:[],outcome:a,stage:i?.stage??r.stage??""}}function KB(t,e){if(t==="done"||t==="blocked")return t;if(e==="failed")return"failed";return e==="advanced"?"advanced":null}async function BB(t,e){if(e.task===void 0)return VB(t,e.clock);let n=await jn(t,e.task),{question:r,status:o}=n.task.record,s=n.task.contract.id;switch(o){case"ready":return(await Xo(t,s,{clock:e.clock})).task.contract.id;case"active":if(!n.active)await Xo(t,s,{clock:e.clock});return s;case"blocked":throw new m(`Task "${s}" is blocked: ${r??"no question was recorded"}`,WE(s));case"draft":throw new m(`Task "${s}" is a draft`,`Complete its contract, then run 'ari ready ${s}'`);case"done":throw new m(`Task "${s}" is already done`,"Run 'ari next' to see what to do")}}async function VB(t,e){let n=await Sl(t);if(n.task!==null&&n.action==="continue")return n.task;if(n.task!==null&&n.action==="start")return(await Xo(t,n.task,{clock:e})).task.contract.id;if(n.task!==null&&n.action==="resolve")throw new m(`Task "${n.task}" is blocked`,WE(n.task));throw new m(`No task can run: ${n.instruction}`,`Run ${n.commands.map((r)=>`'${r}'`).join(", ")}`)}function WE(t){return`A human answers it with 'ari resolve ${t} --answer <text>'`}async function WB(t,e,n){let r=await jn(t,e),o=(await tr(t,{id:e})).text,s=`Current stage: ${r.stage??"none"}. ${r.instruction??""}`.trim(),i=[`Work only inside the scope of task "${e}". Do not edit files under .ari/ other than the task contract.`,"When the stage's work is complete, stop. Ariadne then runs 'ari done' and sends you any failures."].join(`
|
|
216
|
+
`),a=n===null?[]:[JB(n)];return[o,s,...a,i].join(jB)}function JB(t){let e=t.gates.filter((n)=>!n.ok).flatMap((n)=>qB(n));return[`'ari done' failed (attempt ${t.attempts} of ${t.budget}):`,...e].join(`
|
|
217
|
+
`)}function qB(t){let e=t.details.slice(0,MB).map((r)=>` - ${r}`),n=t.checks.filter((r)=>!r.ok).map((r)=>` ${r.name} output:
|
|
218
|
+
${r.outputTail}`);return[`- ${t.gate}: ${t.summary}`,...e,...n]}async function JE(t,e={}){let n=e.task===void 0?void 0:qn(e.task),r=Ln(await P(t));return{entries:r.entries.filter((o)=>n===void 0||o.task===n).map(YB),unreadable:r.unreadable}}async function qE(t,e){let n=jo(await P(t),e),r=qo(n);return{entry:n,integrity:{ok:r.length===0,problems:r}}}function YB(t){let{at:e,id:n,kind:r,pruned:o,task:s}=t;if(t.kind==="restore")return{artifacts:t.written.map((i)=>i.path),at:e,estimatedTokens:null,id:n,kind:r,pruned:o,reason:null,restores:t.restores,stage:null,status:null,task:s,trigger:null};return{artifacts:t.artifacts.map((i)=>i.path),at:e,estimatedTokens:t.context.estimatedTokens,id:n,kind:r,pruned:o,reason:t.reason,restores:null,stage:t.record.stageName,status:t.record.status,task:s,trigger:t.trigger}}var Kr=["draft","ready","active","blocked","done"],XB="fact";function YE(t){return{id:t.contract.id,pack:t.contract.pack,status:t.record.status,title:t.contract.title}}async function $l(t){return Sl(t)}async function Tl(t,e){let n=await vl(t,e.length===0?{}:{statuses:e});return{invalid:n.invalid,tasks:n.tasks.map(YE)}}async function xl(t,e){return jn(t,e)}async function Al(t,e){let n=await IE(t,e.title,{pack:e.pack,scope:e.scope}),r=n.designs.length===0?{}:{designs:n.designs};return{contractPath:n.contractPath,...r,...YE(n.task)}}async function Cl(t,e){let n=await OE(t,e);return{id:n.contract.id,status:n.record.status}}async function Rl(t,e){let n=await Xo(t,e),{record:r}=n.task;return{base:r.base,id:r.id,instruction:n.instruction,stage:n.stage}}async function Il(t,e,n){let r=await DE(t,e,n);return{id:r.contract.id,question:r.record.question,status:r.record.status}}async function Ol(t){let e=await _E(t);return{data:{contractChanged:e.contractChanged,gates:e.gates,gatesChanged:e.gatesChanged,ok:e.ok,stage:e.stage,task:e.task.contract.id},failed:!e.ok}}async function _l(t){let e=await Kg(t),n={attempts:e.attempts,budget:e.budget,gates:e.gates,next:e.next,outcome:e.outcome,sleep:e.sleep,stage:e.stage,task:e.task.contract.id,...e.snapshot===null?{}:{snapshot:e.snapshot}},r=e.snapshotWarning===null?[]:[e.snapshotWarning],o=e.outcome!=="done"&&e.outcome!=="advanced";return{data:n,failed:o,...r.length===0?{}:{warnings:r}}}async function Pl(t,e){let{global:n,kind:r,scope:o,text:s}=e;if(!n&&(r!==void 0||o!==void 0))throw new v("--kind and --scope apply only to knowledge entries","Add --global, or drop them");let i=r??XB;if(!dS(i))throw new v(`--kind must be one of ${le.join(", ")}, got "${i}"`,"Pass --kind fact");if(n)return{entry:await gS(t,{kind:i,scope:[...o??[]],text:s}),target:"knowledge"};let a=await jE(t,s),c=a.record.notes.length-1,l=a.record.notes[c];return{at:l?.at??"",index:c,target:"task",task:a.contract.id,text:l?.text??s}}async function Nl(t,e){let{budget:n}=e;if(n!==void 0&&(!Number.isInteger(n)||n<=0))throw new v(`--budget must be a positive whole number of tokens, got ${n}`,"Pass --budget 6000");return tr(t,{budget:n,id:e.id})}function Dl(t,e,n){return mS(t,e,{all:n})}async function Ll(t,e){return Vp(t,e)}async function Ml(t,e){return JE(t,{task:e})}async function jl(t,e){return qE(t,e)}function XE(t){return t.map((e)=>{let n=Kr.find((r)=>r===e);if(n!==void 0)return n;throw new v(`Unknown status "${e}"`,`Choose from ${Kr.join(", ")}`)})}async function zE(t,e={}){let n=e.staged??!1,{config:r,drift:o,task:s}=await za(t);if(s===null){let d=r.requireTask?"config.requireTask is true, but no task is active in this worktree":null;return{checked:[],ok:d===null,outside:[],reason:d,staged:n,task:null}}let i=ne(n?await zB(t):await xe(t,s.record.base??"HEAD")),a=i.filter((d)=>!et(d,s.contract.scope)),c=wt(a.length,"changed file lies","changed files lie"),l=a.length===0?null:`${a.length} ${c} outside the scope of "${s.contract.id}"`,u=i.length===0?null:o??l;return{checked:i,ok:u===null,outside:a,reason:u,staged:n,task:s.contract.id}}async function zB(t){let e=await F(t,["diff","--cached","--name-only","--no-renames","-z"]);return Ke(e.stdout)}var Bg=1,ZE=E({description:"Print the one next action",examples:["ari next","ari next --json"],json:!0,name:"next",run:async(t)=>{t.output.result(await $l(await _()),ZB)}}),QE=E({description:"Evaluate the active task's current stage without recording an attempt",examples:["ari check"],json:!0,name:"check",run:async(t)=>{let e=await Ol(await _());return t.output.result(e.data,(n)=>{let r=n.ok?`Stage ${n.stage} passes`:`Stage ${n.stage} fails`,s=[...n.contractChanged?["contract"]:[],...n.gatesChanged?["gates (its pack, test globs, regression setup or review command)"]:[]].map((i)=>`The ${i} changed since it was frozen; run 'ari amend ${n.task} --reason <text>' before 'ari done'`);return[oc(n.gates),`${r} for "${n.task}"`,...s].join(`
|
|
219
|
+
`)}),e.failed?Bg:void 0}}),t$=E({description:"Evaluate the current stage's gates, record evidence and advance",examples:["ari done","ari done --json"],json:!0,name:"done",run:async(t)=>{let e=await _l(await _());for(let n of e.warnings??[])process.stderr.write(`${n}
|
|
220
|
+
`);return t.output.result(e.data,QB),e.failed?Bg:void 0}}),e$=E({args:j({staged:{default:!1,description:"Check only staged files (the pre-commit hook)",type:"boolean"}}),description:"Check that changed files lie inside the active task's scope",examples:["ari scope","ari scope --staged"],json:!0,name:"scope",run:async(t)=>{let e=await zE(await _(),{staged:t.args.staged});return t.output.result(e,e2),e.ok?void 0:Bg}});function ZB(t){return[t.instruction,...t.commands.map((e)=>` ${e}`)].join(`
|
|
221
|
+
`)}function QB(t){let e=t.snapshot===void 0?[]:[`Snapshot ${t.snapshot} saved`];return[t2(t),...e].join(`
|
|
222
|
+
`)}function t2(t){switch(t.outcome){case"done":return`Task "${t.task}" is done`;case"advanced":return`Stage ${t.stage} passed. Next stage ${t.next?.stage??""}: ${t.next?.instruction??""}`;case"failed":return[oc(t.gates.filter((e)=>!e.ok)),`Stage ${t.stage} failed: attempt ${t.attempts} of ${t.budget}`].join(`
|
|
223
|
+
`);case"blocked":return[oc(t.gates.filter((e)=>!e.ok)),`Task "${t.task}" is blocked: attempt budget exhausted; a human answers with 'ari resolve ${t.task} --answer <text>'`].join(`
|
|
224
|
+
`)}}function e2(t){if(t.task===null)return t.ok?"No active task; scope passes":`Scope fails: ${t.reason??""}`;if(t.ok){let e=wt(t.checked.length,"changed file lies","changed files lie");return`${t.checked.length} ${e} inside the scope of "${t.task}"`}return[`${t.reason??""}:`,...t.outside.map((e)=>` ${e}`)].join(`
|
|
225
|
+
`)}function n$(t,e,n){let r=`ari hooks ${t} --agent`;return E({args:j({agent:{description:`Agent: ${ng().join(", ")}`,type:"string"}}),description:e,examples:[`${r} claude`,`${r} git`],json:!0,name:t,run:async(o)=>{let s=ln(o.args.agent,"--agent",`${r} <name>`);o.output.result(await n(await _(),s),o2)}})}var n2=E({description:"List the agents ari has hook adapters for and whether they are installed here",examples:["ari hooks list --json"],json:!0,name:"list",run:async(t)=>{let e=await Uv(await _());t.output.result({agents:e},({agents:n})=>n.map(s2).join(`
|
|
226
|
+
`))}}),r$=E({description:"Install, uninstall and list agent and git hook integrations",name:"hooks",subcommands:[n$("install","Install ari hooks into an agent's project settings or into git",Ho),n$("uninstall","Remove ari hooks from an agent's project settings or from git, and nothing else",Hv),n2]}),o$=E({description:"Answer an agent hook: reads the agent's JSON payload on stdin and prints its decision",examples:["ari hook claude before-edit < payload.json"],name:"hook",positionals:st({agent:{description:"Agent name",required:!0},event:{description:"before-edit, before-shell, after-tool, stop, pre-compact or session-start",required:!0}}),run:async(t)=>{let e=process.stdin.isTTY?"":await Bun.stdin.text(),n=await Kv(t.positionals.agent,t.positionals.event,e,process.cwd());if(n.warning!==null)process.stderr.write(`${n.warning}
|
|
185
227
|
`);if(n.stdout.length>0)process.stdout.write(`${n.stdout}
|
|
186
|
-
`);if(n.expired)await
|
|
187
|
-
`);let e="events"in t?`: ${t.events.join(", ")}`:"";return`${t.agent} hooks ${t.action} in ${t.file}${e}`}function
|
|
188
|
-
`,
|
|
189
|
-
|
|
190
|
-
${e.
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
`))
|
|
194
|
-
`)}
|
|
195
|
-
${t.join(`
|
|
196
|
-
|
|
197
|
-
`)}
|
|
198
|
-
`
|
|
199
|
-
`,
|
|
200
|
-
|
|
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}
|
|
228
|
+
`);if(n.expired)await r2()}});async function r2(){return await new Promise((t)=>process.stdout.write("",()=>t())),process.exit()}function o2(t){if("files"in t)return t.files.map((n)=>`git ${n.hook}: ${n.action} (${n.path})`).join(`
|
|
229
|
+
`);let e="events"in t?`: ${t.events.join(", ")}`:"";return`${t.agent} hooks ${t.action} in ${t.file}${e}`}function s2(t){let e=t.installed?"installed":"not installed";return`${t.agent} ${t.support} ${e} ${t.file} ${t.events.join(", ")}`}var s$=E({args:j({agents:{description:"Install agent hooks, comma-separated (claude,codex,gemini,cursor,copilot,git)",type:"string"},gitHooks:{default:!1,description:"Install the pre-commit and pre-push git hooks",type:"boolean"},mcp:{description:"Register ari's MCP server, comma-separated (claude,codex,gemini,cursor)",type:"string"},pack:{description:"Default methodology pack for new tasks",type:"string"},skills:{description:"Install ari's skills, comma-separated (claude,codex,gemini,cursor)",type:"string"}}),description:"Create .ari/ and the AGENTS.md block, and optionally install hooks, MCP servers and skills",examples:["ari init","ari init --pack tdd --agents claude,codex --git-hooks","ari init --agents claude --mcp claude --skills claude"],json:!0,name:"init",run:async(t)=>{let e=await _(),n=await Ir(e,()=>yb(e,{agents:We(t.args.agents),gitHooks:t.args.gitHooks,mcp:We(t.args.mcp),pack:t.args.pack,skills:We(t.args.skills)}));t.output.result(n,i2)}});function i2(t){let e=t.hooks.flatMap((n)=>("files"in n)?n.files.map((r)=>`git ${r.hook}: ${r.action} (${r.path})`):[`${n.agent} hooks: ${n.action} (${n.file})`]);return[`.ari/config.json: ${t.config} (pack ${t.pack})`,`${t.agentsMd.path}: ${t.agentsMd.action}`,...e,...t.mcp.map((n)=>`${n.agent} MCP server: ${n.action} (${n.file})`),...t.skills.map((n)=>`${n.agent} skill ${n.skill}: ${n.action} (${n.file})`),'Next: ari new "<title>"'].join(`
|
|
230
|
+
`)}var a2="--hooks, --mcp, --skills or --git-hooks";function i$(t){let e=new Set([...t.hooks===!0?["hooks"]:[],...t.mcp===!0?["mcp"]:[],...t.skills===!0?["skill"]:[],...t.gitHooks===!0?["git"]:[]]);return{agents:t.agent===void 0?void 0:l2(t.agent),init:t.init,kinds:e.size===0?void 0:e,pack:wi(t.pack,"--pack"),routing:u2(t),scope:t.scope===void 0?void 0:rr(t.scope)}}function a$(t){return Object.values(t).some((e)=>e!==void 0)}function Vg(t,e){return[...or.filter((r)=>e.has(r)).flatMap((r)=>t.map((o)=>Ot(r,o))),...e.has("git")?[qe]:[]]}function Wg(t,e,n){let r=[],o=e.init===!0||e.pack!==void 0;if(!t.initialised&&!o)r.push("--init");let s=e.kinds!==void 0&&[...e.kinds].every((u)=>u==="git"),i=e.agents??(s||!n?[]:ul(t)),a=n&&e.agents===void 0&&!s&&i.length===0;if(e.agents===void 0&&!s&&(!n||a))r.push("--agent");if(e.kinds===void 0&&!n)r.push(a2);if(r.length>0)throw c2(r,a);let c=e.scope??"project",l=e.kinds===void 0;return{agents:i,init:o,pack:e.pack??null,recommended:l,routing:e.routing??null,scope:c,targets:l?Ib(t,i,c,o):Vg(i,e.kinds??new Set)}}function c2(t,e){let n=t.join(" and ");return new v(`ari install needs ${n} when it cannot ask${e?"; no agent was found on PATH":""}`,`For example: ari install ${t.includes("--init")?"--init ":""}--agent claude,codex --yes. --yes installs every supported target; see 'ari install --help'`)}function l2(t){let e=[...new Set(t.split(",").map((n)=>n.trim()).filter((n)=>n.length>0))];if(e.length===0)throw new v("--agent needs at least one agent",`Choose from: ${at.join(", ")}`);return e.map((n)=>{if(ll(n))return n;throw new v(`ari install has no agent "${n}"`,`Choose from: ${at.join(", ")}`)})}function u2(t){let e=wi(t.taskAgent,"--task-agent"),n=wi(t.reviewAgent,"--review-agent"),r=wi(t.taskModel,"--task-model"),o=wi(t.reviewModel,"--review-model");if(e===void 0&&n===void 0){let s=r!==void 0?"--task-model":o!==void 0?"--review-model":null;if(s===null)return;throw new v(`${s} needs --task-agent and --review-agent`,"Pass both agents to set the routing")}if(e===void 0||n===void 0)throw new v(`Routing needs ${e===void 0?"--task-agent":"--review-agent"} as well`,"Pass --task-agent and --review-agent together");return{review:{agent:n,model:o??null},task:{agent:e,model:r??null}}}function wi(t,e){if(t===void 0)return;let n=t.trim();if(n.length>0)return n;throw new v(`${e} must not be empty`,`Leave ${e} out, or give it a value`)}import{join as d$}from"path";import{isDeepStrictEqual as qg}from"util";var d2=1,p2=":",c$="routing.default",g2="review.agent";function u$(t,e){let n=re(rt,t),r=Jg(n,"agents"),o=Jg(n,"routing"),s=Jg(n,"review"),i=m2(r,e),a=i.flatMap(({entry:g,name:f})=>g===null?[]:[[f,g]]),c=k2(o.default,c$,e.task)?o.default:y2(e.task),l=w2(s,e.review)?s:S2(s,e.review),u={...n,agents:{...r,...Object.fromEntries(a)},review:l,routing:{...o,default:c}},d=Ea(u);if(d!==null)throw new m(`ari cannot set the routing: ${d}`,`Fix ${rt}, then run 'ari install' again`,1,{tag:"InvalidConfig"});return{changes:[...i.map(({action:g,name:f,roles:y})=>({action:g,agent:f,detail:`${y.join(" and ")} agent`,key:`agents.${f}`})),{action:l$(o.default,c),agent:e.task.agent,detail:`tasks: ${Br(e.task)}`,key:c$},{action:l$(s.agent===void 0?void 0:s,l),agent:e.review.agent,detail:`reviews: ${Br(e.review)}`,key:g2}],next:zn(t,u)}}function m2(t,e){let n=new Map;for(let[r,o]of[[e.task,"task"],[e.review,"review"]])n.set(r.agent,[...n.get(r.agent)??[],o]);return[...n].map(([r,o])=>f2(r,o,t[r]))}function Br(t){return t.model===null?`${t.agent} (CLI default model)`:`${t.agent} (${t.model})`}function f2(t,e,n){let r=Ve.find((l)=>l.name===t),o=e.length>1?"both":e[0]??"task";if(n===void 0){if(r!==void 0)return{action:"created",entry:Eo(r,o,void 0),name:t,roles:e};throw new v(`No agent named "${t}" is configured, and ari has no preset of that name`,`Choose a configured agent, or one of the presets: ${Ve.map((l)=>l.name).join(", ")}`)}let s=h2(n);if(e.every((l)=>s.includes(l)))return{action:"unchanged",entry:null,name:t,roles:e};let i=z(n)&&typeof n.model==="string"?n.model:void 0,a=r!==void 0&&bo.some((l)=>qg(n,Eo(r,l,i)));if(r!==void 0&&a)return{action:"updated",entry:Eo(r,"both",i),name:t,roles:e};let c=e.filter((l)=>!s.includes(l));throw new m(`agents.${t} has no ${c.join(" or ")} role`,`Add ${c.map((l)=>`"${l}"`).join(" and ")} to agents.${t}.roles in ${rt}, or choose another agent`,d2,{tag:"AgentRoleMismatch"})}function h2(t){if(!z(t)||!Array.isArray(t.roles))return Wu;return t.roles.filter((e)=>typeof e==="string")}function Jg(t,e){let n=t[e];return z(n)?n:{}}function y2(t){return t.model===null?t.agent:`${t.agent}${p2}${t.model}`}function k2(t,e,n){if(t===void 0||t===null)return!1;try{return qg(Ss(t,e),n)}catch{return!1}}function w2(t,e){return t.agent===e.agent&&(t.model??null)===e.model}function S2(t,e){let{model:n,...r}=t;return{...r,agent:e.agent,...e.model===null?{}:{model:e.model}}}function l$(t,e){if(t===void 0||t===null)return"created";return qg(t,e)?"unchanged":"updated"}var v2=new Set(["created","updated","unchanged"]),b2="Fix the cause, then run 'ari install' again; it keeps what is already done";async function Fl(t,e,n,r={}){let o={mode:n,plan:e,root:t,scopes:await _2(t),view:O2(n)},s=[],i=!1;for(let a of e.targets){if(i||a.skip!==null){s.push(vi(a,i?"pending":"skipped",i?null:a.skip));continue}r.start?.(a);try{let c=await E2(o,a);s.push(...c),r.done?.(a,c)}catch(c){let l={...vi(a,"failed",N2(c)),hint:D2(c)};s.push(l),r.failed?.(a,l),i=!0}}return{failed:i,rows:s}}async function E2(t,e){if(e.id===$g)return[Si(e,$2(t))];if(e.id===sr)return[Si(e,T2(t))];let{agent:n}=e;switch(e.kind){case"hooks":return[Si(e,await x2(t,Yg(n)))];case"mcp":return[Si(e,A2(t,Yg(n),e.scope))];case"skill":return[Si(e,C2(t,Yg(n),e.scope))];case"git":return R2(t,e);case"routing":return I2(t,e);case"config":throw Error(`ari has no configuration target "${e.id}"`)}}function $2({mode:t,plan:e,root:n,view:r}){if(t==="apply")return fg(n,e.pack);return bi(r,n,rt,(o)=>hg(o,e.pack))}function T2({mode:t,root:e,view:n}){if(t==="apply")return mg(e).action;return bi(n,e,jt,fi)}async function x2({mode:t,root:e,view:n},r){let o=Pe(r);if(t==="preview")return bi(n,e,o.file,(i)=>Ks(o,i));let s=await Ho(e,r);return"action"in s?s.action:"unchanged"}function A2({mode:t,scopes:e,view:n},r,o){let s=e[o];if(t==="apply")return Ko(me(r),s).action;let i=Ne(me(r),s);return bi(n,i.base,i.file,(a)=>i.install(a))}function C2({mode:t,scopes:e,view:n},r,o){let s=e[o],i=Jt(r);if(t==="apply"){let c=Bo(i,s);return rl(c,r),lg(c.flatMap((l)=>l.action==="refused"?[]:[l.action]))}let a=ot.map((c)=>{let l=ie(i,s,c);return bi(n,l.base,l.file,(u)=>l.install(u))});return lg(a)}async function R2({mode:t,root:e},n){return(t==="apply"?(await ac(e)).files:await Fs(e)).map(({action:o,path:s})=>({...vi(n,Xg(o),null),file:s}))}function I2({mode:t,plan:e,root:n,view:r},o){let s=e.routing;if(s===null)return[];let i=t==="apply"?W(n,rt):r.read(n,rt);if(i===null)throw new m(`${rt} does not exist, so ari cannot set the routing`,"Run 'ari init' first");let a=u$(i,s);if(t==="apply")Ce(n,rt,a.next);else r.write(n,rt,a.next);return a.changes.map((c)=>({...vi(o,Xg(c.action),null),agent:c.agent,detail:c.detail,key:c.key}))}function bi(t,e,n,r){let o=t.read(e,n),s=r(o);return t.write(e,n,s),Ns(o,s)}function O2(t){let e=new Map;return{read:(n,r)=>e.get(d$(n,r))??W(n,r),write:(n,r,o)=>{if(t==="preview")e.set(d$(n,r),o)}}}async function _2(t){return{project:{base:t,receipts:await P(t),scope:"project"},user:await xt("user",t)}}function Si(t,e){return vi(t,Xg(e),null)}function vi(t,e,n){let r=t.file===null?null:t.file;return{action:e,agent:t.agent,detail:null,file:r===null?null:P2(t.scope,r),hint:null,key:null,kind:t.kind,reason:n,scope:t.scope,undo:v2.has(e)?wb(t):null}}function P2(t,e){return t==="user"&&!e.startsWith("~/")?oe(t,e):e}function Xg(t){return t==="removed"?"updated":t}function Yg(t){if(t!==null)return t;throw Error("This target needs an agent")}function N2(t){return t instanceof Error?t.message:String(t)}function D2(t){if(t instanceof m&&t.hint!==void 0&&t.hint.length>0)return t.hint;return b2}import{rmSync as L2}from"fs";var M2="knowledge",p$="Every 'ari sleep' pass and '--apply' writes an entry under <git-path>/ari/sleep/",j2=()=>new Date().toISOString();async function m$(t,e,n={}){let r=await P(t),o=(n.clock??j2)();return Nr(r,()=>{let s=y$(t,r,e);for(let c of s.restore)Tr(Oe(t,c.id),Dr(c.original));for(let c of s.remove)L2(Oe(t,c.id),{force:!0});for(let{notes:c,task:l}of s.unpromote)Vt(t,r,l,(u)=>yy(u,c));let i=k$(s),a=No(r,o,{kind:"undo",removed:i.removed,restored:i.restored,undoes:s.target.id,unpromoted:i.unpromoted});return{...i,ledger:a.id}})}async function f$(t,e){let n=await P(t);return{...k$(y$(t,n,e)),dryRun:!0}}async function h$(t,e){let n=ei(t,e);if(n.status==="active")throw new m(`Knowledge entry "${e}" is already active`,"Run 'ari knowledge list --all' to see archived entries");let r=await P(t);return Nr(r,()=>{let o=Oe(t,e),s=Lo(o),i=ii(r),a=ai(i),c=i.filter(Po).filter((l)=>!a.has(l.id)).reverse().flatMap((l)=>l.archived).find((l)=>l.id===e&&l.sha256===s)?.original;if(c===void 0)ti(t,{...n,status:"active",supersededBy:null});else Tr(o,Dr(c));return ei(t,e)})}function y$(t,e,n){let r=F2(ii(e),n),o=[],s=r.archived.filter((a)=>{let c=Mp(Oe(t,a.id));if(c===a.sha256)return!0;if(c!==a.original.sha256)o.push(`${g$(a.id)} ${c===null?"is missing":"changed after sleep archived it"}`);return!1}),i=r.created.filter((a)=>{let c=Mp(Oe(t,a.id));if(c===null)return!1;if(c===a.sha256)return!0;return o.push(`${g$(a.id)} changed after sleep created it`),!1});if(o.length>0){let a=o.map((c)=>` - ${c}`).join(`
|
|
231
|
+
`);throw new m(`Cannot undo sleep entry ${r.id}; ${o.length} file(s) are not as it left them:
|
|
232
|
+
${a}`,"Nothing was changed. Restore those files from git, undo the later sleep entries first, or use 'ari knowledge restore <id>' for a single entry")}return{remove:i,restore:s,target:r,unpromote:G2(t,r.promoted)}}function F2(t,e){let n=ai(t);if(e===void 0){let s=t.filter(Po).findLast((i)=>!n.has(i.id)&&Gl(i));if(s!==void 0)return s;throw new m("The sleep ledger has no entry that changed knowledge and is not undone yet",p$)}let r=ri(e)?t.find((s)=>s.id===e):void 0;if(r===void 0){let s=t.length===0?"none yet":t.map((i)=>i.id).join(", ");throw new m(`The sleep ledger has no entry "${e}"`,`Known entries: ${s}`)}if(!Po(r))throw new m(`Ledger entry ${e} records an undo itself`,"Run 'ari sleep' or 'ari knowledge restore <id>' instead");let o=n.get(e);if(o!==void 0)throw new m(`Sleep entry ${e} was already undone by ${o}`,p$);if(!Gl(r))throw new m(`Sleep entry ${e} changed no knowledge entry, so there is nothing to undo`,"Journals that sleep pruned cannot be restored");return r}function Gl(t){return t.archived.length>0||t.created.length>0||t.promoted.length>0}function G2(t,e){let n=new Set(In(t));return e.flatMap(({notes:r,task:o})=>{if(!n.has(o))return[];let s=On(t,o),i=r.filter((a)=>s.notes[a]?.promoted===!0);return i.length===0?[]:[{notes:i,task:o}]})}function k$(t){return{journalsNotRestored:t.target.pruned.map((e)=>e.task),removed:t.remove.map(({id:e,sha256:n})=>({id:e,sha256:n})),restored:t.restore.map(({id:e,original:n})=>({id:e,sha256:n.sha256})),undoes:t.target.id,unpromoted:t.unpromote}}function g$(t){return`${J}/${M2}/${t}.md`}var H2=3,w$=new Set(["active","blocked"]);async function S$(t){let e=Hl(()=>M(t));if(e===null)return[];let n=await P(t),r=Hl(()=>Pt(t,e)),o=r?.tasks??[],s=Hl(()=>gt(n))?.task??null,i=await U2(t,o,s),a=o.some((l)=>l.contract.id===s&&w$.has(l.record.status));return["ari next",...o.length+(r?.invalid.length??0)>0?["ari list"]:[],...i.slice(0,H2).map((l)=>`ari start ${l}`),...a?["ari context"]:[],...await B2(t,n)]}async function U2(t,e,n){let r=e.filter((s)=>w$.has(s.record.status)&&s.contract.id!==n);if(r.length===0)return[];let o=await K2(t);return r.map((s)=>s.contract.id).filter((s)=>!o.has(s))}async function K2(t){try{return await ki(t)}catch{return new Map}}async function B2(t,e){let n=await J2(()=>V2(t)),r=Hl(()=>W2(e));return[...n===!0?["ari sleep"]:[],...r===!0?["ari sleep --undo"]:[]]}async function V2(t){return er(await jr(t,{candidates:!1})).due}function W2(t){let e=ii(t),n=ai(e);return e.some((r)=>Po(r)&&!n.has(r.id)&&Gl(r))}async function J2(t){try{return await t()}catch(e){if(e instanceof m)return null;throw e}}function Hl(t){try{return t()}catch(e){if(e instanceof m)return null;throw e}}import{homedir as q2}from"os";var Ei=72,Y2="ari install",X2="ari uninstall",v$=44,z2=28,b$=8,Z2="Kept: .ari/ data, the AGENTS.md block, routing and trust",Q2=[["ari next","what to do now"],["ari list","every task and where it stands"],["ari start ","adopt a task that no worktree holds"],["ari context","the context pack of the active task"],["ari sleep --undo","undo the last memory consolidation"],["ari sleep","consolidate memory, which is due"]],T$=['ari new "Describe the first task"',"ari next"],Zg=20,E$=26,zg=13,x$=8,Vr=11,A$=34,$$=12,tV=/\d+(?:\.\d+)+[\w.+-]*/,C$="\u2026",eV="~",Ul=".ari/config.json",R$=new Set(["created","updated"]),qt=" ",nV=`${w.green("\u2713")} installed ${w.yellow("\u2191")} update ${w.dim("\xB7")} not installed ${w.dim("\u2013")} not supported`,rV={created:"create",failed:"fail",pending:"not run",skipped:"skip",unchanged:"unchanged",updated:"update"};function I$(t,e){let n=t.initialised?`set up, pack ${t.pack??"basic"}`:`not set up yet (${w.yellow(".ari/config.json is missing")})`,r=t.targets.find((a)=>a.id==="agents-md"),o=[zo("Repository",yV(t.root)),zo("Ariadne",`${e} \xB7 ${n}`),...r===void 0?[]:[zo("AGENTS.md",`${L$(r)} ari block`)],...mV(t),zo("Git hooks",fV(t))],s=w.dim([ut("Agent",Zg),ut("On PATH",zg),...or.map((a)=>ut(hV(a),x$))].join("")),i=at.map((a)=>pV(t,Ft(t,a)));return[...o,"",s,...i,"",nV].map(Le).join(`
|
|
233
|
+
`)}function O$(t,e,n){let r=new Map,o=[];for(let c of t){if(c.kind==="routing")continue;if(c.action==="skipped"){let u=Wr(c.reason??"",Ei-qt.length*2).map((d)=>`${qt}${qt}${w.dim(d)}`);o.push(`${qt}${ar(e,c)}`,...u);continue}let l=dV(e,c);r.set(l,[...r.get(l)??[],cV(c)])}let s=[...r].flatMap(([c,l])=>[w.bold(c),...l]),i=n===null?[]:uV(t,n),a=o.length===0?[]:[w.bold("Skipped"),...o];return[...s,...i,...a].map(Le).join(`
|
|
234
|
+
`)}function _$(t,e){let[n]=e;if(n===void 0)return"";if(n.kind==="routing"){let o=e.filter((i)=>R$.has(i.action)).map((i)=>i.key??""),s=o.length===0?"unchanged":"updated";return Le(`${ut("Routing",E$)}${Zo(s,!1)}${o.join(", ")||Ul}`)}let r=e.map((o)=>o.file??"").join(", ");return Le(`${ut(ar(t,n),E$)}${Zo(n.action,!1)}${r}`)}function P$(t){return t.map((e)=>{let n=e.ok?w.green("\u2713"):w.red("\u2717"),r=e.ok?w.dim(e.detail):w.red(e.detail);return Le(`${n} ${ut(e.name,Zg)}${r}`)}).join(`
|
|
235
|
+
`)}function Jr(t,e){return[...Wr(t,Ei),...Wr(e,Ei).map((r)=>w.dim(r))].join(`
|
|
236
|
+
`)}function Wr(t,e){let n=[];for(let r of t.split(`
|
|
237
|
+
`)){let o="";for(let s of r.split(" ")){let i=o.length===0?s:`${o} ${s}`;if(Bun.stringWidth(i)>e&&o.length>0)n.push(o),o=s;else o=i}if(o.length>0)n.push(o)}return n}function Qg(t){let e=["created","updated","unchanged","skipped","failed","pending"].map((o)=>[o,t.targets.filter((s)=>s.action===o).length]).filter(([,o])=>o>0).map(([o,s])=>`${s} ${o==="pending"?"not run":o}`),n=t.checks.filter((o)=>!o.ok).length,r=t.checks.length===0?[]:[`${t.checks.length-n} of ${t.checks.length} checks passed`];return[e.join(" \xB7 "),...r,"",w.bold("Next"),...t.next.map((o)=>`${qt}${o}`)].map(Le).join(`
|
|
238
|
+
`)}function tm(t){let e=new Set,n=t.targets.flatMap((o)=>{if(o.undo===null||e.has(o.undo))return[];return e.add(o.undo),[`${ut(o.undo,v$)}${oV(o)}`]});if(n.length===0)return[];let r=n.length-b$;return[`${ut(X2,v$)}everything ari installed`,...n.slice(0,b$),...r>0?[`and ${r} more: see "undo" in --json`]:[],Z2].map(Le)}function em(t){return t.resume.map((e)=>Le(`${ut(e,z2)}${sV(e)}`))}function oV(t){if(t.kind==="git")return"git hooks";let e=t.kind==="hooks"||t.kind==="mcp"||t.kind==="skill"?Ye[t.kind]:t.kind;return`${t.agent??""} ${e}`.trim()}function sV(t){return Q2.find(([n])=>n.endsWith(" ")?t.startsWith(n):t===n)?.[1]??""}function iV(t){let e=tm(t),n=em(t);return[...e.length===0?[]:["","To undo",...e.map((r)=>`${qt}${r}`)],...n.length===0?[]:["","To get back to your tasks",...n.map((r)=>`${qt}${r}`)]]}function N$(t){let e=t.targets.map((a)=>{let c=[a.agent,a.kind,a.key].filter((d)=>d!==null).join(" "),l=a.reason===null?"":`: ${a.reason}`,u=a.hint===null?"":` (${a.hint})`;return`${ut(a.action,Vr)}${ut(a.file??"-",A$)} ${c}${l}${u}`}),n=t.warnings.flatMap((a)=>[`warning: ${a.message}`,` ${a.fix}`]),r=t.check?Dg(t.checks.map((a)=>ml(a,Y2))):t.checks.map((a)=>`check ${a.ok?"ok":"FAILED"}: ${a.name}: ${a.detail}${a.hint===null?"":` (${a.hint})`}`),o=t.check?[aV(t)]:t.dryRun?["Dry run: nothing was written"]:t.upToDate?["Everything is up to date"]:[],s=t.ok&&!t.dryRun,i=s?t.next.map((a)=>`next: ${a}`):[];return[...e,...n,...r,...o,...i,...s?iV(t):[]].join(`
|
|
239
|
+
`)}function aV(t){if(t.ok)return"Up to date: nothing would change and every check passed";return t.upToDate?"Up to date, but a check failed":"Not up to date"}function ar(t,e){if(e.kind==="git")return"git hooks";if(e.kind==="config")return e.file==="AGENTS.md"?"ari block":"configuration";if(e.kind==="routing")return"routing";return`${e.agent===null?"":`${D$(t,e.agent)} `}${Ye[e.kind]}`}function Zo(t,e){let n=ut(e?rV[t]:t,Vr);switch(t){case"created":return w.green(n);case"updated":return w.yellow(n);case"failed":return w.red(n);case"unchanged":case"skipped":case"pending":return w.dim(n)}}function Le(t){if(Bun.stringWidth(t)<=Ei)return t;return`${Bun.sliceAnsi(t,0,Ei-1)}${C$}`}function Kl(t){if(t.path===null)return"not found";let e=tV.exec(t.version??"")?.[0]??t.version??"found";return e.length>$$?`${e.slice(0,$$-1)}${C$}`:e}function cV(t){let e=t.kind==="config"&&t.file==="AGENTS.md"?"ari block":lV[t.kind],n=t.action==="failed"?w.red(t.reason??""):w.dim(e);return`${qt}${Zo(t.action,!0)}${ut(t.file??"",A$)} ${n}`}var lV={config:"configuration",git:"git hook",hooks:"hooks",mcp:"MCP server",routing:"routing",skill:`${ot.length} skills`};function uV(t,e){let n=t.filter((l)=>l.kind==="routing"),r=n.find((l)=>l.action==="failed"),o=n.some((l)=>l.action==="pending"),s=(l)=>n.filter((u)=>(u.key??"").startsWith(l)&&R$.has(u.action)).map((u)=>u.key??""),i=s("agents."),a=[...s("routing."),...s("review.")],c=r!==void 0?[`${qt}${Zo("failed",!0)}${w.red(r.reason??"")}`]:o?[`${qt}${Zo("pending",!0)}${Ul}`]:i.length+a.length===0?[`${qt}${Zo("unchanged",!0)}${Ul}`]:[...i.length===0?[]:[`${qt}${w.green(ut("add",Vr))}${i.join(", ")}`],...a.length===0?[]:[`${qt}${w.yellow(ut("set",Vr))}${a.join(", ")}`]];return[`${w.bold("Routing")} ${w.dim(Ul)}`,`${qt}${ut("tasks",Vr)}${Br(e.task)}`,`${qt}${ut("reviews",Vr)}${Br(e.review)}`,...c]}function dV(t,e){if(e.agent!==null)return D$(t,e.agent);return e.kind==="git"?"Git hooks":"Repository"}function D$(t,e){return t.agents.find((n)=>n.agent===e)?.label??e}function pV(t,e){let n=e.path===null?w.dim(ut("not found",zg)):ut(Kl(e),zg),r=or.map((o)=>ut(gV(t,e.agent,o),x$));return[ut(e.label,Zg),n,...r].join("")}function gV(t,e,n){if(!Ft(t,e).kinds.includes(n))return w.dim("\u2013");let r=t.targets.filter((i)=>i.agent===e&&i.kind===n);if(r.some((i)=>i.problem!==null))return w.red("!");let o=r.filter((i)=>i.status!=="missing");if(o.length===0)return w.dim("\xB7");let s=o.some((i)=>i.status==="outdated")?w.yellow("\u2191"):w.green("\u2713");if(o.length>1)return`${s} both`;return o[0]?.scope==="user"?`${s} user`:s}function mV(t){let{review:e,task:n}=t.routing;if(n===null&&e===null)return[];let r=n===null?"tasks: not set":`tasks ${Br(n)}`,o=e===null?"reviews: not set":`reviews ${Br(e)}`;return[zo("Routing",r),zo("",o)]}function fV(t){if(t.hookManager!==null)return w.dim(`managed by ${t.hookManager.name}`);let e=t.targets.find((n)=>n.id==="git");if(e===void 0)return w.dim("\xB7");if(e.problem!==null)return`${w.red("!")} ${e.problem.message}`;return`${L$(e)} ${e.status==="missing"?"not installed":"pre-commit, pre-push"}`}function L$(t){if(t.problem!==null)return w.red("!");if(t.status==="current")return w.green("\u2713");return t.status==="outdated"?w.yellow("\u2191"):w.dim("\xB7")}function hV(t){return t==="mcp"?"MCP":t==="hooks"?"Hooks":"Skill"}function zo(t,e){return`${ut(t,Vr+1)}${e}`}function yV(t){let e=q2();return t===e||t.startsWith(`${e}/`)?`${eV}${t.slice(e.length)}`:t}function ut(t,e){let n=Bun.stringWidth(t);return n>=e?`${t} `:`${t}${" ".repeat(e-n)}`}var kV="install plan",wV=new Set(["created","updated"]),SV=/^[\w@%+=:,./-]+$/,nm=6;function M$(t,e,n){let r=e.filter((a)=>wV.has(a.action));if(r.length===0)return null;let o=[...new Set(r.map((a)=>ar(t,a)))],s=o.slice(0,nm).join(", "),i=o.length>nm?` and ${o.length-nm} more`:"";return{detail:`${r.length} file(s) would change: ${s}${i}`,hint:vV(n),name:kV,ok:!1}}function vV(t){return["ari install",...[["--init",t.init],["--pack",t.pack],["--agent",t.agent],["--hooks",t.hooks],["--mcp",t.mcp],["--skills",t.skills],["--git-hooks",t.gitHooks],["--scope",t.scope],["--task-agent",t.taskAgent],["--task-model",t.taskModel],["--review-agent",t.reviewAgent],["--review-model",t.reviewModel]].flatMap(([r,o])=>{if(o===void 0||o===!1)return[];return o===!0?[r]:[`${r} ${bV(o)}`]}),"--yes"].join(" ")}function bV(t){return SV.test(t)?t:`'${t.replaceAll("'","'\\''")}'`}var j$="basic",EV=2,$V="CLI default";async function U$(t,e){let{init:n,pack:r}=await TV(t,e),o=e.agents??await xV(t);LV(t,{agents:o,init:n,scope:"project",targets:[]},["agent-not-found"]);let s=e.scope??await AV(t,o);if(s==="user"&&o.includes("claude"))Qo("Claude Code keeps user-scope MCP servers in its own state file, which ari does not edit",`Run: ${cl}`);let i=e.kinds===void 0?await CV(t,o,s,n):Vg(o,e.kinds),a=e.routing??await OV(t,o,t.initialised||n);return{agents:o,init:n,pack:r,recommended:!1,routing:a,scope:s,targets:i}}async function TV(t,e){let n=e.init===!0||e.pack!==void 0;if(t.initialised||n)return{init:n,pack:e.pack??null};if(Qo(".ari/config.json is missing, so ari is not set up in this repository","Setting it up writes .ari/config.json and a short block in AGENTS.md"),!await Ee({initialValue:!0,message:"Set up ari in this repository?"}))return bt.info(w.dim("Skipped. Routing needs the setup, so that step is skipped too.")),{init:!1,pack:null};let o=await gr({initialValue:j$,message:"Default methodology pack for new tasks",options:t.packs.map(({description:s,name:i})=>({hint:s,label:i,value:i}))});return{init:!0,pack:o===j$?null:o}}async function xV(t){return ea({initialValues:ul(t),message:"Which agents do you use in this repository?",options:at.map((e)=>{let n=Ft(t,e),r=n.path===null?"not on PATH":Kl(n),o=n.support==="verified"?"hooks verified":"hooks in part",s=n.kinds.filter((i)=>i!=="hooks").map((i)=>Ye[i]);return{hint:`${r} \xB7 ${[o,...s].join(", ")}`,label:n.label,value:e}}),required:!1})}async function AV(t,e){if(!e.some((r)=>Ft(t,r).userScope.length>0))return"project";let n=e.includes("claude")?"; Claude Code's MCP server stays per repository":"";return gr({initialValue:"project",message:"Where should MCP servers and skills go?",options:[{hint:"commit them so the whole team gets them",label:"This repository",value:"project"},{hint:`every repository on this machine${n}`,label:"Your home directory",value:"user"}]})}async function CV(t,e,n,r){await RV(t);let o=Ur(t,e,n,r).filter((u)=>u.skip===null);for(let u of o.filter((d)=>d.problem!==null))Qo(u.problem?.message??"",u.problem?.hint??"");let s=o.filter((u)=>u.problem===null);if(s.length===0)return bt.info(w.dim("There is nothing to install for these agents.")),t.hookManager===null?[]:[qe];let i=s.map((u)=>u.id),a=new Map(Wo(t,i).map(({id:u,reason:d})=>[u,d])),c=await ea({initialValues:Ob(t,e,n,r),message:"What should ari install?",options:s.map((u)=>({hint:a.get(u.id)??PV(u),label:NV(t,u),value:u.id})),required:!1}),l=await IV(t,{agents:e,init:r,scope:n,targets:c});return t.hookManager===null?l:[...l,qe]}async function RV(t){let e=t.hookManager;if(e===null)return;if(Qo(`${e.name} manages this repository's git hooks, so ari will not write .git/hooks`,"Add these lines to it, or commits and pushes skip ari's checks"),Nt(e.lines.join(`
|
|
240
|
+
`),"Git hook lines",{format:(r)=>r}),!await Ee({initialValue:!0,message:"Continue without git hooks?"}))throw new vt}async function IV(t,e){let n=[...e.targets],r=dl(t,B$({...e,targets:n})).filter((o)=>o.code==="hooks-twice"||o.code==="skill-twice");for(let o of r){if(Qo(o.message,o.fix),o.drop.length===0)continue;let s=o.drop.map((i)=>K$(t,i)).join(" and ");if(await Ee({initialValue:!0,message:`Leave out the ${s}?`}))n=n.filter((i)=>!o.drop.includes(i))}return n}async function OV(t,e,n){let r=_b(t,e);if(!n||r.length<EV)return null;if(t.routing.reviewCommand!==null)return bt.info(w.dim("Routing skipped: review.command runs the review gate, so ari leaves review.agent alone.")),null;if(Nt(r.map((u)=>_V(t,u)).join(`
|
|
241
|
+
`),"Agents for 'ari run' and 'ari review'",{format:(u)=>u}),!await Ee({initialValue:!1,message:"Run tasks and reviews on different agents or models?"}))return null;let s=await F$("Which agent implements tasks?",r,t.routing.task?.agent??null),i=await G$(`Model for ${s} on tasks`,H$(t.routing.task,s)),a=r.find((u)=>u.name!==s)?.name??null,c=await F$("Which agent reviews changes?",r,t.routing.review?.agent??a),l=await G$(`Model for ${c} on reviews`,H$(t.routing.review,c));return{review:{agent:c,model:l},task:{agent:s,model:i}}}async function F$(t,e,n){let r=e.some((o)=>o.name===n)?n:e[0]?.name;return gr({initialValue:r??void 0,message:t,options:e.map((o)=>({hint:o.configured?`configured, ${o.roles.join(" and ")}`:"preset",label:o.name,value:o.name}))})}async function G$(t,e){let r=(await Tu({initialValue:e??"",message:t,placeholder:$V})??"").trim();return r.length===0?null:r}function H$(t,e){return t!==null&&t.agent===e?t.model:null}function _V(t,e){let n=t.agents.find((i)=>i.agent===e.name),r=n===void 0?"":n.path===null?w.dim(" not on PATH"):w.dim(` ${Kl(n)}`),o=e.configured?`configured: ${e.roles.join(", ")}`:"preset, not configured yet",s=e.model===null?"":w.dim(` model ${e.model}`);return Le(`${e.name.padEnd(10)}${o}${s}${r}`)}function PV(t){if(t.file===null)return;return t.kind==="skill"?`${t.file} \xB7 ${ot.length} skills`:t.file}function NV(t,e){return`${K$(t,e.id)}${DV(e)}`}function K$(t,e){if(e===qe)return"Git hooks";if(e===sr)return"AGENTS.md block";let[n,r]=e.split(":"),o=at.find((a)=>a===r),s=or.find((a)=>a===n);return`${o===void 0?r??"":Ft(t,o).label} ${s===void 0?n??"":Ye[s]}`}function DV(t){if(t.elsewhere!==null&&t.status==="missing")return w.dim(` (${t.elsewhere} scope)`);if(t.status==="current")return w.green(" \u2713");return t.status==="outdated"?w.yellow(" \u2191"):""}function B$(t){return{...t,pack:null,recommended:!1,routing:null}}function LV(t,e,n){for(let r of dl(t,B$(e)))if(n.includes(r.code))Qo(r.message,r.fix)}function Qo(t,e){bt.warn(Jr(t,e))}var MV=1,$i=new Set(["created","updated"]),qr={format:(t)=>t},jV=j({agent:{description:`Agents to set up, comma-separated: ${at.join(", ")}`,type:"string"},check:{description:"Write nothing and exit 1 unless the plan is up to date and every check passes (for CI)",type:"boolean"},dryRun:{alias:"d",description:"Show the plan and write nothing",type:"boolean"},gitHooks:{description:"Install the pre-commit and pre-push git hooks",type:"boolean"},hooks:{description:"Install each agent's hooks",type:"boolean"},init:{description:"Create .ari/config.json and the AGENTS.md block when they are missing",type:"boolean"},mcp:{description:"Register ari's MCP server with each agent",type:"boolean"},pack:{description:"Default methodology pack when setting up (implies --init)",type:"string"},reviewAgent:{description:"Agent for the review gate and 'ari review' (with --task-agent)",type:"string"},reviewModel:{description:"Model for the review agent (default: the agent CLI's own)",type:"string"},scope:{description:"Where MCP servers and skills go: project or user (default: project)",type:"string"},skills:{description:"Install ari's skills for each agent",type:"boolean"},taskAgent:{description:"Agent that 'ari run' gives tasks to (with --review-agent)",type:"string"},taskModel:{description:"Model for the task agent (default: the agent CLI's own)",type:"string"},yes:{alias:"y",description:"Accept the recommended defaults: found agents, every supported target, no questions",type:"boolean"}}),J$=E({args:jV,description:"Set up ari here: configuration, hooks, MCP server, skills, git hooks and agent routing, in one guided step",examples:["ari install","ari install --yes","ari install --init --agent claude,codex --yes --dry-run","ari install --init --agent claude,codex --yes --check","ari install --agent claude,codex --hooks --mcp --skills --task-agent claude --review-agent codex --review-model gpt-5.5"],json:!0,name:"install",prompts:!0,run:async(t)=>FV(t)});async function FV(t){let e=await _(),n=i$(t.args),r=t.args.yes===!0,o=t.args.check===!0,s=t.args.dryRun===!0||o,i=t.interactive,a=i&&!r,c=t.cli.version??"";if(i)fr(`${w.bold("ari install")} ${w.dim(`Ariadne ${c}`)}`);let l=i?await q$("Looking at this repository",()=>yi(e)):await yi(e);if(i)Nt(I$(l,c),"This repository",qr);if(a&&!a$(n)){let S=await KV(l,e);if(S!==null)return Bl(t,l,S,{check:o,dryRun:s,upToDate:!0,visual:i})}let u=await W$(i,()=>a?U$(l,n):Wg(l,n,r)),d=Tg(l,u),p=await Fl(e,d,"preview");if(i)JV(l,d,p.rows,!a);let g=p.rows.some((S)=>$i.has(S.action));if(p.failed||s){let S=p.rows.map(s?HV:UV),I=o&&!p.failed?await GV(i,l,p.rows,t.args):[],C=o&&!p.failed&&!g;return Bl(t,l,{checks:I,plan:d,rows:S},{check:o,dryRun:s,upToDate:C,visual:i})}if(!g){let S=await Vl(i,e,p.rows);return Bl(t,l,{checks:S,plan:d,rows:p.rows},{check:o,dryRun:s,upToDate:!0,visual:i})}if(a)await W$(i,()=>qV());let f=await Ir(e,()=>Fl(e,d,"apply",i?YV(l):{})),y=f.failed?[]:await Vl(i,e,f.rows);return Bl(t,l,{checks:y,plan:d,rows:f.rows},{check:o,dryRun:s,upToDate:!1,visual:i})}async function GV(t,e,n,r){let o=await Vl(t,e.root,n.filter((i)=>i.action==="unchanged")),s=M$(e,n,r);if(s===null)return o;if(t)bt.error(Jr(`${s.name}: ${s.detail}`,s.hint??""));return[s,...o]}function HV(t){return $i.has(t.action)?{...t,undo:null}:t}function UV(t){return $i.has(t.action)?{...t,action:"pending",undo:null}:t}async function KV(t,e){if(!t.initialised)return null;let n=BV(t);if(n===null||n.agents.length===0)return null;let r=Tg(t,n),o=await Fl(e,r,"preview");if(o.failed||o.rows.some((s)=>$i.has(s.action)))return null;return{checks:await Vl(!0,e,o.rows),plan:r,rows:o.rows}}function BV(t){try{return Wg(t,VV(),!0)}catch{return null}}function VV(){return{agents:void 0,init:void 0,kinds:void 0,pack:void 0,routing:void 0,scope:void 0}}async function Bl(t,e,n,r){let o=n.rows.some((i)=>i.action==="failed")||n.checks.some((i)=>!i.ok)||r.check&&!r.upToDate,s={check:r.check,checks:n.checks,dryRun:r.dryRun,next:T$,ok:!o,resume:r.dryRun||o?[]:await S$(e.root),root:e.root,routing:n.plan.routing,targets:n.rows,upToDate:r.upToDate,warnings:n.plan.warnings.map(({code:i,fix:a,message:c})=>({code:i,fix:a,message:c}))};if(r.visual)WV(e,s);return t.output.result(s,r.visual?void 0:N$),o?MV:0}function WV(t,e){let n=e.targets.find((r)=>r.action==="failed");if(n!==void 0){bt.error(Jr(`${ar(t,n)}: ${n.reason??""}`,n.hint??"")),ce(e.targets.some((r)=>$i.has(r.action))&&!e.dryRun?"Stopped; run 'ari install' again to finish":"Nothing was written");return}if(e.check){ce(e.ok?"Up to date: nothing would change and every check passed":"Not up to date, or a check failed");return}if(e.dryRun){ce("Dry run: nothing was written");return}if(e.upToDate){Nt(Qg(e),"Everything is up to date",qr),V$(e),ce(w.dim("To add an agent: ari install --agent <name>"));return}Nt(Qg(e),e.ok?"Done":"Done, with problems",qr),V$(e),ce(e.ok?"ari is ready":"Fix the failed checks, then run 'ari install' again")}function V$(t){let e=tm(t);if(e.length>0)Nt(e.join(`
|
|
242
|
+
`),"To undo",qr);let n=em(t);if(n.length>0)Nt(n.join(`
|
|
243
|
+
`),"To get back to your tasks",qr)}function JV(t,e,n,r){if(r)for(let o of e.warnings)bt.warn(Jr(o.message,o.fix));Nt(O$(n,t,e.routing),"Plan",qr)}async function qV(){if(await Ee({initialValue:!0,message:"Write these changes?"}))return;throw new vt}async function W$(t,e){try{return await e()}catch(n){if(t&&n instanceof vt)ys("Cancelled, nothing changed");throw n}}async function Vl(t,e,n){if(!t)return yg(e,n);let r=await q$("Checking the installation",()=>yg(e,n));if(r.length===0)return r;let o=r.filter((s)=>!s.ok);Nt(P$(r),o.length===0?"Self-check passed":"Self-check found problems",qr);for(let s of o)bt.error(Jr(`${s.name}: ${s.detail}`,s.hint??""));return r}function YV(t){let e=na();return{done:(n,r)=>e.stop(_$(t,r)),failed:(n,r)=>e.error(`${ar(t,r)} failed${n.file===null?"":` (${n.file})`}`),start:(n)=>e.start(`Writing ${n.file??ar(t,{agent:n.agent,file:n.file,kind:n.kind})}`)}}async function q$(t,e){let n=na();n.start(t);try{let r=await e();return n.clear(),r}catch(r){throw n.error(t),r}}var ts=st({id:{description:"Task id",required:!0}}),Y$=E({description:"Validate a draft contract and mark it ready",examples:["ari ready add-profile-inheritance"],json:!0,name:"ready",positionals:ts,run:async(t)=>{let e=await Cl(await _(),t.positionals.id);t.output.result(e,({id:n})=>`Task "${n}" is ready; run 'ari start ${n}'`)}}),X$=E({description:"Start a ready task in this worktree, or adopt one that no worktree holds",examples:["ari start add-profile-inheritance"],json:!0,name:"start",positionals:ts,run:async(t)=>{let e=await Rl(await _(),t.positionals.id);t.output.result(e,({id:n,instruction:r,stage:o})=>`Task "${n}" is active at stage ${o}
|
|
216
244
|
${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
|
-
|
|
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
|
-
`,
|
|
221
|
-
`)
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
`)}
|
|
225
|
-
`)
|
|
226
|
-
`)
|
|
227
|
-
`)}function
|
|
228
|
-
`)
|
|
229
|
-
`)}
|
|
230
|
-
`)}function
|
|
245
|
+
Then: ari check, ari done`)}}),z$=E({args:j({onto:{description:"Move the base to the merge base of HEAD and this ref",type:"string"},reason:{description:"Why the contract or locked files changed",type:"string"}}),description:"Accept a changed contract: re-freeze its hashes and withdraw the stage's approvals",examples:['ari amend add-profile-inheritance --reason "Widen scope to the loader"'],json:!0,name:"amend",positionals:ts,run:async(t)=>{let e=ln(t.args.reason,"--reason",`ari amend ${t.positionals.id} --reason <text>`),n=await NE(await _(),t.positionals.id,e,{onto:t.args.onto}),r={base:n.record.base,id:n.contract.id,reason:e,status:n.record.status};t.output.result(r,({id:o})=>`Task "${o}" amended`)}}),Z$=E({args:j({reason:{description:"The question for a human",type:"string"}}),description:"Block the active task with a question for a human",examples:['ari block add-profile-inheritance --reason "Should child profiles inherit secrets?"'],json:!0,name:"block",positionals:ts,run:async(t)=>{let e=ln(t.args.reason,"--reason",`ari block ${t.positionals.id} --reason <question>`),n=await Il(await _(),t.positionals.id,e);t.output.result(n,({id:r})=>`Task "${r}" is blocked; a human answers with 'ari resolve ${r} --answer <text>'`)}}),Q$=E({args:j({answer:{description:"The answer to the task's question",type:"string"}}),description:"Answer a blocked task's question, record it as a decision and resume the task",examples:['ari resolve add-profile-inheritance --answer "No; secrets stay per profile"'],json:!0,name:"resolve",positionals:ts,run:async(t)=>{let e=ln(t.args.answer,"--answer",`ari resolve ${t.positionals.id} --answer <text>`),n=await LE(await _(),t.positionals.id,e),{contract:r,record:o}=n.task,s={id:r.id,knowledgeId:n.knowledgeId,status:o.status};t.output.result(s,({id:i,knowledgeId:a})=>`Task "${i}" is active again; decision ${a} recorded`)}}),tT=E({description:"Record a human approval for the task's current stage (as git user.name)",examples:["ari approve add-profile-inheritance"],json:!0,name:"approve",positionals:ts,run:async(t)=>{let e=await _(),n=await Oy(e);if(n===null)throw new m("git user.name is not set",`Run 'git config user.name "<your name>"'`);let r=await ME(e,t.positionals.id,n),o=r.record.approvals.at(-1),s=await Fo(e,r.contract.id,"approve");if(s.warning!==null)process.stderr.write(`${s.warning}
|
|
246
|
+
`);let i={by:n,id:r.contract.id,stage:o?.stage??null,...s.id===null?{}:{snapshot:s.id}};t.output.result(i,({id:a,snapshot:c,stage:l})=>{let u=`Approved stage ${l??"unknown"} of "${a}" as ${n}`;return c===void 0?u:`${u}
|
|
247
|
+
Snapshot ${c} saved`})}});import{stripVTControlCharacters as XV}from"util";var eT=1,zV=2,ZV=4,nT="Error",QV="Call the tool with the arguments its inputSchema describes";function rT(t){if(t instanceof b){let r=`Invalid arguments: ${t.message}`;return{error:{_tag:"UsageError",causes:[],exitCode:zV,hint:QV,message:r}}}if(!(t instanceof Error))return{error:{_tag:nT,causes:[],exitCode:eT,message:Wl(String(t))}};let e=t instanceof m,n=e&&typeof t.hint==="string"?{hint:Wl(t.hint)}:{};return{error:{_tag:e?t._tag:t.name||nT,causes:tW(t),exitCode:e?t.exitCode:eT,message:Wl(t.message),...n}}}function tW(t){let e=[],n=new Set([t]),r=t.cause;while(r!==void 0&&!n.has(r)&&e.length<ZV)n.add(r),e.push(Wl(r instanceof Error?r.message:String(r))),r=r instanceof Error?r.cause:void 0;return e}function Wl(t){return XV(t)}var uT=["2026-07-28"],Yl=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],Zl="2.0",eW=-32700,Xl=-32600,nW=-32601,es=-32602,rW=-32603,oW=-32022,zl="_meta",ql="io.modelcontextprotocol/protocolVersion",oT="io.modelcontextprotocol/clientCapabilities",sW="io.modelcontextprotocol/serverInfo",iW="complete",sT=3600000,iT="public",aW="2025-06-18",aT={tools:{listChanged:!1}},dT=[...uT,...Yl];function pT(t){let e={legacy:null},n=(c)=>{let l=cW(c);if("error"in l)return ye(l.error);let u=l.value,d=!("method"in u)&&(("result"in u)||("error"in u));if(!("id"in u)||d)return ye(null);let p=lW(u);if("error"in p)return ye(p.error);let{id:g,method:f,params:y}=p.value,S=!uW(y);if(S&&f==="initialize")return ye(r(g,y));if(S&&f==="ping")return ye(Jl(g,{}));let I=dW(g,y,e.legacy);if("error"in I)return ye(I.error);switch(f){case"server/discover":return I.value.kind==="modern"?ye(a(g,I.value,o())):ye(lT(g,f));case"tools/list":return ye(a(g,I.value,s(I.value)));case"tools/call":return i(g,I.value,y);default:return ye(lT(g,f))}},r=(c,l)=>{let u=l.protocolVersion,d=typeof u==="string"&&Yl.includes(u)?u:Yl[0]??"";e.legacy=d;let{info:p,instructions:g}=t;return Jl(c,{capabilities:aT,instructions:g,protocolVersion:d,serverInfo:p})},o=()=>({cacheScope:iT,capabilities:aT,instructions:t.instructions,supportedVersions:dT,ttlMs:sT}),s=(c)=>{let l=t.tools.map(({annotations:u,description:d,inputSchema:p,name:g,title:f})=>({annotations:u,description:d,inputSchema:p,name:g,title:f}));return c.kind==="modern"?{cacheScope:iT,tools:l,ttlMs:sT}:{tools:l}},i=(c,l,u)=>{let{arguments:d={},name:p}=u;if(typeof p!=="string")return ye(ke(c,es,"tools/call needs a tool name"));let g=t.tools.find((y)=>y.name===p);if(g===void 0)return ye(ke(c,es,`Unknown tool: ${p}`));if(!z(d))return ye(ke(c,es,"tools/call arguments must be an object"));let f=async()=>{try{let y=await g.call(await t.root(),d);return a(c,l,cT(l,y.data,y.failed))}catch(y){return a(c,l,cT(l,rT(y),!0))}};return{kind:"queued",run:()=>f().catch((y)=>gW(c,y))}},a=(c,l,u)=>{if(l.kind==="legacy")return Jl(c,u);let d={[sW]:t.info};return Jl(c,{...u,[zl]:d,resultType:iW})};return{receive:n}}function ye(t){return{kind:"now",message:t}}function cT(t,e,n){let r=[{text:JSON.stringify(e,null,2),type:"text"}],o=t.kind==="modern"||t.version>=aW;return{content:r,isError:n,...o?{structuredContent:e}:{}}}function cW(t){let e;try{e=JSON.parse(t)}catch{return{error:ke(null,eW,"Parse error: each line must hold one JSON-RPC message")}}if(Array.isArray(e))return{error:ke(null,Xl,"JSON-RPC batches are not supported")};if(!z(e))return{error:ke(null,Xl,"A JSON-RPC message must be an object")};return{value:e}}function lW(t){let{id:e,jsonrpc:n,method:r,params:o={}}=t;if(!(typeof e==="string"||typeof e==="number"&&Number.isInteger(e)))return{error:ke(null,Xl,"A request id must be a string or an integer")};if(n!==Zl||typeof r!=="string")return{error:ke(e,Xl,'A request needs "jsonrpc": "2.0" and a method name')};if(!z(o))return{error:ke(e,es,"params must be an object")};return{value:{id:e,method:r,params:o}}}function uW(t){return z(t[zl])&&ql in t[zl]}function dW(t,e,n){let r=e[zl];if(z(r)&&ql in r){let s=r[ql];if(typeof s!=="string"||!uT.includes(s))return{error:pW(t,s)};if(!z(r[oT]))return{error:ke(t,es,`_meta needs "${oT}"`)};return{value:{kind:"modern",version:s}}}if(n!==null)return{value:{kind:"legacy",version:n}};let o=`Missing _meta "${ql}"; clients of protocol ${Yl[0]} and earlier send initialize first`;return{error:ke(t,es,o)}}function pW(t,e){return{error:{code:oW,data:{requested:e,supported:dT},message:"Unsupported protocol version"},id:t,jsonrpc:Zl}}function lT(t,e){return ke(t,nW,`Method not found: ${e}`)}function gW(t,e){return ke(t,rW,`Internal error: ${e instanceof Error?e.message:String(e)}`)}function Jl(t,e){return{id:t,jsonrpc:Zl,result:e}}function ke(t,e,n){return{error:{code:e,message:n},id:t,jsonrpc:Zl}}var cr="arguments",Yr={destructiveHint:!1,readOnlyHint:!0},Ti={destructiveHint:!1,readOnlyHint:!1},mW={destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1},gT={readOnlyHint:!1},$T={description:"Task id",type:"string"},rm={items:{type:"string"},type:"array"};function Yt(t){let{properties:e,required:n=[],...r}=t,o={additionalProperties:!1,properties:e,...n.length===0?{}:{required:[...n]},type:"object"};return{...r,inputSchema:o}}function we(t){return{data:t,failed:!1}}function Xt(t,e){return T(t,cr,Object.keys(e))}function ae(t,e){return nt(t,`${cr}.${e}`)}function mT(t,e){return t===void 0?void 0:L(t,`${cr}.${e}`,x)}var ns={},rs={id:$T},fT={status:{...rm,description:"Only tasks with these statuses",items:{enum:Kr}}},hT={pack:{description:"Methodology pack (defaults to config.pack)",type:"string"},scope:{...rm,description:"Globs of the files the task may change"},title:{description:"Task title",type:"string"}},yT={global:{description:"Write a project knowledge entry instead of a task note",type:"boolean"},kind:{description:"Knowledge entry kind, with global",enum:le},scope:{...rm,description:"Globs the knowledge entry applies to, with global"},text:{description:"The note",type:"string"}},kT={budget:{description:"Token budget (default: context.budget)",minimum:1,type:"integer"},id:{description:"Task id (default: the active task)",type:"string"}},wT={reason:{description:"Why the snapshot is taken, for example 'design ready'",type:"string"},task:{description:"Task id (default: the active task)",type:"string"}},ST={task:{description:"Only the entries of this task",type:"string"}},vT={id:{description:"Snapshot id, as ari_snapshot_list shows it",type:"string"}},bT={id:$T,reason:{description:"The question for a human",type:"string"}},ET={all:{description:"Include archived entries",type:"boolean"},query:{description:"Words to search for",type:"string"}},TT=[Yt({annotations:Yr,call:async(t,e)=>(Xt(e,ns),we(await $l(t))),description:"Start here: the one next action for this repository's Ariadne tasks. Loop: ari_next, change only files in the task's scope, ari_check, then ari_done until it passes.",name:"ari_next",properties:ns,title:"Next action"}),Yt({annotations:Yr,call:async(t,e)=>{let n=Xt(e,fT),r=D(n.status,[],(o)=>L(o,`${cr}.status`,(s,i)=>K(Kr,s,i)));return we(await Tl(t,r))},description:"List tasks (id, title, pack, status) and contracts or records that cannot be read.",name:"ari_list",properties:fT,title:"List tasks"}),Yt({annotations:Yr,call:async(t,e)=>we(await xl(t,ae(Xt(e,rs).id,"id"))),description:"Show a task's contract, record, current stage and stage instruction.",name:"ari_show",properties:rs,required:["id"],title:"Show task"}),Yt({annotations:Ti,call:async(t,e)=>{let n=Xt(e,hT),r=n.pack===void 0?void 0:ae(n.pack,"pack"),o=mT(n.scope,"scope")??[];return we(await Al(t,{pack:r,scope:o,title:ae(n.title,"title")}))},description:"Create a draft task contract from a title. Then edit .ari/tasks/<id>.md (scope, criteria bound to checks) and call ari_ready.",name:"ari_new",properties:hT,required:["title"],title:"New task"}),Yt({annotations:Ti,call:async(t,e)=>we(await Cl(t,ae(Xt(e,rs).id,"id"))),description:"Validate a draft contract, its pack and its dependencies, and mark it ready.",name:"ari_ready",properties:rs,required:["id"],title:"Ready task"}),Yt({annotations:Ti,call:async(t,e)=>we(await Rl(t,ae(Xt(e,rs).id,"id"))),description:"Start a ready task in this worktree (needs no uncommitted changes outside .ari/), or adopt an active task no worktree holds.",name:"ari_start",properties:rs,required:["id"],title:"Start task"}),Yt({annotations:gT,call:async(t,e)=>(Xt(e,ns),Ol(t)),description:"Evaluate the active task's current stage gates without recording an attempt. isError is true while a gate fails.",name:"ari_check",properties:ns,title:"Check stage"}),Yt({annotations:gT,call:async(t,e)=>(Xt(e,ns),_l(t)),description:"Finish the current stage: run its gates, record the evidence and advance. isError is true when a gate fails; a failure uses an attempt, so run ari_check first.",name:"ari_done",properties:ns,title:"Finish stage"}),Yt({annotations:Ti,call:async(t,e)=>{let n=Xt(e,yT),r=D(n.global,!1,(i)=>$t(i,`${cr}.global`)),o=n.kind===void 0?void 0:K(le,n.kind,`${cr}.kind`),s=mT(n.scope,"scope");return we(await Pl(t,{global:r,kind:o,scope:s,text:ae(n.text,"text")}))},description:"Record a learning: a note on the active task, or with global a project knowledge entry (kind fact, decision, constraint, pattern or gotcha).",name:"ari_note",properties:yT,required:["text"],title:"Add note"}),Yt({annotations:Yr,call:async(t,e)=>{let n=Xt(e,kT),r=n.id===void 0?void 0:ae(n.id,"id"),o=n.budget===void 0?void 0:Kt(n.budget,`${cr}.budget`);return we(await Nl(t,{budget:o,id:r}))},description:"The task's context pack: contract, last failure, constraints, notes and knowledge within a budget.",name:"ari_context",properties:kT,title:"Task context"}),Yt({annotations:Ti,call:async(t,e)=>{let n=Xt(e,bT);return we(await Il(t,ae(n.id,"id"),ae(n.reason,"reason")))},description:"Block the active task with a question for a human when the contract is wrong or you are stuck. Only a human answers it.",name:"ari_block",properties:bT,required:["id","reason"],title:"Block task"}),Yt({annotations:Yr,call:async(t,e)=>{let n=Xt(e,ET),r=D(n.all,!1,(o)=>$t(o,`${cr}.all`));return we(Dl(t,ae(n.query,"query"),r))},description:"Search the project's knowledge entries, ranked with BM25.",name:"ari_knowledge_search",properties:ET,required:["query"],title:"Search knowledge"}),Yt({annotations:mW,call:async(t,e)=>{let n=Xt(e,wT),r=n.task===void 0?void 0:ae(n.task,"task"),o=n.reason===void 0?void 0:ae(n.reason,"reason");return we(await Ll(t,{reason:o,task:r}))},description:"Save the plan (contract, stage, design files, notes) and the context pack of a task before a risky change or when a design is ready. Writes nothing when nothing changed since the last snapshot. Restoring one is for humans only.",name:"ari_snapshot",properties:wT,title:"Save snapshot"}),Yt({annotations:Yr,call:async(t,e)=>{let n=Xt(e,ST),r=n.task===void 0?void 0:ae(n.task,"task");return we(await Ml(t,r))},description:"List the saved snapshots and restores, oldest first, optionally of one task.",name:"ari_snapshot_list",properties:ST,title:"List snapshots"}),Yt({annotations:Yr,call:async(t,e)=>we(await jl(t,ae(Xt(e,vT).id,"id"))),description:"Show a snapshot: its plan summary, design files and the context pack it saved. Use it after a reset or compaction to get back what you knew.",name:"ari_snapshot_show",properties:vT,required:["id"],title:"Show snapshot"})];var xT=`
|
|
248
|
+
`,fW=/\r$/,hW={name:"ari",title:"Ariadne",version:ya},yW=["Ariadne tracks this repository's work as tasks with contracts and gates that it evaluates itself.","Loop: call ari_next and follow its action, change only files inside the active task's scope, call ari_check, then ari_done until it passes.","Save the plan with ari_snapshot before a risky change and read it back with ari_snapshot_show after a reset.","Ask a human with ari_block when stuck. Approving a stage, amending a contract, answering a blocked task and restoring a snapshot are for humans only (ari approve, ari amend, ari resolve, ari snapshot restore)."].join(" ");function kW(t){return pT({info:hW,instructions:yW,root:()=>Jn(t),tools:TT})}async function CT(t){let e=kW(t.cwd),n=(a)=>{if(a!==null)t.write(`${JSON.stringify(a)}${xT}`)},r=Promise.resolve(),o=(a)=>{if(a.kind==="now")n(a.message);else r=r.then(async()=>n(await a.run()))},s=new TextDecoder,i="";for await(let a of t.input){i+=s.decode(a,{stream:!0});let c=i.split(xT);i=c.pop()??"";for(let l of c)AT(e,l,o)}AT(e,i+s.decode(),o),await r}function AT(t,e,n){let r=e.replace(fW,"");if(r.trim().length>0)n(t.receive(r))}function RT(t,e){let{agents:n,example:r,group:o,noun:s}=t,i=(c,l)=>{let u=`ari ${o} ${c} --agent`;return E({args:j({agent:{description:`Agent: ${n.join(", ")}`,type:"string"},scope:{description:`Where to write: ${Mn.join(" or ")} (default: project)`,type:"string"}}),description:e[c],examples:[`${u} ${r.project}`,`${u} ${r.user} --scope user`],json:!0,name:c,run:async(d)=>{let p=t.target(ln(d.args.agent,"--agent",`${u} <name>`)),g=await xt(rr(d.args.scope),process.cwd()),f=l(p,g);d.output.result(f,(y)=>`${y.agent} ${s} ${y.action} in ${y.file} (${y.scope} scope)`)}})},a=E({description:e.list,examples:[`ari ${o} list --json`],json:!0,name:"list",run:async(c)=>{let l=process.cwd(),u=t.summaries(await xt("project",l),await xt("user",l));c.output.result({agents:u},({agents:d})=>d.map(wW).join(`
|
|
249
|
+
`))}});return[i("install",t.install),i("uninstall",t.uninstall),a]}function wW(t){let e=t.files.map((n)=>`${n.scope} ${n.installed?"installed":"not installed"} ${n.file}`);return`${t.agent} ${e.join("; ")}`}var SW=`ari mcp serve speaks the Model Context Protocol on stdin and stdout; an agent starts it. Press Ctrl-D to stop.
|
|
250
|
+
`,vW=E({description:"Serve the task loop to an agent as a stdio MCP server",examples:["ari mcp serve"],name:"serve",run:async()=>{if(process.stdin.isTTY)process.stderr.write(SW);await CT({cwd:process.cwd(),input:Bun.stdin.stream(),write:(t)=>{process.stdout.write(t)}})}}),bW=RT({agents:se.map((t)=>t.agent),example:{project:"claude",user:"codex"},group:"mcp",install:Ko,noun:'MCP server "ari"',summaries:Zv,target:me,uninstall:Qc},{install:"Register 'ari mcp serve' in an agent's MCP configuration",list:"List the agents ari can register its MCP server with, and where it is registered",uninstall:"Remove ari's MCP server from an agent's configuration, and nothing else"}),IT=E({description:"Serve ari's task tools to agents over MCP, and register the server with them",name:"mcp",subcommands:[vW,...bW]});var OT=1;async function _T(t,e){let n=M(t),r=Cr(n,{...e,role:"review",route:$W(n)}),o=e.task??await TW(t),s=await jn(t,o),i=s.stage??s.task.record.status,{contractText:a}=it(t,o,n),c=EW(n,e),l={config:n,contractText:a,root:t,stage:i,task:s.task,...c===null?{}:{argus:c}},{evidence:u,...d}=await yp(l,r);return{...d,stage:i,task:o}}function EW(t,e){if(e.argus===!1&&e.argusVerdicts===!0)throw new v("--argus-verdicts needs argus evidence, and --no-argus leaves it out","Pass only one of them");if(e.argus===!1)return null;let n=t.review.argus,r=e.argusVerdicts===!0&&e.argus!==!0?"--argus-verdicts":"--argus";if(n===void 0&&e.argus!==!0&&e.argusVerdicts!==!0)return null;if(n===void 0)throw new m(`${r} needs review.argus in .ari/config.json`,`Add "review": { "argus": { "config": "<path of the argus config>" } } to .ari/config.json, or leave out ${r}`,OT,{tag:"ArgusNotConfigured"});let{verdicts:o,...s}=n;return{argus:e.argusVerdicts??o===!0?{...s,verdicts:!0}:s,explicit:e.argus===!0,verdictsExplicit:e.argusVerdicts===!0,...e.notify?{notify:e.notify}:{}}}function $W(t){if(t.routing.review!==null)return t.routing.review;let{agent:e,model:n}=t.review;return e===void 0?null:{agent:e,model:n??null}}async function TW(t){let e=gt(await P(t));if(e!==null)return e.task;throw new m("No task is active in this worktree","Pass --task <id>, or run 'ari next' to see what to do",OT,{tag:"NoActiveTask"})}var xW=1,PT=E({args:j({agent:{description:"Review agent from config.agents (default: routing.review, then review.agent)",type:"string"},argus:{description:"Add (--argus, fails when argus cannot answer) or leave out (--no-argus) argus candidates; see review.argus",type:"boolean"},argusVerdicts:{description:"Send the review agent's answers about argus candidates back to argus (--argus-verdicts, fails when argus cannot answer) or not (--no-argus-verdicts); see review.argus.verdicts",type:"boolean"},model:{description:"Model for the review agent",type:"string"},task:{description:"Task id (default: the active task)",type:"string"}}),description:"Have a review agent judge a task's change in a temporary copy; any doubt fails the review",examples:["ari review","ari review --agent codex --model gpt-5.5 --json","ari review --argus","ari review --argus-verdicts"],json:!0,name:"review",run:async(t)=>{let e=await _T(await _(),{agent:Re(t.args.agent,"--agent"),argus:t.args.argus,argusVerdicts:t.args.argusVerdicts,model:Re(t.args.model,"--model"),notify:(n)=>bt.info(n),task:Re(t.args.task,"--task")});return t.output.result(e,AW),e.ok?void 0:xW}});function AW(t){let e=t.model===null?"":` (${t.model})`,n=`Review of "${t.task}" by ${t.agent}${e}: ${t.ok?"pass":"FAIL"}`,r=t.findings.map((i)=>` - ${Ec(i)}`),o=t.problems.map((i)=>` ! ${i}`),s=(t.argus===void 0?[]:Sc(t.argus)).map((i)=>` ~ ${i}`);return[n,...o,...s,...r].join(`
|
|
251
|
+
`)}var CW=1,NT=E({args:j({agent:{description:"Agent name from config.agents (default: the routing for each stage)",type:"string"},model:{description:"Model for the agent, overriding its model and the routing's",type:"string"},task:{description:"Task id (defaults to the active task, then the next startable one)",type:"string"}}),description:"Drive a task headlessly with an agent until it is done, blocked or out of attempts",examples:["ari run --agent claude","ari run --agent codex --model gpt-5.5 --task add-profile-inheritance --json","ari run --json"],json:!0,name:"run",run:async(t)=>{let e=await VE(await _(),{agent:Re(t.args.agent,"--agent"),model:Re(t.args.model,"--model"),output:t.json?"stderr":"inherit",task:t.args.task});return t.output.result(e,RW),e.outcome==="done"?void 0:CW}});function RW(t){return[...t.turns.map((n,r)=>`turn ${r+1}: stage ${n.stage}, ${n.agent}${n.model===null?"":` (${n.model})`} ${n.timedOut?"timed out":`exit ${n.agentExitCode}`}, ${n.outcome}${n.failing.length===0?"":` (${n.failing.join(", ")})`}`),`Task "${t.task}" is ${t.outcome}`].join(`
|
|
252
|
+
`)}var IW=1,OW=ot.map((t)=>t.name),_W=fe.map((t)=>t.agent),PW=j({agent:{description:`Agent: ${_W.join(", ")}`,type:"string"},scope:{description:`Where to write: ${Mn.join(" or ")} (default: project)`,type:"string"},skill:{description:`Skills, comma-separated (default: all): ${OW.join(", ")}`,type:"string"}}),NW={install:"Write ari's skills into an agent's skills directory, one directory for each skill",uninstall:"Remove the skills that ari installed, and nothing else"};function DT(t){let e=`ari skills ${t} --agent`;return E({args:PW,description:NW[t],examples:[`${e} claude`,`${e} codex --scope user`,`${e} claude --skill ariadne-design,ariadne-memory`],json:!0,name:t,run:async(n)=>{let r=Jt(ln(n.args.agent,"--agent",`${e} <name>`)),o=await xt(rr(n.args.scope),process.cwd()),s=lb(We(n.args.skill)),i=t==="install"?Bo(r,o,s):nl(r,o,s);return n.output.result(i,(a)=>LW(a,r.agent)),i.some((a)=>a.action==="refused")?IW:void 0}})}var DW=E({description:"List ari's skills, and for each agent which of them are installed and current",examples:["ari skills list --json"],json:!0,name:"list",run:async(t)=>{let e=process.cwd(),n=xb(await xt("project",e),await xt("user",e)),r=ot.map(({description:o,name:s})=>({description:o,name:s}));t.output.result({skills:r,agents:n},(o)=>MW(o.skills,o.agents))}}),LT=E({description:"Install ari's skills, which teach an agent the task loop, designs, contracts, review and memory",name:"skills",subcommands:[DT("install"),DT("uninstall"),DW]});function LW(t,e){let n=t.map((o)=>o.action==="refused"?`${o.agent} skill "${o.skill}" refused: ${o.reason??""}`:`${o.agent} skill "${o.skill}" ${o.action} in ${o.file} (${o.scope} scope)`),r=t.filter((o)=>o.action==="refused").length;return r===0?n.join(`
|
|
253
|
+
`):[...n,ol(r,e)].join(`
|
|
254
|
+
`)}function MW(t,e){let n=t.map((o)=>`${o.name} ${o.description}`),r=e.flatMap((o)=>Mn.map((s)=>`${o.agent} ${s} ${jW(o.files.filter((i)=>i.scope===s))}`));return[...n,"",...r].join(`
|
|
255
|
+
`)}function jW(t){if(!t.some((s)=>s.installed))return"not installed";let e=t.filter((s)=>s.current).length,n=t.filter((s)=>!s.installed).map((s)=>s.skill),r=t.filter((s)=>s.installed&&!s.current).map((s)=>s.skill);return[`${e} of ${t.length} current`,...n.length===0?[]:[`missing ${n.join(", ")}`],...r.length===0?[]:[`outdated ${r.join(", ")}`]].join("; ")}import{readFileSync as FW}from"fs";import{join as MT}from"path";var GW=()=>new Date().toISOString(),xi="Nothing was changed.",HW="it lies outside .ari/designs/, and a restore writes only designs";async function jT(t,e,n={}){let r=M(t),o=await P(t),s=jo(o,e);if(!Wp(s))throw new m(`Snapshot entry ${e} records a restore, not a saved plan`,"Restore an entry that 'ari snapshot list' shows as a save");let i=qo(s);if(i.length>0)throw new m(`Snapshot ${e} is not intact: ${i.join("; ")}`,`${xi} Restore another snapshot, or delete the entry file`);let{contractText:a,task:c}=it(t,s.task,r);UW(s,c.record.status,Bt(a));let l=Ue(c.contract.pack,Gt(t)),u=new Set(Nc(l,s.task)),d=s.artifacts.filter(({path:A})=>!u.has(A)).map(({path:A})=>A);if(d.length>0)throw new m(`Snapshot ${e} names ${d.join(", ")}, which ${d.length===1?"is":"are"} not an artifact path of pack "${l.name}"`,`${xi} The entry was edited or the pack changed; delete the entry file`);let p=s.artifacts.filter(({path:A})=>Up(A)),g=s.artifacts.filter(({path:A})=>!Up(A)).map(({path:A})=>({path:A,reason:HW})),f=KW(t,p),y=n.dryRun===!0,{estimatedTokens:S,knowledge:I,sha256:C,text:q}=s.context,G=f.write.map(({artifact:A,before:R})=>({before:R?.sha256??null,path:A.path,sha256:A.file.sha256})),N={context:{estimatedTokens:S,knowledge:I,sha256:C,text:q},dryRun:y,ledger:null,notRestored:g,notice:f.write.length===0?null:BW(s.task),snapshot:e,task:s.task,unchanged:f.unchanged,written:G};if(y||f.write.length===0)return N;let H=(n.clock??GW)();return Lc(o,()=>{for(let{artifact:Q}of f.write)Tr(MT(t,Q.path),Dr(Q.file));let A=Ln(o).entries.filter((Q)=>Q.task===s.task),B=A.filter((Q)=>Q.id!==e).slice(0,Math.max(0,A.length+1-r.snapshots.keep)).map((Q)=>Q.id),_t=Mc(o,H,{kind:"restore",pruned:B,restores:e,task:s.task,written:f.write.map(({artifact:Q,before:Xr})=>({before:Xr,path:Q.path,sha256:Q.file.sha256}))});return jc(o,B),{...N,ledger:_t.id}})}function UW(t,e,n){if(e==="done")throw new m(`Task "${t.task}" is done, so its plan is final and snapshot ${t.id} cannot be restored`,`${xi} 'ari snapshot show ${t.id}' prints what the snapshot held`);if(n===t.contract.sha256)return;throw new m(`The contract of "${t.task}" changed since snapshot ${t.id} was taken, so the designs of that plan may no longer fit it`,`${xi} Run 'ari amend ${t.task} --reason <text>' if the change was intended and take a new snapshot, or put the contract back from 'ari snapshot show ${t.id}' first`)}function KW(t,e){let n=[],r={unchanged:[],write:[]};for(let o of e){let s=MT(t,o.path),i=$e(s);if(i?.isSymbolicLink()===!0||Te(t,o.path)){n.push(`${o.path} is a symbolic link or lies behind one`);continue}if(i!==null&&!i.isFile()){n.push(`${o.path} is not a regular file`);continue}let a=i===null?null:Do(FW(s));if(a?.sha256===o.file.sha256)r.unchanged.push(o.path);else r.write.push({artifact:o,before:a})}if(n.length===0)return r;throw new m(`A restore would write through a path that is not an ordinary file: ${n.join("; ")}`,`${xi} Replace it with a regular file or remove it, then restore again`)}function BW(t){return`An approval covers the exact bytes it was given for, so an approval of the previous bytes no longer applies to the restored files; a human runs 'ari approve ${t}' again after reviewing them`}function GT(t){let e=t.warnings.map((o)=>`warning: ${o}`);if(!t.saved)return[`Nothing changed since snapshot ${t.id} of task "${t.task}"; no new snapshot was written`,...e].join(`
|
|
256
|
+
`);let n=t.stage===null?t.status:`stage ${t.stage}`,r=t.pruned.length===0?[]:[`Pruned the oldest: ${t.pruned.join(", ")}`];return[`Saved snapshot ${t.id} of task "${t.task}" (${n}, ${os(t.artifacts.length,"artifact")}, context of about ${t.context.estimatedTokens} tokens)`,...r,...e].join(`
|
|
257
|
+
`)}function HT(t){let e=t.entries.map(VW),n=t.unreadable.map(({id:r,problem:o})=>`${r} unreadable ${o}`);if(e.length===0&&n.length===0)return"No snapshots yet. Run 'ari snapshot' to save one";return[...e,...n].join(`
|
|
258
|
+
`)}function UT({entry:t,integrity:e}){let n=e.ok?[]:[`Integrity: ${e.problems.join("; ")}`];if(t.kind==="restore")return[...FT(t),...WW(t),...n].join(`
|
|
259
|
+
`);let{artifacts:r,context:o,contract:s,notes:i,record:a}=t,c=r.map(({file:l,path:u})=>` ${u} ${l.sha256}`);return[...FT(t),`Reason: ${t.reason??"none"}`,`Pack: ${a.pack}; stage ${a.stageName??"none"} (${a.stage+1}); status ${a.status}`,`Contract: ${s.sha256}`,`Artifacts: ${c.length===0?"none":""}`.trimEnd(),...c,`Notes: ${i.length}`,`Context pack: about ${o.estimatedTokens} tokens of ${o.budget}; knowledge ${o.knowledge.join(", ")||"none"}`,...t.pruned.length===0?[]:[`Pruned: ${t.pruned.join(", ")}`],...n,"",o.text].join(`
|
|
260
|
+
`)}function KT(t){let e=t.dryRun?"Would write":"Wrote",n=t.written.map((i)=>` ${e.toLowerCase()} ${i.path}`),r=t.unchanged.map((i)=>` unchanged ${i}`),o=t.notRestored.map((i)=>` not restored ${i.path}: ${i.reason}`);return[t.dryRun?`Dry run: restoring snapshot ${t.snapshot} would write ${os(t.written.length,"file")}`:`Restored snapshot ${t.snapshot} of task "${t.task}": ${os(t.written.length,"file")} written`,...n,...r,...o,...t.notice===null?[]:[t.notice],...t.ledger===null?[]:[`Logged as ${t.ledger}`],"",t.context.text].join(`
|
|
261
|
+
`)}function VW(t){if(t.kind==="restore")return`${t.id} restore of ${t.restores??"?"} ${t.task} ${os(t.artifacts.length,"file")}`;let e=`${t.stage??"none"} (${t.status??"none"})`,n=t.reason===null?"":` ${t.reason}`;return`${t.id} save ${t.trigger??""} ${t.task} ${e} ${os(t.artifacts.length,"artifact")}${n}`}function FT(t){let e=t.kind==="save"?`save, ${t.trigger}`:`restore of ${t.restores}`;return[`Snapshot ${t.id} (${e}) of task "${t.task}"`,`Taken: ${t.at}`]}function WW(t){let e=t.written.map((n)=>` ${n.path} now ${n.sha256}; before ${n.before?.sha256??"absent"}`);return[`Wrote ${os(e.length,"file")}:`,...e,...t.pruned.length===0?[]:[`Pruned: ${t.pruned.join(", ")}`]]}function os(t,e){return`${t} ${t===1?e:`${e}s`}`}var JW={description:"Task id (default: the active task)",type:"string"},qW=E({args:j({task:{description:"Only the entries of this task",type:"string"}}),description:"List saved snapshots and restores, oldest first",examples:["ari snapshot list","ari snapshot list --task add-profile-inheritance --json"],json:!0,name:"list",run:async(t)=>{t.output.result(await Ml(await _(),t.args.task),HT)}}),YW=E({description:"Print a snapshot's plan summary and the context pack it saved",examples:["ari snapshot show 20261202T101530123Z --json"],json:!0,name:"show",positionals:st({id:{description:"Snapshot id, as 'ari snapshot list' prints it",required:!0}}),run:async(t)=>{t.output.result(await jl(await _(),t.positionals.id),UT)}}),XW=E({args:j({dryRun:{default:!1,description:"Show what would be written and write nothing",type:"boolean"}}),description:"Write a snapshot's design files back byte for byte and print its saved context pack",examples:["ari snapshot restore 20261202T101530123Z --dry-run","ari snapshot restore 20261202T101530123Z"],json:!0,name:"restore",positionals:st({id:{description:"Snapshot id, as 'ari snapshot list' prints it",required:!0}}),run:async(t)=>{let e=await jT(await _(),t.positionals.id,{dryRun:t.args.dryRun});t.output.result(e,KT)}}),BT=E({args:j({reason:{description:"Why the snapshot is taken",type:"string"},task:JW}),description:"Save the plan and context pack of a task, and list, show and restore saved ones",examples:["ari snapshot",'ari snapshot --reason "Before the design review"',"ari snapshot list"],json:!0,name:"snapshot",run:async(t)=>{let e=await Ll(await _(),{reason:Re(t.args.reason,"--reason"),task:t.args.task});t.output.result(e,GT)},subcommands:[qW,YW,XW]});var VT=E({args:j({pack:{description:"Methodology pack (defaults to config.pack)",type:"string"},scope:{description:"Scope globs, comma-separated",type:"string"}}),description:"Create a task contract from a title",examples:['ari new "Add profile inheritance" --pack tdd --scope "src/profiles/**"'],json:!0,name:"new",positionals:st({title:{description:"Task title",required:!0}}),run:async(t)=>{let e=await Al(await _(),{pack:t.args.pack,scope:We(t.args.scope),title:t.positionals.title});t.output.result(e,({contractPath:n,designs:r,id:o})=>[`Created task "${o}" at ${n}`,...(r??[]).map(zW),`Complete its scope, criteria and checks, then run 'ari ready ${o}'`].join(`
|
|
262
|
+
`))}}),WT=E({args:j({status:{description:`Only these statuses, comma-separated (${Kr.join(",")})`,type:"string"}}),description:"List tasks and any unreadable contracts or records",examples:["ari list","ari list --status ready,active --json"],json:!0,name:"list",run:async(t)=>{let e=XE(We(t.args.status));t.output.result(await Tl(await _(),e),ZW)}}),JT=E({description:"Show a task's contract, record and current stage",examples:["ari show add-profile-inheritance --json"],json:!0,name:"show",positionals:st({id:{description:"Task id",required:!0}}),run:async(t)=>{t.output.result(await xl(await _(),t.positionals.id),QW)}});function zW({created:t,path:e}){return t?`Wrote the design template to ${e}`:`Kept the existing design at ${e}`}function ZW(t){if(t.tasks.length===0&&t.invalid.length===0)return'No tasks yet. Run ari new "<title>"';let e=t.tasks.map((r)=>`${r.id} ${r.status} ${r.pack} ${r.title}`),n=t.invalid.map((r)=>`${r.id} unreadable ${r.problem}`);return[...e,...n].join(`
|
|
263
|
+
`)}function QW(t){let{contract:e,record:n}=t.task,r=t.stage===null?[]:[`Stage: ${t.stage}${t.active?" (active here)":""}`],o=t.instruction===null?[]:[`Instruction: ${t.instruction}`],s=n.question===null?[]:[`Question: ${n.question}`];return[`${e.id}: ${e.title}`,`Status: ${n.status} Pack: ${e.pack} Attempts: ${n.attempts}/${e.budget.attempts}`,...r,...o,...s,`Scope: ${e.scope.join(", ")||"none"}`,...e.criteria.map((i)=>`${i.id}: ${i.text} [${i.checks.join(", ")}]`),...e.checks.map((i)=>`check ${i.name} (expect ${i.expect}): ${i.run}`)].join(`
|
|
264
|
+
`)}var tJ=1,eJ=12,YT=E({args:j({revoke:{default:!1,description:"Forget the trust record of this repository",type:"boolean"},yes:{alias:"y",default:!1,description:"Trust the commands without asking",type:"boolean"}}),description:"Show, grant or revoke trust in the commands that .ari makes ari run",examples:["ari trust","ari trust --yes","ari trust --revoke","ari trust --json"],json:!0,name:"trust",run:async(t)=>{if(t.args.revoke&&t.args.yes)throw new v("--revoke and --yes conflict","Pass only one of them");let e=await _(),n=M(e),r=So();if(t.args.revoke){let c=sk(e),l={...Be(e,n),action:c?"revoked":"none",environment:r};t.output.result(l,qT);return}let o=Be(e,n),s=_n(o)&&(t.args.yes||await nJ(t.json,o)),i=s?vo(e,n):o,a={...i,action:s?"trusted":"none",environment:r};return t.output.result(a,qT),_n(i)&&!r?tJ:void 0}});async function nJ(t,e){if(!ur({json:t}))return!1;return Nd(e.root,e.commands)}function qT(t){let e=[`Trust for ${t.root}: ${rJ(t)}`,...Pd(t.commands)],n=[...t.action==="trusted"?["Trusted the commands above"]:[],...t.action==="revoked"?["Revoked the trust record of this repository"]:[],...t.environment?[`${xr}=1 is set, so ari runs these commands without a record`]:[],..._n(t)&&t.action!=="revoked"?["Review the commands above, then run 'ari trust --yes' or answer the prompt in a terminal"]:[]];return[...e,...n].join(`
|
|
265
|
+
`)}function rJ(t){switch(t.state){case"trusted":return`trusted since ${t.trustedAt} (configuration ${t.sha256.slice(0,eJ)})`;case"changed":return`not trusted: the commands changed since ${t.trustedAt}`;case"untrusted":return"not trusted";case"not-required":return"nothing to trust, the configuration starts no commands"}}var oJ="Fix the cause, then run 'ari uninstall' again; it keeps what is already done",sJ="as it was before the install, byte for byte",iJ="only ari's entries: the file changed after the install, so your edits stay";async function om(t,e,n,r){let o={bases:n,mode:r,preview:tp(),root:t},s=[];for(let i of e.targets){if(i.skip!==null){s.push(Ql(i,"skipped",{reason:i.skip}));continue}try{s.push(...await aJ(o,i))}catch(a){let c=Ql(i,"failed",{hint:yJ(a),reason:hJ(a)});s.push({...c,file:dJ(i)})}}return s}async function aJ(t,e){if(e.kind==="git")return uJ(t,e);let n=fJ(e.agent),r=mJ(t,e.scope),o=t.mode==="preview"?t.preview:tp(),s=await cJ(t,e,n,r,o);if(t.mode==="apply")await lJ(t,e,n,r);return[pJ(e,s,XT(e.kind,n,e.scope))]}async function cJ(t,e,n,r,o){if(e.kind==="hooks"){let i=sm(t);return op(i,Pe(n),{forget:!1,state:await P(i),view:o})}if(e.kind==="mcp")return Yc(Ne(me(n),r),o,!1);let s=Jt(n);return gb(ot.map((i)=>Yc(ie(s,r,i),o,!1)))}async function lJ(t,e,n,r){if(e.kind==="hooks"){let o=sm(t);pc(o,Pe(n),await P(o));return}if(e.kind==="mcp")Qc(me(n),r);else nl(Jt(n),r)}async function uJ(t,e){let n=sm(t),r=await Gs(n);if(t.mode==="apply")await cc(n);return r.map(({action:o,path:s})=>({...Ql(e,o==="removed"?"removed":"unchanged",{}),file:s}))}function dJ(t){return t.agent===null?null:XT(t.kind,t.agent,t.scope)}function XT(t,e,n){if(t==="hooks")return Pe(e).file;let r=t==="mcp"?me(e)[n]:Jt(e)[n];return oe(n,r??"")}function pJ(t,e,n){let r=gJ(e),o=e.restored===null?null:e.restored==="original"?sJ:iJ;return{...Ql(t,r,{detail:o}),file:n}}function gJ({action:t}){return t==="removed"?"removed":t==="unchanged"?"unchanged":"restored"}function Ql(t,e,n){return{action:e,agent:t.agent,detail:n.detail??null,file:null,hint:n.hint??null,kind:t.kind,reason:n.reason??null,scope:t.scope}}function mJ(t,e){let n=t.bases[e];if(n!==void 0)return n;throw Error(`The ${e} scope is not part of this uninstall`)}function sm({root:t}){if(t!==null)return t;throw Error("This uninstall target needs a repository")}function fJ(t){if(t!==null)return t;throw Error("This uninstall target needs an agent")}function hJ(t){return t instanceof Error?t.message:String(t)}function yJ(t){return t instanceof m&&t.hint!==void 0&&t.hint.length>0?t.hint:oJ}var kJ=[{how:"Delete the directory yourself: rm -r .ari",what:".ari/: tasks, knowledge, configuration and routing, packs"},{how:"Delete the lines from <!-- ari:begin --> to <!-- ari:end --> by hand",what:"The ari block in AGENTS.md"},{how:'Delete the directory yourself: rm -r "$(git rev-parse --git-path ari)"',what:"Journals, the active-task pointer and the sleep ledger under the git directory"},{how:"Run 'ari trust --revoke' in this repository",what:"The trust record for this repository on this machine"}],wJ=[{how:"Delete the directory yourself: rm -r ~/.ari",what:"~/.ari: the trust records and the receipts of anything still installed"}];function zT(t){return t==="project"?kJ:wJ}var SJ=["git","skill","mcp","hooks"],vJ=["skill","mcp"],bJ=new Set(["hooks","git"]),EJ=[...at].reverse(),ZT="ari does not write this",$J={claude:"Claude Code keeps user-scope MCP servers itself; run 'claude mcp remove --scope user ari'"};async function QT(t,e){if(e==="user")return{user:await xt("user",process.cwd())};if(t===null)throw Error("A project-scope uninstall needs a repository root");return{project:{base:t,receipts:await P(t),scope:e}}}function tx(t){if(t.scope!=="user"||t.kinds===void 0)return;if(![...t.kinds].some((e)=>bJ.has(e)))return;throw new v("--hooks and --git-hooks belong to a repository, so they cannot go with --scope user","Use --mcp or --skills with --scope user, or drop --scope")}async function ex(t,e,n){let{scope:r}=e,o=r==="user"?vJ:SJ,s=[];for(let i of o.filter((a)=>e.kinds?.has(a)??!0))s.push(...i==="git"?await xJ(t,e):TJ(i,t,e,n));return{scope:r,targets:s}}function TJ(t,e,n,r){let{agents:o,scope:s}=n,i=r[s];if(i===void 0)return[];return EJ.filter((a)=>o?.includes(a)??!0).flatMap((a)=>{let c=AJ(t,a,s);if(c===void 0)return[];let l={agent:a,kind:t,scope:s};if(c===null)return o===void 0?[]:[{...l,skip:CJ(t,a,s)}];return IJ(()=>RJ(t,a,e,i),!0)||o!==void 0?[{...l,skip:null}]:[]})}async function xJ(t,e){let n=e.kinds?.has("git")===!0;if(t===null||e.agents!==void 0&&!n)return[];return(await Gs(t)).some(({action:o})=>o==="removed")||n?[{agent:null,kind:"git",scope:"project",skip:null}]:[]}function AJ(t,e,n){if(t==="hooks"){let o=Ie.find((s)=>s.name===e);return o===void 0?void 0:n==="project"?o.file:null}return(t==="mcp"?se:fe).find((o)=>o.agent===e)?.[n]}function CJ(t,e,n){if(t==="mcp")return $J[e]??`${ZT} ${e}'s ${n}-scope MCP configuration`;return`${ZT} ${e}'s ${n}-scope ${t}`}function RJ(t,e,n,r){if(t==="mcp")return mn(Ne(me(e),r));if(t==="skill"){let s=Jt(e);return ot.some((i)=>mn(ie(s,r,i)))}let o=Ie.find((s)=>s.name===e);return n!==null&&o!==void 0&&un(n,o)}function IJ(t,e){try{return t()}catch{return e}}var tu=" ",nx=11,OJ=34,_J=66,rx=72,PJ=["removed","restored","unchanged","skipped","failed"],NJ={failed:"failed",removed:"remove",restored:"restore",skipped:"skip",unchanged:"unchanged"};function ox(t){return t.targets.length===0}function DJ(t){if(t.kind==="git")return"git hook";return`${t.agent??""} ${Ye[t.kind]}`.trim()}function sx(t){return t.flatMap((e)=>ax(e,!0)).join(`
|
|
266
|
+
`)}function LJ(t){return t.targets.flatMap((e)=>ax(e,t.dryRun)).join(`
|
|
267
|
+
`)}function im(t){return t.flatMap((e)=>[...Wr(e.what,rx),...Wr(e.how,rx-tu.length).map((n)=>w.dim(`${tu}${n}`))]).join(`
|
|
268
|
+
`)}function am(t){let e=PJ.flatMap((n)=>{let r=t.filter((o)=>o.action===n).length;return r===0?[]:[`${r} ${n}`]});return e.length===0?"Nothing to remove":e.join(", ")}function ix(t){let e=t.dryRun?"Dry run: nothing was written":am(t.targets),n=ox(t)?[]:[LJ(t),""],r=ox(t)?[]:["","Kept",im(t.kept)];return[...n,e,...r].join(`
|
|
269
|
+
`)}function ax(t,e){let n=ut(e?NJ[t.action]:t.action,nx),r=ut(t.file??"",OJ),o=`${tu}${MJ(t.action,n)}${r}${w.dim(DJ(t))}`,s=[t.detail,t.reason,t.hint].flatMap((i)=>i===null?[]:Wr(i,_J).map((a)=>`${tu}${" ".repeat(nx)}${w.dim(a)}`));return[Le(o),...s]}function MJ(t,e){switch(t){case"removed":case"restored":return w.green(e);case"failed":return w.red(e);case"skipped":return w.yellow(e);case"unchanged":return w.dim(e)}}var jJ=1,cm={format:(t)=>t},FJ=j({agent:{description:`Only these agents, comma-separated: ${at.join(", ")}`,type:"string"},dryRun:{alias:"d",description:"Show what would be removed and write nothing",type:"boolean"},gitHooks:{description:"Remove the pre-commit and pre-push git hooks",type:"boolean"},hooks:{description:"Remove each agent's hooks",type:"boolean"},mcp:{description:"Remove ari's MCP server from each agent",type:"boolean"},scope:{description:"Where MCP servers and skills were installed: project or user (default: project)",type:"string"},skills:{description:"Remove ari's skills from each agent",type:"boolean"},yes:{alias:"y",description:"Remove without asking",type:"boolean"}}),lx=E({args:FJ,description:"Remove what 'ari install' put here: agent hooks, MCP server, skills and git hooks, giving every file back as it was",examples:["ari uninstall --dry-run","ari uninstall --yes","ari uninstall --agent claude --yes","ari uninstall --mcp --scope user --yes"],json:!0,name:"uninstall",prompts:!0,run:async(t)=>GJ(t)});async function GJ(t){let e=BJ(t.args),n=t.args.dryRun===!0,r=t.args.yes===!0;if(!t.interactive&&!r&&!n)throw WJ();let o=t.interactive,s=e.scope==="project"?await _():null,i=await QT(s,e.scope);if(o)fr(`${w.bold("ari uninstall")} ${w.dim(`Ariadne ${t.cli.version??""}`)}`);let a=await ex(s,e,i),c=await om(s,a,i,"preview");if(o&&c.length>0)Nt(sx(c),"Plan",cm);let l=c.some((d)=>d.action==="removed"||d.action==="restored");if(n)return cx(t,s,e,c,{dryRun:n,visual:o});if(l&&o&&!r)await KJ(()=>UJ());let u=await om(s,a,i,"apply");return cx(t,s,e,u,{dryRun:!1,visual:o})}function cx(t,e,n,r,o){let s=r.some((a)=>a.action==="failed"),i={dryRun:o.dryRun,kept:[...zT(n.scope)],ok:!s,root:e,scope:n.scope,targets:r};if(o.visual)HJ(i);return t.output.result(i,o.visual?void 0:ix),s?jJ:0}function HJ(t){if(t.targets.length===0){ce("Nothing to remove");return}if(t.dryRun){ce("Dry run: nothing was written");return}Nt(am(t.targets),t.ok?"Done":"Done, with problems",cm),Nt(im(t.kept),"Kept",cm),ce(t.ok?"ari is out of this setup":"Fix the failed rows, then run 'ari uninstall' again")}async function UJ(){if(await Ee({initialValue:!0,message:"Remove these?"}))return;throw new vt}async function KJ(t){try{await t()}catch(e){if(e instanceof vt)ys("Cancelled, nothing changed");throw e}}function BJ(t){let e=new Set([...t.hooks===!0?["hooks"]:[],...t.mcp===!0?["mcp"]:[],...t.skills===!0?["skill"]:[],...t.gitHooks===!0?["git"]:[]]),n={agents:t.agent===void 0?void 0:VJ(t.agent),kinds:e.size===0?void 0:e,scope:rr(t.scope)};return tx(n),n}function VJ(t){let e=[...new Set(We(t))];if(e.length===0)throw new v("--agent needs at least one agent",`Choose from: ${at.join(", ")}`);return e.map((n)=>{if(ll(n))return n;throw new v(`ari uninstall has no agent "${n}"`,`Choose from: ${at.join(", ")}`)})}function WJ(){return new v("ari uninstall needs --yes or --dry-run when it cannot ask","Run 'ari uninstall --dry-run' to see what it would remove, then 'ari uninstall --yes'")}var ux=E({name:"context",description:"Print the context pack of a task within a token budget",args:j({budget:{description:"Token budget (default: context.budget from .ari/config.json)",type:"number"}}),positionals:st({id:{description:"Task id (default: the active task of this worktree)"}}),json:!0,examples:["ari context","ari context add-profile-inheritance --budget 2000","ari context --json"],run:async(t)=>{let e=await Nl(await _(),{budget:t.args.budget,id:t.positionals.id});t.output.result(e,({text:n})=>n)}});var JJ=" ",qJ=E({name:"list",description:"List project knowledge entries",args:j({all:{default:!1,description:"Include archived entries",type:"boolean"}}),json:!0,examples:["ari knowledge list","ari knowledge list --all --json"],run:async(t)=>{let e=Tp(await _(),{all:t.args.all});t.output.result(e,QJ)}}),YJ=E({name:"search",description:"Rank knowledge entries against a query with BM25",args:j({all:{default:!1,description:"Include archived entries",type:"boolean"}}),positionals:st({query:{description:"Words to search for",required:!0,variadic:!0}}),json:!0,examples:["ari knowledge search profile resolution"],run:async(t)=>{let e=t.positionals.query.join(JJ),n=Dl(await _(),e,t.args.all);t.output.result(n,tq)}}),XJ=E({name:"show",description:"Show one knowledge entry and how many done tasks used it",positionals:st({id:{description:"Knowledge entry id",required:!0}}),json:!0,run:async(t)=>{let e=await _(),{tasks:n}=await vl(e);t.output.result(fS(e,t.positionals.id,n),eq)}}),zJ=E({name:"archive",description:"Archive a knowledge entry",args:j({force:{default:!1,description:"Allow archiving a constraint or decision",type:"boolean"}}),positionals:st({id:{description:"Knowledge entry id",required:!0}}),json:!0,run:async(t)=>{let e=await _(),n=hS(e,t.positionals.id,{force:t.args.force});t.output.result(n,(r)=>`Archived ${r.kind} ${r.id}`)}}),ZJ=E({name:"restore",description:"Restore an archived knowledge entry, byte for byte when the sleep ledger holds its original",positionals:st({id:{description:"Knowledge entry id",required:!0}}),json:!0,examples:["ari knowledge restore build-uses-bun"],run:async(t)=>{let e=await h$(await _(),t.positionals.id);t.output.result(e,(n)=>`Restored ${n.kind} ${n.id}`)}}),dx=E({name:"knowledge",description:"List, search, show, archive and restore project knowledge",subcommands:[qJ,YJ,XJ,zJ,ZJ]});function px(t){let e=t.status==="active"?"":` [${t.status}]`,n=t.text.split(`
|
|
270
|
+
`)[0]??"";return`${t.id} (${t.kind})${e}: ${n}`}function QJ(t){return t.entries.length===0?"No knowledge entries":t.entries.map(px).join(`
|
|
271
|
+
`)}function tq(t){if(t.matches.length===0)return`No knowledge entry matches "${t.query}"`;return t.matches.map((e)=>`${e.score.toFixed(2)} ${px(e.entry)}`).join(`
|
|
272
|
+
`)}function eq(t){let{entry:e}=t,n=(r)=>r.length===0?"none":r.join(", ");return[`${e.id} (${e.kind}, ${e.status})`,`Scope: ${n(e.scope)}`,`Sources: ${n(e.sources)}`,`Created: ${e.created}`,`Used by done tasks: ${t.uses}`,...e.supersedes.length===0?[]:[`Supersedes: ${n(e.supersedes)}`],...e.supersededBy===null?[]:[`Superseded by: ${e.supersededBy}`],"",e.text].join(`
|
|
273
|
+
`)}var nq=" ",gx=E({name:"note",description:"Add a note to the active task, or a project knowledge entry with --global",args:j({global:{default:!1,description:"Write a project knowledge entry instead of a task note",type:"boolean"},kind:{description:`Entry kind with --global: ${le.join(", ")} (default: fact)`,type:"string"},scope:{description:"Comma-separated globs the entry applies to, with --global (default: everywhere)",type:"string"}}),positionals:st({text:{description:"The note text",required:!0,variadic:!0}}),json:!0,examples:['ari note "The fixture needs a real git repository"','ari note --global --kind constraint --scope "packages/atlas/src/**" "Profile resolution stays synchronous"'],run:async(t)=>{let{global:e,kind:n,scope:r}=t.args,o={global:e,kind:n,scope:r===void 0?void 0:pS(r),text:t.positionals.text.join(nq)};t.output.result(await Pl(await _(),o),rq)}});function rq(t){return t.target==="task"?`Added note ${t.index} to ${t.task}`:`Added ${t.entry.kind} ${t.entry.id} to .ari/knowledge`}var lm="HEAD~1",oq={fail:"fail",pass:"pass",regression:"pass"};async function mx(t,e={}){let n=M(t),r=e.since??lm,o=await fo(t,r),s=ne(await xe(t,o)),{tasks:i}=Pt(t,n),a=i.filter((u)=>u.record.status==="done"&&s.some((d)=>et(d,u.contract.scope))),c=pe(t),l=[];for(let u of a){let d=await iq(t,u),p=c.filter((g)=>g.sources.includes(u.contract.id)).map((g)=>g.id);l.push({checks:d,knowledge:p,ok:d.every((g)=>g.ok),task:u.contract.id})}return{changed:s.length,commit:o,regressed:l.filter((u)=>!u.ok).map((u)=>u.task),since:r,tasks:l}}function sq(t){return{command:t.command,exitCode:t.exitCode,expect:t.expect,name:t.name,ok:t.ok,outputTail:t.outputTail,timedOut:t.timedOut}}async function iq(t,e){let n=[];for(let r of e.contract.checks){let[o]=await Je([cq(r)],aq(e,r),t);if(o!==void 0)n.push(sq(o))}return n}function aq(t,e){return(t.record.evidence.at(-1)?.gates.flatMap((r)=>r.checks)??[]).findLast((r)=>r.name===e.name)?.expect??oq[e.expect]}function cq(t){return{name:t.name,run:t.run,timeoutSeconds:t.timeoutSeconds}}var lq=1,fx=E({name:"replay",description:"Re-run the checks of done tasks whose scope changed since a reference",args:j({since:{default:lm,description:"Reference to compare with",type:"string"}}),json:!0,examples:["ari replay","ari replay --since origin/develop --json"],run:async(t)=>{let e=await mx(await _(),{since:t.args.since});return t.output.result(e,uq),e.regressed.length===0?void 0:lq}});function uq(t){let e=`Replayed ${t.tasks.length} done tasks against ${t.since} (${t.changed} changed files)`,n=t.tasks.flatMap((r)=>{if(r.ok)return[`ok ${r.task}`];let o=r.checks.filter((i)=>!i.ok),s=r.knowledge.length===0?[]:[` cited by: ${r.knowledge.join(", ")}`];return[`REGRESSED ${r.task}`,...o.flatMap((i)=>[` ${i.name} should ${i.expect}: ${i.command}`,dq(i.outputTail)]),...s]});return[e,...n].join(`
|
|
274
|
+
`)}function dq(t){return t.trimEnd().split(`
|
|
231
275
|
`).map((e)=>` ${e}`).join(`
|
|
232
|
-
`)}import{resolve as
|
|
233
|
-
`)
|
|
234
|
-
|
|
235
|
-
`)
|
|
236
|
-
|
|
237
|
-
`)}
|
|
276
|
+
`)}import{resolve as Eq}from"path";import{existsSync as pq,readFileSync as gq}from"fs";var Ai="Fix the proposal file, then run 'ari sleep --apply <file>' again",mq=["merges","promotions","archive","reason"],fq=["replace","entry"],hq=["task","notes","entry"],yq=["kind","scope","text"],kq=1;function yx(t,e){if(!pq(t))throw new m(`The proposal file ${t} does not exist`,Ai);let n=gq(t),r;try{r=JSON.parse(n.toString("utf8"))}catch(s){let i=s instanceof Error?s.message:String(s);throw new m(`The proposal file ${t} is not valid JSON (${i})`,Ai)}return{proposal:At("sleep proposal",Ai,()=>wq(r,e.knowledge.maxEntryBytes)),sha256:Z(n)}}function kx(t,e,n,r){let o=[],s=new Map,i=(c,l)=>{let u=e.get(c),d=s.get(c);if(u===void 0)o.push(`${l} names the unknown entry "${c}"`);else if(u.status!=="active")o.push(`${l} names the archived entry "${c}"`);else if(pn(u)&&!r)o.push(`${l} retires the ${u.kind} "${c}"; pass --force to retire ${u.kind} entries`);if(d!==void 0)o.push(`${l} names "${c}", which ${d} already retires`);s.set(c,l)};t.merges.forEach((c,l)=>{if(c.replace.length<kq)o.push(`merges[${l}].replace is empty`);c.replace.forEach((u,d)=>{i(u,`merges[${l}].replace[${d}]`)})}),t.archive.forEach((c,l)=>{i(c,`archive[${l}]`)});let a=new Map;return t.promotions.forEach((c,l)=>{let u=`promotions[${l}]`,d=n.get(c.task);if(d===void 0){o.push(`${u}.task names the unknown or unreadable task "${c.task}"`);return}if(c.notes.length===0)o.push(`${u}.notes is empty`);let p=a.get(c.task)??new Set;for(let g of c.notes){let f=d.notes[g];if(f===void 0)o.push(`${u}.notes names note ${g}, but "${c.task}" has none`);else if(f.promoted)o.push(`${u}.notes names note ${g}, which is already promoted`);if(p.has(g))o.push(`${u}.notes names note ${g} of "${c.task}" twice`);p.add(g)}a.set(c.task,p)}),o}function wq(t,e){let n=T(t,"proposal",mq);return{archive:D(n.archive,[],(r)=>L(r,"archive",x)),merges:D(n.merges,[],(r)=>L(r,"merges",(o,s)=>{let i=T(o,s,fq);return{entry:hx(i.entry,`${s}.entry`,e),replace:ft(i.replace,`${s}.replace`,(a,c)=>L(a,c,x))}})),promotions:D(n.promotions,[],(r)=>L(r,"promotions",(o,s)=>{let i=T(o,s,hq);return{entry:hx(i.entry,`${s}.entry`,e),notes:ft(i.notes,`${s}.notes`,(a,c)=>L(a,c,ht)),task:ft(i.task,`${s}.task`,x)}})),reason:D(n.reason,null,(r)=>nt(r,"reason").trim())}}function hx(t,e,n){let r=ft(t,e,(o,s)=>T(o,s,yq));return bp({kind:r.kind,scope:r.scope??[],text:r.text},e,n)}var Sq="(merged entry ";function Sx(t,e,n,r){let o=Fp(e),s=Fp(vq(t,e)),i=new Map;for(let a of Lr(n).slice(0,r))for(let c of a.record.knowledgeUsed){if(o(c)===null||s(c)!==null)continue;i.set(c,[...i.get(c)??[],a.contract.id])}return[...i.entries()].map(([a,c])=>({entry:a,tasks:c})).sort((a,c)=>O(a.entry,c.entry))}function vx(t){let e=t.tasks.map((r)=>`"${r}"`).join(", "),n=t.tasks.length===1?"task":"tasks";return`"${t.entry}" would no longer be active or replaced by an active entry, but ${n} ${e} used it`}function vq(t,e){let n=new Map(e);t.merges.forEach((r,o)=>{let s=`${Sq}${o})`;n.set(s,Qs(r.entry,{created:"",id:s,sources:[],supersedes:r.replace}));for(let i of r.replace)wx(n,i,s)});for(let r of t.archive)wx(n,r,null);return n}function wx(t,e,n){let r=t.get(e);if(r!==void 0)t.set(e,dn(r,n))}var bx=()=>new Date().toISOString();async function Ex(t,e,n={}){let r=M(t),o=await P(t),s=(n.clock??bx)(),i=n.force===!0;return Nr(o,()=>{let{entries:a,proposal:c,sha256:l}=Tx(t,e,r,i),u=new Set(an(t)),d=xx(c,a,Io(s),(f,y)=>$p(t,f,y,u)),p=_c(t,d.retirements);for(let{notes:f,task:y}of c.promotions)Vt(t,o,y,(S)=>hy(S,f));let g=No(o,s,{archived:p,created:VS(t,d.creations),forced:i,kind:"apply",promoted:Ax(c),proposal:{sha256:l},pruned:[],reason:c.reason});return{...Cx(d,c),ledger:g.id}})}function $x(t,e,n={}){let r=M(t),o=(n.clock??bx)(),{entries:s,proposal:i}=Tx(t,e,r,n.force===!0),a=new Set(an(t)),c=xx(i,s,Io(o),(l,u)=>Qs(l,{...u,id:Ep(l,a)}));return{...Cx(c,i),changes:Pc(t,c.retirements,c.creations),dryRun:!0}}function Tx(t,e,n,r){let{proposal:o,sha256:s}=yx(e,n),i=new Map(pe(t).map((p)=>[p.id,p])),{tasks:a}=Pt(t,n),c=new Map(a.map((p)=>[p.contract.id,p.record])),l=kx(o,i,c,r);if(l.length>0){let p=l.map((g)=>` - ${g}`).join(`
|
|
277
|
+
`);throw new m(`The sleep proposal has ${l.length} problem(s):
|
|
278
|
+
${p}`,Ai)}let u=n.knowledge.rehearsalTasks,d=r?[]:Sx(o,i,a,u);if(d.length>0)throw bq(d,Math.min(u,Lr(a).length));return{entries:i,proposal:o,sha256:s}}function bq(t,e){let n=t.map((r)=>` - ${vx(r)}`).join(`
|
|
279
|
+
`);return new m(`The sleep proposal fails the rehearsal against the last ${e} done task(s):
|
|
280
|
+
${n}`,"Keep those entries out of the proposal, merge them into a successor, or run 'ari sleep --apply <file> --force' to apply it anyway")}function xx(t,e,n,r){let o=[],s=[];for(let i of t.merges){let a=i.replace.map((u)=>e.get(u)).filter((u)=>u!==void 0),c=[...new Set(a.flatMap((u)=>u.sources))].sort(O),l=r(i.entry,{created:n,sources:c,supersedes:[...i.replace]});o.push({entry:l,notes:[],origin:"merge",replaces:[...i.replace],task:null}),s.push(...a.map((u)=>({after:dn(u,l.id),reason:"merge"})))}for(let i of t.promotions){let a=r(i.entry,{created:n,sources:[i.task],supersedes:[]});o.push({entry:a,notes:[...i.notes],origin:"promotion",replaces:[],task:i.task})}for(let i of t.archive){let a=e.get(i);if(a!==void 0)s.push({after:dn(a,null),reason:"proposal"})}return{creations:o,retirements:s}}function Ax(t){return t.promotions.map((e)=>({notes:[...e.notes],task:e.task}))}function Cx(t,e){return{archived:t.retirements.map(({after:n})=>({id:n.id,supersededBy:n.supersededBy})),created:t.creations.map(({entry:n,origin:r})=>({id:n.id,kind:n.kind,origin:r})),promoted:Ax(e)}}function um(t){let e=t.archived.map((s)=>` ${s.id} (${s.reason}${s.supersededBy===null?"":` of ${s.supersededBy}`})`),{clusters:n,decisions:r,notes:o}=t.candidates;return[..."dryRun"in t?["Dry run: nothing was written"]:[],`Pruned journals: ${t.pruned.length===0?"none":t.pruned.map((s)=>s.task).join(", ")}`,`Archived entries: ${e.length===0?"none":""}`.trimEnd(),...e,`Active knowledge: ${t.activeBytes} of ${t.maxBytes} bytes`,`Candidates: ${n.length} merge clusters, ${o.length} unpromoted notes, ${r.length} overlapping decision pairs`,...n.map((s)=>` merge? ${s.ids.join(", ")} (similarity ${s.similarity})`),...o.map((s)=>` promote? ${s.task} note ${s.note}: ${s.text.split(`
|
|
281
|
+
`)[0]??""}`),...r.map((s)=>` reconcile? ${s.ids.join(" and ")}`),..."changes"in t?_x(t.changes):[],..."ledger"in t?[`Ledger entry: ${t.ledger}`]:[]].join(`
|
|
282
|
+
`)}function Rx(t){return[..."dryRun"in t?["Dry run: nothing was written"]:[],`Created: ${t.created.length===0?"none":t.created.map((e)=>e.id).join(", ")}`,`Archived: ${t.archived.length===0?"none":t.archived.map((e)=>e.id).join(", ")}`,`Promoted notes: ${t.promoted.length===0?"none":t.promoted.map((e)=>`${e.task} ${e.notes.join(", ")}`).join("; ")}`,..."changes"in t?_x(t.changes):[],..."ledger"in t?[`Ledger entry: ${t.ledger}`]:[]].join(`
|
|
283
|
+
`)}function Ix(t){let e=(r)=>r.length===0?"none":r.map((o)=>o.id).join(", "),n=t.unpromoted.map((r)=>`${r.task} ${r.notes.join(", ")}`).join("; ");return[..."dryRun"in t?["Dry run: nothing was written"]:[],`Undoing sleep entry ${t.undoes}`,`Restored: ${e(t.restored)}`,`Removed: ${e(t.removed)}`,`Reopened notes: ${n===""?"none":n}`,...t.journalsNotRestored.length===0?[]:[`Pruned journals are not restored: ${t.journalsNotRestored.join(", ")}`],..."ledger"in t?[`Ledger entry: ${t.ledger}`]:[]].join(`
|
|
284
|
+
`)}function Ox(t){let{due:e,sleep:n}=t;if(n===null)return`Sleep is not due: no journals of done tasks, ${e.activeBytes} of ${e.maxBytes} bytes of active knowledge, no candidates`;return[`Sleep is due: ${e.reasons.join(", ")}`,um(n)].join(`
|
|
285
|
+
`)}function _x(t){return t.flatMap((e)=>{let n=e.supersededBy===null?"":` by ${e.supersededBy}`;return[`${e.change} ${e.id} (${e.reason}${n})`,...e.diff.map((r)=>` ${r}`)]})}var Nx=E({name:"sleep",description:"Consolidate memory: prune journals, archive duplicates, decay and enforce the budget",args:j({apply:{description:"Apply a validated JSON proposal of merges, promotions and archives",type:"string"},dryRun:{default:!1,description:"Show what would change, with a diff of each entry, and write nothing",type:"boolean"},force:{default:!1,description:"With --apply, allow retiring constraint and decision entries and entries that recent tasks used",type:"boolean"},ifDue:{default:!1,description:"Run the pass only when sleep is due, otherwise say that nothing is due",type:"boolean"},undo:{default:!1,description:"Undo a sleep ledger entry (the id is the argument; default: the latest that changed knowledge)",type:"boolean"}}),positionals:st({id:{description:"With --undo, the sleep ledger entry to undo"}}),json:!0,examples:["ari sleep","ari sleep --json","ari sleep --if-due","ari sleep --dry-run","ari sleep --apply proposal.json --dry-run","ari sleep --apply proposal.json","ari sleep --undo"],run:async(t)=>{let{apply:e,dryRun:n,force:r,ifDue:o,undo:s}=t.args,{id:i}=t.positionals;$q({apply:e,dryRun:n,force:r,ifDue:o,undo:s},i);let a=await _();if(s){t.output.result(n?await f$(a,i):await m$(a,i),Ix);return}if(e!==void 0){let c=Eq(process.cwd(),e),l=n?$x(a,c,{force:r}):await Ex(a,c,{force:r});t.output.result(l,Rx);return}if(o){let c=er(await jr(a)),l=c.due?await Px(a,n):null,u={due:c,sleep:l};t.output.result(u,Ox);return}t.output.result(await Px(a,n),um)}});function Px(t,e){return e?WS(t):Mr(t)}function $q(t,e){let{apply:n,force:r,ifDue:o,undo:s}=t;if(e!==void 0&&!s)throw new v("A ledger id needs --undo",`Run 'ari sleep --undo ${e}'`);if(s){let i=[n===void 0?"":"--apply",r?"--force":"",o?"--if-due":""].filter((a)=>a.length>0);if(i.length>0)throw new v(`--undo cannot be combined with ${i.join(" or ")}`,"Run 'ari sleep --undo [<id>]'");return}if(n!==void 0&&o)throw new v("--if-due cannot be combined with --apply","Run one of them");if(r&&n===void 0)throw new v("--force applies only with --apply","Run 'ari sleep --apply <file> --force'")}import{existsSync as zx}from"fs";import{basename as Wq,extname as Jq,join as Zx}from"path";import{readFileSync as Tq}from"fs";import{join as xq}from"path";var Lx=["checks","invariants","scope","locked"];function Mx(t,e,{exact:n,pack:r}){if(r===null)return[`the pack "${e.contract.pack}" is not a built-in or project pack`];let o=e.record.status==="done",s=o?[...Pq(t,e),...Rq(e)]:[],i=e.record.evidence.flatMap(_q);if(!n)return[...s,...Aq(e,r),...i];let a=o?Nq(e,r):[];return[...s,...Iq(e,r),...i,...a]}function jx(t,{exact:e}){let{evidence:n}=t.record;if(e)return n.at(-1)?.gates??[];return Lx.flatMap((r)=>{let o=eu(t,r),s=o.at(-1);return s===void 0?[]:[{...s,checks:Fx(o)}]})}function Aq(t,e){let n=e.stages.flatMap((u)=>u.gates),o=Lx.filter((u)=>n.some((d)=>d.kind===u)).filter((u)=>eu(t,u).length===0).map((u)=>`the record holds no ${u} evidence, but pack "${e.name}" runs that gate`),s=new Set(n.flatMap((u)=>Cq(t.contract,u))),i=Fx(eu(t,"checks")),a=[...s].filter((u)=>!i.some((d)=>d.name===u.name&&d.command===u.run)).map((u)=>`the record holds no evidence that ${u.name} (${JSON.stringify(u.run)}) passed`),c=eu(t,"invariants").at(-1)?.checks.map((u)=>u.command),l=c===void 0||pm(c,t.contract.invariants)?[]:[`the invariants evidence ran ${JSON.stringify(c)}, but the contract asks for ${JSON.stringify(t.contract.invariants)}`];return[...o,...a,...l]}function Cq(t,e){return e.kind==="checks"&&e.expect==="pass"?po(t,e.select):[]}function eu(t,e){return t.record.evidence.flatMap((n)=>n.gates.filter((r)=>r.gate===e))}function Fx(t){let e=t.flatMap((n)=>n.checks).filter((n)=>n.expect==="pass");return[...new Map(e.map((n)=>[dm(n),n])).values()]}function Rq(t){return t.record.gatesHash===null?["the record has no frozen gates hash"]:[]}function Iq(t,e){let{record:n}=t,r=n.status==="done"?e.stages.length:n.stage,o=n.evidence.length;return[...o===r?[]:[`the record holds evidence for ${o} ${wt(o,"stage","stages")}, but pack "${e.name}" expects ${r} at this point`],...n.evidence.flatMap((i,a)=>Oq(i,e,a))]}function Oq(t,e,n){let r=e.stages[n];if(r===void 0)return[];if(t.stage!==r.name)return[`evidence ${n+1} is for stage "${t.stage}", but stage ${n+1} of pack "${e.name}" is "${r.name}"`];let o=t.gates.map((i)=>i.gate),s=r.gates.map((i)=>i.kind);if(pm(o,s))return[];return[`the evidence of stage "${r.name}" records the gates [${o.join(", ")}], but the pack runs [${s.join(", ")}]`]}function _q(t){return t.gates.filter((e)=>!e.ok||e.checks.some((n)=>!n.ok)).map((e)=>`the evidence of stage "${t.stage}" records a failing ${e.gate} gate`)}function Pq(t,e){let n=e.record.contractHash;if(n===null)return["the record has no frozen contract hash"];let r=Tq(xq(t,It(e.contract.id)),"utf8");if(Bt(r)===n)return[];return["the contract changed after 'ari start' or the last 'ari amend' froze it; a done contract must not change"]}function Nq(t,e){let n=t.record.evidence.length-1,r=t.record.evidence[n],o=e.stages[n];if(r===void 0||o===void 0||r.stage!==o.name)return[];return r.gates.flatMap((s,i)=>Dq(t.contract,o,s,i))}function Dq(t,e,n,r){let o=e.gates[r];if(o===void 0||o.kind!==n.gate)return[];let s=Lq(t,o);if(s===null)return[];let i=n.checks.map(Mq);if(pm(i.map(dm),s.map(dm)))return[];return[`the ${n.gate} evidence of stage "${e.name}" ran ${Dx(i)}, but the contract asks for ${Dx(s)}`]}function Lq(t,e){switch(e.kind){case"checks":return po(t,e.select).map((n)=>({command:n.run,expect:e.expect,name:n.name}));case"invariants":return t.invariants.map((n,r)=>({command:n,expect:"pass",name:`invariants[${r}]`}));default:return null}}function Mq(t){return{command:t.command,expect:t.expect,name:t.name}}function dm(t){return JSON.stringify([t.name,t.command,t.expect])}function Dx(t){if(t.length===0)return"nothing";return t.map((e)=>`${e.name} (${JSON.stringify(e.command)}, expect ${e.expect})`).join(", ")}function pm(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var lr=0,mm=1,jq=128,Fq=`
|
|
286
|
+
`;async function Gx(t,e){let n=e.evidence.at(-1);if(e.status!=="done"||n===void 0)return null;let r=Rn(e.id),o=await F(t,["log","--reverse","--format=%H","HEAD","--",r]),s=null;for(let i of o.stdout.split(Fq).filter((a)=>a.length>0)){let a=Wx(await Ci(t,i,r));if(a===null||a.created!==e.history[0]?.at)continue;if(a.base!==null)s??=i;if(Gq(a,n))return{finished:i,started:s??i}}return null}async function Hx(t,e,n){return Wx(await Ci(t,e,Rn(n)))?.status??null}async function Ci(t,e,n){let r=await F(t,["show",`${e}:${n}`],{allowedExitCodes:[lr,jq]});return r.exitCode===lr?r.stdout:null}async function Ux(t,e){return await Vx(t,e)!==null}async function Kx(t,e){return Vx(t,`${e}^`)}async function Ri(t,e,n){return(await F(t,["merge-base","--is-ancestor",e,n],{allowedExitCodes:[lr,mm]})).exitCode===lr}async function fm(t,e,n){let r=await F(t,["merge-base",e,n],{allowedExitCodes:[lr,mm]});return r.exitCode===lr?r.stdout.trim():null}async function hm(t,e,n){return Number((await F(t,["rev-list","--count",`${e}..${n}`])).stdout.trim())}async function Bx(t){return(await F(t,["rev-parse","--is-shallow-repository"])).stdout.trim()==="true"}async function Vx(t,e){let n=["rev-parse","--verify","--quiet","--end-of-options",`${e}^{commit}`],r=await F(t,n,{allowedExitCodes:[lr,mm]});return r.exitCode===lr?r.stdout.trim():null}function Wx(t){let e=Hq(t);if(!gm(e))return null;let n=Array.isArray(e.evidence)?e.evidence.at(-1):null,r=Array.isArray(e.history)?e.history[0]:null;return{base:e.base??null,created:gm(r)?r.at:null,evidence:gm(n)?n:null,status:e.status}}function Gq(t,{at:e,stage:n,treeHash:r}){let o=t.evidence;return o!==null&&o.at===e&&o.stage===n&&o.treeHash===r}function Hq(t){if(t===null)return null;try{return JSON.parse(t)}catch(e){if(e instanceof SyntaxError)return null;throw e}}function gm(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function ym({packs:t},e){return{exact:!0,pack:km(t,e.contract.pack)}}async function Jx(t,e,n,r){let{gatesHash:o}=e.record,s=r===null?null:await Uq(t,r,e.contract.pack),i=[n,s].find((a)=>a!==null&&Kq(a,e)===o);if(i)return ym(i,e);return{exact:!1,pack:km((s??n).packs,e.contract.pack)}}async function Uq(t,e,n){let r=Ad(n),o=await Ci(t,e,r),s=await Ci(t,e,rt);try{return{config:vr(s===null?{}:JSON.parse(s)),packs:Tn(o===null?[]:[Ia(o,r)])}}catch(i){if(i instanceof m||i instanceof SyntaxError)return null;throw i}}function Kq({config:t,packs:e},n){let r=km(e,n.contract.pack);return r===null?null:Oa(r,t)}function km(t,e){return t.find((n)=>n.name===e)??null}async function Yx(t){let{commits:e,record:n,root:r,target:o}=t,{base:s}=n;if(s===null)return Xx("the record has no base commit");let i=await Ux(r,s);if(e===null){if(!i)return wm(s);return nu(await xe(r,await qx(r,s,o,"HEAD")))}let{finished:a}=e,c=i&&await Ri(r,s,a),l=o===null?null:await fm(r,o,a);if(l===null||l===a)return Vq(t,e,c?s:null);let u=c?await qx(r,s,o,a):await Bq(r,l,t.otherFinishes,a);return nu(await Ga(r,u,a))}async function qx(t,e,n,r){let o=n===null?null:await fm(t,n,r);return o!==null&&await Ri(t,e,o)?o:e}async function Bq(t,e,n,r){let o={commit:e,distance:await hm(t,e,r)};for(let s of n){if(s===r||!await Ri(t,e,s)||!await Ri(t,s,r))continue;let i=await hm(t,s,r);if(i<o.distance)o={commit:s,distance:i}}return o.commit}async function Vq(t,e,n){let{record:r,root:o}=t,{finished:s,started:i}=e;if(n===null&&await Bx(o))return wm(r.base);let a=await Kx(o,i),c=a===null?null:await Ga(o,a,s);if(n===null)return c===null?wm(r.base):nu(c);let l=await Ga(o,n,s);return nu(c===null?l:l.filter((u)=>c.includes(u)))}function nu(t){return{files:t,problem:null}}function Xx(t){return{files:[],problem:t}}function wm(t){return Xx(`the base commit ${t} is not in this clone; fetch the full history`)}var qq="\x00",Sm="HEAD",$m="done",vm=[Er,Gy],Yq="invalid";async function Qx(t,e){let n=M(t);await Fa(t);let r=Pt(t,n),o=Tn(Gt(t)),s=e.kind==="base"?await fo(t,e.ref):null,i=new Map(r.tasks.map((p)=>[p.contract.id,p])),a=new Map(r.invalid.map((p)=>[p.id,p])),c=await Xq(t,e,s,i),l=new Map;for(let p of c){let g=i.get(p);if(g!==void 0)l.set(p,await Gx(t,g.record))}let u={commits:l,config:n,mode:e.kind,packs:o,root:t,target:s},d=[];for(let p of c){let g=i.get(p);if(g!==void 0){d.push(await Qq(u,g));continue}let f=a.get(p)?.problem??Zq(t,p);if(f===null)continue;d.push({gates:[],ok:!1,problems:[f],stage:null,status:Yq,task:p})}return{failed:d.filter((p)=>!p.ok).map((p)=>p.task),mode:e.kind,ref:e.kind==="base"?e.ref:null,tasks:d}}async function Xq(t,e,n,r){let o=n??Sm,s=async(i)=>(r.get(i)?.record.status??await zq(t,i,o))===$m;switch(e.kind){case"all":return Em(In(t),s);case"base":{let i=["diff","--name-only","--no-renames","-z",o,Sm,"--",...vm],a=(await F(t,i)).stdout.split(qq),c=new Set(bm(a,Er));return Em(bm(a,...vm),async(l)=>c.has(l)||s(l))}case"local":{let i=gt(await P(t))?.task,a=await Em(bm(await xe(t,Sm),...vm),s);return[...new Set([...i===void 0?[]:[i],...a])]}}}async function zq(t,e,n){if(!zx(Zx(t,Rn(e))))return Hx(t,n,e);try{return On(t,e).status}catch(r){if(r instanceof m)return $m;throw r}}function Zq(t,e){let n=Rn(e);return zx(Zx(t,n))?`${n} has a record but no contract`:null}function bm(t,...e){let n=t.filter((r)=>et(r,e)).map((r)=>Wq(r,Jq(r)));return[...new Set(n)].filter(xd).sort(O)}async function Em(t,e){let n=[];for(let r of t)if(await e(r))n.push(r);return n}async function Qq(t,e){let{record:n}=e,r=n.evidence.at(-1),o={status:n.status,task:e.contract.id};if(r===void 0){let u=n.status===$m?["the task is done but has no stage evidence"]:[];return{...o,gates:[],ok:u.length===0,problems:u,stage:null}}let{root:s}=t,i=t.mode==="all"?await Jx(s,e,t,tA(t,e)?.finished??null):ym(t,e),a=Mx(s,e,i),c=[];for(let u of jx(e,i)){let d=await t5(t,e,u);if(d===null)continue;let p=d.current===u.ok&&d.details.length===0;c.push({current:d.current,details:d.details,gate:u.gate,ok:p,recorded:u.ok})}let l=a.length===0&&c.every((u)=>u.ok);return{...o,gates:c,ok:l,problems:a,stage:r.stage}}function tA(t,e){return t.commits.get(e.contract.id)??null}async function t5(t,e,n){switch(n.gate){case"checks":case"invariants":{let r=e5(e,n.checks);return r.length===0?null:n5(t,e,r)}case"locked":return o5(t,e);case"scope":return s5(t,e);default:return null}}function e5(t,e){if(t.record.status==="done")return[...e];return e.filter((n)=>n.expect==="pass")}async function n5(t,e,n){let r=[],o=!0;for(let s of n){let i={name:s.name,run:s.command,timeoutSeconds:r5(t,e,s.name)},[a]=await Je([i],s.expect,t.root);if(a===void 0)continue;if(o&&=a.ok,a.ok===s.ok)continue;r.push(a.ok?`${s.name} now meets its expectation (${s.expect})`:dp(a))}return{current:o,details:r}}function r5(t,e,n){return e.contract.checks.find((o)=>o.name===n)?.timeoutSeconds??t.config.checkTimeoutSeconds}async function o5(t,e){let n=await An(t.root,e.contract.lock),r=Xs(e.record.lockHashes,n);return{current:r.length===0,details:r}}async function s5(t,e){let{commits:n,root:r,target:o}=t,s=[...n].flatMap(([c,l])=>l===null||c===e.contract.id?[]:[l.finished]),i=await Yx({commits:tA(t,e),otherFinishes:s,record:e.record,root:r,target:o});if(i.problem!==null)return{current:!1,details:[i.problem]};let a=ne(i.files).filter((c)=>!et(c,e.contract.scope));return{current:a.length===0,details:a.map((c)=>`outside the scope: ${c}`)}}var i5=1,nA=E({name:"verify",description:"Re-evaluate the reproducible gates of done tasks against their evidence",args:j({all:{default:!1,description:"Verify every done task",type:"boolean"},base:{description:"Verify tasks whose record changed between this reference and HEAD (CI mode)",type:"string"}}),json:!0,examples:["ari verify","ari verify --base origin/develop","ari verify --all --json"],run:async(t)=>{let{all:e,base:n}=t.args;if(e&&n!==void 0)throw new v("--all and --base exclude each other","Pass one of them");let r=n!==void 0?{kind:"base",ref:n}:e?{kind:"all"}:{kind:"local"},o=await Qx(await _(),r);return t.output.result(o,a5),o.failed.length===0?void 0:i5}});function a5(t){if(t.tasks.length===0)return"No task to verify";return t.tasks.flatMap((e)=>{let n=e.stage===null?"":` (${e.stage})`,r=e.gates.filter((i)=>!i.ok).flatMap((i)=>[` ${i.gate}: recorded ${eA(i.recorded)}, now ${eA(i.current)}`,...i.details.map((a)=>` ${a}`)]),o=e.problems.map((i)=>` ${i}`),s=e.ok&&e.gates.length===0?" (no evidence to reproduce yet)":"";return[`${e.ok?"ok":"FAILED"} ${e.task}${n}${s}`,...o,...r]}).join(`
|
|
287
|
+
`)}function eA(t){return t?"passed":"failed"}var rA=[ux,gx,dx,Nx,fx,nA];var u5=".ari",d5="cli-state.json",p5=Du({bin:"ari",commands:[s$,J$,lx,bE,VT,WT,JT,Y$,X$,ZE,QE,t$,z$,Z$,Q$,tT,BT,e$,...rA,r$,o$,NT,PT,IT,LT,Ck,YT],config:new Ku(l5(c5(),u5,d5),{}),description:"Task contracts, CLI-evaluated gates and tiered memory for coding agents",name:"Ariadne",version:ya});p5.main();
|