@brainervirus/workit-claude-code 8.31.1 → 8.32.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.
@@ -57,7 +57,7 @@ ${t.join(`
57
57
  }
58
58
  `)}return v.write("payload.value = newResult;"),v.write("return payload;"),v.compile()},i,a=rr,c=!De.jitless,u=c&&Xd.value,d=t.catchall,p;e._zod.parse=(f,g)=>{p??(p=r.value);let h=f.value;if(!a(h))return f.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),f;if(c&&u&&g?.async===!1&&g.jitless!==!0){if(!i)i=s(t.shape);if(f=i(f,g),!d)return f;return tg([],h,f,g,p,e,g?.abortEarly===!0)}return n(f,g)}});function ff(e,t,n,r){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter((s)=>!St(s));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((s)=>s.issues.map((i)=>_t(i,r,He())))}),t}var Qa=S("$ZodUnion",(e,t)=>{ee.init(e,t),Z(e,"optin",(r)=>r.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":r.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),Z(e,"optout",(r)=>r.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),Z(e,"values",(r)=>{if(r.def.options.every((o)=>o._zod.values))return new Set(r.def.options.flatMap((o)=>Array.from(o._zod.values)));return}),Z(e,"pattern",(r)=>{if(r.def.options.every((o)=>o._zod.pattern)){let o=r.def.options.map((s)=>s._zod.pattern);return new RegExp(`^(${o.map((s)=>es(s.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let a of t.options){let c=a._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}if(!s)return ff(i,r,e,o);return Promise.all(i).then((a)=>ff(a,r,e,o))}});function u_(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let o of r)if(t.has(o)){if(o!==void 0)throw Error(`Duplicate discriminator value "${String(o)}"`);t.set(o,null)}else t.set(o,n)}return t}var rg=S("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Qa.init(e,t);let n=e._zod.parse;Z(e,"propValues",(o)=>{let s={},i=0;for(let a of o.def.options){let c=a._zod.propValues;if(!c||Object.keys(c).length===0)throw Error(`Invalid discriminated union option at index "${o.def.options.indexOf(a)}"`);if(c[o.def.discriminator]?.has(void 0))i++;for(let[l,u]of Object.entries(c)){if(!Object.prototype.hasOwnProperty.call(s,l))et(s,l,new Set);for(let d of u)s[l].add(d)}}if(!o.def.unionFallback&&i>1)s[o.def.discriminator]?.delete(void 0);return s}),t.options.forEach((o,s)=>{let i=Zr(o._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw Error(`Invalid discriminated union option at index "${s}"`)});let r=Hr(()=>u_(t));e._zod.parse=(o,s)=>{let i=o.value;if(!rr(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=i?.[t.discriminator],c=r.value.get(a);if(c&&(a!==void 0||s.direction!=="backward"))return c._zod.run(o,s);if(t.unionFallback||s.direction==="backward")return n(o,s);return o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()).filter((l)=>r.value.get(l)!==null),input:i,path:[t.discriminator],inst:e}),o}}),og=S("$ZodIntersection",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,s=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([c,l])=>gf(n,c,l));return gf(n,s,i)}});function Ga(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Nn(e)&&Nn(t)){let n=Object.keys(t),r=Object.keys(e).filter((s)=>n.indexOf(s)!==-1),o={...e,...t};if(Object.prototype.hasOwnProperty.call(o,"__proto__"))delete o.__proto__;for(let s of r){if(s==="__proto__")continue;let i=Ga(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let o=e[r],s=t[r],i=Ga(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function gf(e,t,n){let r=new Map,o,s=new Map,i=(l,u)=>{let d;if(l.code==="unrecognized_keys"&&!l.path?.length)o??(o=l),d=l.keys;else if(l.code==="invalid_key"&&l.origin==="record"&&l.path?.length===1){let p=String(l.path[0]);if(!s.has(p))s.set(p,l);d=[p]}else return!1;for(let p of d){if(!r.has(p))r.set(p,{});r.get(p)[u]=!0}return!0};for(let l of t.issues)if(!i(l,"l"))e.issues.push(l);for(let l of n.issues)if(!i(l,"r"))e.issues.push(l);let a=[...r].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(a.length){let l=o?a.filter((u)=>o.keys.includes(u)):[];if(l.length)e.issues.push({...o,keys:l});for(let u of a)if(!l.includes(u)&&s.has(u))e.issues.push(s.get(u))}let c=Ga(t.value,n.value);if(!c.valid){if(St(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var sg=S("$ZodRecord",(e,t)=>{ee.init(e,t);let n=De.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let s=r.value;if(!Nn(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),r;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},o):{};let c=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(c.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let d=t.keyType._zod.run({value:u,issues:[]},o);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((g)=>_t(g,o,He())),input:u,path:[u],inst:e});continue}let p=d.value;if(p==="__proto__")continue;let f=t.valueType._zod.run({value:s[u],issues:[]},o);if(f instanceof Promise)i.push(f.then((g)=>{if(g.issues.length)r.issues.push(...an(u,g.issues));r.value[p]=g.value}));else{if(f.issues.length)r.issues.push(...an(u,f.issues));r.value[p]=f.value}}let l;for(let u in s)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;r.value[u]=s[u]}else l=l??[],l.push(u);if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},o):{};let c;for(let l of Reflect.ownKeys(s)){if(l==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(s,l))continue;let u=t.keyType._zod.run({value:l,issues:[]},o);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof l==="string"&&Kr.test(l)&&u.issues.length){let g=t.keyType._zod.run({value:Number(l),issues:[]},o);if(g instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(g.issues.length===0)u=g}if(u.issues.length){if(t.mode==="loose")r.value[l]=s[l];else if(a)c=c??[],c.push(l);else r.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((g)=>_t(g,o,He())),input:l,path:[l],inst:e});continue}let p=u.value;if(p==="__proto__")continue;let f=t.valueType._zod.run({value:s[l],issues:[]},o);if(f instanceof Promise)i.push(f.then((g)=>{if(g.issues.length)r.issues.push(...an(l,g.issues));r.value[p]=g.value}));else{if(f.issues.length)r.issues.push(...an(l,f.issues));r.value[p]=f.value}}if(c&&c.length>0)r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}if(i.length)return Promise.all(i).then(()=>r);return r}});var ig=S("$ZodEnum",(e,t)=>{ee.init(e,t);let n=Fr(t.entries),r=new Set(n);e._zod.values=r,Z(e,"pattern",(o)=>{let s=Fr(o.def.entries).filter((i)=>Yd.has(typeof i));return new RegExp(s.length?`^(${s.map((i)=>sn(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,s)=>{let i=o.value;if(r.has(i))return o;return o.issues.push({code:"invalid_value",values:n,input:i,inst:e}),o}}),ag=S("$ZodLiteral",(e,t)=>{ee.init(e,t);let n=new Set(t.values);e._zod.values=n,Z(e,"pattern",(r)=>{let o=r.def.values;return new RegExp(o.length?`^(${o.map((s)=>typeof s==="string"?sn(s):s?sn(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,o)=>{let s=r.value;if(n.has(s))return r;return r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}});var cg=S("$ZodTransform",(e,t)=>{ee.init(e,t),e._zod.optin="optional",De.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Ur(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then((i)=>(n.value=i,n));if(o instanceof Promise)throw new Rt;return n.value=o,n}});function hf(e,t){return e.value=t.issues.length?void 0:t.value,e}var ec=S("$ZodOptional",(e,t)=>{ee.init(e,t),Z(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",Z(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),Z(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${es(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((s)=>hf(n,s));return hf(n,o)}return t.innerType._zod.run(n,r)}}),lg=S("$ZodExactOptional",(e,t)=>{ec.init(e,t),Z(e,"values",(n)=>n.def.innerType._zod.values),Z(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),ug=S("$ZodNullable",(e,t)=>{ee.init(e,t),Z(e,"optin",(n)=>n.def.innerType._zod.optin),Z(e,"optout",(n)=>n.def.innerType._zod.optout),Z(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${es(r.source)}|null)$`):void 0}),Z(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),dg=S("$ZodDefault",(e,t)=>{ee.init(e,t),e._zod.optin="defaulted",Z(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>mf(s,t));return mf(o,t)}});function mf(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var pg=S("$ZodPrefault",(e,t)=>{ee.init(e,t),e._zod.optin="defaulted",Z(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),fg=S("$ZodNonOptional",(e,t)=>{ee.init(e,t),Z(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(n,r)=>{let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>kf(s,e));return kf(o,e)}});function kf(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function yf(e,t,n,r){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((o)=>_t(o,r,He()))},input:e.value}),e}var gg=S("$ZodCatch",(e,t)=>{ee.init(e,t),Z(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),Z(e,"optout",(n)=>n.def.innerType._zod.optout),Z(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((s)=>yf(n,s,t,r));return yf(n,o,t,r)}});var hg=S("$ZodPipe",(e,t)=>{ee.init(e,t),Z(e,"values",(n)=>n.def.in._zod.values),Z(e,"optin",(n)=>n.def.in._zod.optin),Z(e,"optout",(n)=>n.def.out._zod.optout),Z(e,"propValues",(n)=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=t.out._zod.run(n,r);if(s instanceof Promise)return s.then((i)=>ps(i,t.in,r));return ps(s,t.in,r)}let o=t.in._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>ps(s,t.out,r));return ps(o,t.out,r)}});function ps(e,t,n){if(e.issues.some((r)=>r.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var mg=S("$ZodReadonly",(e,t)=>{ee.init(e,t),Z(e,"propValues",(n)=>n.def.innerType._zod.propValues),Z(e,"values",(n)=>n.def.innerType._zod.values),Z(e,"optin",(n)=>n.def.innerType?._zod?.optin),Z(e,"optout",(n)=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then(vf);return vf(o)}});function vf(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var kg=S("$ZodCustom",(e,t)=>{Se.init(e,t),ee.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then((s)=>wf(s,n,r,e));wf(o,n,r,e);return}});function wf(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)o.params=r._zod.def.params;t.issues.push(Ln(o))}}class vg extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var nc="~memo",yg=[];function wg(e){return e!==null&&typeof e==="object"}function tc(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var bg=new WeakMap,Gr=0,vs=1,Vr=2;function ws(e,t,n){let r=bg.get(e);if(r!==void 0)return r?Vr:Gr;if(t.has(e))return Vr;t.add(e);let o=Gr,s=(u)=>{if(o!==Vr&&u?._zod){let d=ws(u,t,n);if(d>o)o=d}},i=(u,d)=>{let p=Gr;for(let f of Reflect.ownKeys(u)){let g=Object.getOwnPropertyDescriptor(u,f);if(d&&!g.enumerable)continue;let h=g.get?vs:g.value?._zod?ws(g.value,t,n):Gr;if(h>p)p=h}return p},a=(u)=>{if(u>o)o=u},c=e._zod.def,l=c.type;switch(l){case"object":{let u=Zr(c);a(u?i(u,!0):vs),s(c.catchall);break}case"array":s(c.element);break;case"tuple":for(let u of c.items)s(u);s(c.rest);break;case"record":case"map":s(c.keyType),s(c.valueType);break;case"set":s(c.valueType);break;case"union":for(let u of c.options)s(u);break;case"intersection":s(c.left),s(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(c.innerType);break;case"pipe":s(c.in),s(c.out);break;case"function":s(c.input),s(c.output);break;case"lazy":{let u=c._cachedInner??(n?e._zod.innerType:void 0);a(u?ws(u,t,!1):vs);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let u in c){let d=Object.getOwnPropertyDescriptor(c,u);if(!d||d.get)continue;let p=d.value;if(!p||typeof p!=="object")continue;if(p._zod)s(p);else if(Array.isArray(p))for(let f of p)s(f)}}return t.delete(e),d_(e,o)}function d_(e,t){if(t!==vs)bg.set(e,t===Vr);return t}function p_(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var ks,ys=[],f_={alloc(e,t,n){let r=ks;if(!r)return n;ks=void 0;let o={value:n,issues:null};return r.set(t.value,o),ys.push(o),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(o,s)=>{if(s.direction!=="backward"&&g_(s,o.value))throw new vg;return n(o,s)};if(e._zod.parse=r,e._zod.run===n)e._zod.run=r})},attach(e){var t;let n,r=!1,o,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,a=(c,l)=>{if(n===void 0){let m=ws(e,new Set,!1);if(m===Gr){if(e._zod.parse=i,e._zod.run===a)e._zod.run=i;return i(c,l)}if(m===Vr||r)n=!0;else r=!0}let u=c.value;if(!wg(u))return i(c,l);let d=l[nc];if(!d)d={buckets:new WeakMap,backEdges:void 0},l[nc]=d;let p;if(o===l)p=s;else p=p_(d,e),o=l,s=p;let f=p.get(u);if(f){if(c.value=f.value,f.issues){if(f.issues.length)c.issues.push(...tc(f.issues))}else c.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(f.value);return c}ks=p;let g=ys.length,h=i(c,l);ks=void 0;let v=ys.length>g?ys.pop():void 0;if(h instanceof Promise)return h.then((m)=>{if(v)v.issues=m.issues.length?tc(m.issues):yg;return m});if(v)v.issues=h.issues.length?tc(h.issues):yg;return h};if(e._zod.parse=a,e._zod.run===i)e._zod.run=a})}};function xg(){return f_}function g_(e,t){let n=e[nc]?.backEdges;return n!==void 0&&wg(t)&&n.has(t)}var h_=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(s){return e[s]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function o(s,i){if(s==="number"&&typeof i==="number"&&!Number.isFinite(i))return String(i);return r[s]??s}return(s)=>{switch(s.code){case"invalid_type":{let i=o(s.expected),a=rp(s.input),c=o(a,s.input);return`Invalid input: expected ${i}, received ${c}`}case"invalid_value":if(s.values.length===1)return`Invalid input: expected ${za(s.values[0])}`;return`Invalid option: expected one of ${Ca(s.values,"|")}`;case"too_big":{let i=s.exact?"exactly ":s.inclusive?"<=":"<",a=t(s.origin);if(a)return`Too big: expected ${s.origin??"value"} to have ${i}${s.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${s.origin??"value"} to be ${i}${s.maximum.toString()}`}case"too_small":{let i=s.exact?"exactly ":s.inclusive?">=":">",a=t(s.origin);if(a)return`Too small: expected ${s.origin} to have ${i}${s.minimum.toString()} ${a.unit}`;return`Too small: expected ${s.origin} to be ${i}${s.minimum.toString()}`}case"invalid_format":{let i=s;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${n[i.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${Ca(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":if(s.options&&Array.isArray(s.options)&&s.options.length>0)return`Invalid discriminator value. Expected ${s.options.map((a)=>`'${a}'`).join(" | ")}`;if(s.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function rc(){return{localeError:h_()}}var Sg;class _g{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function m_(){return new _g}(Sg=globalThis).__zod_globalRegistry??(Sg.__zod_globalRegistry=m_());var Dn=globalThis.__zod_globalRegistry;function Rg(e){if(e.checks)e.checks=[...e.checks];return e}function $g(e,t){return new e(Rg({type:"string",...z(t)}))}function Ig(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...z(t)})}function Tg(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...z(t)})}function Og(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...z(t)})}function Eg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...z(t)})}function Cg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...z(t)})}function Ag(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...z(t)})}function Pg(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...z(t)})}function zg(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...z(t)})}function Ng(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...z(t)})}function Lg(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...z(t)})}function Dg(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...z(t)})}function jg(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...z(t)})}function Wg(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...z(t)})}function Mg(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...z(t)})}function Fg(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...z(t)})}function Bg(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...z(t)})}function Hg(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...z(t)})}function Zg(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...z(t)})}function Ug(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...z(t)})}function Kg(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...z(t)})}function qg(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...z(t)})}function Jg(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...z(t)})}function Gg(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...z(t)})}function Vg(e,t){return new e({type:"string",format:"date",check:"string_format",...z(t)})}function Xg(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...z(t)})}function Yg(e,t){return new e({type:"string",format:"duration",check:"string_format",...z(t)})}function Qg(e,t){return new e(Rg({type:"number",checks:[],...z(t)}))}function eh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...z(t)})}function th(e,t){return new e({type:"boolean",...z(t)})}function nh(e){return new e({type:"unknown"})}function rh(e,t){return new e({type:"never",...z(t)})}function bs(e,t){return new Ka({check:"less_than",...z(t),value:e,inclusive:!1})}function Xr(e,t){return new Ka({check:"less_than",...z(t),value:e,inclusive:!0})}function xs(e,t){return new qa({check:"greater_than",...z(t),value:e,inclusive:!1})}function Yr(e,t){return new qa({check:"greater_than",...z(t),value:e,inclusive:!0})}function Ss(e,t){return new Vp({check:"multiple_of",...z(t),value:e})}function _s(e,t){return new Yp({check:"max_length",...z(t),maximum:e})}function or(e,t){return new Qp({check:"min_length",...z(t),minimum:e})}function Rs(e,t){return new ef({check:"length_equals",...z(t),length:e})}function oc(e,t){return new tf({check:"string_format",format:"regex",...z(t),pattern:e})}function sc(e){return new nf({check:"string_format",format:"lowercase",...z(e)})}function ic(e){return new rf({check:"string_format",format:"uppercase",...z(e)})}function ac(e,t){return new of({check:"string_format",format:"includes",...z(t),includes:e})}function cc(e,t){return new sf({check:"string_format",format:"starts_with",...z(t),prefix:e})}function lc(e,t){return new af({check:"string_format",format:"ends_with",...z(t),suffix:e})}function cn(e){return new cf({check:"overwrite",tx:e})}function uc(e){return cn((t)=>t.normalize(e))}function dc(){return cn((e)=>e.trim())}function pc(){return cn((e)=>e.toLowerCase())}function fc(){return cn((e)=>e.toUpperCase())}function gc(){return cn((e)=>Vd(e))}function oh(e,t,n){return new e({type:"array",element:t,...z(n)})}function sh(e,t,n){let r=z(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function ih(e,t,n){return new e({type:"custom",check:"custom",fn:t,...z(n)})}function ah(e,t){let n=k_((r)=>(r.addIssue=(o)=>{if(typeof o==="string")r.issues.push(Ln(o,r.value,n._zod.def));else{let s=o;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=r.value;s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(Ln(s))}},e(r.value,r)),t);return n}function k_(e,t){let n=new Se({check:"custom",...z(t)});return n._zod.check=e,n}function Qr(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,r))et(e,r,n[r]);return e}function mc(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Dn,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Dt(e,t,n,r,o){let s=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:r.path,message:o}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw Error(o);return Object.assign(n,s),!0}function ae(e,t,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,n.schemaPath.includes(e))s.cycle=n.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let u={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,u);else{let p=i.schema,f=t.processors[o.type];if(!f)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(e,t,p,u)}let d=e._zod.parent;if(d){if(!i.ref)i.ref=d;ae(d,t,u),t.seen.get(d).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Qr(i.schema,c);if(t.io==="input"&&Pe(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(r=i.schema).default??(r.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function ch(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function kc(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let c=r.get(a);if(c&&c!==i[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}let o=(i)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(i[0])?.id,p=e.external.uri??((g)=>g);if(d)return{ref:p(d)};let f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${ch(f)}`}}let c="#",l=`${c}/${a}/`;if(i[1]===n&&!i[1].schema.id)return{ref:c};let u=i[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:l+ch(u)}},s=(i)=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:l}=o(i);if(a.def={...a.schema},l)a.defId=l;let u=a.schema;for(let d in u)delete u[d];u.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
59
59
 
60
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let l=e.external.registry.get(i[0])?.id;if(t!==i[0]&&l){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref")s(i)}}if(e.external)e.sharedDefsExtractedFor=e.external}function dh(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!=="object")return;dh(r);let o=Object.keys(r);if(o.length!==1||o[0]!=="type")return;let s=r.type;for(let i of Array.isArray(s)?s:[s]){if(typeof i!=="string")return;if(!n.includes(i))n.push(i)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ph=new Set(["type","properties","required","additionalProperties"]),lh=["oneOf","anyOf"];function uh(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function hc(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let i in s)if(!ph.has(i))return null;t.push(s)}let n={},r=new Set;for(let s of t){for(let i in s.properties){if(Object.prototype.hasOwnProperty.call(n,i))continue;let a=[];for(let l of t){let u=l.properties?.[i]??uh(l);if(u===null||u===void 0)continue;if(!a.some((d)=>JSON.stringify(d)===JSON.stringify(u)))a.push(u)}let c=a.length===1?a[0]:hc(a)??{allOf:a};et(n,i,c)}for(let i of s.required??[])r.add(i)}let o={type:"object",properties:n};if(r.size)o.required=[...r];if(t.every((s)=>s.additionalProperties===!1))o.additionalProperties=!1;else{let s=[];for(let i of t){let a=uh(i);if(a&&!s.some((c)=>JSON.stringify(c)===JSON.stringify(a)))s.push(a)}if(s.length===1)o.additionalProperties=s[0];else if(s.length>1)o.additionalProperties={allOf:s}}return o}function y_(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of ph)if(o in e)return;let n=t.filter((o)=>lh.some((s)=>Array.isArray(o[s]))),r=null;if(!n.length)r=hc(t);else{let o=n[0],s=lh.find((c)=>Array.isArray(o[c]));if(Object.keys(o).length!==1)return;let i=t.filter((c)=>c!==o),a=o[s].map((c)=>hc([...i,c]));if(a.some((c)=>!c))return;r={[s]:a}}if(!r)return;delete e.allOf,Qr(e,r)}function yc(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,u={...l},d=c.ref;if(c.ref=null,d){r(d);let f=e.seen.get(d),g=f.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(g);else Qr(l,g);if(Qr(l,u),a._zod.parent===d)for(let v in l){if(v==="$ref"||v==="allOf")continue;if(!(v in u))delete l[v]}if(g.$ref&&f.def)for(let v in l){if(v==="$ref"||v==="allOf")continue;if(v in f.def&&JSON.stringify(l[v])===JSON.stringify(f.def[v]))delete l[v]}}let p=a._zod.parent;if(p&&p!==d){r(p);let f=e.seen.get(p);if(f?.schema.$ref){if(l.$ref=f.schema.$ref,f.def)for(let g in l){if(g==="$ref"||g==="allOf")continue;if(g in f.def&&JSON.stringify(l[g])===JSON.stringify(f.def[g]))delete l[g]}}}e.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())r(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())dh(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let l of[c.schema,c.def]){let u=l?.allOf;if(!Array.isArray(u))continue;let d=a.get(u);if(d)d.push(l);else a.set(u,[l])}for(let c of e.intersections)for(let l of a.get(c)??[])y_(l)}}let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Qr(o,n.defId?n.schema:n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&o.id===s)delete o.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;et(i,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")o.$defs=i;else o.definitions=i;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:eo(t,"input",e.processors),output:eo(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Pe(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Pe(r.element,n);if(r.type==="set")return Pe(r.valueType,n);if(r.type==="lazy")return Pe(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return Pe(r.innerType,n);if(r.type==="intersection")return Pe(r.left,n)||Pe(r.right,n);if(r.type==="record"||r.type==="map")return Pe(r.keyType,n)||Pe(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Pe(r.in,n)||Pe(r.out,n)}if(r.type==="object"){for(let o in r.shape)if(Pe(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(Pe(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(Pe(o,n))return!0;if(r.rest&&Pe(r.rest,n))return!0;return!1}return!1}var fh=(e,t={})=>(n)=>{let r=mc({...n,processors:t});return ae(e,r),kc(r,e),yc(r,e)},eo=(e,t,n={})=>(r)=>{let{libraryOptions:o,target:s}=r??{},i=mc({...o??{},target:s,io:t,processors:n});return ae(e,i),kc(i,e),yc(i,e)};var sr=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},ir=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},gh=(e,t)=>{sr(e,"minimum",t),ir(e,"maximum",t)},yh=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},vh=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},wh=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},bh=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},hh=(e,t)=>sr(e,"minimum",t.minimum),mh=(e,t)=>ir(e,"maximum",t.maximum),kh=(e)=>(t,n)=>{bh(t,n.format);let[r,o]=e[n.format];sr(t,"minimum",r),ir(t,"maximum",o)},v_={greater_than:(e,t)=>sr(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>ir(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>yh(e,t.value),number_format:kh(ts),bigint_format:kh(Na),min_length:hh,max_length:mh,length_equals:(e,t)=>gh(e,t.length),min_size:hh,max_size:mh,size_equals:(e,t)=>gh(e,t.size),string_format:(e,t)=>{if(bh(e,t.format),t.pattern)vh(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>wh(e,t.mime)};function tt(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let s of r)v_[s._zod.def.check]?.(t,s._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)sr(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)sr(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)ir(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)ir(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)yh(t,o.multipleOf);if(o.format!==void 0){if(t.format??(t.format=o.format),o.format.includes("int"))t.isInt=!0}if(o.mime)wh(t,o.mime);for(let s of o.patterns??[])vh(t,s);return t}var w_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},b_=new Map([[Xa,jp],[ms,Wp]]),xh=(e)=>b_.get(e)??e,Sh=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:l,laxFormat:u}=tt(e);if(typeof s==="number")o.minLength=s;if(typeof i==="number")o.maxLength=i;if(a){if(o.format=w_[a]??a,o.format==="")delete o.format;if(a==="time"||u)delete o.format}if(l)o.contentEncoding=l;if(c&&c.size>0){let d=[...c].map(xh);if(d.length===1)o.pattern=d[0].source;else if(d.length>1)o.allOf=[...d.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},_h=(e,t,n,r)=>{let o=n,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=tt(e);o.type=u?"integer":"number";let d=typeof l==="number"&&l>=(s??Number.NEGATIVE_INFINITY),p=typeof c==="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(d)if(f)o.minimum=l,o.exclusiveMinimum=!0;else o.exclusiveMinimum=l;else if(typeof s==="number")o.minimum=s;if(p)if(f)o.maximum=c,o.exclusiveMaximum=!0;else o.exclusiveMaximum=c;else if(typeof i==="number")o.maximum=i;if(a){let g=new Set;for(let m of a)if(Number.isFinite(m)&&m!==0)g.add(Math.abs(m));else Dt(e,t,o,r,`A multipleOf divisor of ${m} cannot be represented in JSON Schema`);let[h,...v]=g;if(h!==void 0)o.multipleOf=h;if(v.length)o.allOf=[...o.allOf??[],...v.map((m)=>({multipleOf:m}))]}},Rh=(e,t,n,r)=>{n.type="boolean"};var $h=(e,t,n,r)=>{n.not={}};var Ih=(e,t,n,r)=>{};var Th=(e,t,n,r)=>{let o=e._zod.def,s=Fr(o.entries);if(s.length===0){n.not={};return}if(s.every((i)=>typeof i==="number"))n.type="number";if(s.every((i)=>typeof i==="string"))n.type="string";n.enum=s},Oh=(e,t,n,r)=>{let o=e._zod.def;if(o.values.length===0){n.not={};return}let s=[];for(let i of o.values)if(i===void 0){if(Dt(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i==="bigint"){if(Dt(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(i))}else s.push(i);if(s.length===0);else if(s.length===1){let i=s[0];if(n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[i];else n.const=i}else{if(s.every((i)=>typeof i==="number"))n.type="number";if(s.every((i)=>typeof i==="string"))n.type="string";if(s.every((i)=>typeof i==="boolean"))n.type="boolean";if(s.every((i)=>i===null))n.type="null";n.enum=s}};var Eh=(e,t,n,r)=>{Dt(e,t,n,r,"Custom types cannot be represented in JSON Schema")};var Ch=(e,t,n,r)=>{Dt(e,t,n,r,"Transforms cannot be represented in JSON Schema")};var Ah=(e,t,n,r)=>{let o=n,s=e._zod.def,{minimum:i,maximum:a}=tt(e);if(typeof i==="number")o.minItems=i;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=ae(s.element,t,{...r,path:[...r.path,"items"]})};function $s(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return $s(t.out);if(t.type==="catch")return $s(t.innerType);return e._zod.optin}var Ph=(e,t,n,r)=>{let o=n,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&Dt(e,t,o,r,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let l in i)et(o.properties,l,ae(i[l],t,{...r,path:[...r.path,"properties",l]}));let c=[];for(let l of Object.keys(i)){let u=s.shape[l];if(t.io==="input"?$s(u)===void 0:u._zod.optout===void 0)c.push(l)}if(c.length>0)o.required=c;if(s.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")o.additionalProperties=!1}else if(s.catchall)o.additionalProperties=ae(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},zh=(e,t,n,r)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>ae(a,t,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));if(s)n.oneOf=i;else n.anyOf=i},Nh=(e,t,n,r)=>{let o=e._zod.def,s=ae(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=ae(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c,t.intersections.push(c)};function vc(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let g=e.get(t)?.def;if(!g)return t;let h=vc(e,g,n);return h===g?t:h}for(let g of["anyOf","oneOf"]){let h=t[g];if(!Array.isArray(h))continue;let v=h.map((m)=>vc(e,m,n));if(v.some((m,y)=>m!==h[y]))t={...t,[g]:v}}let r=Array.isArray(t.type)?t.type:[t.type],o=!r.includes("string")&&r.some((g)=>g==="number"||g==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some((g)=>typeof g==="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:p,...f}=t;if(f.enum)f.enum=f.enum.map((g)=>typeof g==="number"?String(g):g);else if(typeof f.const==="number")f.const=String(f.const);if(!o)return f;if(f.type="string",!s)f.pattern=(r.includes("number")?Kr:Za).source;return f}var wc=new WeakMap;function x_(e){let t=new Map;for(let r of e.seen.values())if(r.def&&!t.has(r.schema))t.set(r.schema,r);let n=new Map;for(let r of wc.get(e)??[]){let o=e.seen.get(r),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||n.has(s))continue;let i=vc(t,s,new Set);if(i!==s)n.set(s,i)}if(!n.size)return;for(let r of e.seen.values())for(let o of[r.schema,r.def]){let s=o&&n.get(o.propertyNames);if(s)o.propertyNames=s}}var Lh=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object";let i=s.keyType,a=tt(i).patterns;if(s.mode==="loose"&&a&&a.size>0){let u=ae(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let d of a)et(o.patternProperties,xh(d).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=ae(s.keyType,t,{...r,path:[...r.path,"propertyNames"]});let u=wc.get(t);if(!u)u=[],wc.set(t,u),t.deferred.push(()=>x_(t));u.push(e)}o.additionalProperties=ae(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let c=i._zod.values,l=t.io==="input"&&$s(s.valueType)!==void 0;if(c&&!s.partial&&!l){let u=[...c].filter((d)=>typeof d==="string"||typeof d==="number");if(u.length>0)o.required=u.map(String)}},Dh=(e,t,n,r)=>{let o=e._zod.def,s=ae(o.innerType,t,r),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=o.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},jh=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},bc=Symbol();function Wh(e,t,n,r,o){let s=!1,i=JSON.stringify(e,(a,c)=>{if(typeof c!=="bigint")return c;return s=!0,null});if(!s)return JSON.parse(i);return Dt(t,n,r,o,"BigInt defaults cannot be represented in JSON Schema"),bc}var Mh=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i=Wh(o.defaultValue,e,t,n,r);if(i!==bc)n.default=i},Fh=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=Wh(o.defaultValue,e,t,n,r);if(i!==bc)n._prefault=i},Bh=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{Dt(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=i},Hh=(e,t,n,r)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;ae(i,t,r);let a=t.seen.get(e);a.ref=i},Zh=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0};var xc=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType};var Uh=new WeakSet([Object.prototype,Error.prototype]);function Is(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var E_=(e,t)=>{dp.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(Uh.has(n))return;Uh.add(n),Is(n,"format",(r)=>(o)=>fp(r,o)),Is(n,"flatten",(r)=>(o)=>pp(r,o)),Is(n,"addIssue",(r)=>(o)=>{r.issues.push(o),r.message=JSON.stringify(r.issues,Br,2)}),Is(n,"addIssues",(r)=>(o)=>{r.issues.push(...o),r.message=JSON.stringify(r.issues,Br,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var Ze=S("ZodError",E_,void 0,{Parent:Error});var Kh=as(Ze),qh=cs(Ze),Jh=ls(Ze),Gh=us(Ze),Vh=hp(Ze),Xh=mp(Ze),Yh=kp(Ze),Qh=yp(Ze),em=vp(Ze),tm=wp(Ze),nm=bp(Ze),rm=xp(Ze);function A_(){if(!De.localeError)He(rc())}function Os(){if(!De.memoizer)He({memoizer:xg()})}var re=S("ZodType",(e,t)=>(A_(),ee.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Be(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return xt(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(SR(e,t))},superRefine(e,t){return this.check(_R(e,t))},overwrite(e){return this.check(cn(e))},optional(){return im(this)},exactOptional(){return fR(this)},nullable(){return am(this)},nullish(){return im(am(this))},nonoptional(e){return kR(this,e)},array(){return P(this)},or(e){return $c([this,e])},and(e){return lR(this,e)},transform(e){return cm(this,pR(e))},default(e){return gR(this,e)},prefault(e){return mR(this,e)},catch(e){return vR(this,e)},pipe(e){return cm(this,e)},readonly(){return xR(this)},describe(e){let t=this.clone();return Dn.add(t,{description:e}),t},meta(...e){if(e.length===0)return Dn.get(this);let t=this.clone();return Dn.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return ss(this,"~standard",{...Va(this),jsonSchema:{input:eo(this,"input"),output:eo(this,"output")}})},set "~standard"(e){Lt(this,"~standard",e)},parse:function e(t,n){return Kh(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await qh(this,t,n,{callee:e})},safeParse(e,t){return Jh(this,e,t)},async safeParseAsync(e,t){return Gh(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Lt(this,"spa",e)},validate(e,t){return Ma(this,e,t)},validateAsync(e,t){return Fa(this,e,t)},encode:function e(t,n){return Vh(this,t,n,{callee:e})},decode:function e(t,n){return Xh(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Yh(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Qh(this,t,n,{callee:e})},safeEncode(e,t){return em(this,e,t)},safeDecode(e,t){return tm(this,e,t)},async safeEncodeAsync(e,t){return nm(this,e,t)},async safeDecodeAsync(e,t){return rm(this,e,t)},toJSONSchema(e){return fh(this,{})(e)},get description(){return Dn.get(this)?.description},get _def(){return this._zod.def}}),lm=S("_ZodString",(e,t)=>{hs.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sh(e,n,r,o)},sp({format:(e)=>tt(e).format??null,minLength:(e)=>tt(e).minimum??null,maxLength:(e)=>tt(e).maximum??null},{regex(...e){return this.check(oc(...e))},includes(...e){return this.check(ac(...e))},startsWith(...e){return this.check(cc(...e))},endsWith(...e){return this.check(lc(...e))},min(...e){return this.check(or(...e))},max(...e){return this.check(_s(...e))},length(...e){return this.check(Rs(...e))},nonempty(...e){return this.check(or(1,...e))},lowercase(e){return this.check(sc(e))},uppercase(e){return this.check(ic(e))},trim(){return this.check(dc())},normalize(...e){return this.check(uc(...e))},toLowerCase(){return this.check(pc())},toUpperCase(){return this.check(fc())},slugify(){return this.check(gc())}})),P_=S("ZodString",(e,t)=>{hs.init(e,t),lm.init(e,t)},{email(e){return this.check(Ig(j_,e))},url(e){return this.check(Pg(M_,e))},jwt(e){return this.check(Jg(tR,e))},emoji(e){return this.check(zg(F_,e))},guid(e){return this.check(Tg(W_,e))},uuid(e){return this.check(Og(Ts,e))},uuidv4(e){return this.check(Eg(Ts,e))},uuidv6(e){return this.check(Cg(Ts,e))},uuidv7(e){return this.check(Ag(Ts,e))},nanoid(e){return this.check(Ng(B_,e))},cuid(e){return this.check(Lg(H_,e))},cuid2(e){return this.check(Dg(Z_,e))},ulid(e){return this.check(jg(U_,e))},base64(e){return this.check(Ug(Y_,e))},base64url(e){return this.check(Kg(Q_,e))},xid(e){return this.check(Wg(K_,e))},ksuid(e){return this.check(Mg(q_,e))},ipv4(e){return this.check(Fg(J_,e))},ipv6(e){return this.check(Bg(G_,e))},cidrv4(e){return this.check(Hg(V_,e))},cidrv6(e){return this.check(Zg(X_,e))},e164(e){return this.check(qg(eR,e))},datetime(e){return this.check(Gg(z_,e))},date(e){return this.check(Vg(N_,e))},time(e){return this.check(Xg(L_,e))},duration(e){return this.check(Yg(D_,e))}});function nt(e){return $g(P_,e)}var oe=S("ZodStringFormat",(e,t)=>{Q.init(e,t),lm.init(e,t)}),z_=S("ZodISODateTime",(e,t)=>{Nf.init(e,t),oe.init(e,t)}),N_=S("ZodISODate",(e,t)=>{Lf.init(e,t),oe.init(e,t)}),L_=S("ZodISOTime",(e,t)=>{Df.init(e,t),oe.init(e,t)}),D_=S("ZodISODuration",(e,t)=>{jf.init(e,t),oe.init(e,t)}),j_=S("ZodEmail",(e,t)=>{_f.init(e,t),oe.init(e,t)});var W_=S("ZodGUID",(e,t)=>{xf.init(e,t),oe.init(e,t)});var Ts=S("ZodUUID",(e,t)=>{Sf.init(e,t),oe.init(e,t)});var M_=S("ZodURL",(e,t)=>{If.init(e,t),oe.init(e,t)});var F_=S("ZodEmoji",(e,t)=>{Tf.init(e,t),oe.init(e,t)});var B_=S("ZodNanoID",(e,t)=>{Of.init(e,t),oe.init(e,t)});var H_=S("ZodCUID",(e,t)=>{Ef.init(e,t),oe.init(e,t)});var Z_=S("ZodCUID2",(e,t)=>{Cf.init(e,t),oe.init(e,t)});var U_=S("ZodULID",(e,t)=>{Af.init(e,t),oe.init(e,t)});var K_=S("ZodXID",(e,t)=>{Pf.init(e,t),oe.init(e,t)});var q_=S("ZodKSUID",(e,t)=>{zf.init(e,t),oe.init(e,t)});var J_=S("ZodIPv4",(e,t)=>{Wf.init(e,t),oe.init(e,t)});var G_=S("ZodIPv6",(e,t)=>{Ff.init(e,t),oe.init(e,t)});var V_=S("ZodCIDRv4",(e,t)=>{Bf.init(e,t),oe.init(e,t)});var X_=S("ZodCIDRv6",(e,t)=>{Hf.init(e,t),oe.init(e,t)});var Y_=S("ZodBase64",(e,t)=>{Uf.init(e,t),oe.init(e,t)});var Q_=S("ZodBase64URL",(e,t)=>{Kf.init(e,t),oe.init(e,t)});var eR=S("ZodE164",(e,t)=>{qf.init(e,t),oe.init(e,t)});var tR=S("ZodJWT",(e,t)=>{Jf.init(e,t),oe.init(e,t)});var um=S("ZodNumber",(e,t)=>{Ya.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>_h(e,n,r,o),e.isFinite=!0},sp({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=tt(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=tt(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=tt(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>tt(e).format??null},{gt(e,t){return this.check(xs(e,t))},gte(e,t){return this.check(Yr(e,t))},min(e,t){return this.check(Yr(e,t))},lt(e,t){return this.check(bs(e,t))},lte(e,t){return this.check(Xr(e,t))},max(e,t){return this.check(Xr(e,t))},int(e){return this.check(om(e))},safe(e){return this.check(om(e))},positive(e){return this.check(xs(0,e))},nonnegative(e){return this.check(Yr(0,e))},negative(e){return this.check(bs(0,e))},nonpositive(e){return this.check(Xr(0,e))},multipleOf(e,t){return this.check(Ss(e,t))},step(e,t){return this.check(Ss(e,t))},finite(){return this}}));function to(e){return Qg(um,e)}var nR=S("ZodNumberFormat",(e,t)=>{Gf.init(e,t),um.init(e,t)});function om(e){return eh(nR,e)}var rR=S("ZodBoolean",(e,t)=>{Vf.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rh(e,n,r,o)});function ue(e){return th(rR,e)}var oR=S("ZodUnknown",(e,t)=>{Xf.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ih(e,n,r,o)});function pt(){return nh(oR)}var sR=S("ZodNever",(e,t)=>{Yf.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$h(e,n,r,o)});function iR(e){return rh(sR,e)}var Rc=S("ZodArray",(e,t)=>{Os(),Qf.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ah(e,n,r,o),e.element=t.element},{min(e,t){return this.check(or(e,t))},nonempty(e){return this.check(or(1,e))},max(e,t){return this.check(_s(e,t))},length(e,t){return this.check(Rs(e,t))},unwrap(){return this.element}});function P(e,t){return oh(Rc,e,t)}var Es=S("ZodObject",(e,t)=>{Os(),ng.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ph(e,n,r,o),MS(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return B(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Be(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Be(this._zod.def,{catchall:pt()}))},loose(){return this.clone(Be(this._zod.def,{catchall:pt()}))},strict(){return this.clone(Be(this._zod.def,{catchall:iR()}))},strip(){return this.clone(Be(this._zod.def,{catchall:void 0}))},extend(e){return AS(this,e)},safeExtend(e){return PS(this,e)},merge(e){return zS(this,e)},pick(e){return ES(this,e)},omit(e){return CS(this,e)},partial(...e){return tp(no,this,e[0])},exactPartial(...e){return tp(fm,this,e[0],"exactPartial")},required(...e){return NS(gm,this,e[0])}});function C(e,t){let n={type:"object",shape:e??{},...z(t)};return new Es(n)}function dm(e,t){return new Es({type:"object",shape:e,catchall:pt(),...z(t)})}var pm=S("ZodUnion",(e,t)=>{Qa.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>zh(e,n,r,o),e.options=t.options});function $c(e,t){return new pm({type:"union",options:e,...z(t)})}var aR=S("ZodDiscriminatedUnion",(e,t)=>{pm.init(e,t),rg.init(e,t)});function ft(e,t,n){return new aR({type:"union",options:t,discriminator:e,...z(n)})}var cR=S("ZodIntersection",(e,t)=>{og.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Nh(e,n,r,o)});function lR(e,t){return new cR({type:"intersection",left:e,right:t})}var sm=S("ZodRecord",(e,t)=>{Os(),sg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Lh(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function ar(e,t,n){if(!t||!t._zod)return new sm({type:"record",keyType:nt(),valueType:e,...z(t)});return new sm({type:"record",keyType:e,valueType:t,...z(n)})}var _c=S("ZodEnum",(e,t)=>{ig.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,s)=>Th(e,r,o,s),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new _c({...t,checks:[],...z(o),entries:s})},e.exclude=(r,o)=>{let s={...t.entries};for(let i of r)if(n.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new _c({...t,checks:[],...z(o),entries:s})}});function B(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new _c({type:"enum",entries:n,...z(t)})}var uR=S("ZodLiteral",(e,t)=>{ag.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Oh(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function M(e,t){return new uR({type:"literal",values:Array.isArray(e)?e:[e],...z(t)})}var dR=S("ZodTransform",(e,t)=>{Os(),cg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ch(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Ur(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(Ln(s,n.value,t));else{let i=s;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=n.value;i.inst??(i.inst=e),n.issues.push(Ln(i))}};let o=t.transform(n.value,n);if(o instanceof Promise)return o.then((s)=>(n.value=s,n));return n.value=o,n}});function pR(e){return new dR({type:"transform",transform:e})}var no=S("ZodOptional",(e,t)=>{ec.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xc(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function im(e){return new no({type:"optional",innerType:e})}var fm=S("ZodExactOptional",(e,t)=>{lg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xc(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function fR(e){return new fm({type:"optional",innerType:e})}var Cs=S("ZodNullable",(e,t)=>{ug.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Dh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function am(e){return new Cs({type:"nullable",innerType:e})}var As=S("ZodDefault",(e,t)=>{dg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Mh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function gR(e,t){return new As({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Pa(t)}})}var hR=S("ZodPrefault",(e,t)=>{pg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Fh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function mR(e,t){return new hR({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Pa(t)}})}var gm=S("ZodNonOptional",(e,t)=>{fg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>jh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function kR(e,t){return new gm({type:"nonoptional",innerType:e,...z(t)})}var yR=S("ZodCatch",(e,t)=>{gg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Bh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function vR(e,t){return new yR({type:"catch",innerType:e,catchValue:typeof t==="function"?t:ip(t)})}var wR=S("ZodPipe",(e,t)=>{hg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hh(e,n,r,o),e.in=t.in,e.out=t.out});function cm(e,t){return new wR({type:"pipe",in:e,out:t})}var bR=S("ZodReadonly",(e,t)=>{mg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Zh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function xR(e){return new bR({type:"readonly",innerType:e})}var hm=S("ZodCustom",(e,t)=>{kg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Eh(e,n,r,o)});function mm(e,t){return sh(hm,e??(()=>!0),t)}function SR(e,t={}){return ih(hm,e,t)}function _R(e,t){return ah(e,t)}var F=nt().refine((e)=>e.trim().length>0,"must not be blank"),bm=mm((e)=>typeof e==="string"&&Object.hasOwn(Qe,e),"unsupported branch preset"),TR=mm((e)=>typeof e==="string"&&Vo.includes(e),"unsupported commit preset"),Oc=C({preset:bm,developBranch:F.optional(),prefixes:C({feature:F,bugfix:F,release:F,hotfix:F}).passthrough().optional(),allowed:P(F).optional(),protected:P(F).optional(),integration:B(["pr","merge"]).optional()}).strict(),Ec=C({preset:TR,pattern:nt().optional()}).strict(),OR=C({branchPolicy:Oc.optional(),commitPolicy:Ec.optional()}).strict().refine((e)=>e.branchPolicy!==void 0||e.commitPolicy!==void 0,{message:"a profile must define branchPolicy or commitPolicy"}),ER=ft("kind",[C({kind:M("package-json"),path:F,field:F}).strict(),C({kind:M("git-tag")}).strict(),C({kind:M("manual")}).strict()]),CR=C({strategy:bm.optional(),productionBranch:F,integrationBranch:F,naming:C({feature:F.optional(),release:F.optional(),hotfix:F.optional()}).passthrough().optional(),baseBranch:F.optional(),mergeBackBranches:P(F).optional(),pullRequestTarget:F.optional(),tagNamespace:nt().optional(),versionSource:ER.optional(),requiredChecks:P(F).optional(),critical:P(F).optional()}).passthrough().superRefine((e,t)=>{for(let[n,r]of[["mergeBackBranches",e.mergeBackBranches??[]],["requiredChecks",e.requiredChecks??[]]])if(new Set(r).size!==r.length)t.addIssue({code:"custom",path:[n],message:"entries must be unique"});if(e.versionSource?.kind==="package-json"&&(ln.posix.isAbsolute(e.versionSource.path.replaceAll("\\","/"))||/^[A-Za-z]:\//u.test(e.versionSource.path.replaceAll("\\","/"))||e.versionSource.path.replaceAll("\\","/").split("/").includes("..")))t.addIssue({code:"custom",path:["versionSource","path"],message:"must stay inside the repository"})}),AR=C({name:F,glob:F,vcs:C({provider:B(["gitlab","github"]),defaultTargetBranch:F.optional(),tokenFile:F.optional(),account:F.optional()}).passthrough().optional(),autoApprove:$c([ue(),P(F)]).optional(),defaultEndpoint:pt().optional(),verification:B(["proportional","self","independent"]).optional(),delegation:pt().optional(),trailers:ue().optional(),liveSessionGuard:ue().optional(),fanout:C({tierModels:pt().optional()}).passthrough().optional(),models:C({roles:pt().optional()}).passthrough().optional(),autonomy:C(Object.fromEntries(["push","pr","merge","release","rerun"].map((e)=>[e,$c([ue(),M("verified")]).optional()]))).passthrough().optional(),youtrack:C({baseUrl:F.optional(),link_issues:ue().optional()}).passthrough().optional(),issues:C({provider:B(["github","gitlab","youtrack"]).optional(),link:ue().optional(),relation:pt().optional(),backlink:ue().optional(),link_on_pr:ue().optional()}).passthrough().optional(),branchPolicy:Oc.optional(),commitPolicy:Ec.optional(),defaultProfile:F.optional(),profiles:ar(F,OR).optional(),releaseTracks:ar(F,CR).optional()}).passthrough().superRefine((e,t)=>{if(e.defaultProfile!==void 0&&!Object.hasOwn(e.profiles??{},e.defaultProfile))t.addIssue({code:"custom",path:["defaultProfile"],message:"does not name a configured profile"})}),PR=C({workspaces:P(AR).optional(),models:C({roles:pt().optional()}).passthrough().optional()}).passthrough().superRefine((e,t)=>{let n=new Set;for(let[r,o]of(e.workspaces??[]).entries()){if(n.has(o.name))t.addIssue({code:"custom",path:["workspaces",r,"name"],message:`duplicate workspace name ${JSON.stringify(o.name)}`});n.add(o.name)}});var Ic=(e)=>IR("sha256").update(e??"<missing>").digest("hex"),xm=(e,t)=>{if(!Ra(e))return{status:"malformed",path:t,entries:[],error:`${t} is not a JSON object`};let n=PR.safeParse(e,{reportInput:!0});if(!n.success){let o=n.error.issues.map((s)=>{let i=String(s.path[s.path.length-1]??""),a=["provider","preset","strategy"].includes(i)&&typeof s.input==="string"?` (${JSON.stringify(s.input)})`:"";return`${s.path.map(String).join(".")||"workspaces"}: ${s.message}${a}`}).join("; ");return{status:"invalid",path:t,entries:[],error:`${t} has invalid workspace configuration: ${o}`}}for(let[o,s]of(n.data.workspaces??[]).entries()){let i=_m(s.glob);if(!i.ok)return{status:"invalid",path:t,entries:[],error:`${t} workspaces.${o}.glob: ${i.error}`}}let r=e;return{status:"valid",path:t,entries:r.workspaces??[],document:r}},Sm=(e=rn())=>{let t=ln.join(e,"workspaces.json"),n;try{n=Tc(t,"utf8")}catch(o){if(o.code==="ENOENT")return{status:"missing",path:t,entries:[],revision:Ic(null)};return{status:"malformed",path:t,entries:[],error:`${t} could not be read: ${o instanceof Error?o.message:String(o)}`}}let r;try{r=JSON.parse(n)}catch{return{status:"malformed",path:t,entries:[],revision:Ic(n),error:`${t} is not valid JSON`}}return{...xm(r,t),revision:Ic(n)}};var zR=(e)=>{let t="";for(let n=0;n<e.length;n++){let r=e[n];if(r==="*")if(e[n+1]==="*")if(e[n+2]==="/"){if(t==="")t+="/?";t+="(?:[^/]+/)*",n+=2}else{if(n+2>=e.length)if(t.endsWith("/"))t=t.slice(0,-1),t+="(?:/.*)?";else t+=".*";else t+=".*";n++}else t+="[^/]*";else t+=r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${t}$`)},vm=(e,t)=>zR(e.replaceAll("\\","/")).test(t.replaceAll("\\","/")),NR=/[?[\]{}]/,LR=/[@+*]\(|!/,_m=(e)=>{let t=e.trim();if(!t)return{ok:!1,error:"workspace pattern is required"};let n=NR.exec(t);if(n)return{ok:!1,error:`unsupported glob character ${JSON.stringify(n[0])} in workspace pattern ${JSON.stringify(e)} — the matcher supports * and ** only (e.g. /work/**)`};let r=LR.exec(t);if(r){let o=r[0];return{ok:!1,error:`unsupported glob ${o==="!"?"negation (!)":`extglob (${o})`} in workspace pattern ${JSON.stringify(e)} — the matcher supports * and ** only (e.g. /work/**)`}}return{ok:!0}};class Ue extends Error{name="WorkspaceConfigError"}var wm=new Map,DR=(e)=>{let t=wm.get(e);if(t!==void 0)return t;let n={...process.env};for(let c of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"])delete n[c];let r=(c)=>{let l=$R("git",c,{cwd:e,env:n,encoding:"utf8",timeout:5000,windowsHide:!0});return l.status===0?l.stdout:null},o=null,s=r(["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"]),[i,a]=(s??"").trim().split(/\r?\n/u);if(i&&a&&ln.resolve(i)!==ln.resolve(a))o=/^worktree (.+)$/mu.exec(r(["worktree","list","--porcelain"])??"")?.[1]?.trim()||(ln.basename(a)===".git"?ln.dirname(a):a);return wm.set(e,o),o},Rm=(e,t)=>{let n=(s)=>{let i=[s,$m(s)].map((a)=>a.replaceAll("\\","/"));return t.filter((a)=>{let c=a.glob.replaceAll("\\","/"),l=jR(c);return i.some((u)=>vm(c,u)||l!==c&&vm(l,u))})},r=n(e);if(r.length)return r;let o=DR(e);return o?n(o):r},$m=(e)=>{let t=ym.native??ym;try{return t(e)}catch{return e}},jR=(e)=>{let t=/[*?[\]{]/.exec(e),n=t?e.slice(0,t.index):e,r=t?e.slice(t.index):"";if(!n)return e;return $m(n.replace(/\/+$/,"")||"/")+(n.endsWith("/")?"/":"")+r},cr=(e)=>e.replaceAll("\\","/").split("/").filter((t)=>t.length>0&&!/[*?[\]{]/.test(t)).length;var Im=(e,t,n)=>{if(n!==void 0){let s=e.filter((i)=>i.name===n);if(s.length===1)return s[0];if(s.length>1)throw new Ue(`ambiguous workspace ${JSON.stringify(n)} for ${t}`);if(e.length>0)throw new Ue(`workspace ${JSON.stringify(n)} does not match ${t}; matching choices: ${e.map((i)=>i.name).join(", ")}`);throw new Ue(`workspace ${JSON.stringify(n)} does not match ${t}`)}if(e.length<2)return e[0];let r=Math.max(...e.map((s)=>cr(s.glob))),o=e.filter((s)=>cr(s.glob)===r);if(o.length>1)throw new Ue(`ambiguous workspace for ${t}; choose one of: ${o.map((s)=>s.name).join(", ")}`);return o[0]},WR=(e,t,n)=>{let r=Rm(e,t);return Im(r,e,n)??null},Tm=(e,t,n)=>{let r=Sm(t);if(r.status==="malformed"||r.status==="invalid")throw new Ue(r.error);return WR(e,r.entries,n)};var MR=(e)=>{let t=e==="branch"?"branchPolicy":e==="commit"?"commitPolicy":"vcs",n=e==="branch"?Oc:e==="commit"?Ec:C({provider:B(["gitlab","github"]),defaultTargetBranch:F.optional(),account:F.optional()}).passthrough(),r=C({[t]:n.optional()}).passthrough();return C({name:F,glob:F,[t]:n.optional(),defaultProfile:F.optional(),profiles:ar(F,r).optional()}).passthrough()},ro=(e)=>zm(e,"vcs"),FR=C({workspaces:P(C({name:F,glob:F}).passthrough()).optional()}).passthrough(),Ps=(e,t=rn())=>{let n=ln.join(t,"workspaces.json"),r;try{r=Tc(n,"utf8")}catch(u){if(u.code==="ENOENT")return null;throw new Ue(`${n} could not be read: ${u instanceof Error?u.message:String(u)}`,{cause:u})}let o;try{o=JSON.parse(r)}catch{throw new Ue(`${n} is not valid JSON`)}let s=FR.safeParse(o);if(!s.success){let u=s.error.issues.map((d)=>`${d.path.map(String).join(".")||"workspaces"}: ${d.message}`).join("; ");throw new Ue(`${n} has invalid workspace matching data: ${u}`)}let i=s.data.workspaces;for(let u of i??[]){let d=_m(u.glob);if(!d.ok)throw new Ue(`${n} workspace ${u.name}: ${d.error}`)}let a=Rm(e,i??[]),c=process.env.WORKFLOW_WORKSPACE_NAME?.trim()||void 0,l=Im(a,e,c);return l?{file:n,selected:l,matches:a}:null},Om=(e)=>{let t=Ps(e);return t?{workspace:t.selected.name,releaseTracks:t.selected.releaseTracks}:null},Em=(e,t,n)=>{let r;try{r=Ps(e,t)}catch{return null}if(!r)return null;let{selected:o,matches:s}=r,i=s.filter((a)=>a!==o).toSorted((a,c)=>cr(c.glob)-cr(a.glob));return{workspace:o.name,source:[o,...i].find(n)??null}},Cm=(e,t)=>{let n=Em(e,t,(r)=>typeof r.trailers==="boolean");return{enabled:n?.source?.trailers!==!1,workspace:n?.workspace??null,from:n?.source?.name??null}},Am=(e,t)=>Em(e,t,(n)=>typeof n.liveSessionGuard==="boolean")?.source?.liveSessionGuard!==!1;var Pm=(e,t)=>{let n=[];try{let r=Ps(e,t);if(r){let o=r.matches.filter((s)=>s!==r.selected).toSorted((s,i)=>cr(i.glob)-cr(s.glob));for(let s of[r.selected,...o])n.push({name:s.name,global:!1,models:s.models,tierModels:s.fanout?.tierModels})}}catch{}try{let r=JSON.parse(Tc(ln.join(t??rn(),"workspaces.json"),"utf8"));if(r&&typeof r==="object"&&!Array.isArray(r))n.push({name:"global",global:!0,models:r.models,tierModels:void 0})}catch{}return n},Cc=(e)=>e.replace(/_(?:cli|desktop)$/u,"");var zm=(e,t)=>{let n=Ps(e);if(!n)return null;let{file:r,selected:o}=n,s=MR(t).safeParse(o);if(!s.success){let i=s.error.issues.map((a)=>`${a.path.map(String).join(".")||"workspace"}: ${a.message}`).join("; ");throw new Ue(`${r} has invalid ${t} policy configuration: ${i}`)}return s.data},zs=(e,t,n)=>{let r=zm(e,t);if(!r)return{policy:void 0,source:"user-default"};let o=t==="branch"?"branchPolicy":"commitPolicy",s=n?.trim()||r.defaultProfile;if(r.defaultProfile&&!Object.hasOwn(r.profiles??{},r.defaultProfile))throw new Ue(`workspace ${JSON.stringify(r.name)} has no profile ${JSON.stringify(r.defaultProfile)}`);let i=s?r.profiles?.[s]:void 0;if(s&&!i)throw new Ue(`workspace ${JSON.stringify(r.name)} has no profile ${JSON.stringify(s)}`);let a=i?.[o],c=r[o];return{policy:a??c,source:a?`profile:${s}`:c?`workspace:${r.name}`:"user-default"}};function Ac(e,t){let n=ro(e),r=n?.branchPolicy??{},o=typeof r.preset==="string"&&Object.hasOwn(Qe,r.preset),s=zs(e,"branch",process.env.WORKFLOW_PROFILE?.trim()||void 0),i=Go(qo(),s.policy?{branchPolicy:s.policy}:null,()=>Qo(e)).defaultTargetBranch;return String(n?.vcs?.defaultTargetBranch??(o?i:t??i)??"develop")}import i$ from"node:fs";import Ym from"node:path";import{spawnSync as a$}from"node:child_process";import{createHash as KR}from"node:crypto";import{spawnSync as qR}from"node:child_process";import{spawnSync as Nm}from"node:child_process";import{createHash as Lm}from"node:crypto";import un from"node:fs";import BR from"node:os";import Ns from"node:path";var Dm=268435456,dn={local:20000,worktree:120000,network:15000},te=(e,t,n={})=>{let r=Nm("git",t,{cwd:e,encoding:"utf8",env:n.env??process.env,input:n.input,maxBuffer:Dm,timeout:n.timeoutMs??dn.local,killSignal:"SIGKILL",windowsHide:!0}),o=r.error;return{ok:r.status===0,stdout:r.stdout??"",stderr:r.stderr??"",timedOut:o?.code==="ETIMEDOUT"}},Ke=(e)=>{if(!e.ok)return null;let t=e.stdout.trim();return t?t:null},jt=(e)=>e.length>0&&!e.startsWith("-");function oo(e){return Ke(te(e,["rev-parse","--verify","-q","HEAD^{commit}"]))}var HR=(e)=>Ke(te(e,["mktree"],{input:""})),ZR=5242880,UR=(e,t)=>{un.copyFileSync(e,t);let{atimeNs:n,mtimeNs:r}=un.statSync(e,{bigint:!0}),o=(s)=>(Number(s/1000n)-1)/1e6;un.utimesSync(t,o(n),o(r))};function zc(e,t={}){let n=Ke(te(e,["rev-parse","--show-toplevel"])),r=Ke(te(e,["rev-parse","--path-format=absolute","--git-path","index"]));if(!n||!r)return null;let o=t.maxUntrackedBytes??ZR,s=t.timeoutMs??dn.worktree,i=un.mkdtempSync(Ns.join(BR.tmpdir(),"workit-tree-"));try{let a=Ns.join(i,"index");if(un.existsSync(r))UR(r,a);let c={...process.env,GIT_INDEX_FILE:a},l=te(n,["ls-files","--others","--exclude-standard","-z"],{env:c,timeoutMs:s});if(!l.ok)return null;let u=[];for(let h of l.stdout.split("\x00").filter(Boolean))try{let v=un.statSync(Ns.join(n,h));if(v.isFile()&&v.size>o)u.push({path:h,size:v.size,mtimeMs:Math.trunc(v.mtimeMs)})}catch{}if(u.sort((h,v)=>h.path<v.path?-1:h.path>v.path?1:0),!(u.length?te(n,["add","-A","--pathspec-from-file=-","--pathspec-file-nul"],{env:c,timeoutMs:s,input:[".",...u.map((h)=>`:(exclude,literal)${h.path}`)].join("\x00")}):te(n,["add","-A"],{env:c,timeoutMs:s})).ok)return null;let p=Ke(te(n,["write-tree"],{env:c,timeoutMs:s}));if(!p)return null;let f=Ke(te(n,["rev-parse","--verify","-q","HEAD^{tree}"]))??HR(n),g=u.length?`sha256:${Lm("sha256").update(JSON.stringify({tree:p,skipped:u})).digest("hex")}`:p;return{tree:p,key:g,dirty:p!==f||u.length>0,skipped:u}}finally{un.rmSync(i,{recursive:!0,force:!0})}}function Ds(e,t={}){let n=Ke(te(e,["rev-parse","--show-toplevel"]));if(!n)return null;let r=te(n,["status","--porcelain=v1","-z","--untracked-files=all","--no-renames","--ignore-submodules=dirty"],{env:{...process.env,GIT_OPTIONAL_LOCKS:"0"},timeoutMs:t.timeoutMs??dn.worktree});if(!r.ok)return null;let o=Lm("sha256");o.update(`${oo(n)??"unborn"}\x00`);for(let s of r.stdout.split("\x00")){if(s.length<4)continue;let i=s.slice(3),a=Ns.join(n,i),c="-";try{let l=un.lstatSync(a,{bigint:!0});if(c=`${l.mode.toString(8)}:${l.size}:${l.mtimeNs}`,l.isDirectory())c+=`:${oo(a)??"-"}`}catch{}o.update(`${s.slice(0,2)}\x00${i}\x00${c}\x00`)}return`sig:${o.digest("hex")}`}function Wt(e,t,n){if(!jt(t)||!jt(n))return null;return Ke(te(e,["merge-base",t,n]))}function jm(e,t,n){if(!jt(t)||!jt(n))return null;let r=te(e,["diff","-U3","--diff-algorithm=myers","--indent-heuristic","--no-color","--no-ext-diff","--no-textconv","--no-renames","--full-index","--src-prefix=a/","--dst-prefix=b/",`${t}...${n}`,"--"]);if(!r.ok||!r.stdout.trim())return null;let o=te(e,["patch-id","--stable"],{input:r.stdout});return Ke(o)?.split(/\s+/u)[0]??null}function Nc(e){return(te(e,["remote"]).stdout??"").split(/\r?\n/u).map((t)=>t.trim()).filter(Boolean)}function $t(e,t){if(!jt(t))return null;return Ke(te(e,["rev-parse","--verify","-q",`${t}^{commit}`]))}function Wm(e){return Ke(te(e,["symbolic-ref","-q","--short","refs/remotes/origin/HEAD"]))}function Lc(e,t){let n=Ls(e,t.fromFork,t.from),r=Ls(e,t.toFork,t.to);if(!n||!r)return null;let o=new Map(n.map((a)=>[a.path,a])),s=new Map(r.map((a)=>[a.path,a])),i=(a,c)=>a!==void 0&&c!==void 0&&a.oldMode===c.oldMode&&a.oldBlob===c.oldBlob&&a.newMode===c.newMode&&a.newBlob===c.newBlob;return[...new Set([...o.keys(),...s.keys()])].filter((a)=>!i(o.get(a),s.get(a))).toSorted()}function Dc(e,t){let n=Wt(e,t.fromBase,t.from),r=Wt(e,t.toBase,t.to);if(!n||!r)return!1;return Lc(e,{from:t.from,to:t.to,fromFork:n,toFork:r})?.length===0}var Mm=["-c","core.quotePath=false","diff","--no-color","--no-ext-diff","--no-textconv","--no-renames"],Fm=(e,t)=>{if(!jt(e)||t!==null&&!jt(t))return null;return t===null?[e]:[e,t]};function jc(e,t,n){let r=Fm(t,n);if(!r)return null;let o=te(e,[...Mm,"--numstat","-z",...r,"--"]);if(!o.ok)return null;let s=[];for(let i of o.stdout.split("\x00")){let a=/^(-|\d+)\t(-|\d+)\t(.+)$/su.exec(i.replace(/^\n/u,""));if(!a)continue;let c=a[1]==="-";s.push({path:a[3],added:c?0:Number(a[1]),deleted:c?0:Number(a[2]),binary:c})}return s}function Ls(e,t,n){let r=Fm(t,n);if(!r)return null;let o=te(e,[...Mm,"--raw","-z","--no-abbrev",...r,"--"]);if(!o.ok)return null;let s=o.stdout.split("\x00"),i=[];for(let a=0;a+1<s.length;a+=2){let c=/^:(\d{6}) (\d{6}) ([0-9a-f]+) ([0-9a-f]+) [A-Z]\d*$/u.exec(s[a].replace(/^\n/u,""));if(!c)return null;i.push({path:s[a+1],oldMode:c[1],newMode:c[2],oldBlob:c[3],newBlob:c[4]})}return i}function Wc(e,t){let n=new Map,r=[...new Set(t)].filter((a)=>/^[0-9a-f]{40,64}$/u.test(a));if(!r.length)return n;let o=Nm("git",["cat-file","--batch"],{cwd:e,input:`${r.join(`
60
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let l=e.external.registry.get(i[0])?.id;if(t!==i[0]&&l){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref")s(i)}}if(e.external)e.sharedDefsExtractedFor=e.external}function dh(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!=="object")return;dh(r);let o=Object.keys(r);if(o.length!==1||o[0]!=="type")return;let s=r.type;for(let i of Array.isArray(s)?s:[s]){if(typeof i!=="string")return;if(!n.includes(i))n.push(i)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ph=new Set(["type","properties","required","additionalProperties"]),lh=["oneOf","anyOf"];function uh(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function hc(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let i in s)if(!ph.has(i))return null;t.push(s)}let n={},r=new Set;for(let s of t){for(let i in s.properties){if(Object.prototype.hasOwnProperty.call(n,i))continue;let a=[];for(let l of t){let u=l.properties?.[i]??uh(l);if(u===null||u===void 0)continue;if(!a.some((d)=>JSON.stringify(d)===JSON.stringify(u)))a.push(u)}let c=a.length===1?a[0]:hc(a)??{allOf:a};et(n,i,c)}for(let i of s.required??[])r.add(i)}let o={type:"object",properties:n};if(r.size)o.required=[...r];if(t.every((s)=>s.additionalProperties===!1))o.additionalProperties=!1;else{let s=[];for(let i of t){let a=uh(i);if(a&&!s.some((c)=>JSON.stringify(c)===JSON.stringify(a)))s.push(a)}if(s.length===1)o.additionalProperties=s[0];else if(s.length>1)o.additionalProperties={allOf:s}}return o}function y_(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of ph)if(o in e)return;let n=t.filter((o)=>lh.some((s)=>Array.isArray(o[s]))),r=null;if(!n.length)r=hc(t);else{let o=n[0],s=lh.find((c)=>Array.isArray(o[c]));if(Object.keys(o).length!==1)return;let i=t.filter((c)=>c!==o),a=o[s].map((c)=>hc([...i,c]));if(a.some((c)=>!c))return;r={[s]:a}}if(!r)return;delete e.allOf,Qr(e,r)}function yc(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,u={...l},d=c.ref;if(c.ref=null,d){r(d);let f=e.seen.get(d),g=f.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(g);else Qr(l,g);if(Qr(l,u),a._zod.parent===d)for(let v in l){if(v==="$ref"||v==="allOf")continue;if(!(v in u))delete l[v]}if(g.$ref&&f.def)for(let v in l){if(v==="$ref"||v==="allOf")continue;if(v in f.def&&JSON.stringify(l[v])===JSON.stringify(f.def[v]))delete l[v]}}let p=a._zod.parent;if(p&&p!==d){r(p);let f=e.seen.get(p);if(f?.schema.$ref){if(l.$ref=f.schema.$ref,f.def)for(let g in l){if(g==="$ref"||g==="allOf")continue;if(g in f.def&&JSON.stringify(l[g])===JSON.stringify(f.def[g]))delete l[g]}}}e.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())r(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())dh(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let l of[c.schema,c.def]){let u=l?.allOf;if(!Array.isArray(u))continue;let d=a.get(u);if(d)d.push(l);else a.set(u,[l])}for(let c of e.intersections)for(let l of a.get(c)??[])y_(l)}}let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Qr(o,n.defId?n.schema:n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&o.id===s)delete o.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;et(i,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")o.$defs=i;else o.definitions=i;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:eo(t,"input",e.processors),output:eo(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Pe(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Pe(r.element,n);if(r.type==="set")return Pe(r.valueType,n);if(r.type==="lazy")return Pe(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return Pe(r.innerType,n);if(r.type==="intersection")return Pe(r.left,n)||Pe(r.right,n);if(r.type==="record"||r.type==="map")return Pe(r.keyType,n)||Pe(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Pe(r.in,n)||Pe(r.out,n)}if(r.type==="object"){for(let o in r.shape)if(Pe(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(Pe(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(Pe(o,n))return!0;if(r.rest&&Pe(r.rest,n))return!0;return!1}return!1}var fh=(e,t={})=>(n)=>{let r=mc({...n,processors:t});return ae(e,r),kc(r,e),yc(r,e)},eo=(e,t,n={})=>(r)=>{let{libraryOptions:o,target:s}=r??{},i=mc({...o??{},target:s,io:t,processors:n});return ae(e,i),kc(i,e),yc(i,e)};var sr=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},ir=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},gh=(e,t)=>{sr(e,"minimum",t),ir(e,"maximum",t)},yh=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},vh=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},wh=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},bh=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},hh=(e,t)=>sr(e,"minimum",t.minimum),mh=(e,t)=>ir(e,"maximum",t.maximum),kh=(e)=>(t,n)=>{bh(t,n.format);let[r,o]=e[n.format];sr(t,"minimum",r),ir(t,"maximum",o)},v_={greater_than:(e,t)=>sr(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>ir(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>yh(e,t.value),number_format:kh(ts),bigint_format:kh(Na),min_length:hh,max_length:mh,length_equals:(e,t)=>gh(e,t.length),min_size:hh,max_size:mh,size_equals:(e,t)=>gh(e,t.size),string_format:(e,t)=>{if(bh(e,t.format),t.pattern)vh(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>wh(e,t.mime)};function tt(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let s of r)v_[s._zod.def.check]?.(t,s._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)sr(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)sr(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)ir(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)ir(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)yh(t,o.multipleOf);if(o.format!==void 0){if(t.format??(t.format=o.format),o.format.includes("int"))t.isInt=!0}if(o.mime)wh(t,o.mime);for(let s of o.patterns??[])vh(t,s);return t}var w_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},b_=new Map([[Xa,jp],[ms,Wp]]),xh=(e)=>b_.get(e)??e,Sh=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:l,laxFormat:u}=tt(e);if(typeof s==="number")o.minLength=s;if(typeof i==="number")o.maxLength=i;if(a){if(o.format=w_[a]??a,o.format==="")delete o.format;if(a==="time"||u)delete o.format}if(l)o.contentEncoding=l;if(c&&c.size>0){let d=[...c].map(xh);if(d.length===1)o.pattern=d[0].source;else if(d.length>1)o.allOf=[...d.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},_h=(e,t,n,r)=>{let o=n,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=tt(e);o.type=u?"integer":"number";let d=typeof l==="number"&&l>=(s??Number.NEGATIVE_INFINITY),p=typeof c==="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(d)if(f)o.minimum=l,o.exclusiveMinimum=!0;else o.exclusiveMinimum=l;else if(typeof s==="number")o.minimum=s;if(p)if(f)o.maximum=c,o.exclusiveMaximum=!0;else o.exclusiveMaximum=c;else if(typeof i==="number")o.maximum=i;if(a){let g=new Set;for(let m of a)if(Number.isFinite(m)&&m!==0)g.add(Math.abs(m));else Dt(e,t,o,r,`A multipleOf divisor of ${m} cannot be represented in JSON Schema`);let[h,...v]=g;if(h!==void 0)o.multipleOf=h;if(v.length)o.allOf=[...o.allOf??[],...v.map((m)=>({multipleOf:m}))]}},Rh=(e,t,n,r)=>{n.type="boolean"};var $h=(e,t,n,r)=>{n.not={}};var Ih=(e,t,n,r)=>{};var Th=(e,t,n,r)=>{let o=e._zod.def,s=Fr(o.entries);if(s.length===0){n.not={};return}if(s.every((i)=>typeof i==="number"))n.type="number";if(s.every((i)=>typeof i==="string"))n.type="string";n.enum=s},Oh=(e,t,n,r)=>{let o=e._zod.def;if(o.values.length===0){n.not={};return}let s=[];for(let i of o.values)if(i===void 0){if(Dt(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i==="bigint"){if(Dt(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(i))}else s.push(i);if(s.length===0);else if(s.length===1){let i=s[0];if(n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[i];else n.const=i}else{if(s.every((i)=>typeof i==="number"))n.type="number";if(s.every((i)=>typeof i==="string"))n.type="string";if(s.every((i)=>typeof i==="boolean"))n.type="boolean";if(s.every((i)=>i===null))n.type="null";n.enum=s}};var Eh=(e,t,n,r)=>{Dt(e,t,n,r,"Custom types cannot be represented in JSON Schema")};var Ch=(e,t,n,r)=>{Dt(e,t,n,r,"Transforms cannot be represented in JSON Schema")};var Ah=(e,t,n,r)=>{let o=n,s=e._zod.def,{minimum:i,maximum:a}=tt(e);if(typeof i==="number")o.minItems=i;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=ae(s.element,t,{...r,path:[...r.path,"items"]})};function $s(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return $s(t.out);if(t.type==="catch")return $s(t.innerType);return e._zod.optin}var Ph=(e,t,n,r)=>{let o=n,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&Dt(e,t,o,r,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let l in i)et(o.properties,l,ae(i[l],t,{...r,path:[...r.path,"properties",l]}));let c=[];for(let l of Object.keys(i)){let u=s.shape[l];if(t.io==="input"?$s(u)===void 0:u._zod.optout===void 0)c.push(l)}if(c.length>0)o.required=c;if(s.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")o.additionalProperties=!1}else if(s.catchall)o.additionalProperties=ae(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},zh=(e,t,n,r)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>ae(a,t,{...r,path:[...r.path,s?"oneOf":"anyOf",c]}));if(s)n.oneOf=i;else n.anyOf=i},Nh=(e,t,n,r)=>{let o=e._zod.def,s=ae(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=ae(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c,t.intersections.push(c)};function vc(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let g=e.get(t)?.def;if(!g)return t;let h=vc(e,g,n);return h===g?t:h}for(let g of["anyOf","oneOf"]){let h=t[g];if(!Array.isArray(h))continue;let v=h.map((m)=>vc(e,m,n));if(v.some((m,y)=>m!==h[y]))t={...t,[g]:v}}let r=Array.isArray(t.type)?t.type:[t.type],o=!r.includes("string")&&r.some((g)=>g==="number"||g==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some((g)=>typeof g==="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:p,...f}=t;if(f.enum)f.enum=f.enum.map((g)=>typeof g==="number"?String(g):g);else if(typeof f.const==="number")f.const=String(f.const);if(!o)return f;if(f.type="string",!s)f.pattern=(r.includes("number")?Kr:Za).source;return f}var wc=new WeakMap;function x_(e){let t=new Map;for(let r of e.seen.values())if(r.def&&!t.has(r.schema))t.set(r.schema,r);let n=new Map;for(let r of wc.get(e)??[]){let o=e.seen.get(r),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||n.has(s))continue;let i=vc(t,s,new Set);if(i!==s)n.set(s,i)}if(!n.size)return;for(let r of e.seen.values())for(let o of[r.schema,r.def]){let s=o&&n.get(o.propertyNames);if(s)o.propertyNames=s}}var Lh=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object";let i=s.keyType,a=tt(i).patterns;if(s.mode==="loose"&&a&&a.size>0){let u=ae(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let d of a)et(o.patternProperties,xh(d).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=ae(s.keyType,t,{...r,path:[...r.path,"propertyNames"]});let u=wc.get(t);if(!u)u=[],wc.set(t,u),t.deferred.push(()=>x_(t));u.push(e)}o.additionalProperties=ae(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let c=i._zod.values,l=t.io==="input"&&$s(s.valueType)!==void 0;if(c&&!s.partial&&!l){let u=[...c].filter((d)=>typeof d==="string"||typeof d==="number");if(u.length>0)o.required=u.map(String)}},Dh=(e,t,n,r)=>{let o=e._zod.def,s=ae(o.innerType,t,r),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=o.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},jh=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},bc=Symbol();function Wh(e,t,n,r,o){let s=!1,i=JSON.stringify(e,(a,c)=>{if(typeof c!=="bigint")return c;return s=!0,null});if(!s)return JSON.parse(i);return Dt(t,n,r,o,"BigInt defaults cannot be represented in JSON Schema"),bc}var Mh=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i=Wh(o.defaultValue,e,t,n,r);if(i!==bc)n.default=i},Fh=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=Wh(o.defaultValue,e,t,n,r);if(i!==bc)n._prefault=i},Bh=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{Dt(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=i},Hh=(e,t,n,r)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;ae(i,t,r);let a=t.seen.get(e);a.ref=i},Zh=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0};var xc=(e,t,n,r)=>{let o=e._zod.def;ae(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType};var Uh=new WeakSet([Object.prototype,Error.prototype]);function Is(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var E_=(e,t)=>{dp.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(Uh.has(n))return;Uh.add(n),Is(n,"format",(r)=>(o)=>fp(r,o)),Is(n,"flatten",(r)=>(o)=>pp(r,o)),Is(n,"addIssue",(r)=>(o)=>{r.issues.push(o),r.message=JSON.stringify(r.issues,Br,2)}),Is(n,"addIssues",(r)=>(o)=>{r.issues.push(...o),r.message=JSON.stringify(r.issues,Br,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var Ze=S("ZodError",E_,void 0,{Parent:Error});var Kh=as(Ze),qh=cs(Ze),Jh=ls(Ze),Gh=us(Ze),Vh=hp(Ze),Xh=mp(Ze),Yh=kp(Ze),Qh=yp(Ze),em=vp(Ze),tm=wp(Ze),nm=bp(Ze),rm=xp(Ze);function A_(){if(!De.localeError)He(rc())}function Os(){if(!De.memoizer)He({memoizer:xg()})}var re=S("ZodType",(e,t)=>(A_(),ee.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Be(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return xt(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(SR(e,t))},superRefine(e,t){return this.check(_R(e,t))},overwrite(e){return this.check(cn(e))},optional(){return im(this)},exactOptional(){return fR(this)},nullable(){return am(this)},nullish(){return im(am(this))},nonoptional(e){return kR(this,e)},array(){return P(this)},or(e){return $c([this,e])},and(e){return lR(this,e)},transform(e){return cm(this,pR(e))},default(e){return gR(this,e)},prefault(e){return mR(this,e)},catch(e){return vR(this,e)},pipe(e){return cm(this,e)},readonly(){return xR(this)},describe(e){let t=this.clone();return Dn.add(t,{description:e}),t},meta(...e){if(e.length===0)return Dn.get(this);let t=this.clone();return Dn.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return ss(this,"~standard",{...Va(this),jsonSchema:{input:eo(this,"input"),output:eo(this,"output")}})},set "~standard"(e){Lt(this,"~standard",e)},parse:function e(t,n){return Kh(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await qh(this,t,n,{callee:e})},safeParse(e,t){return Jh(this,e,t)},async safeParseAsync(e,t){return Gh(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Lt(this,"spa",e)},validate(e,t){return Ma(this,e,t)},validateAsync(e,t){return Fa(this,e,t)},encode:function e(t,n){return Vh(this,t,n,{callee:e})},decode:function e(t,n){return Xh(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Yh(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Qh(this,t,n,{callee:e})},safeEncode(e,t){return em(this,e,t)},safeDecode(e,t){return tm(this,e,t)},async safeEncodeAsync(e,t){return nm(this,e,t)},async safeDecodeAsync(e,t){return rm(this,e,t)},toJSONSchema(e){return fh(this,{})(e)},get description(){return Dn.get(this)?.description},get _def(){return this._zod.def}}),lm=S("_ZodString",(e,t)=>{hs.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sh(e,n,r,o)},sp({format:(e)=>tt(e).format??null,minLength:(e)=>tt(e).minimum??null,maxLength:(e)=>tt(e).maximum??null},{regex(...e){return this.check(oc(...e))},includes(...e){return this.check(ac(...e))},startsWith(...e){return this.check(cc(...e))},endsWith(...e){return this.check(lc(...e))},min(...e){return this.check(or(...e))},max(...e){return this.check(_s(...e))},length(...e){return this.check(Rs(...e))},nonempty(...e){return this.check(or(1,...e))},lowercase(e){return this.check(sc(e))},uppercase(e){return this.check(ic(e))},trim(){return this.check(dc())},normalize(...e){return this.check(uc(...e))},toLowerCase(){return this.check(pc())},toUpperCase(){return this.check(fc())},slugify(){return this.check(gc())}})),P_=S("ZodString",(e,t)=>{hs.init(e,t),lm.init(e,t)},{email(e){return this.check(Ig(j_,e))},url(e){return this.check(Pg(M_,e))},jwt(e){return this.check(Jg(tR,e))},emoji(e){return this.check(zg(F_,e))},guid(e){return this.check(Tg(W_,e))},uuid(e){return this.check(Og(Ts,e))},uuidv4(e){return this.check(Eg(Ts,e))},uuidv6(e){return this.check(Cg(Ts,e))},uuidv7(e){return this.check(Ag(Ts,e))},nanoid(e){return this.check(Ng(B_,e))},cuid(e){return this.check(Lg(H_,e))},cuid2(e){return this.check(Dg(Z_,e))},ulid(e){return this.check(jg(U_,e))},base64(e){return this.check(Ug(Y_,e))},base64url(e){return this.check(Kg(Q_,e))},xid(e){return this.check(Wg(K_,e))},ksuid(e){return this.check(Mg(q_,e))},ipv4(e){return this.check(Fg(J_,e))},ipv6(e){return this.check(Bg(G_,e))},cidrv4(e){return this.check(Hg(V_,e))},cidrv6(e){return this.check(Zg(X_,e))},e164(e){return this.check(qg(eR,e))},datetime(e){return this.check(Gg(z_,e))},date(e){return this.check(Vg(N_,e))},time(e){return this.check(Xg(L_,e))},duration(e){return this.check(Yg(D_,e))}});function nt(e){return $g(P_,e)}var oe=S("ZodStringFormat",(e,t)=>{Q.init(e,t),lm.init(e,t)}),z_=S("ZodISODateTime",(e,t)=>{Nf.init(e,t),oe.init(e,t)}),N_=S("ZodISODate",(e,t)=>{Lf.init(e,t),oe.init(e,t)}),L_=S("ZodISOTime",(e,t)=>{Df.init(e,t),oe.init(e,t)}),D_=S("ZodISODuration",(e,t)=>{jf.init(e,t),oe.init(e,t)}),j_=S("ZodEmail",(e,t)=>{_f.init(e,t),oe.init(e,t)});var W_=S("ZodGUID",(e,t)=>{xf.init(e,t),oe.init(e,t)});var Ts=S("ZodUUID",(e,t)=>{Sf.init(e,t),oe.init(e,t)});var M_=S("ZodURL",(e,t)=>{If.init(e,t),oe.init(e,t)});var F_=S("ZodEmoji",(e,t)=>{Tf.init(e,t),oe.init(e,t)});var B_=S("ZodNanoID",(e,t)=>{Of.init(e,t),oe.init(e,t)});var H_=S("ZodCUID",(e,t)=>{Ef.init(e,t),oe.init(e,t)});var Z_=S("ZodCUID2",(e,t)=>{Cf.init(e,t),oe.init(e,t)});var U_=S("ZodULID",(e,t)=>{Af.init(e,t),oe.init(e,t)});var K_=S("ZodXID",(e,t)=>{Pf.init(e,t),oe.init(e,t)});var q_=S("ZodKSUID",(e,t)=>{zf.init(e,t),oe.init(e,t)});var J_=S("ZodIPv4",(e,t)=>{Wf.init(e,t),oe.init(e,t)});var G_=S("ZodIPv6",(e,t)=>{Ff.init(e,t),oe.init(e,t)});var V_=S("ZodCIDRv4",(e,t)=>{Bf.init(e,t),oe.init(e,t)});var X_=S("ZodCIDRv6",(e,t)=>{Hf.init(e,t),oe.init(e,t)});var Y_=S("ZodBase64",(e,t)=>{Uf.init(e,t),oe.init(e,t)});var Q_=S("ZodBase64URL",(e,t)=>{Kf.init(e,t),oe.init(e,t)});var eR=S("ZodE164",(e,t)=>{qf.init(e,t),oe.init(e,t)});var tR=S("ZodJWT",(e,t)=>{Jf.init(e,t),oe.init(e,t)});var um=S("ZodNumber",(e,t)=>{Ya.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>_h(e,n,r,o),e.isFinite=!0},sp({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=tt(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=tt(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=tt(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>tt(e).format??null},{gt(e,t){return this.check(xs(e,t))},gte(e,t){return this.check(Yr(e,t))},min(e,t){return this.check(Yr(e,t))},lt(e,t){return this.check(bs(e,t))},lte(e,t){return this.check(Xr(e,t))},max(e,t){return this.check(Xr(e,t))},int(e){return this.check(om(e))},safe(e){return this.check(om(e))},positive(e){return this.check(xs(0,e))},nonnegative(e){return this.check(Yr(0,e))},negative(e){return this.check(bs(0,e))},nonpositive(e){return this.check(Xr(0,e))},multipleOf(e,t){return this.check(Ss(e,t))},step(e,t){return this.check(Ss(e,t))},finite(){return this}}));function to(e){return Qg(um,e)}var nR=S("ZodNumberFormat",(e,t)=>{Gf.init(e,t),um.init(e,t)});function om(e){return eh(nR,e)}var rR=S("ZodBoolean",(e,t)=>{Vf.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rh(e,n,r,o)});function ce(e){return th(rR,e)}var oR=S("ZodUnknown",(e,t)=>{Xf.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ih(e,n,r,o)});function pt(){return nh(oR)}var sR=S("ZodNever",(e,t)=>{Yf.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$h(e,n,r,o)});function iR(e){return rh(sR,e)}var Rc=S("ZodArray",(e,t)=>{Os(),Qf.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ah(e,n,r,o),e.element=t.element},{min(e,t){return this.check(or(e,t))},nonempty(e){return this.check(or(1,e))},max(e,t){return this.check(_s(e,t))},length(e,t){return this.check(Rs(e,t))},unwrap(){return this.element}});function P(e,t){return oh(Rc,e,t)}var Es=S("ZodObject",(e,t)=>{Os(),ng.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ph(e,n,r,o),MS(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return B(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Be(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Be(this._zod.def,{catchall:pt()}))},loose(){return this.clone(Be(this._zod.def,{catchall:pt()}))},strict(){return this.clone(Be(this._zod.def,{catchall:iR()}))},strip(){return this.clone(Be(this._zod.def,{catchall:void 0}))},extend(e){return AS(this,e)},safeExtend(e){return PS(this,e)},merge(e){return zS(this,e)},pick(e){return ES(this,e)},omit(e){return CS(this,e)},partial(...e){return tp(no,this,e[0])},exactPartial(...e){return tp(fm,this,e[0],"exactPartial")},required(...e){return NS(gm,this,e[0])}});function C(e,t){let n={type:"object",shape:e??{},...z(t)};return new Es(n)}function dm(e,t){return new Es({type:"object",shape:e,catchall:pt(),...z(t)})}var pm=S("ZodUnion",(e,t)=>{Qa.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>zh(e,n,r,o),e.options=t.options});function $c(e,t){return new pm({type:"union",options:e,...z(t)})}var aR=S("ZodDiscriminatedUnion",(e,t)=>{pm.init(e,t),rg.init(e,t)});function ft(e,t,n){return new aR({type:"union",options:t,discriminator:e,...z(n)})}var cR=S("ZodIntersection",(e,t)=>{og.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Nh(e,n,r,o)});function lR(e,t){return new cR({type:"intersection",left:e,right:t})}var sm=S("ZodRecord",(e,t)=>{Os(),sg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Lh(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function ar(e,t,n){if(!t||!t._zod)return new sm({type:"record",keyType:nt(),valueType:e,...z(t)});return new sm({type:"record",keyType:e,valueType:t,...z(n)})}var _c=S("ZodEnum",(e,t)=>{ig.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,o,s)=>Th(e,r,o,s),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new _c({...t,checks:[],...z(o),entries:s})},e.exclude=(r,o)=>{let s={...t.entries};for(let i of r)if(n.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new _c({...t,checks:[],...z(o),entries:s})}});function B(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new _c({type:"enum",entries:n,...z(t)})}var uR=S("ZodLiteral",(e,t)=>{ag.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Oh(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function M(e,t){return new uR({type:"literal",values:Array.isArray(e)?e:[e],...z(t)})}var dR=S("ZodTransform",(e,t)=>{Os(),cg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ch(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Ur(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(Ln(s,n.value,t));else{let i=s;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=n.value;i.inst??(i.inst=e),n.issues.push(Ln(i))}};let o=t.transform(n.value,n);if(o instanceof Promise)return o.then((s)=>(n.value=s,n));return n.value=o,n}});function pR(e){return new dR({type:"transform",transform:e})}var no=S("ZodOptional",(e,t)=>{ec.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xc(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function im(e){return new no({type:"optional",innerType:e})}var fm=S("ZodExactOptional",(e,t)=>{lg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xc(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function fR(e){return new fm({type:"optional",innerType:e})}var Cs=S("ZodNullable",(e,t)=>{ug.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Dh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function am(e){return new Cs({type:"nullable",innerType:e})}var As=S("ZodDefault",(e,t)=>{dg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Mh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function gR(e,t){return new As({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Pa(t)}})}var hR=S("ZodPrefault",(e,t)=>{pg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Fh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function mR(e,t){return new hR({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Pa(t)}})}var gm=S("ZodNonOptional",(e,t)=>{fg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>jh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function kR(e,t){return new gm({type:"nonoptional",innerType:e,...z(t)})}var yR=S("ZodCatch",(e,t)=>{gg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Bh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function vR(e,t){return new yR({type:"catch",innerType:e,catchValue:typeof t==="function"?t:ip(t)})}var wR=S("ZodPipe",(e,t)=>{hg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hh(e,n,r,o),e.in=t.in,e.out=t.out});function cm(e,t){return new wR({type:"pipe",in:e,out:t})}var bR=S("ZodReadonly",(e,t)=>{mg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Zh(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function xR(e){return new bR({type:"readonly",innerType:e})}var hm=S("ZodCustom",(e,t)=>{kg.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Eh(e,n,r,o)});function mm(e,t){return sh(hm,e??(()=>!0),t)}function SR(e,t={}){return ih(hm,e,t)}function _R(e,t){return ah(e,t)}var F=nt().refine((e)=>e.trim().length>0,"must not be blank"),bm=mm((e)=>typeof e==="string"&&Object.hasOwn(Qe,e),"unsupported branch preset"),TR=mm((e)=>typeof e==="string"&&Vo.includes(e),"unsupported commit preset"),Oc=C({preset:bm,developBranch:F.optional(),prefixes:C({feature:F,bugfix:F,release:F,hotfix:F}).passthrough().optional(),allowed:P(F).optional(),protected:P(F).optional(),integration:B(["pr","merge"]).optional()}).strict(),Ec=C({preset:TR,pattern:nt().optional()}).strict(),OR=C({branchPolicy:Oc.optional(),commitPolicy:Ec.optional()}).strict().refine((e)=>e.branchPolicy!==void 0||e.commitPolicy!==void 0,{message:"a profile must define branchPolicy or commitPolicy"}),ER=ft("kind",[C({kind:M("package-json"),path:F,field:F}).strict(),C({kind:M("git-tag")}).strict(),C({kind:M("manual")}).strict()]),CR=C({strategy:bm.optional(),productionBranch:F,integrationBranch:F,naming:C({feature:F.optional(),release:F.optional(),hotfix:F.optional()}).passthrough().optional(),baseBranch:F.optional(),mergeBackBranches:P(F).optional(),pullRequestTarget:F.optional(),tagNamespace:nt().optional(),versionSource:ER.optional(),requiredChecks:P(F).optional(),critical:P(F).optional()}).passthrough().superRefine((e,t)=>{for(let[n,r]of[["mergeBackBranches",e.mergeBackBranches??[]],["requiredChecks",e.requiredChecks??[]]])if(new Set(r).size!==r.length)t.addIssue({code:"custom",path:[n],message:"entries must be unique"});if(e.versionSource?.kind==="package-json"&&(ln.posix.isAbsolute(e.versionSource.path.replaceAll("\\","/"))||/^[A-Za-z]:\//u.test(e.versionSource.path.replaceAll("\\","/"))||e.versionSource.path.replaceAll("\\","/").split("/").includes("..")))t.addIssue({code:"custom",path:["versionSource","path"],message:"must stay inside the repository"})}),AR=C({name:F,glob:F,vcs:C({provider:B(["gitlab","github"]),defaultTargetBranch:F.optional(),tokenFile:F.optional(),account:F.optional()}).passthrough().optional(),autoApprove:$c([ce(),P(F)]).optional(),defaultEndpoint:pt().optional(),verification:B(["proportional","self","independent"]).optional(),delegation:pt().optional(),trailers:ce().optional(),deleteBranch:ce().optional(),liveSessionGuard:ce().optional(),fanout:C({tierModels:pt().optional()}).passthrough().optional(),models:C({roles:pt().optional()}).passthrough().optional(),autonomy:C(Object.fromEntries(["push","pr","merge","release","rerun"].map((e)=>[e,$c([ce(),M("verified")]).optional()]))).passthrough().optional(),youtrack:C({baseUrl:F.optional(),link_issues:ce().optional()}).passthrough().optional(),issues:C({provider:B(["github","gitlab","youtrack"]).optional(),link:ce().optional(),relation:pt().optional(),backlink:ce().optional(),link_on_pr:ce().optional()}).passthrough().optional(),branchPolicy:Oc.optional(),commitPolicy:Ec.optional(),defaultProfile:F.optional(),profiles:ar(F,OR).optional(),releaseTracks:ar(F,CR).optional()}).passthrough().superRefine((e,t)=>{if(e.defaultProfile!==void 0&&!Object.hasOwn(e.profiles??{},e.defaultProfile))t.addIssue({code:"custom",path:["defaultProfile"],message:"does not name a configured profile"})}),PR=C({workspaces:P(AR).optional(),models:C({roles:pt().optional()}).passthrough().optional()}).passthrough().superRefine((e,t)=>{let n=new Set;for(let[r,o]of(e.workspaces??[]).entries()){if(n.has(o.name))t.addIssue({code:"custom",path:["workspaces",r,"name"],message:`duplicate workspace name ${JSON.stringify(o.name)}`});n.add(o.name)}});var Ic=(e)=>IR("sha256").update(e??"<missing>").digest("hex"),xm=(e,t)=>{if(!Ra(e))return{status:"malformed",path:t,entries:[],error:`${t} is not a JSON object`};let n=PR.safeParse(e,{reportInput:!0});if(!n.success){let o=n.error.issues.map((s)=>{let i=String(s.path[s.path.length-1]??""),a=["provider","preset","strategy"].includes(i)&&typeof s.input==="string"?` (${JSON.stringify(s.input)})`:"";return`${s.path.map(String).join(".")||"workspaces"}: ${s.message}${a}`}).join("; ");return{status:"invalid",path:t,entries:[],error:`${t} has invalid workspace configuration: ${o}`}}for(let[o,s]of(n.data.workspaces??[]).entries()){let i=_m(s.glob);if(!i.ok)return{status:"invalid",path:t,entries:[],error:`${t} workspaces.${o}.glob: ${i.error}`}}let r=e;return{status:"valid",path:t,entries:r.workspaces??[],document:r}},Sm=(e=rn())=>{let t=ln.join(e,"workspaces.json"),n;try{n=Tc(t,"utf8")}catch(o){if(o.code==="ENOENT")return{status:"missing",path:t,entries:[],revision:Ic(null)};return{status:"malformed",path:t,entries:[],error:`${t} could not be read: ${o instanceof Error?o.message:String(o)}`}}let r;try{r=JSON.parse(n)}catch{return{status:"malformed",path:t,entries:[],revision:Ic(n),error:`${t} is not valid JSON`}}return{...xm(r,t),revision:Ic(n)}};var zR=(e)=>{let t="";for(let n=0;n<e.length;n++){let r=e[n];if(r==="*")if(e[n+1]==="*")if(e[n+2]==="/"){if(t==="")t+="/?";t+="(?:[^/]+/)*",n+=2}else{if(n+2>=e.length)if(t.endsWith("/"))t=t.slice(0,-1),t+="(?:/.*)?";else t+=".*";else t+=".*";n++}else t+="[^/]*";else t+=r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${t}$`)},vm=(e,t)=>zR(e.replaceAll("\\","/")).test(t.replaceAll("\\","/")),NR=/[?[\]{}]/,LR=/[@+*]\(|!/,_m=(e)=>{let t=e.trim();if(!t)return{ok:!1,error:"workspace pattern is required"};let n=NR.exec(t);if(n)return{ok:!1,error:`unsupported glob character ${JSON.stringify(n[0])} in workspace pattern ${JSON.stringify(e)} — the matcher supports * and ** only (e.g. /work/**)`};let r=LR.exec(t);if(r){let o=r[0];return{ok:!1,error:`unsupported glob ${o==="!"?"negation (!)":`extglob (${o})`} in workspace pattern ${JSON.stringify(e)} — the matcher supports * and ** only (e.g. /work/**)`}}return{ok:!0}};class Ue extends Error{name="WorkspaceConfigError"}var wm=new Map,DR=(e)=>{let t=wm.get(e);if(t!==void 0)return t;let n={...process.env};for(let c of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"])delete n[c];let r=(c)=>{let l=$R("git",c,{cwd:e,env:n,encoding:"utf8",timeout:5000,windowsHide:!0});return l.status===0?l.stdout:null},o=null,s=r(["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"]),[i,a]=(s??"").trim().split(/\r?\n/u);if(i&&a&&ln.resolve(i)!==ln.resolve(a))o=/^worktree (.+)$/mu.exec(r(["worktree","list","--porcelain"])??"")?.[1]?.trim()||(ln.basename(a)===".git"?ln.dirname(a):a);return wm.set(e,o),o},Rm=(e,t)=>{let n=(s)=>{let i=[s,$m(s)].map((a)=>a.replaceAll("\\","/"));return t.filter((a)=>{let c=a.glob.replaceAll("\\","/"),l=jR(c);return i.some((u)=>vm(c,u)||l!==c&&vm(l,u))})},r=n(e);if(r.length)return r;let o=DR(e);return o?n(o):r},$m=(e)=>{let t=ym.native??ym;try{return t(e)}catch{return e}},jR=(e)=>{let t=/[*?[\]{]/.exec(e),n=t?e.slice(0,t.index):e,r=t?e.slice(t.index):"";if(!n)return e;return $m(n.replace(/\/+$/,"")||"/")+(n.endsWith("/")?"/":"")+r},cr=(e)=>e.replaceAll("\\","/").split("/").filter((t)=>t.length>0&&!/[*?[\]{]/.test(t)).length;var Im=(e,t,n)=>{if(n!==void 0){let s=e.filter((i)=>i.name===n);if(s.length===1)return s[0];if(s.length>1)throw new Ue(`ambiguous workspace ${JSON.stringify(n)} for ${t}`);if(e.length>0)throw new Ue(`workspace ${JSON.stringify(n)} does not match ${t}; matching choices: ${e.map((i)=>i.name).join(", ")}`);throw new Ue(`workspace ${JSON.stringify(n)} does not match ${t}`)}if(e.length<2)return e[0];let r=Math.max(...e.map((s)=>cr(s.glob))),o=e.filter((s)=>cr(s.glob)===r);if(o.length>1)throw new Ue(`ambiguous workspace for ${t}; choose one of: ${o.map((s)=>s.name).join(", ")}`);return o[0]},WR=(e,t,n)=>{let r=Rm(e,t);return Im(r,e,n)??null},Tm=(e,t,n)=>{let r=Sm(t);if(r.status==="malformed"||r.status==="invalid")throw new Ue(r.error);return WR(e,r.entries,n)};var MR=(e)=>{let t=e==="branch"?"branchPolicy":e==="commit"?"commitPolicy":"vcs",n=e==="branch"?Oc:e==="commit"?Ec:C({provider:B(["gitlab","github"]),defaultTargetBranch:F.optional(),account:F.optional()}).passthrough(),r=C({[t]:n.optional()}).passthrough();return C({name:F,glob:F,[t]:n.optional(),defaultProfile:F.optional(),profiles:ar(F,r).optional()}).passthrough()},ro=(e)=>zm(e,"vcs"),FR=C({workspaces:P(C({name:F,glob:F}).passthrough()).optional()}).passthrough(),Ps=(e,t=rn())=>{let n=ln.join(t,"workspaces.json"),r;try{r=Tc(n,"utf8")}catch(u){if(u.code==="ENOENT")return null;throw new Ue(`${n} could not be read: ${u instanceof Error?u.message:String(u)}`,{cause:u})}let o;try{o=JSON.parse(r)}catch{throw new Ue(`${n} is not valid JSON`)}let s=FR.safeParse(o);if(!s.success){let u=s.error.issues.map((d)=>`${d.path.map(String).join(".")||"workspaces"}: ${d.message}`).join("; ");throw new Ue(`${n} has invalid workspace matching data: ${u}`)}let i=s.data.workspaces;for(let u of i??[]){let d=_m(u.glob);if(!d.ok)throw new Ue(`${n} workspace ${u.name}: ${d.error}`)}let a=Rm(e,i??[]),c=process.env.WORKFLOW_WORKSPACE_NAME?.trim()||void 0,l=Im(a,e,c);return l?{file:n,selected:l,matches:a}:null},Om=(e)=>{let t=Ps(e);return t?{workspace:t.selected.name,releaseTracks:t.selected.releaseTracks}:null},Em=(e,t,n)=>{let r;try{r=Ps(e,t)}catch{return null}if(!r)return null;let{selected:o,matches:s}=r,i=s.filter((a)=>a!==o).toSorted((a,c)=>cr(c.glob)-cr(a.glob));return{workspace:o.name,source:[o,...i].find(n)??null}};var Cm=(e,t)=>{let n=Em(e,t,(r)=>typeof r.trailers==="boolean");return{enabled:n?.source?.trailers!==!1,workspace:n?.workspace??null,from:n?.source?.name??null}},Am=(e,t)=>Em(e,t,(n)=>typeof n.liveSessionGuard==="boolean")?.source?.liveSessionGuard!==!1;var Pm=(e,t)=>{let n=[];try{let r=Ps(e,t);if(r){let o=r.matches.filter((s)=>s!==r.selected).toSorted((s,i)=>cr(i.glob)-cr(s.glob));for(let s of[r.selected,...o])n.push({name:s.name,global:!1,models:s.models,tierModels:s.fanout?.tierModels})}}catch{}try{let r=JSON.parse(Tc(ln.join(t??rn(),"workspaces.json"),"utf8"));if(r&&typeof r==="object"&&!Array.isArray(r))n.push({name:"global",global:!0,models:r.models,tierModels:void 0})}catch{}return n},Cc=(e)=>e.replace(/_(?:cli|desktop)$/u,"");var zm=(e,t)=>{let n=Ps(e);if(!n)return null;let{file:r,selected:o}=n,s=MR(t).safeParse(o);if(!s.success){let i=s.error.issues.map((a)=>`${a.path.map(String).join(".")||"workspace"}: ${a.message}`).join("; ");throw new Ue(`${r} has invalid ${t} policy configuration: ${i}`)}return s.data},zs=(e,t,n)=>{let r=zm(e,t);if(!r)return{policy:void 0,source:"user-default"};let o=t==="branch"?"branchPolicy":"commitPolicy",s=n?.trim()||r.defaultProfile;if(r.defaultProfile&&!Object.hasOwn(r.profiles??{},r.defaultProfile))throw new Ue(`workspace ${JSON.stringify(r.name)} has no profile ${JSON.stringify(r.defaultProfile)}`);let i=s?r.profiles?.[s]:void 0;if(s&&!i)throw new Ue(`workspace ${JSON.stringify(r.name)} has no profile ${JSON.stringify(s)}`);let a=i?.[o],c=r[o];return{policy:a??c,source:a?`profile:${s}`:c?`workspace:${r.name}`:"user-default"}};function Ac(e,t){let n=ro(e),r=n?.branchPolicy??{},o=typeof r.preset==="string"&&Object.hasOwn(Qe,r.preset),s=zs(e,"branch",process.env.WORKFLOW_PROFILE?.trim()||void 0),i=Go(qo(),s.policy?{branchPolicy:s.policy}:null,()=>Qo(e)).defaultTargetBranch;return String(n?.vcs?.defaultTargetBranch??(o?i:t??i)??"develop")}import i$ from"node:fs";import Ym from"node:path";import{spawnSync as a$}from"node:child_process";import{createHash as KR}from"node:crypto";import{spawnSync as qR}from"node:child_process";import{spawnSync as Nm}from"node:child_process";import{createHash as Lm}from"node:crypto";import un from"node:fs";import BR from"node:os";import Ns from"node:path";var Dm=268435456,dn={local:20000,worktree:120000,network:15000},te=(e,t,n={})=>{let r=Nm("git",t,{cwd:e,encoding:"utf8",env:n.env??process.env,input:n.input,maxBuffer:Dm,timeout:n.timeoutMs??dn.local,killSignal:"SIGKILL",windowsHide:!0}),o=r.error;return{ok:r.status===0,stdout:r.stdout??"",stderr:r.stderr??"",timedOut:o?.code==="ETIMEDOUT"}},Ke=(e)=>{if(!e.ok)return null;let t=e.stdout.trim();return t?t:null},jt=(e)=>e.length>0&&!e.startsWith("-");function oo(e){return Ke(te(e,["rev-parse","--verify","-q","HEAD^{commit}"]))}var HR=(e)=>Ke(te(e,["mktree"],{input:""})),ZR=5242880,UR=(e,t)=>{un.copyFileSync(e,t);let{atimeNs:n,mtimeNs:r}=un.statSync(e,{bigint:!0}),o=(s)=>(Number(s/1000n)-1)/1e6;un.utimesSync(t,o(n),o(r))};function zc(e,t={}){let n=Ke(te(e,["rev-parse","--show-toplevel"])),r=Ke(te(e,["rev-parse","--path-format=absolute","--git-path","index"]));if(!n||!r)return null;let o=t.maxUntrackedBytes??ZR,s=t.timeoutMs??dn.worktree,i=un.mkdtempSync(Ns.join(BR.tmpdir(),"workit-tree-"));try{let a=Ns.join(i,"index");if(un.existsSync(r))UR(r,a);let c={...process.env,GIT_INDEX_FILE:a},l=te(n,["ls-files","--others","--exclude-standard","-z"],{env:c,timeoutMs:s});if(!l.ok)return null;let u=[];for(let h of l.stdout.split("\x00").filter(Boolean))try{let v=un.statSync(Ns.join(n,h));if(v.isFile()&&v.size>o)u.push({path:h,size:v.size,mtimeMs:Math.trunc(v.mtimeMs)})}catch{}if(u.sort((h,v)=>h.path<v.path?-1:h.path>v.path?1:0),!(u.length?te(n,["add","-A","--pathspec-from-file=-","--pathspec-file-nul"],{env:c,timeoutMs:s,input:[".",...u.map((h)=>`:(exclude,literal)${h.path}`)].join("\x00")}):te(n,["add","-A"],{env:c,timeoutMs:s})).ok)return null;let p=Ke(te(n,["write-tree"],{env:c,timeoutMs:s}));if(!p)return null;let f=Ke(te(n,["rev-parse","--verify","-q","HEAD^{tree}"]))??HR(n),g=u.length?`sha256:${Lm("sha256").update(JSON.stringify({tree:p,skipped:u})).digest("hex")}`:p;return{tree:p,key:g,dirty:p!==f||u.length>0,skipped:u}}finally{un.rmSync(i,{recursive:!0,force:!0})}}function Ds(e,t={}){let n=Ke(te(e,["rev-parse","--show-toplevel"]));if(!n)return null;let r=te(n,["status","--porcelain=v1","-z","--untracked-files=all","--no-renames","--ignore-submodules=dirty"],{env:{...process.env,GIT_OPTIONAL_LOCKS:"0"},timeoutMs:t.timeoutMs??dn.worktree});if(!r.ok)return null;let o=Lm("sha256");o.update(`${oo(n)??"unborn"}\x00`);for(let s of r.stdout.split("\x00")){if(s.length<4)continue;let i=s.slice(3),a=Ns.join(n,i),c="-";try{let l=un.lstatSync(a,{bigint:!0});if(c=`${l.mode.toString(8)}:${l.size}:${l.mtimeNs}`,l.isDirectory())c+=`:${oo(a)??"-"}`}catch{}o.update(`${s.slice(0,2)}\x00${i}\x00${c}\x00`)}return`sig:${o.digest("hex")}`}function Wt(e,t,n){if(!jt(t)||!jt(n))return null;return Ke(te(e,["merge-base",t,n]))}function jm(e,t,n){if(!jt(t)||!jt(n))return null;let r=te(e,["diff","-U3","--diff-algorithm=myers","--indent-heuristic","--no-color","--no-ext-diff","--no-textconv","--no-renames","--full-index","--src-prefix=a/","--dst-prefix=b/",`${t}...${n}`,"--"]);if(!r.ok||!r.stdout.trim())return null;let o=te(e,["patch-id","--stable"],{input:r.stdout});return Ke(o)?.split(/\s+/u)[0]??null}function Nc(e){return(te(e,["remote"]).stdout??"").split(/\r?\n/u).map((t)=>t.trim()).filter(Boolean)}function $t(e,t){if(!jt(t))return null;return Ke(te(e,["rev-parse","--verify","-q",`${t}^{commit}`]))}function Wm(e){return Ke(te(e,["symbolic-ref","-q","--short","refs/remotes/origin/HEAD"]))}function Lc(e,t){let n=Ls(e,t.fromFork,t.from),r=Ls(e,t.toFork,t.to);if(!n||!r)return null;let o=new Map(n.map((a)=>[a.path,a])),s=new Map(r.map((a)=>[a.path,a])),i=(a,c)=>a!==void 0&&c!==void 0&&a.oldMode===c.oldMode&&a.oldBlob===c.oldBlob&&a.newMode===c.newMode&&a.newBlob===c.newBlob;return[...new Set([...o.keys(),...s.keys()])].filter((a)=>!i(o.get(a),s.get(a))).toSorted()}function Dc(e,t){let n=Wt(e,t.fromBase,t.from),r=Wt(e,t.toBase,t.to);if(!n||!r)return!1;return Lc(e,{from:t.from,to:t.to,fromFork:n,toFork:r})?.length===0}var Mm=["-c","core.quotePath=false","diff","--no-color","--no-ext-diff","--no-textconv","--no-renames"],Fm=(e,t)=>{if(!jt(e)||t!==null&&!jt(t))return null;return t===null?[e]:[e,t]};function jc(e,t,n){let r=Fm(t,n);if(!r)return null;let o=te(e,[...Mm,"--numstat","-z",...r,"--"]);if(!o.ok)return null;let s=[];for(let i of o.stdout.split("\x00")){let a=/^(-|\d+)\t(-|\d+)\t(.+)$/su.exec(i.replace(/^\n/u,""));if(!a)continue;let c=a[1]==="-";s.push({path:a[3],added:c?0:Number(a[1]),deleted:c?0:Number(a[2]),binary:c})}return s}function Ls(e,t,n){let r=Fm(t,n);if(!r)return null;let o=te(e,[...Mm,"--raw","-z","--no-abbrev",...r,"--"]);if(!o.ok)return null;let s=o.stdout.split("\x00"),i=[];for(let a=0;a+1<s.length;a+=2){let c=/^:(\d{6}) (\d{6}) ([0-9a-f]+) ([0-9a-f]+) [A-Z]\d*$/u.exec(s[a].replace(/^\n/u,""));if(!c)return null;i.push({path:s[a+1],oldMode:c[1],newMode:c[2],oldBlob:c[3],newBlob:c[4]})}return i}function Wc(e,t){let n=new Map,r=[...new Set(t)].filter((a)=>/^[0-9a-f]{40,64}$/u.test(a));if(!r.length)return n;let o=Nm("git",["cat-file","--batch"],{cwd:e,input:`${r.join(`
61
61
  `)}
62
62
  `,maxBuffer:Dm,timeout:dn.local,killSignal:"SIGKILL",windowsHide:!0});if(o.status!==0||!o.stdout)return null;let s=o.stdout,i=0;for(let a of r){let c=s.indexOf(10,i);if(c<0)return null;let l=s.subarray(i,c).toString("utf8").split(" ");if(i=c+1,l[1]==="missing")continue;let u=Number(l[2]);if(l[0]!==a||!Number.isSafeInteger(u))return null;n.set(a,s.subarray(i,i+u)),i+=u+1}return n}function Bm(e,t,n){if(!jt(t))return null;let r=te(e,["ls-tree","-r","-z","--full-tree",t]);if(!r.ok)return null;let o=new Map;for(let s of r.stdout.split("\x00")){let i=/^\d{6} blob ([0-9a-f]+)\t(.+)$/su.exec(s);if(i&&(i[2]===n||i[2].endsWith(`/${n}`)))o.set(i[2],i[1])}return o}function js(e,t,n){if(!jt(t))return null;let r=te(e,["cat-file","blob",`${t}:${n}`]);return r.ok?r.stdout:null}function Hm(e){let t=te(e,["ls-files","-z","--others","--exclude-standard"]);return t.ok?t.stdout.split("\x00").filter(Boolean):[]}var Pc=(e,t)=>Ke(te(e,["config","--get",t]));function je(e){return Ke(te(e,["symbolic-ref","--short","-q","HEAD"]))}function Ws(e,t){let n=t??je(e),r=Nc(e),o=[n?Pc(e,`branch.${n}.pushRemote`):null,Pc(e,"remote.pushDefault"),n?Pc(e,`branch.${n}.remote`):null];for(let s of o)if(s&&s!=="."&&r.includes(s))return s;if(r.includes("origin"))return"origin";return r.length===1?r[0]:null}class Bc extends Error{}var JR=new Set(["strategy","productionBranch","integrationBranch","naming","baseBranch","mergeBackBranches","pullRequestTarget","tagNamespace","versionSource","requiredChecks","critical"]),GR=["productionBranch","integrationBranch","baseBranch","pullRequestTarget"],Um=/\{[^}]*\}/gu,VR=/\{[^}]*\}/u,Mc=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),lr=(e)=>typeof e==="string"&&e.trim()&&!e.trim().startsWith("-")?e.trim():null,XR=(e)=>[...GR.map((t)=>lr(e[t])),...Array.isArray(e.mergeBackBranches)?e.mergeBackBranches.map(lr):[]].filter((t)=>t!==null),YR=(e)=>e.replace(Um,"").replace(/[*/]/gu,"").trim();function QR(e){let t={tracks:[],issues:[],error:null,protectedBranches:[]};if(e===void 0||e===null)return t;if(!Mc(e))return t.issues.push("releaseTracks is not an object; ignored"),t;let n=[],r=new Set;for(let[o,s]of Object.entries(e).toSorted(([i],[a])=>i<a?-1:1)){let i=`release track ${JSON.stringify(o)}`;if(!Mc(s)){t.issues.push(`${i} is not an object; ignored`);continue}for(let m of XR(s))r.add(m);if(!o.trim()){t.issues.push("a release track with a blank name was ignored");continue}let a=[];if(Array.isArray(s.critical))a=s.critical.filter((m)=>typeof m==="string");else if(s.critical!==void 0)t.issues.push(`${i} critical: must be a list of field names; ignored`);let c=(m)=>a.some((y)=>m===y||m.startsWith(`${y}.`)),l=(m,y)=>{if(c(m))n.push(`${i} ${m}: ${y}`);else t.issues.push(`${i} ${m}: ${y}`)};for(let m of Object.keys(s))if(!JR.has(m))l(m,"unknown field, ignored");let u=lr(s.productionBranch),d=lr(s.integrationBranch);if(!u)l("productionBranch","missing or not a branch name");if(!d)l("integrationBranch","missing or not a branch name");let p=(m)=>{if(s[m]===void 0)return null;let y=lr(s[m]);if(!y)l(m,"not a branch name; using the integration branch");return y},f=p("baseBranch"),g=p("pullRequestTarget"),h=[];if(s.mergeBackBranches!==void 0){let m=Array.isArray(s.mergeBackBranches)?s.mergeBackBranches.map(lr):[null];if(m.some((y)=>y===null))l("mergeBackBranches","must be a list of branch names; ignored");else h=[...new Set(m)]}let v={};if(s.naming!==void 0)if(!Mc(s.naming))l("naming","not an object; ignored");else for(let m of["feature","release","hotfix"]){let y=s.naming[m];if(y===void 0)continue;if(typeof y!=="string"||!y.trim())l(`naming.${m}`,"not a template string; ignored");else if(!YR(y))l(`naming.${m}`,"needs literal text besides placeholders; ignored");else v[m]=y.trim()}if(!u||!d){t.issues.push(`${i} was skipped: it needs a productionBranch and integrationBranch`);continue}t.tracks.push({name:o,productionBranch:u,integrationBranch:d,baseBranch:f??d,pullRequestTarget:g??d,mergeBackBranches:h,naming:v})}if(t.protectedBranches=[...r],n.length)t.error=`workspace releaseTracks cannot be read by this Workit (${n.join("; ")}); upgrade Workit or fix the track`;return t}var Km=(e)=>[...new Set(e.flatMap((t)=>[t.productionBranch,t.integrationBranch,t.baseBranch,t.pullRequestTarget,...t.mergeBackBranches]))],qm=(e)=>VR.test(e)?e.replace(Um,"*"):`${e.replace(/\/?\*?$/u,"")}/*`;var Ms="",Fc=(e,t)=>e.filter((n)=>[n.integrationBranch,n.productionBranch,n.baseBranch].includes(t)),e$=(e,t)=>{let n=e.replace(/^refs\/heads\//u,"").replace(/^refs\/remotes\/[^/]+\//u,""),r=t.find((o)=>n.startsWith(`${o}/`));return r?n.slice(r.length+1):n},t$=10;function n$(e){let t=[...e.tracks],n=[...e.issues??[]],r=e.requested?.trim();if(t.length===0){if(r)return{status:"invalid",error:`no release tracks configured for this workspace; --track ${r} cannot apply`,issues:n};return{status:"none",issues:n}}let o=t.map((T)=>T.name).join(", "),s=null,i=(T,L,X,K=[],Ie=null)=>({status:"resolved",track:T&&T.name!==Ms?T:null,source:L,detail:X,warnings:[...n,...s?[s]:[],...K],tracks:t,blocking:s??Ie});if(r){let T=t.find((L)=>L.name===r);if(!T)return{status:"invalid",error:`no release track ${JSON.stringify(r)}; configured: ${o}`,issues:n};return i(T,"flag",`track ${T.name} was requested explicitly`)}let a=(T)=>T!==null&&t.some((L)=>[L.integrationBranch,L.productionBranch,L.baseBranch,L.pullRequestTarget].includes(T)),c=e.defaultBranch&&!a(e.defaultBranch)?{name:Ms,productionBranch:e.defaultBranch,integrationBranch:e.defaultBranch,baseBranch:e.defaultBranch,pullRequestTarget:e.defaultBranch,mergeBackBranches:[],naming:{}}:null,l=c?[...t,c]:t,u=(T)=>T.name===Ms?`the workspace default line (${T.integrationBranch})`:`track ${T.name}`,d=(T)=>{let L=e.defaultBranch?t.filter((Fe)=>Fe.integrationBranch===e.defaultBranch||Fe.pullRequestTarget===e.defaultBranch):[],X=L.length===1?L[0]:null,K=X?`track ${X.name}`:`default target ${e.defaultBranch??"(none)"}`,Ie=l.length>=2?`can't tell which release line ${e.branch??"HEAD"} is on (${T}); pass --track <name> (${o}) or --base <branch>`:null;return i(X,"default",`${T}; using the workspace ${K}`,[`release track not determined: ${T}; using the workspace ${K} (pass --track <name> to choose)`],Ie)},p=e.branch;if(p){let T=Fc(l,p);if(T.length===1)return i(T[0],"branch",`${p} is a branch of ${u(T[0])}`);if(T.length>1)return d(`${p} belongs to more than one track (${T.map((L)=>L.name).join(", ")})`)}let f=e.envRequested?.trim();if(f){let T=t.find((L)=>L.name===f);if(T)return i(T,"env",`WORKFLOW_RELEASE_TRACK selects track ${T.name}`);s=`WORKFLOW_RELEASE_TRACK=${f} names no release track of this workspace (${o}); ignored`}if(!p)return d("HEAD is detached");if(t.length===1&&!c)return i(t[0],"only-track",`${t[0].name} is the only track`);let g=null,h=(T)=>e$(T,g??=e.probe.remotes()),v=(T)=>{let L=Fc(l,h(T));return L.length===1?L[0]:null},m=(T)=>{let L=T,X=new Set([T]);for(let K=0;K<t$;K+=1){let Ie=e.probe.recordedBase(L);if(!Ie)return null;let Fe=h(Ie),ut=v(Fe);if(ut)return ut;if(Fc(l,Fe).length>1||X.has(Fe))return null;X.add(Fe),L=Fe}return null},y=m(p);if(y)return i(y,"recorded-base",`${p} was created on ${u(y)}'s line (recorded base)`);for(let T of["reflog","checkout"]){let L=T==="reflog"?e.probe.createdFrom(p):e.probe.checkedOutFrom(p);if(!L)continue;let X=v(L)??m(h(L));if(X)return i(X,T,`${p} was created from ${h(L)} (${T==="reflog"?"branch reflog":"HEAD reflog"})`)}let w=[];for(let T of l)for(let L of new Set([T.integrationBranch,T.baseBranch])){let X=e.probe.mergeBase(p,L);if(X)w.push({track:T,ref:L,sha:X})}if(w.length===0)return d(`no track branch could be compared with ${p} (fetch the track branches)`);let b=new Map,_=(T,L)=>{if(T===L)return!1;let X=`${T}>${L}`;if(!b.has(X))b.set(X,e.probe.isAncestor(T,L));return b.get(X)},O=w.filter((T)=>w.every((L)=>L.track===T.track||_(L.sha,T.sha))),N=[...new Set(O.map((T)=>T.track))];if(N.length===1&&w.some((T)=>T.track!==N[0])){let T=O[0];return i(T.track,"ancestry",`${p} forked from ${T.ref} at ${T.sha.slice(0,12)}, after every other line's fork point`)}if(N.length===1)return d(`only ${u(N[0])} could be compared with ${p}`);let D=w.filter((T)=>!w.some((L)=>_(T.sha,L.sha)));return d(`${p} has the same or unrelated fork points with ${[...new Set(D.map((T)=>`${T.ref} (${T.track.name===Ms?"workspace default":T.track.name})`))].join(" and ")}`)}var pn=(e,t)=>{let n=qR("git",t,{cwd:e,encoding:"utf8",timeout:20000,windowsHide:!0,stdio:["ignore","pipe","ignore"]});return n.status===0?(n.stdout??"").trim():null},Jm=(e)=>`branch.${e}.workitBase`;var r$=(e)=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),Zm=(e,t)=>(pn(e,["log","-g","--date=unix","--format=%H%x09%gd%x09%gs",t,"--"])??"").split(`
63
63
  `).map((n)=>{let[r="",o="",...s]=n.split("\t");return{sha:r,time:Number(/@\{(\d+)\}$/u.exec(o)?.[1]??Number.NaN),subject:s.join("\t")}}).filter((n)=>n.sha&&Number.isFinite(n.time));function o$(e){let t,n,r=(o)=>(t??=Ws(e)??"origin",$t(e,`refs/remotes/${t}/${o}`)??$t(e,`refs/heads/${o}`));return{remotes:()=>n??=Nc(e),recordedBase:(o)=>pn(e,["config","--get",Jm(o)])||null,createdFrom:(o)=>{let i=pn(e,["reflog","show","--format=%gs",`refs/heads/${o}`,"--"])?.split(`
@@ -129,7 +129,7 @@ Skills: load the skill, never act from memory (aliases /wk-<name>).
129
129
  - retro (user-invoked; offer it): workit-retro
130
130
  - architecture, deepen modules (user-invoked; offer it): workit-architecture
131
131
  `.trim();import{spawnSync as O$}from"node:child_process";import{createHash as E$}from"node:crypto";import ke from"node:fs";import G from"node:path";var C$=/not a git repository \(or any (of the parent directories|parent up to)/u,ao=(e,t)=>{let n=O$("git",t,{cwd:e,encoding:"utf8",timeout:20000,killSignal:"SIGKILL",windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0",LC_ALL:"C",LANGUAGE:"C"}}),r=n.error;return{ok:n.status===0,stdout:n.stdout??"",stderr:r?String(r.message):n.stderr??"",missing:r?.code==="ENOENT"}},Ks=(e)=>E$("sha256").update(e).digest("hex").slice(0,12),Mt=(e)=>{try{return ke.realpathSync.native(e)}catch{return e}},A$=["GIT_DIR","GIT_COMMON_DIR","GIT_WORK_TREE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"],P$=(e)=>{try{return ke.statSync(G.join(e,"HEAD")).isFile()&&ke.statSync(G.join(e,"objects")).isDirectory()&&ke.statSync(G.join(e,"refs")).isDirectory()}catch{return!1}},z$=(e)=>{try{return/^\s*refstorage\s*=\s*reftable\s*$/imu.test(ke.readFileSync(G.join(e,"config"),"utf8"))}catch{return!1}};function N$(e){if(A$.some((r)=>process.env[r]))return null;let t=Mt(e),n=null;for(;;){let r;try{r=ke.statSync(t)}catch{return null}if(n!==null&&r.dev!==n)return{kind:"none"};n=r.dev;let o=G.join(t,".git"),s=null;try{s=ke.statSync(o)}catch{}let i=null,a=null;if(s){if(a=t,s.isDirectory())i=o;else if(s.isFile()){let l="";try{l=ke.readFileSync(o,"utf8")}catch{return null}let u=/^gitdir: (.+)$/mu.exec(l);if(!u)return null;i=G.resolve(t,u[1].trim())}else return null;if(!ke.existsSync(G.join(i,"HEAD")))return null}else if(P$(t))i=t;if(i){let l=i;try{l=G.resolve(i,ke.readFileSync(G.join(i,"commondir"),"utf8").trim())}catch{}if(!ke.existsSync(G.join(l,"objects")))return null;return{kind:"repo",common:Mt(l),gitDir:Mt(i),top:a===null?null:Mt(a),reftable:z$(l)}}let c=G.dirname(t);if(c===t)return{kind:"none"};t=c}}function _e(e){e=G.resolve(e);let t=!1;try{t=ke.statSync(e).isDirectory()}catch{}if(!t)return{dir:G.join(e,".workit"),shared:!1,top:null};let n=N$(e);if(n?.kind==="none")return{dir:G.join(e,".workit"),shared:!1,top:null};if(n?.kind==="repo")return{dir:G.join(n.common,"workit"),shared:!0,top:n.top,git:{gitDir:n.gitDir,top:n.top,reftable:n.reftable}};let r=ao(e,["rev-parse","--path-format=absolute","--git-common-dir"]),o=r.stdout.trim();if(r.ok&&o){let s=ao(e,["rev-parse","--path-format=absolute","--show-toplevel"]);return{dir:G.join(Mt(G.resolve(e,o)),"workit"),shared:!0,top:s.ok&&s.stdout.trim()?Mt(s.stdout.trim()):null}}if(r.missing||!r.ok&&C$.test(r.stderr))return{dir:G.join(e,".workit"),shared:!1,top:null};return Error(`cannot locate the workit store: git rev-parse failed (${r.stderr.trim().split(`
132
- `)[0]||"no output"}); fix the repository (git status should work here)`)}var sk=(e)=>{for(let t of["rebase-merge","rebase-apply"])try{let n=ke.readFileSync(G.join(e,t,"head-name"),"utf8").trim(),r=/^refs\/heads\/(.+)$/u.exec(n);if(r)return r[1]}catch{}return null};function qs(e,t){if(!t.shared)return{key:`dir-${Ks(e)}`,kind:"dir",branch:null};let n=(c)=>({key:c,kind:"branch",branch:c});if(t.git&&!t.git.reftable){let c="";try{c=ke.readFileSync(G.join(t.git.gitDir,"HEAD"),"utf8").trim()}catch{}let l=/^ref: refs\/heads\/(.+)$/u.exec(c);if(l&&l[1]!==".invalid")return n(l[1]);if(/^[0-9a-f]{40,64}$/u.test(c)){let u=sk(t.git.gitDir);if(u)return n(u);return{key:`detached-${Ks(t.git.top??t.git.gitDir)}`,kind:"detached",branch:null}}}let r=ao(e,["symbolic-ref","-q","--short","HEAD"]),o=r.ok?r.stdout.trim():"";if(o&&o!==".invalid")return n(o);let s=ao(e,["rev-parse","--path-format=absolute","--git-dir"]);if(s.ok&&s.stdout.trim()){let c=sk(s.stdout.trim());if(c)return n(c)}let i=ao(e,["rev-parse","--path-format=absolute","--show-toplevel"]),a=i.ok&&i.stdout.trim()?i.stdout.trim():e;return{key:`detached-${Ks(Mt(a))}`,kind:"detached",branch:null}}function Js(e,t){let n=G.resolve(e),r=n;try{r=ke.realpathSync(n)}catch{return n}let o=t??_e(r);if(o instanceof Error||!o.shared||!o.top)return r;if(Mt(r)===o.top)return r;try{return ke.realpathSync(o.top)}catch{return r}}function Kc(e){if(!e.shared)return[];let t=[],n=(s)=>{let i;try{i=ke.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of i)if(a.isDirectory())n(G.join(s,a.name));else t.push(G.join(s,a.name))};if(n(G.join(G.dirname(e.dir),"logs","refs","heads")),e.git)t.push(G.join(e.git.gitDir,"logs","HEAD"));let r=new Set,o=[];for(let s of t){let i="";try{i=ke.readFileSync(s,"utf8")}catch{continue}for(let a of i.matchAll(/ (\d+) [+-]\d{4}\tBranch: renamed refs\/heads\/(\S+) to refs\/heads\/(\S+)/gu)){let c={from:a[2],to:a[3],at:Number(a[1])},l=`${c.at}\x00${c.from}\x00${c.to}`;if(r.has(l))continue;r.add(l),o.push(c)}}return o.toSorted((s,i)=>s.at-i.at)}function ik(e,t,n){let r=e,o=Math.floor(Date.parse(t)/1000);for(let s of n)if(s.from===r&&s.at>=o)r=s.to,o=s.at;return r}var co=(e)=>{let t=Mt(e);if(process.platform==="win32")t=t.toLowerCase();return`${G.basename(t).replace(/[^A-Za-z0-9._-]/g,"_").slice(0,40)||"root"}-${Ks(t)}`};import{createHash as L$,randomUUID as uk}from"node:crypto";var hn=1,It="1.0.0";var dk=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,D$=/^[0-9a-f]{64}$/,Gs=(e)=>{for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let r=e.charCodeAt(t+1);if(Number.isNaN(r)||r<56320||r>57343)return!0;t+=1}else if(n>=56320&&n<=57343)return!0}return!1},A=nt().check((e)=>{if(Gs(e.value))e.issues.push({code:"custom",input:e.value,message:"invalid Unicode",path:[]})}),J=A.regex(dk,"expected lowercase UUID"),Xc=/^[0-9a-f][0-9a-f-]{7,35}$/,Vs=A.regex(Xc,"expected a UUID or an id prefix of 8+ characters"),ze=A.regex(D$,"expected lowercase SHA-256 digest"),se=A.regex(dk,"expected UUID revision"),j$=(e)=>{let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/.exec(e);if(!t)return!1;let[,n,r,o,s,i,a]=t,c=new Date(0);return c.setUTCFullYear(Number(n),Number(r)-1,Number(o)),c.setUTCHours(Number(s),Number(i),Number(a),0),c.getUTCFullYear()===Number(n)&&c.getUTCMonth()===Number(r)-1&&c.getUTCDate()===Number(o)&&c.getUTCHours()===Number(s)&&c.getUTCMinutes()===Number(i)&&c.getUTCSeconds()===Number(a)},W$=A.check((e)=>{if(!j$(e.value))e.issues.push({code:"custom",input:e.value,message:"expected UTC timestamp",path:[]})}),Ft=W$,qc=to().int().safe(),Te=A.min(1),Xs=Te.check((e)=>{if(e.value!=="."&&(e.value.includes("\\")||e.value.split("/").includes("..")))e.issues.push({code:"custom",input:e.value,message:"invalid path",path:[]})}),gn=ze.nullable(),M$=J.nullable(),Yc=B(["opencode","cursor","codex_cli","codex_desktop","pi","workit_cli","claude_code"]),F$=B(["enforced","agent_guided","unavailable"]),pk=B(["verified","accepted_limitations","stopped"]),mn=C({description:A,paths:P(Xs),exclusions:P(Xs)}).strict(),kn=(e,t)=>{let n=(l)=>l.length>1?l.replace(/\/+$/,""):l,r={...e,paths:e.paths.map(n),exclusions:e.exclusions.map(n)},o=(t.paths.length?t.paths:["."]).map(n),s=t.exclusions.map(n),i=(l,u)=>u.exclusions.some((d)=>d===l||l.startsWith(`${d}/`)),a=(l)=>r.paths.some((u)=>u==="."||l===u||l.startsWith(`${u}/`))&&!i(l,r),c=(l)=>s.some((u)=>u===l||l.startsWith(`${u}/`));return o.every(a)&&!r.exclusions.some((l)=>o.some((u)=>(u==="."||l===u||l.startsWith(`${u}/`))&&!c(l)))},pe=ft("kind",[C({kind:M("file"),path:Xs,digest:gn}).strict(),C({kind:M("record"),collection:B(["evidence","decisions","findings","workers"]),id:J}).strict(),C({kind:M("host"),host:Yc,handle:Te}).strict(),C({kind:M("external"),url:A.url()}).strict()]),Jc=(e,t)=>{if(Array.isArray(e)){let n=[];for(let r of e){let o=Jc(r,t);if(!o.drop)n.push(o.value)}return{drop:!1,value:n}}if(typeof e==="object"&&e!==null){if(pe.safeParse(e).success){let r=t(e);return r===null?{drop:!0}:{drop:!1,value:r}}let n={};for(let[r,o]of Object.entries(e)){let s=Jc(o,t);n[r]=s.drop?null:s.value}return{drop:!1,value:n}}return{drop:!1,value:e}},Gc=(e,t,n)=>{if(typeof e==="object"&&e!==null&&!Array.isArray(e)&&pe.safeParse(e).success){let o=n(e);return o===null?{drop:!0}:{drop:!1,value:o}}let r=t;while(r instanceof Cs||r instanceof no||r instanceof As)r=r.unwrap();if(r===pe){if(!pe.safeParse(e).success)return{drop:!1,value:e};let o=n(e);return o===null?{drop:!0}:{drop:!1,value:o}}if(r instanceof Rc){if(!Array.isArray(e))return{drop:!1,value:e};let o=[];for(let s of e){let i=Gc(s,r.element,n);if(!i.drop)o.push(i.value)}return{drop:!1,value:o}}if(r instanceof Es){if(typeof e!=="object"||e===null||Array.isArray(e))return{drop:!1,value:e};let o=r.shape,s=e,i={};for(let[a,c]of Object.entries(s)){if(!(a in o)){let d=Jc(c,n);i[a]=d.drop?null:d.value;continue}let l=o[a],u=Gc(c,l,n);if(u.drop){if(l instanceof no||l instanceof As)continue;if(l instanceof Cs){i[a]=null;continue}return{drop:!0}}i[a]=u.value}return{drop:!1,value:i}}return{drop:!1,value:e}},yn=(e,t,n)=>{let r=Gc(e,t,n);return r.drop?null:r.value},pr=C({kind:B(["host_observed","agent_reported","imported"]),host:Yc,session:pe.nullable(),workerId:M$}).strict(),Wn=(e)=>C({id:J,recordedAt:Ft,provenance:pr,data:e}).strict(),B$=["trivial","normal","high"],lo=C({riskTier:B(B$),behaviorChange:ue(),productChoiceOpen:ue(),needsPlan:ue(),note:A.nullable(),refs:P(pe)}).strict(),Qc=dm({}),H$=C({id:Te,kind:B(["host","project","user"]),statement:A,source:pe,acceptanceAllowed:ue(),requires:P(C({kind:B(["check","method","decision"]),scope:mn,refs:P(pe),method:B(["investigation","challenge","artifacts","testing","verification","review","delegation","continuity","decisions"]).nullable(),before:B(["dependent_action","write","close"]),dependentAction:A.nullable()}).strict().check((e)=>{let t=e.value;if(!(t.kind==="method"&&t.method!==null||t.kind!=="method"&&t.method===null))e.issues.push({code:"custom",input:t,message:"method obligations require a method; checks and decisions do not",path:["method"]})}))}).strict(),Fn=C({objective:A,scope:mn,authorityRefs:P(pe)}).strict(),el=C({summary:A,nextAction:A.nullable(),blockers:P(C({reason:A,dependentAction:A,refs:P(pe)}).strict())}).strict(),Z$=B(["investigation","challenge","artifacts","testing","verification","review","delegation","continuity","decisions"]),Bn=C({policyVersion:A.regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/),inputDigest:ze,requirements:P(C({id:ze,ruleId:Te,dimension:Z$,scope:mn,reason:A,satisfaction:A,before:B(["dependent_action","write","close"]),dependentAction:A.nullable(),acceptanceAllowed:ue()}).strict())}).strict(),Uj=Bn.shape.requirements.element,tl=C({recordedAt:Ft,fromInputDigest:gn,toInputDigest:ze,added:P(ze),retired:P(ze),reason:A}).strict(),nl=C({id:ze,scope:mn,completeness:B(["known","uncertain"]),files:P(C({path:Xs,kind:B(["file","symlink","absent"]),digest:gn,executable:ue().nullable()}).strict().check((e)=>{let t=e.value;if(!(t.kind==="absent"?t.digest===null&&t.executable===null:t.kind==="file"?t.digest!==null&&typeof t.executable==="boolean":t.digest!==null&&t.executable===null))e.issues.push({code:"custom",input:t,message:"invalid file metadata",path:[]})})),environment:P(C({name:Te,value:A.nullable(),refs:P(pe)}).strict()).check((e)=>{if(new Set(e.value.map((t)=>t.name)).size!==e.value.length)e.issues.push({code:"custom",input:e.value,message:"duplicate environment name",path:[]})}),head:A.nullable()}).strict().check((e)=>{if(e.value.id!==hl(e.value))e.issues.push({code:"custom",input:e.value,message:"candidate identity does not match its content",path:["id"]})}),rl=C({observer:M("workit_cli"),name:Te.nullable(),configured:ue(),argv:P(A).min(1),shell:ue(),cwd:Te,exitCode:qc,durationMs:qc.min(0),timedOut:ue(),head:A.nullable(),tree:A.nullable(),dirty:ue().nullable(),signal:A.nullable(),treeAfter:A.nullable(),modifiedWorktree:ue(),base:A.nullable(),patchId:A.nullable(),environment:C({platform:Te,arch:Te,vars:ar(Te,A.nullable())}).strict(),logDigest:A.nullable(),logRef:A.nullable(),logTail:P(A).max(40),ledgerRowId:A.nullable(),attestation:C({host:Te,session:A.nullable(),agentId:A.nullable()}).strict().nullable()}).strict(),fk="evidence.*.data.observation",gk={kind:B(["check","review","investigation","artifact"]),claim:A,requirementIds:P(ze),beforeCandidateId:gn.optional(),candidateId:gn.optional(),result:B(["passed","failed","missing","skipped"]),summary:A,refs:P(pe),exitCode:qc.nullable(),reviewContext:pe.nullable()},ol=C({...gk,observation:rl.optional()}).strict(),U$=C(gk).strict(),K$=C({evidenceId:J,status:B(["passed","failed","missing","skipped","stale"]),reason:A}).strict(),dr=C({purpose:B(["design","action","limitation","preference"]),binding:C({taskId:J,workspaceId:J,scope:mn,presented:A,contentRefs:P(pe),statedChoice:C({ref:A,text:A}).strict().optional()}).strict(),digest:ze,response:B(["approved","rejected","stated"]),requirementIds:P(ze),revoked:C({at:Ft,reason:A}).strict().nullable()}).strict(),sl=C({claim:A,consequence:A,scope:mn,candidateId:gn,refs:P(pe),disposition:B(["open","fixed","dismissed","deferred"]),resolution:C({reason:A,evidenceIds:P(J),decisionIds:P(J)}).strict().nullable()}).strict(),hk=C({role:B(["investigator","reviewer","implementer"]),objective:A,scope:mn,decisionIds:P(J),requirementIds:P(ze),candidateId:gn.optional(),stoppingCondition:A}).strict(),mk=C({outcome:B(["completed","failed","cancelled"]),summary:A,evidenceIds:P(J),findingIds:P(Vs)}).strict(),q$=C({assignment:hk,state:B(["assigned","dispatching","running","cancelling","stopped","unknown"]),session:pe.nullable(),coordinator:pe.optional(),report:mk.nullable()}).strict(),kk=C({outcome:pk,at:Ft,summary:A,decisionIds:P(J),evidenceIds:P(J)}).strict(),il=C({createdWith:A.nullable(),updatedWith:A}).strict(),gt=C({schemaVersion:M(1),id:J,workspaceId:J,revision:se,createdAt:Ft,updatedAt:Ft,origin:C({workspaceId:J,taskId:J,exportDigest:ze}).strict().nullable(),intent:Wn(Fn),constraints:P(H$),status:B(["active","paused","closed"]),closure:kk.nullable(),progress:el,pauseReason:A.nullable().optional(),runtime:il.optional(),assessments:P(Wn(Qc)),judgments:P(Wn(lo)).optional(),policy:Bn.nullable(),policyChanges:P(tl),candidates:P(nl),evidence:P(Wn(ol)),decisions:P(Wn(dr)),findings:P(Wn(sl)),workers:P(Wn(q$)),critical:P(Te).optional()}).strict(),ak=(e)=>e.reduce((t,n)=>t+n.keys.length,0),yk=(e,t=[])=>{let n=[];for(let r of e){if(r.code==="unrecognized_keys"){n.push({path:[...t,...r.path],keys:r.keys});continue}if(r.code!=="invalid_union")return null;let o=r.errors.map((s)=>yk(s,[...t,...r.path])).filter((s)=>s!==null&&s.length>0).reduce((s,i)=>s===null||ak(i)<ak(s)?i:s,null);if(!o)return null;n.push(...o)}return n},J$=(e)=>e.map((t)=>typeof t==="number"?"*":String(t)).join("."),G$=(e,t)=>e===t||e.startsWith(`${t}.`)||t.startsWith(`${e}.`),vk=(e,t)=>{let n=e.safeParse(t);if(n.success)return{success:!0,data:n.data,stripped:[]};let r={success:!1,error:n.error,critical:[]},o=typeof t==="object"&&t!==null&&Array.isArray(t.critical)?t.critical.filter((c)=>typeof c==="string").map((c)=>c.split(".").map((l)=>/^\d+$/.test(l)?"*":l).join(".")):[],s=[],i=structuredClone(t);for(let c=0;c<8&&!n.success;c++){let l=yk(n.error.issues);if(l===null||l.length===0)return r;for(let u of l){let d=i;for(let p of u.path)d=typeof d==="object"&&d!==null?d[p]:void 0;if(typeof d!=="object"||d===null)return r;for(let p of u.keys)s.push(J$([...u.path,p])),delete d[p]}n=e.safeParse(i)}if(!n.success)return r;let a=[...new Set(s.filter((c)=>o.some((l)=>G$(c,l))))];if(a.length>0)return{...r,critical:a};return{success:!0,data:n.data,stripped:[...new Set(s)]}},fr=C({schemaVersion:M(1),id:J,revision:se,root:Te,runtime:il.optional(),critical:P(Te).optional()}).strict(),V$=C({name:Te,surface:Te,assurance:F$,reason:A,refs:P(pe)}).strict(),wk=C({requirementId:ze,status:B(["satisfied","unsatisfied","accepted_limitation","unavailable"]),evidenceIds:P(J),decisionIds:P(J),reason:A}).strict(),Kj=C({task:gt,workspace:fr,capabilities:P(V$),requirements:P(wk),evidence:P(K$)}).strict(),X$=C({id:J,revision:se,workspaceRevision:se,createdAt:Ft,updatedAt:Ft,runtime:il.nullable(),objective:A,status:B(["active","paused","closed"]),closure:kk.nullable(),progress:el,policy:Bn.nullable(),requirements:P(wk)}).strict(),qj=X$.omit({policy:!0,requirements:!0}).extend({source:pr.pick({host:!0,kind:!0})}).strict(),Ys=C({schemaVersion:M(1),exportedAt:Ft,sourceWorkspaceId:J,task:gt,digest:ze}).strict(),Jj=C({host:Yc,actor:A}).strict(),Y$={schemaVersion:M(1)},ur={expectedRevision:se.optional(),expectedWorkspaceRevision:se.optional()},ye={taskId:J},ce=(e)=>C({...Y$,...e}).strict(),al={start:ce({action:M("start"),expectedWorkspaceRevision:se.nullable().optional(),intent:Fn}),list:ce({action:M("list"),status:B(["open","closed","all"]).optional(),query:nt().trim().min(1).max(200).optional(),limit:to().int().min(1).max(50).optional()}),inspect:ce({action:M("inspect"),...ye,view:B(["summary","full"]).optional()}),revise:ce({action:M("revise"),...ye,...ur,expectedWorkspaceRevision:se.optional(),intent:Fn,reason:A}),progress:ce({action:M("progress"),...ye,expectedRevision:se.optional(),progress:el}),pause:ce({action:M("pause"),...ye,...ur,expectedWorkspaceRevision:se.optional(),reason:A}),resume:ce({action:M("resume"),...ye,...ur,expectedWorkspaceRevision:se.optional()}),close:ce({action:M("close"),...ye,...ur,expectedWorkspaceRevision:se.optional(),outcome:pk,summary:A,decisionIds:P(J).optional()})},ck=ar(nt(),pt()),cl={assess:ce({action:M("assess"),...ye,expectedRevision:se.optional(),judgment:ck}),preview:ce({action:M("preview"),...ye,judgment:ck}),explain:ce({action:M("explain"),...ye})},ll={record:ce({action:M("record"),...ye,expectedRevision:se.optional(),evidence:U$})},ul={record:ce({action:M("record"),...ye,expectedRevision:se.optional(),claim:A,consequence:A,scope:mn,candidateId:gn.optional(),refs:P(pe)}),resolve:ce({action:M("resolve"),...ye,expectedRevision:se.optional(),findingId:Vs,disposition:B(["open","fixed","dismissed","deferred"]),reason:A,evidenceIds:P(J),decisionIds:P(J)})},dl={record:ce({action:M("record"),...ye,expectedRevision:se.optional(),purpose:dr.shape.purpose,binding:dr.shape.binding.extend({taskId:J.optional(),workspaceId:J.optional()}),response:dr.shape.response,requirementIds:P(ze)}),revoke:ce({action:M("revoke"),...ye,expectedRevision:se.optional(),decisionId:J,reason:A})},pl={assign:ce({action:M("assign"),...ye,...ur,expectedWorkspaceRevision:se.optional(),assignment:hk}),report:ce({action:M("report"),...ye,expectedRevision:se.optional(),expectedWorkspaceRevision:se.optional(),workerId:Vs,report:mk}),cancel:ce({action:M("cancel"),...ye,...ur,expectedWorkspaceRevision:se.optional(),workerId:Vs,reason:A})},fl={export:ce({action:M("export"),...ye}),import:ce({action:M("import"),expectedWorkspaceRevision:se.nullable().optional(),bundle:Ys})},Q$={task:ft("action",Object.values(al)),policy:ft("action",Object.values(cl)),evidence:ft("action",Object.values(ll)),finding:ft("action",Object.values(ul)),decision:ft("action",Object.values(dl)),worker:ft("action",Object.values(pl)),state:ft("action",Object.values(fl))},eI={task:Object.keys(al),policy:Object.keys(cl),evidence:Object.keys(ll),finding:Object.keys(ul),decision:Object.keys(dl),worker:Object.keys(pl),state:Object.keys(fl)},tI=(e)=>Object.values(e).map((t)=>("taskId"in t.shape)?t.extend({taskId:J.optional()}):t),Mn=(e)=>ft("action",tI(e)),nI={task:Mn(al),policy:Mn(cl),evidence:Mn(ll),finding:Mn(ul),decision:Mn(dl),worker:Mn(pl),state:Mn(fl)},x=(e,t,n)=>({ok:!0,schemaVersion:1,revision:e,workspaceRevision:t,data:n}),k=(e,t,n={})=>({ok:!1,schemaVersion:1,code:e,error:t,details:n});function gr(e,t,n){if(n.includes(t))return x(null,null,t);let r=n.filter((o)=>o.startsWith(t));if(r.length===1)return x(null,null,r[0]);if(r.length===0)return k("not_found",`${e} not found`);return k("invalid_input",`${e} prefix ${t} is ambiguous; candidates: ${r.join(", ")}`)}function vn(e,t){if(typeof t==="object"&&t!==null&&"schemaVersion"in t&&t.schemaVersion!==hn)return k("unsupported_version","unsupported schema version",{operation:e});let n=Q$[e].safeParse(t);if(n.success)return x(null,null,n.data);let r=n.error.issues.map((o)=>({path:o.code==="unrecognized_keys"?o.keys.join("."):o.path.join("."),reason:o.message}));return k("invalid_input","operation input is invalid",{fields:r})}function Vc(e,t){if(e===null||typeof e==="boolean"||typeof e==="string"){if(typeof e==="string"&&Gs(e))throw TypeError("invalid Unicode");return e}if(typeof e==="number"){if(!Number.isSafeInteger(e))throw TypeError("number must be a finite safe integer");return e}if(typeof e!=="object")throw TypeError("value is not JSON serializable");if(t.has(e))throw TypeError("cyclic value");t.add(e);let n;if(Array.isArray(e)){for(let r=0;r<e.length;r+=1)if(!(r in e))throw TypeError("sparse array");n=e.map((r)=>Vc(r,t))}else{if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError("value is not a JSON object");if(Reflect.ownKeys(e).some((r)=>typeof r!=="string"))throw TypeError("symbol key is not JSON");if(Object.keys(e).some((r)=>Gs(r)))throw TypeError("invalid Unicode");n=Object.fromEntries(Object.keys(e).toSorted().map((r)=>[r,Vc(e[r],t)]))}return t.delete(e),n}function qe(e){return JSON.stringify(Vc(e,new Set))}function rt(e){if(typeof e==="string"&&Gs(e))throw TypeError("invalid Unicode");return L$("sha256").update(typeof e==="string"?e:qe(e),"utf8").digest("hex")}function ve(){return uk().toLowerCase()}function ht(){return uk().toLowerCase()}var fn=(e,t)=>{let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let o=e.charCodeAt(r)-t.charCodeAt(r);if(o!==0)return o}return e.length-t.length},lk=(e,t)=>e===t?0:e===null?-1:t===null?1:fn(e,t),rI=(e,t)=>e===t?0:e===null?-1:t===null?1:Number(e)-Number(t);function gl(e){let{digest:t,revoked:n,...r}=e;return rt(r)}function hl(e){let t={description:e.scope.description,paths:[...e.scope.paths].toSorted(fn),exclusions:[...e.scope.exclusions].toSorted(fn)};return rt({scope:t,completeness:e.completeness,files:[...e.files].toSorted((n,r)=>fn(n.path,r.path)||fn(n.kind,r.kind)||lk(n.digest,r.digest)||rI(n.executable,r.executable)),environment:e.environment.map(({name:n,value:r})=>({name:n,value:r})).toSorted((n,r)=>fn(n.name,r.name)||lk(n.value,r.value)),head:e.head})}function bk(e){return rt({...e,scope:{description:e.scope.description,paths:[...e.scope.paths].toSorted(fn),exclusions:[...e.scope.exclusions].toSorted(fn)}})}import{createHash as MO}from"node:crypto";import*as de from"node:fs";import{spawnSync as au}from"node:child_process";import Ee from"node:path";import{spawnSync as oI}from"node:child_process";import Bt from"node:fs";import ot from"node:path";var sI=["test","lint","typecheck","check"],hr=".workit/checks.json",ei="workit.checks.json";function ml(e){let t=ot.join(e,hr),n=ot.join(e,ei);return!Bt.existsSync(t)&&Bt.existsSync(n)?n:t}function ti(e){try{let t=JSON.parse(Bt.readFileSync(ml(e),"utf8")),n=Hn(t)?t.resources:void 0,r=Hn(n)?n.heavyCommands:void 0;return Array.isArray(r)?r.filter((o)=>typeof o==="string"):[]}catch{return[]}}var Hn=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),iI=/[|&;<>()$`\\*?[\]{}~!#]/u;function aI(e){let t=[],n="",r=null,o=!1;for(let s of e){if(r){if(s===r)r=null;else n+=s;continue}if(s==='"'||s==="'"){r=s,o=!0;continue}if(/\s/u.test(s)){if(o)t.push(n);n="",o=!1;continue}if(iI.test(s))return Error(`"${e}" uses shell syntax (${s}); configure an argv array instead`);n+=s,o=!0}if(r)return Error(`"${e}" has an unterminated quote`);if(o)t.push(n);return t.length?t:Error("empty command")}var _k=(e,t)=>{let n=oI("git",t,{cwd:e,encoding:"utf8",timeout:20000,killSignal:"SIGKILL",windowsHide:!0});return(n.status===0?(n.stdout??"").trim():"")||null};function cI(e){return ot.resolve(_k(e,["rev-parse","--show-toplevel"])??e)}var lI=(e)=>{let t=(n)=>Bt.existsSync(ot.join(e,n));if(t("bun.lock")||t("bun.lockb"))return"bun";if(t("pnpm-lock.yaml"))return"pnpm";if(t("yarn.lock"))return"yarn";return"npm"},uI=(e,t)=>{let n=[e,"run",t],r=[n];if(e==="pnpm"||e==="yarn"||e==="npm"&&t==="test")r.push([e,t]);return{name:t,argv:n,accepts:r}},xk=/^[a-z0-9][a-z0-9:._-]{0,63}$/u;function dI(e){let t=(a)=>{try{return Bt.readFileSync(ot.join(e,a),"utf8")}catch{return null}},n=[],r=(a)=>{if(!n.some((c)=>c.name===a.name))n.push(a)},o=t("package.json");if(o!==null){let a=null;try{a=JSON.parse(o)}catch{}let c=Hn(a)&&Hn(a.scripts)?a.scripts:{},l=lI(e);for(let u of sI){let d=c[u];if(typeof d==="string"&&d.trim()!=="")r(uI(l,u))}}let s=(a,c)=>({name:a,argv:c,accepts:[c]});if(t("go.mod")!==null)r(s("test",["go","test","./..."]));if(t("Cargo.toml")!==null)r(s("test",["cargo","test"]));if(t("pytest.ini")!==null||/\bpytest\b/u.test(t("pyproject.toml")??""))r(s("test",["pytest"]));let i=t("Makefile")??t("makefile")??t("GNUmakefile");if(i!==null&&/^test\s*:(?!=)/mu.test(i))r(s("test",["make","test"]));return n}var Sk=["testing","verification"];function pI(e){let t=ml(e);if(Bt.existsSync(t))return t;let n=_k(e,["rev-parse","--path-format=absolute","--git-common-dir"]);if(!n||ot.basename(n)!==".git")return t;let r=ot.dirname(n);if(ot.resolve(r)===ot.resolve(e))return t;let o=ml(r);return Bt.existsSync(o)?o:t}function Rk(e){let t=cI(e),n=pI(t),r=ot.basename(n)===ei,o=r?ei:hr,s=r?{note:`${ei} is deprecated; move it to ${hr} (workit doctor --fix)`}:{},i=(d=null)=>({source:d?o:"none",root:t,checks:[],gates:{},error:d,...s}),a=null;try{a=Bt.readFileSync(n,"utf8")}catch(d){if(d.code!=="ENOENT")return i(`cannot read ${o}: ${d.message}`)}if(a===null){let d=dI(t);return d.length?{source:"defaults",root:t,checks:d,gates:{},error:null}:i()}let c;try{c=JSON.parse(a)}catch{return i(`${o} is not valid JSON`)}if(!Hn(c)||!Hn(c.checks))return i(`${o} must be {"checks":{"<name>":"<command>"|["argv",…]}}`);let l=[];for(let[d,p]of Object.entries(c.checks)){if(!xk.test(d))return i(`${o}: check name "${d}" must match ${xk.source}`);let f=typeof p==="string"?aI(p):Array.isArray(p)&&p.length>0&&p.every((g)=>typeof g==="string"&&g.length>0)?p:Error("expected a command string or a non-empty argv array");if(f instanceof Error)return i(`${o}: check "${d}": ${f.message}`);l.push({name:d,argv:f,accepts:[f]})}let u={};if(c.gates!==void 0){if(!Hn(c.gates))return i(`${o}: gates must be {"testing":"<name>"|["<name>",…]}`);for(let[d,p]of Object.entries(c.gates)){if(!Sk.includes(d))return i(`${o}: unknown gate "${d}" (use ${Sk.join(" or ")})`);let f=typeof p==="string"?[p]:p;if(!Array.isArray(f)||f.length===0||!f.every((g)=>typeof g==="string"&&l.some((h)=>h.name===g)))return i(`${o}: gates.${d} must name configured checks`);u[d]=f}}return{source:o,root:t,checks:l,gates:u,error:null,...s,resources:c.resources}}var fI=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]);function $k(e,t,n,r){if(e.error||t===null||r!==".")return!1;let o=e.checks.find((s)=>s.name===t);return Boolean(o?.accepts.some((s)=>fI(s,n)))}function Ik(e,t){let n=e.gates[t];if(n)return n;let r=e.checks.map((o)=>o.name);if(t==="testing")return r.includes("test")?["test"]:[];return r}var Qs;function gI(e=process.env){if(Qs!==void 0)return Qs;let n=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean):[""];return Qs=(e.PATH??e.Path??"").split(ot.delimiter).filter(Boolean).some((o)=>n.some((s)=>{try{return Bt.statSync(ot.join(o,`workit${s}`)).isFile()}catch{return!1}})),Qs}function ni(e,t,n=gI()){return n?`workit check ${e}`:`npx -y @brainervirus/workit-cli@${t} check ${e}`}import{createHash as pT,randomUUID as Sy}from"node:crypto";import*as I from"node:fs";import E from"node:path";var hI=new Set(["helper-failed","helper-unavailable","not-empty","not-found","not-removable","permission-unverified","read-failed","timeout","unsupported-platform"]);function mI(e){return hI.has(e)?"operational":"policy"}class Tt extends Error{code;category;details;constructor(e,t,n={}){super(t,n);this.name="FsSafeError",this.code=e,this.category=mI(e),this.details=n.details}}function Tk(e){return e===0||e===0n}function kI(e,t){return typeof e===typeof t?e===t:BigInt(e)===BigInt(t)}function Ok(e,t,n){if(kI(e,t))return!1;return n!=="win32"||!Tk(e)&&!Tk(t)}function ri(e,t,n=process.platform){return!Ok(e.dev,t.dev,n)&&!Ok(e.ino,t.ino,n)}import{randomBytes as SI}from"node:crypto";import uo from"node:fs";import Ht from"node:path";import yI from"node:fs";function Ek(e,t={}){let n=e===void 0?t.defaultValue:e;if(n===void 0||n===Number.POSITIVE_INFINITY)return n;if(!Number.isSafeInteger(n)||n<0)throw RangeError(`${t.label??"maxBytes"} must be a non-negative safe integer or Infinity`);return n}var Ck=65536;function vI(e){let t=Number.isFinite(e)?Math.min(Ck,e+1):Ck;return Buffer.allocUnsafe(Math.max(1,t))}function wI(e,t,n){return Number.isFinite(t)?Math.min(n,t-e+1):n}function bI(e){let t=e.total+e.bytesRead;if(t>e.maxBytes)throw new Tt("too-large",`file exceeds limit of ${e.maxBytes} bytes (got at least ${t})`);return e.chunks.push(Buffer.from(e.scratch.subarray(0,e.bytesRead))),t}function Ak(e,t){Ek(t);let n=[],r=vI(t),o=0;while(!0){let s=wI(o,t,r.length),i=yI.readSync(e,r,0,s,null);if(i===0)return Buffer.concat(n,o);o=bI({chunks:n,scratch:r,bytesRead:i,total:o,maxBytes:t})}}import xI from"node:fs";function Pk(e){let t=e?.constants??xI.constants,n=process.platform!=="win32"&&e?.followSymlinks!==!0&&typeof t.O_NOFOLLOW==="number"?t.O_NOFOLLOW:0,r=process.platform!=="win32"&&typeof t.O_NONBLOCK==="number"?t.O_NONBLOCK:0;return t.O_RDONLY|n|r}var kl=1048576,Nk=16,_I=Nk*8,Lk="\t".repeat(8),RI=new RegExp(`\\n(${Lk}[ \\t]{${_I}})\\n$`);function vl(e,t){return e&&{...e,payload:II(e.raw,t)}}function $I(){let e=Lk;for(let t of SI(Nk))for(let n=7;n>=0;n-=1)e+=t&1<<n?"\t":" ";return e}function yl(e){return RI.exec(e)?.[1]}function Dk(e){let t=$I(),n=`${JSON.stringify(e,null,2)}
132
+ `)[0]||"no output"}); fix the repository (git status should work here)`)}var sk=(e)=>{for(let t of["rebase-merge","rebase-apply"])try{let n=ke.readFileSync(G.join(e,t,"head-name"),"utf8").trim(),r=/^refs\/heads\/(.+)$/u.exec(n);if(r)return r[1]}catch{}return null};function qs(e,t){if(!t.shared)return{key:`dir-${Ks(e)}`,kind:"dir",branch:null};let n=(c)=>({key:c,kind:"branch",branch:c});if(t.git&&!t.git.reftable){let c="";try{c=ke.readFileSync(G.join(t.git.gitDir,"HEAD"),"utf8").trim()}catch{}let l=/^ref: refs\/heads\/(.+)$/u.exec(c);if(l&&l[1]!==".invalid")return n(l[1]);if(/^[0-9a-f]{40,64}$/u.test(c)){let u=sk(t.git.gitDir);if(u)return n(u);return{key:`detached-${Ks(t.git.top??t.git.gitDir)}`,kind:"detached",branch:null}}}let r=ao(e,["symbolic-ref","-q","--short","HEAD"]),o=r.ok?r.stdout.trim():"";if(o&&o!==".invalid")return n(o);let s=ao(e,["rev-parse","--path-format=absolute","--git-dir"]);if(s.ok&&s.stdout.trim()){let c=sk(s.stdout.trim());if(c)return n(c)}let i=ao(e,["rev-parse","--path-format=absolute","--show-toplevel"]),a=i.ok&&i.stdout.trim()?i.stdout.trim():e;return{key:`detached-${Ks(Mt(a))}`,kind:"detached",branch:null}}function Js(e,t){let n=G.resolve(e),r=n;try{r=ke.realpathSync(n)}catch{return n}let o=t??_e(r);if(o instanceof Error||!o.shared||!o.top)return r;if(Mt(r)===o.top)return r;try{return ke.realpathSync(o.top)}catch{return r}}function Kc(e){if(!e.shared)return[];let t=[],n=(s)=>{let i;try{i=ke.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of i)if(a.isDirectory())n(G.join(s,a.name));else t.push(G.join(s,a.name))};if(n(G.join(G.dirname(e.dir),"logs","refs","heads")),e.git)t.push(G.join(e.git.gitDir,"logs","HEAD"));let r=new Set,o=[];for(let s of t){let i="";try{i=ke.readFileSync(s,"utf8")}catch{continue}for(let a of i.matchAll(/ (\d+) [+-]\d{4}\tBranch: renamed refs\/heads\/(\S+) to refs\/heads\/(\S+)/gu)){let c={from:a[2],to:a[3],at:Number(a[1])},l=`${c.at}\x00${c.from}\x00${c.to}`;if(r.has(l))continue;r.add(l),o.push(c)}}return o.toSorted((s,i)=>s.at-i.at)}function ik(e,t,n){let r=e,o=Math.floor(Date.parse(t)/1000);for(let s of n)if(s.from===r&&s.at>=o)r=s.to,o=s.at;return r}var co=(e)=>{let t=Mt(e);if(process.platform==="win32")t=t.toLowerCase();return`${G.basename(t).replace(/[^A-Za-z0-9._-]/g,"_").slice(0,40)||"root"}-${Ks(t)}`};import{createHash as L$,randomUUID as uk}from"node:crypto";var hn=1,It="1.0.0";var dk=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,D$=/^[0-9a-f]{64}$/,Gs=(e)=>{for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let r=e.charCodeAt(t+1);if(Number.isNaN(r)||r<56320||r>57343)return!0;t+=1}else if(n>=56320&&n<=57343)return!0}return!1},A=nt().check((e)=>{if(Gs(e.value))e.issues.push({code:"custom",input:e.value,message:"invalid Unicode",path:[]})}),J=A.regex(dk,"expected lowercase UUID"),Xc=/^[0-9a-f][0-9a-f-]{7,35}$/,Vs=A.regex(Xc,"expected a UUID or an id prefix of 8+ characters"),ze=A.regex(D$,"expected lowercase SHA-256 digest"),se=A.regex(dk,"expected UUID revision"),j$=(e)=>{let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$/.exec(e);if(!t)return!1;let[,n,r,o,s,i,a]=t,c=new Date(0);return c.setUTCFullYear(Number(n),Number(r)-1,Number(o)),c.setUTCHours(Number(s),Number(i),Number(a),0),c.getUTCFullYear()===Number(n)&&c.getUTCMonth()===Number(r)-1&&c.getUTCDate()===Number(o)&&c.getUTCHours()===Number(s)&&c.getUTCMinutes()===Number(i)&&c.getUTCSeconds()===Number(a)},W$=A.check((e)=>{if(!j$(e.value))e.issues.push({code:"custom",input:e.value,message:"expected UTC timestamp",path:[]})}),Ft=W$,qc=to().int().safe(),Te=A.min(1),Xs=Te.check((e)=>{if(e.value!=="."&&(e.value.includes("\\")||e.value.split("/").includes("..")))e.issues.push({code:"custom",input:e.value,message:"invalid path",path:[]})}),gn=ze.nullable(),M$=J.nullable(),Yc=B(["opencode","cursor","codex_cli","codex_desktop","pi","workit_cli","claude_code"]),F$=B(["enforced","agent_guided","unavailable"]),pk=B(["verified","accepted_limitations","stopped"]),mn=C({description:A,paths:P(Xs),exclusions:P(Xs)}).strict(),kn=(e,t)=>{let n=(l)=>l.length>1?l.replace(/\/+$/,""):l,r={...e,paths:e.paths.map(n),exclusions:e.exclusions.map(n)},o=(t.paths.length?t.paths:["."]).map(n),s=t.exclusions.map(n),i=(l,u)=>u.exclusions.some((d)=>d===l||l.startsWith(`${d}/`)),a=(l)=>r.paths.some((u)=>u==="."||l===u||l.startsWith(`${u}/`))&&!i(l,r),c=(l)=>s.some((u)=>u===l||l.startsWith(`${u}/`));return o.every(a)&&!r.exclusions.some((l)=>o.some((u)=>(u==="."||l===u||l.startsWith(`${u}/`))&&!c(l)))},pe=ft("kind",[C({kind:M("file"),path:Xs,digest:gn}).strict(),C({kind:M("record"),collection:B(["evidence","decisions","findings","workers"]),id:J}).strict(),C({kind:M("host"),host:Yc,handle:Te}).strict(),C({kind:M("external"),url:A.url()}).strict()]),Jc=(e,t)=>{if(Array.isArray(e)){let n=[];for(let r of e){let o=Jc(r,t);if(!o.drop)n.push(o.value)}return{drop:!1,value:n}}if(typeof e==="object"&&e!==null){if(pe.safeParse(e).success){let r=t(e);return r===null?{drop:!0}:{drop:!1,value:r}}let n={};for(let[r,o]of Object.entries(e)){let s=Jc(o,t);n[r]=s.drop?null:s.value}return{drop:!1,value:n}}return{drop:!1,value:e}},Gc=(e,t,n)=>{if(typeof e==="object"&&e!==null&&!Array.isArray(e)&&pe.safeParse(e).success){let o=n(e);return o===null?{drop:!0}:{drop:!1,value:o}}let r=t;while(r instanceof Cs||r instanceof no||r instanceof As)r=r.unwrap();if(r===pe){if(!pe.safeParse(e).success)return{drop:!1,value:e};let o=n(e);return o===null?{drop:!0}:{drop:!1,value:o}}if(r instanceof Rc){if(!Array.isArray(e))return{drop:!1,value:e};let o=[];for(let s of e){let i=Gc(s,r.element,n);if(!i.drop)o.push(i.value)}return{drop:!1,value:o}}if(r instanceof Es){if(typeof e!=="object"||e===null||Array.isArray(e))return{drop:!1,value:e};let o=r.shape,s=e,i={};for(let[a,c]of Object.entries(s)){if(!(a in o)){let d=Jc(c,n);i[a]=d.drop?null:d.value;continue}let l=o[a],u=Gc(c,l,n);if(u.drop){if(l instanceof no||l instanceof As)continue;if(l instanceof Cs){i[a]=null;continue}return{drop:!0}}i[a]=u.value}return{drop:!1,value:i}}return{drop:!1,value:e}},yn=(e,t,n)=>{let r=Gc(e,t,n);return r.drop?null:r.value},pr=C({kind:B(["host_observed","agent_reported","imported"]),host:Yc,session:pe.nullable(),workerId:M$}).strict(),Wn=(e)=>C({id:J,recordedAt:Ft,provenance:pr,data:e}).strict(),B$=["trivial","normal","high"],lo=C({riskTier:B(B$),behaviorChange:ce(),productChoiceOpen:ce(),needsPlan:ce(),note:A.nullable(),refs:P(pe)}).strict(),Qc=dm({}),H$=C({id:Te,kind:B(["host","project","user"]),statement:A,source:pe,acceptanceAllowed:ce(),requires:P(C({kind:B(["check","method","decision"]),scope:mn,refs:P(pe),method:B(["investigation","challenge","artifacts","testing","verification","review","delegation","continuity","decisions"]).nullable(),before:B(["dependent_action","write","close"]),dependentAction:A.nullable()}).strict().check((e)=>{let t=e.value;if(!(t.kind==="method"&&t.method!==null||t.kind!=="method"&&t.method===null))e.issues.push({code:"custom",input:t,message:"method obligations require a method; checks and decisions do not",path:["method"]})}))}).strict(),Fn=C({objective:A,scope:mn,authorityRefs:P(pe)}).strict(),el=C({summary:A,nextAction:A.nullable(),blockers:P(C({reason:A,dependentAction:A,refs:P(pe)}).strict())}).strict(),Z$=B(["investigation","challenge","artifacts","testing","verification","review","delegation","continuity","decisions"]),Bn=C({policyVersion:A.regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/),inputDigest:ze,requirements:P(C({id:ze,ruleId:Te,dimension:Z$,scope:mn,reason:A,satisfaction:A,before:B(["dependent_action","write","close"]),dependentAction:A.nullable(),acceptanceAllowed:ce()}).strict())}).strict(),Uj=Bn.shape.requirements.element,tl=C({recordedAt:Ft,fromInputDigest:gn,toInputDigest:ze,added:P(ze),retired:P(ze),reason:A}).strict(),nl=C({id:ze,scope:mn,completeness:B(["known","uncertain"]),files:P(C({path:Xs,kind:B(["file","symlink","absent"]),digest:gn,executable:ce().nullable()}).strict().check((e)=>{let t=e.value;if(!(t.kind==="absent"?t.digest===null&&t.executable===null:t.kind==="file"?t.digest!==null&&typeof t.executable==="boolean":t.digest!==null&&t.executable===null))e.issues.push({code:"custom",input:t,message:"invalid file metadata",path:[]})})),environment:P(C({name:Te,value:A.nullable(),refs:P(pe)}).strict()).check((e)=>{if(new Set(e.value.map((t)=>t.name)).size!==e.value.length)e.issues.push({code:"custom",input:e.value,message:"duplicate environment name",path:[]})}),head:A.nullable()}).strict().check((e)=>{if(e.value.id!==hl(e.value))e.issues.push({code:"custom",input:e.value,message:"candidate identity does not match its content",path:["id"]})}),rl=C({observer:M("workit_cli"),name:Te.nullable(),configured:ce(),argv:P(A).min(1),shell:ce(),cwd:Te,exitCode:qc,durationMs:qc.min(0),timedOut:ce(),head:A.nullable(),tree:A.nullable(),dirty:ce().nullable(),signal:A.nullable(),treeAfter:A.nullable(),modifiedWorktree:ce(),base:A.nullable(),patchId:A.nullable(),environment:C({platform:Te,arch:Te,vars:ar(Te,A.nullable())}).strict(),logDigest:A.nullable(),logRef:A.nullable(),logTail:P(A).max(40),ledgerRowId:A.nullable(),attestation:C({host:Te,session:A.nullable(),agentId:A.nullable()}).strict().nullable()}).strict(),fk="evidence.*.data.observation",gk={kind:B(["check","review","investigation","artifact"]),claim:A,requirementIds:P(ze),beforeCandidateId:gn.optional(),candidateId:gn.optional(),result:B(["passed","failed","missing","skipped"]),summary:A,refs:P(pe),exitCode:qc.nullable(),reviewContext:pe.nullable()},ol=C({...gk,observation:rl.optional()}).strict(),U$=C(gk).strict(),K$=C({evidenceId:J,status:B(["passed","failed","missing","skipped","stale"]),reason:A}).strict(),dr=C({purpose:B(["design","action","limitation","preference"]),binding:C({taskId:J,workspaceId:J,scope:mn,presented:A,contentRefs:P(pe),statedChoice:C({ref:A,text:A}).strict().optional()}).strict(),digest:ze,response:B(["approved","rejected","stated"]),requirementIds:P(ze),revoked:C({at:Ft,reason:A}).strict().nullable()}).strict(),sl=C({claim:A,consequence:A,scope:mn,candidateId:gn,refs:P(pe),disposition:B(["open","fixed","dismissed","deferred"]),resolution:C({reason:A,evidenceIds:P(J),decisionIds:P(J)}).strict().nullable()}).strict(),hk=C({role:B(["investigator","reviewer","implementer"]),objective:A,scope:mn,decisionIds:P(J),requirementIds:P(ze),candidateId:gn.optional(),stoppingCondition:A}).strict(),mk=C({outcome:B(["completed","failed","cancelled"]),summary:A,evidenceIds:P(J),findingIds:P(Vs)}).strict(),q$=C({assignment:hk,state:B(["assigned","dispatching","running","cancelling","stopped","unknown"]),session:pe.nullable(),coordinator:pe.optional(),report:mk.nullable()}).strict(),kk=C({outcome:pk,at:Ft,summary:A,decisionIds:P(J),evidenceIds:P(J)}).strict(),il=C({createdWith:A.nullable(),updatedWith:A}).strict(),gt=C({schemaVersion:M(1),id:J,workspaceId:J,revision:se,createdAt:Ft,updatedAt:Ft,origin:C({workspaceId:J,taskId:J,exportDigest:ze}).strict().nullable(),intent:Wn(Fn),constraints:P(H$),status:B(["active","paused","closed"]),closure:kk.nullable(),progress:el,pauseReason:A.nullable().optional(),runtime:il.optional(),assessments:P(Wn(Qc)),judgments:P(Wn(lo)).optional(),policy:Bn.nullable(),policyChanges:P(tl),candidates:P(nl),evidence:P(Wn(ol)),decisions:P(Wn(dr)),findings:P(Wn(sl)),workers:P(Wn(q$)),critical:P(Te).optional()}).strict(),ak=(e)=>e.reduce((t,n)=>t+n.keys.length,0),yk=(e,t=[])=>{let n=[];for(let r of e){if(r.code==="unrecognized_keys"){n.push({path:[...t,...r.path],keys:r.keys});continue}if(r.code!=="invalid_union")return null;let o=r.errors.map((s)=>yk(s,[...t,...r.path])).filter((s)=>s!==null&&s.length>0).reduce((s,i)=>s===null||ak(i)<ak(s)?i:s,null);if(!o)return null;n.push(...o)}return n},J$=(e)=>e.map((t)=>typeof t==="number"?"*":String(t)).join("."),G$=(e,t)=>e===t||e.startsWith(`${t}.`)||t.startsWith(`${e}.`),vk=(e,t)=>{let n=e.safeParse(t);if(n.success)return{success:!0,data:n.data,stripped:[]};let r={success:!1,error:n.error,critical:[]},o=typeof t==="object"&&t!==null&&Array.isArray(t.critical)?t.critical.filter((c)=>typeof c==="string").map((c)=>c.split(".").map((l)=>/^\d+$/.test(l)?"*":l).join(".")):[],s=[],i=structuredClone(t);for(let c=0;c<8&&!n.success;c++){let l=yk(n.error.issues);if(l===null||l.length===0)return r;for(let u of l){let d=i;for(let p of u.path)d=typeof d==="object"&&d!==null?d[p]:void 0;if(typeof d!=="object"||d===null)return r;for(let p of u.keys)s.push(J$([...u.path,p])),delete d[p]}n=e.safeParse(i)}if(!n.success)return r;let a=[...new Set(s.filter((c)=>o.some((l)=>G$(c,l))))];if(a.length>0)return{...r,critical:a};return{success:!0,data:n.data,stripped:[...new Set(s)]}},fr=C({schemaVersion:M(1),id:J,revision:se,root:Te,runtime:il.optional(),critical:P(Te).optional()}).strict(),V$=C({name:Te,surface:Te,assurance:F$,reason:A,refs:P(pe)}).strict(),wk=C({requirementId:ze,status:B(["satisfied","unsatisfied","accepted_limitation","unavailable"]),evidenceIds:P(J),decisionIds:P(J),reason:A}).strict(),Kj=C({task:gt,workspace:fr,capabilities:P(V$),requirements:P(wk),evidence:P(K$)}).strict(),X$=C({id:J,revision:se,workspaceRevision:se,createdAt:Ft,updatedAt:Ft,runtime:il.nullable(),objective:A,status:B(["active","paused","closed"]),closure:kk.nullable(),progress:el,policy:Bn.nullable(),requirements:P(wk)}).strict(),qj=X$.omit({policy:!0,requirements:!0}).extend({source:pr.pick({host:!0,kind:!0})}).strict(),Ys=C({schemaVersion:M(1),exportedAt:Ft,sourceWorkspaceId:J,task:gt,digest:ze}).strict(),Jj=C({host:Yc,actor:A}).strict(),Y$={schemaVersion:M(1)},ur={expectedRevision:se.optional(),expectedWorkspaceRevision:se.optional()},ye={taskId:J},le=(e)=>C({...Y$,...e}).strict(),al={start:le({action:M("start"),expectedWorkspaceRevision:se.nullable().optional(),intent:Fn}),list:le({action:M("list"),status:B(["open","closed","all"]).optional(),query:nt().trim().min(1).max(200).optional(),limit:to().int().min(1).max(50).optional()}),inspect:le({action:M("inspect"),...ye,view:B(["summary","full"]).optional()}),revise:le({action:M("revise"),...ye,...ur,expectedWorkspaceRevision:se.optional(),intent:Fn,reason:A}),progress:le({action:M("progress"),...ye,expectedRevision:se.optional(),progress:el}),pause:le({action:M("pause"),...ye,...ur,expectedWorkspaceRevision:se.optional(),reason:A}),resume:le({action:M("resume"),...ye,...ur,expectedWorkspaceRevision:se.optional()}),close:le({action:M("close"),...ye,...ur,expectedWorkspaceRevision:se.optional(),outcome:pk,summary:A,decisionIds:P(J).optional()})},ck=ar(nt(),pt()),cl={assess:le({action:M("assess"),...ye,expectedRevision:se.optional(),judgment:ck}),preview:le({action:M("preview"),...ye,judgment:ck}),explain:le({action:M("explain"),...ye})},ll={record:le({action:M("record"),...ye,expectedRevision:se.optional(),evidence:U$})},ul={record:le({action:M("record"),...ye,expectedRevision:se.optional(),claim:A,consequence:A,scope:mn,candidateId:gn.optional(),refs:P(pe)}),resolve:le({action:M("resolve"),...ye,expectedRevision:se.optional(),findingId:Vs,disposition:B(["open","fixed","dismissed","deferred"]),reason:A,evidenceIds:P(J),decisionIds:P(J)})},dl={record:le({action:M("record"),...ye,expectedRevision:se.optional(),purpose:dr.shape.purpose,binding:dr.shape.binding.extend({taskId:J.optional(),workspaceId:J.optional()}),response:dr.shape.response,requirementIds:P(ze)}),revoke:le({action:M("revoke"),...ye,expectedRevision:se.optional(),decisionId:J,reason:A})},pl={assign:le({action:M("assign"),...ye,...ur,expectedWorkspaceRevision:se.optional(),assignment:hk}),report:le({action:M("report"),...ye,expectedRevision:se.optional(),expectedWorkspaceRevision:se.optional(),workerId:Vs,report:mk}),cancel:le({action:M("cancel"),...ye,...ur,expectedWorkspaceRevision:se.optional(),workerId:Vs,reason:A})},fl={export:le({action:M("export"),...ye}),import:le({action:M("import"),expectedWorkspaceRevision:se.nullable().optional(),bundle:Ys})},Q$={task:ft("action",Object.values(al)),policy:ft("action",Object.values(cl)),evidence:ft("action",Object.values(ll)),finding:ft("action",Object.values(ul)),decision:ft("action",Object.values(dl)),worker:ft("action",Object.values(pl)),state:ft("action",Object.values(fl))},eI={task:Object.keys(al),policy:Object.keys(cl),evidence:Object.keys(ll),finding:Object.keys(ul),decision:Object.keys(dl),worker:Object.keys(pl),state:Object.keys(fl)},tI=(e)=>Object.values(e).map((t)=>("taskId"in t.shape)?t.extend({taskId:J.optional()}):t),Mn=(e)=>ft("action",tI(e)),nI={task:Mn(al),policy:Mn(cl),evidence:Mn(ll),finding:Mn(ul),decision:Mn(dl),worker:Mn(pl),state:Mn(fl)},x=(e,t,n)=>({ok:!0,schemaVersion:1,revision:e,workspaceRevision:t,data:n}),k=(e,t,n={})=>({ok:!1,schemaVersion:1,code:e,error:t,details:n});function gr(e,t,n){if(n.includes(t))return x(null,null,t);let r=n.filter((o)=>o.startsWith(t));if(r.length===1)return x(null,null,r[0]);if(r.length===0)return k("not_found",`${e} not found`);return k("invalid_input",`${e} prefix ${t} is ambiguous; candidates: ${r.join(", ")}`)}function vn(e,t){if(typeof t==="object"&&t!==null&&"schemaVersion"in t&&t.schemaVersion!==hn)return k("unsupported_version","unsupported schema version",{operation:e});let n=Q$[e].safeParse(t);if(n.success)return x(null,null,n.data);let r=n.error.issues.map((o)=>({path:o.code==="unrecognized_keys"?o.keys.join("."):o.path.join("."),reason:o.message}));return k("invalid_input","operation input is invalid",{fields:r})}function Vc(e,t){if(e===null||typeof e==="boolean"||typeof e==="string"){if(typeof e==="string"&&Gs(e))throw TypeError("invalid Unicode");return e}if(typeof e==="number"){if(!Number.isSafeInteger(e))throw TypeError("number must be a finite safe integer");return e}if(typeof e!=="object")throw TypeError("value is not JSON serializable");if(t.has(e))throw TypeError("cyclic value");t.add(e);let n;if(Array.isArray(e)){for(let r=0;r<e.length;r+=1)if(!(r in e))throw TypeError("sparse array");n=e.map((r)=>Vc(r,t))}else{if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError("value is not a JSON object");if(Reflect.ownKeys(e).some((r)=>typeof r!=="string"))throw TypeError("symbol key is not JSON");if(Object.keys(e).some((r)=>Gs(r)))throw TypeError("invalid Unicode");n=Object.fromEntries(Object.keys(e).toSorted().map((r)=>[r,Vc(e[r],t)]))}return t.delete(e),n}function qe(e){return JSON.stringify(Vc(e,new Set))}function rt(e){if(typeof e==="string"&&Gs(e))throw TypeError("invalid Unicode");return L$("sha256").update(typeof e==="string"?e:qe(e),"utf8").digest("hex")}function ve(){return uk().toLowerCase()}function ht(){return uk().toLowerCase()}var fn=(e,t)=>{let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let o=e.charCodeAt(r)-t.charCodeAt(r);if(o!==0)return o}return e.length-t.length},lk=(e,t)=>e===t?0:e===null?-1:t===null?1:fn(e,t),rI=(e,t)=>e===t?0:e===null?-1:t===null?1:Number(e)-Number(t);function gl(e){let{digest:t,revoked:n,...r}=e;return rt(r)}function hl(e){let t={description:e.scope.description,paths:[...e.scope.paths].toSorted(fn),exclusions:[...e.scope.exclusions].toSorted(fn)};return rt({scope:t,completeness:e.completeness,files:[...e.files].toSorted((n,r)=>fn(n.path,r.path)||fn(n.kind,r.kind)||lk(n.digest,r.digest)||rI(n.executable,r.executable)),environment:e.environment.map(({name:n,value:r})=>({name:n,value:r})).toSorted((n,r)=>fn(n.name,r.name)||lk(n.value,r.value)),head:e.head})}function bk(e){return rt({...e,scope:{description:e.scope.description,paths:[...e.scope.paths].toSorted(fn),exclusions:[...e.scope.exclusions].toSorted(fn)}})}import{createHash as MO}from"node:crypto";import*as de from"node:fs";import{spawnSync as au}from"node:child_process";import Ee from"node:path";import{spawnSync as oI}from"node:child_process";import Bt from"node:fs";import ot from"node:path";var sI=["test","lint","typecheck","check"],hr=".workit/checks.json",ei="workit.checks.json";function ml(e){let t=ot.join(e,hr),n=ot.join(e,ei);return!Bt.existsSync(t)&&Bt.existsSync(n)?n:t}function ti(e){try{let t=JSON.parse(Bt.readFileSync(ml(e),"utf8")),n=Hn(t)?t.resources:void 0,r=Hn(n)?n.heavyCommands:void 0;return Array.isArray(r)?r.filter((o)=>typeof o==="string"):[]}catch{return[]}}var Hn=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),iI=/[|&;<>()$`\\*?[\]{}~!#]/u;function aI(e){let t=[],n="",r=null,o=!1;for(let s of e){if(r){if(s===r)r=null;else n+=s;continue}if(s==='"'||s==="'"){r=s,o=!0;continue}if(/\s/u.test(s)){if(o)t.push(n);n="",o=!1;continue}if(iI.test(s))return Error(`"${e}" uses shell syntax (${s}); configure an argv array instead`);n+=s,o=!0}if(r)return Error(`"${e}" has an unterminated quote`);if(o)t.push(n);return t.length?t:Error("empty command")}var _k=(e,t)=>{let n=oI("git",t,{cwd:e,encoding:"utf8",timeout:20000,killSignal:"SIGKILL",windowsHide:!0});return(n.status===0?(n.stdout??"").trim():"")||null};function cI(e){return ot.resolve(_k(e,["rev-parse","--show-toplevel"])??e)}var lI=(e)=>{let t=(n)=>Bt.existsSync(ot.join(e,n));if(t("bun.lock")||t("bun.lockb"))return"bun";if(t("pnpm-lock.yaml"))return"pnpm";if(t("yarn.lock"))return"yarn";return"npm"},uI=(e,t)=>{let n=[e,"run",t],r=[n];if(e==="pnpm"||e==="yarn"||e==="npm"&&t==="test")r.push([e,t]);return{name:t,argv:n,accepts:r}},xk=/^[a-z0-9][a-z0-9:._-]{0,63}$/u;function dI(e){let t=(a)=>{try{return Bt.readFileSync(ot.join(e,a),"utf8")}catch{return null}},n=[],r=(a)=>{if(!n.some((c)=>c.name===a.name))n.push(a)},o=t("package.json");if(o!==null){let a=null;try{a=JSON.parse(o)}catch{}let c=Hn(a)&&Hn(a.scripts)?a.scripts:{},l=lI(e);for(let u of sI){let d=c[u];if(typeof d==="string"&&d.trim()!=="")r(uI(l,u))}}let s=(a,c)=>({name:a,argv:c,accepts:[c]});if(t("go.mod")!==null)r(s("test",["go","test","./..."]));if(t("Cargo.toml")!==null)r(s("test",["cargo","test"]));if(t("pytest.ini")!==null||/\bpytest\b/u.test(t("pyproject.toml")??""))r(s("test",["pytest"]));let i=t("Makefile")??t("makefile")??t("GNUmakefile");if(i!==null&&/^test\s*:(?!=)/mu.test(i))r(s("test",["make","test"]));return n}var Sk=["testing","verification"];function pI(e){let t=ml(e);if(Bt.existsSync(t))return t;let n=_k(e,["rev-parse","--path-format=absolute","--git-common-dir"]);if(!n||ot.basename(n)!==".git")return t;let r=ot.dirname(n);if(ot.resolve(r)===ot.resolve(e))return t;let o=ml(r);return Bt.existsSync(o)?o:t}function Rk(e){let t=cI(e),n=pI(t),r=ot.basename(n)===ei,o=r?ei:hr,s=r?{note:`${ei} is deprecated; move it to ${hr} (workit doctor --fix)`}:{},i=(d=null)=>({source:d?o:"none",root:t,checks:[],gates:{},error:d,...s}),a=null;try{a=Bt.readFileSync(n,"utf8")}catch(d){if(d.code!=="ENOENT")return i(`cannot read ${o}: ${d.message}`)}if(a===null){let d=dI(t);return d.length?{source:"defaults",root:t,checks:d,gates:{},error:null}:i()}let c;try{c=JSON.parse(a)}catch{return i(`${o} is not valid JSON`)}if(!Hn(c)||!Hn(c.checks))return i(`${o} must be {"checks":{"<name>":"<command>"|["argv",…]}}`);let l=[];for(let[d,p]of Object.entries(c.checks)){if(!xk.test(d))return i(`${o}: check name "${d}" must match ${xk.source}`);let f=typeof p==="string"?aI(p):Array.isArray(p)&&p.length>0&&p.every((g)=>typeof g==="string"&&g.length>0)?p:Error("expected a command string or a non-empty argv array");if(f instanceof Error)return i(`${o}: check "${d}": ${f.message}`);l.push({name:d,argv:f,accepts:[f]})}let u={};if(c.gates!==void 0){if(!Hn(c.gates))return i(`${o}: gates must be {"testing":"<name>"|["<name>",…]}`);for(let[d,p]of Object.entries(c.gates)){if(!Sk.includes(d))return i(`${o}: unknown gate "${d}" (use ${Sk.join(" or ")})`);let f=typeof p==="string"?[p]:p;if(!Array.isArray(f)||f.length===0||!f.every((g)=>typeof g==="string"&&l.some((h)=>h.name===g)))return i(`${o}: gates.${d} must name configured checks`);u[d]=f}}return{source:o,root:t,checks:l,gates:u,error:null,...s,resources:c.resources}}var fI=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]);function $k(e,t,n,r){if(e.error||t===null||r!==".")return!1;let o=e.checks.find((s)=>s.name===t);return Boolean(o?.accepts.some((s)=>fI(s,n)))}function Ik(e,t){let n=e.gates[t];if(n)return n;let r=e.checks.map((o)=>o.name);if(t==="testing")return r.includes("test")?["test"]:[];return r}var Qs;function gI(e=process.env){if(Qs!==void 0)return Qs;let n=process.platform==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean):[""];return Qs=(e.PATH??e.Path??"").split(ot.delimiter).filter(Boolean).some((o)=>n.some((s)=>{try{return Bt.statSync(ot.join(o,`workit${s}`)).isFile()}catch{return!1}})),Qs}function ni(e,t,n=gI()){return n?`workit check ${e}`:`npx -y @brainervirus/workit-cli@${t} check ${e}`}import{createHash as pT,randomUUID as Sy}from"node:crypto";import*as I from"node:fs";import E from"node:path";var hI=new Set(["helper-failed","helper-unavailable","not-empty","not-found","not-removable","permission-unverified","read-failed","timeout","unsupported-platform"]);function mI(e){return hI.has(e)?"operational":"policy"}class Tt extends Error{code;category;details;constructor(e,t,n={}){super(t,n);this.name="FsSafeError",this.code=e,this.category=mI(e),this.details=n.details}}function Tk(e){return e===0||e===0n}function kI(e,t){return typeof e===typeof t?e===t:BigInt(e)===BigInt(t)}function Ok(e,t,n){if(kI(e,t))return!1;return n!=="win32"||!Tk(e)&&!Tk(t)}function ri(e,t,n=process.platform){return!Ok(e.dev,t.dev,n)&&!Ok(e.ino,t.ino,n)}import{randomBytes as SI}from"node:crypto";import uo from"node:fs";import Ht from"node:path";import yI from"node:fs";function Ek(e,t={}){let n=e===void 0?t.defaultValue:e;if(n===void 0||n===Number.POSITIVE_INFINITY)return n;if(!Number.isSafeInteger(n)||n<0)throw RangeError(`${t.label??"maxBytes"} must be a non-negative safe integer or Infinity`);return n}var Ck=65536;function vI(e){let t=Number.isFinite(e)?Math.min(Ck,e+1):Ck;return Buffer.allocUnsafe(Math.max(1,t))}function wI(e,t,n){return Number.isFinite(t)?Math.min(n,t-e+1):n}function bI(e){let t=e.total+e.bytesRead;if(t>e.maxBytes)throw new Tt("too-large",`file exceeds limit of ${e.maxBytes} bytes (got at least ${t})`);return e.chunks.push(Buffer.from(e.scratch.subarray(0,e.bytesRead))),t}function Ak(e,t){Ek(t);let n=[],r=vI(t),o=0;while(!0){let s=wI(o,t,r.length),i=yI.readSync(e,r,0,s,null);if(i===0)return Buffer.concat(n,o);o=bI({chunks:n,scratch:r,bytesRead:i,total:o,maxBytes:t})}}import xI from"node:fs";function Pk(e){let t=e?.constants??xI.constants,n=process.platform!=="win32"&&e?.followSymlinks!==!0&&typeof t.O_NOFOLLOW==="number"?t.O_NOFOLLOW:0,r=process.platform!=="win32"&&typeof t.O_NONBLOCK==="number"?t.O_NONBLOCK:0;return t.O_RDONLY|n|r}var kl=1048576,Nk=16,_I=Nk*8,Lk="\t".repeat(8),RI=new RegExp(`\\n(${Lk}[ \\t]{${_I}})\\n$`);function vl(e,t){return e&&{...e,payload:II(e.raw,t)}}function $I(){let e=Lk;for(let t of SI(Nk))for(let n=7;n>=0;n-=1)e+=t&1<<n?"\t":" ";return e}function yl(e){return RI.exec(e)?.[1]}function Dk(e){let t=$I(),n=`${JSON.stringify(e,null,2)}
133
133
  ${t}
134
134
  `,r=Buffer.byteLength(n,"utf8");if(r>kl)throw new Tt("too-large",`sidecar lock payload exceeds limit of ${kl} bytes (got ${r})`);return{raw:n,ownershipToken:t}}function jk(e,t){let n=Ht.resolve(t),r=Ht.relative(e.rootDir,n),o=r!==".."&&!r.startsWith(`..${Ht.sep}`)&&!Ht.isAbsolute(r)?r:Ht.relative(e.rootReal,n);if(!o||o===".."||o.startsWith(`..${Ht.sep}`)||Ht.isAbsolute(o))throw new Tt("outside-workspace","sidecar lock path is outside lockRoot");return o.split(Ht.sep).join(Ht.posix.sep)}function II(e,t){if(t)return t(e);try{let n=JSON.parse(e);return n&&typeof n==="object"&&!Array.isArray(n)?n:null}catch{return null}}function TI(e){if(e.code==="ENOENT")return null;throw e}function zk(e){try{return uo.lstatSync(e)}catch(t){return TI(t)}}function wl(e,t,n={}){return vl(bl(e,n),t)}function bl(e,t={}){let n;try{let r=zk(e);if(!r)return null;if(!r.isFile()||r.isSymbolicLink()){if(t.rejectNonFile)throw new Tt("not-file",`sidecar lock is not a regular file: ${e}`);return null}try{n=uo.openSync(e,Pk())}catch(a){if(a.code==="ENOENT")return null;throw t.onOpenFailure?.(a),a}let o=uo.fstatSync(n);if(!o.isFile()){if(t.rejectNonFile)throw new Tt("not-file",`sidecar lock is not a regular file: ${e}`);return null}let s=Ak(n,kl).toString("utf8"),i=zk(e);if(!i||!ri(r,o)||!ri(o,i))return null;return{raw:s,stat:i,ownershipToken:yl(s)}}finally{if(n!==void 0)uo.closeSync(n)}}function po(e,t){let n=wl(e);if(!n||!xl(n,t))return!1;return uo.rmSync(e),!0}function xl(e,t){if(t.ownershipToken!==void 0)return e.stat?.isFile()===!0&&e.raw!==void 0&&t.raw!==void 0&&yl(e.raw)===t.ownershipToken&&yl(t.raw)===t.ownershipToken&&e.raw===t.raw;if(t.stat&&e.stat&&!ri(t.stat,e.stat))return!1;if(t.raw!==void 0)return e.raw===t.raw;return t.stat!==void 0&&e.stat!==void 0}function oi(e,t){if(!Number.isFinite(e)||e<0)throw RangeError(`${t} must be a finite non-negative number`)}function Sl(e){if(e.retries!==void 0&&(!Number.isSafeInteger(e.retries)||e.retries<0))throw RangeError("lock retry.retries must be a non-negative safe integer");if(e.factor!==void 0)oi(e.factor,"lock retry.factor");if(e.minTimeout!==void 0)oi(e.minTimeout,"lock retry.minTimeout");if(e.maxTimeout!==void 0)oi(e.maxTimeout,"lock retry.maxTimeout");if(e.minTimeout!==void 0&&e.maxTimeout!==void 0&&e.minTimeout>e.maxTimeout)throw RangeError("lock retry.minTimeout must not exceed retry.maxTimeout")}function Wk(e){if(e===void 0||e===Number.POSITIVE_INFINITY)return;oi(e,"lock timeoutMs")}function Mk(e,t){Sl(e);let n=e.minTimeout??50,r=e.maxTimeout??1000,o=e.factor??1,s=Math.min(r,Math.max(n,n*o**t)),i=e.randomize?1+Math.random():1;return Math.min(r,Math.round(s*i))}var Fk=8;function si(e,t){let n=e;return process.platform==="win32"&&n?.code==="EPERM"&&n.path===t}function Bk(e){let t=e&&typeof e==="object"&&"createdAt"in e&&typeof e.createdAt==="string"?e.createdAt:"",n=Date.parse(t);return Number.isFinite(n)?n:null}var OI={staleRecovery:"fail-closed"},_l={...OI};function Hk(){return{..._l,retry:_l.retry?{..._l.retry}:void 0}}import fe from"node:fs";import st from"node:path";function Zk(e){if(e<=0)return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}var Rl=Symbol.for("fsSafe.syncSidecarLocks"),Uk=Symbol.for("fsSafe.syncSidecarLockCleanupRegistered"),EI=Symbol.for("fsSafe.syncSidecarLockCleanupHandler");function $l(){let e=globalThis;if(!e[Rl])e[Rl]=new Map;return e[Rl]}function Kk(){let e=$l();for(let[t,n]of e){if(n.timer)clearInterval(n.timer),n.timer=void 0;try{if(n.fd!==void 0)fe.closeSync(n.fd)}catch{}try{po(n.lockPath,n.snapshot)}catch{}e.delete(t)}}function CI(){let e=globalThis;if(e[Uk])return;e[Uk]=!0,e[EI]=Kk,process.on("exit",Kk)}function AI(e){let t=wl(e.lockPath,e.parsePayload);return!!t&&xl(t,e.snapshot)}function PI(e){let t=$l();if(t.get(e.normalizedTargetPath)!==e)return!1;if(e.refCount>1)return e.refCount-=1,!1;if(e.timer)clearInterval(e.timer),e.timer=void 0;if(e.fd!==void 0){let n=e.fd;e.fd=void 0,fe.closeSync(n)}return po(e.lockPath,e.snapshot),t.delete(e.normalizedTargetPath),!0}function qk(e){let t=!1,n=()=>{if(t)return;PI(e),t=!0};return{lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,verifyStillHeld:()=>AI(e),release:n,[Symbol.dispose]:n}}function Jk(e){return process.platform==="win32"?fe.realpathSync.native(e):fe.realpathSync(e)}function zI(e){let t=st.resolve(e);fe.mkdirSync(st.dirname(t),{recursive:!0});try{return st.join(Jk(st.dirname(t)),st.basename(t))}catch{return t}}function NI(e,t){let n=st.resolve(e);if(!t)return n;jk(t,n);let r=st.dirname(n),o=Jk(r),s=st.relative(t.rootReal,o);if(s===".."||s.startsWith(`..${st.sep}`)||st.isAbsolute(s))throw new Tt("outside-workspace","sidecar lock parent is outside lockRoot");return st.join(o,st.basename(n))}function LI(e,t,n){let r=Bk(e.payload);if(r!==null)return n-r>t;return!e.stat||n-e.stat.mtimeMs>t}function DI(e){try{return fe.lstatSync(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Il(e,t){let n=Hk(),r=t.retry??n.retry??{},o=t.timeoutMs??n.timeoutMs;Sl(r),Wk(o);let s=zI(e),i=NI(t.lockPath??`${s}.lock`,t.lockRoot),a=$l(),c=a.get(s);if(c&&t.reentrantOwner!==void 0&&c.reentrantOwner!==void 0&&t.reentrantOwner===c.reentrantOwner)return c.refCount+=1,qk(c);let l=t.staleMs??n.staleMs??30000,u=t.staleRecovery??n.staleRecovery,d=Date.now(),p=0,f=0,g=`${i}.reclaim`,h=()=>{let m=Date.now()-d;if(o!==void 0&&m>=o||r.retries!==void 0&&p>=r.retries)throw Object.assign(Error(`file lock timeout for ${s}`),{code:"file_lock_timeout",lockPath:i,normalizedTargetPath:s});let w=o===void 0||o===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,o-m);Zk(Math.min(Mk(r,p),w)),p+=1},v=(m)=>{if(!si(m,i)||++f>Fk)return!1;try{h()}catch(y){if(y.code==="file_lock_timeout")throw m;throw y}return!0};while(!0){if(DI(g)){h();continue}let m,y=t.payload(),{raw:w,ownershipToken:b}=Dk(y),_=!1;try{let O=process.platform!=="win32"&&typeof fe.constants.O_NOFOLLOW==="number"?fe.constants.O_NOFOLLOW:0;try{m=fe.openSync(i,fe.constants.O_WRONLY|fe.constants.O_CREAT|fe.constants.O_EXCL|O,384)}catch(L){throw _=si(L,i),L}fe.writeFileSync(m,w,"utf8"),fe.fsyncSync(m);let N={raw:w,payload:y,stat:fe.fstatSync(m),ownershipToken:b},D={fd:m,lockPath:i,normalizedTargetPath:s,parsePayload:t.parsePayload,refCount:1,reentrantOwner:t.reentrantOwner,snapshot:N};a.set(s,D),CI();let T=qk(D);if(t.onCompromised&&(t.compromiseCheckIntervalMs??0)>0)D.timer=setInterval(()=>{let L;try{L=T.verifyStillHeld()}catch{L=!1}if(!L&&D.timer)clearInterval(D.timer),D.timer=void 0,t.onCompromised?.({lockPath:i,normalizedTargetPath:s})},t.compromiseCheckIntervalMs),D.timer.unref();return m=void 0,T}catch(O){if(m!==void 0){let K={payload:null,stat:fe.fstatSync(m)};fe.closeSync(m),m=void 0,po(i,K)}if(_&&v(O))continue;if(O.code!=="EEXIST")throw O;if(a.has(s)){h();continue}let N,D=!1;try{N=bl(i,{rejectNonFile:!0,onOpenFailure:(K)=>{D=si(K,i)}})}catch(K){if(D&&v(K))continue;throw K}let T=vl(N,t.parsePayload);if(!T){h();continue}let L=Date.now();if(t.shouldReclaim?t.shouldReclaim({lockPath:i,normalizedTargetPath:s,payload:T.payload,staleMs:l,nowMs:L,heldByThisProcess:!1}):LI(T,l,L)){if(u==="remove-if-unchanged"&&T.raw!==void 0&&t.shouldRemoveStaleLock?.({lockPath:i,normalizedTargetPath:s,raw:T.raw,payload:T.payload})){let K=!1;try{if(fe.mkdirSync(g),K=!0,po(i,T))continue}catch(Ie){if(Ie.code!=="EEXIST")throw Ie;h();continue}finally{if(K)try{fe.rmdirSync(g)}catch{}}}throw Object.assign(Error(`file lock stale for ${s}`),{code:"file_lock_stale",lockPath:i,normalizedTargetPath:s})}h()}}}import{createHash as Yk,randomBytes as jI,timingSafeEqual as P1}from"node:crypto";import ge from"node:fs";import we from"node:path";var WI=[["OPENCODE_SESSION_ID",()=>"opencode"],["PI_SESSION_ID",()=>"pi"],["CODEX_THREAD_ID",(e)=>e.CODEX_INTERNAL_ORIGINATOR_OVERRIDE==="Codex Desktop"||e.CODEX_ELECTRON_RESOURCES_PATH?"codex_desktop":"codex_cli"]],Gk=(e)=>e?.replace(/_(?:cli|desktop)$/,"")??null;function Tl(e){let t=(o)=>e[o]?.trim()||null,n=null;for(let[o,s]of WI){let i=t(o);if(i){n={host:s(e),session:i};break}}let r=t("WORKIT_HOST");if(e.WORKIT_SESSION_ID!==void 0){if(!(n!==null&&r!==null&&Gk(r)!==Gk(n.host)))return{host:r,session:t("WORKIT_SESSION_ID")}}return n?{host:n.host,session:n.session}:{host:r,session:null}}var Vk=64,MI="workit-issued-sessions/3",Zn=(e)=>Yk("sha256").update(e).digest("hex").slice(0,32),Ol=()=>we.join(Le(),"issued"),Qk=()=>we.join(Le(),"issued-tokens");function ey(e){if(e===void 0)return;let t;try{let n=_e(e);if(n instanceof Error)return;if(t=we.join(n.dir,"hooks","issued"),!ge.existsSync(t))return}catch{return}for(let n of ty(t))try{let r=we.join(t,n);if(!ge.statSync(r).isDirectory())continue;let o=we.join(Ol(),n);ge.mkdirSync(o,{recursive:!0,mode:448});for(let s of ge.readdirSync(r)){try{ge.copyFileSync(we.join(r,s),we.join(o,s),ge.constants.COPYFILE_EXCL)}catch(i){if(i.code!=="EEXIST")throw i}ge.rmSync(we.join(r,s),{force:!0})}Xk(r)}catch{}Xk(t)}var ty=(e)=>{try{return ge.readdirSync(e)}catch{return[]}},Xk=(e)=>{try{ge.rmdirSync(e)}catch{}};var FI=(e)=>Yk("sha256").update(e).digest("hex");function ny(e,t,n){let r=jI(18).toString("hex");try{ey(e);let o=Zn(n),s=we.join(Qk(),Zn(t));ge.mkdirSync(s,{recursive:!0,mode:448}),ge.writeFileSync(we.join(s,o),`${FI(r)}
135
135
  `,{mode:384,flag:"wx"});let i=we.join(Ol(),Zn(t));return ge.mkdirSync(i,{recursive:!0,mode:448}),ge.writeFileSync(we.join(i,o),`${MI}
@@ -205,9 +205,9 @@ ${n.addendum}`:""}
205
205
  `)){if(!l.startsWith(r)||!l.endsWith(o))continue;let u=l.slice(r.length,l.length-o.length),{name:d}=Gw(s+u+i);if(d)c.push(d)}return c},bC=(e,t,n,r,o)=>{let s=e.implicit?[]:[...e.targets],i=[...e.globs??[]],a=e.matching===!0,c=e.implicit?n.get(`remote.${o}.push`):void 0;if(c?.length){let l=Vw(c);s.push(...l.targets),i.push(...l.globs),a||=l.matching}else if(e.implicit){let l=(Xt(n,"push.default")??"simple").toLowerCase(),u=t.branch?Xt(n,`branch.${t.branch}.merge`):void 0;if(l==="matching")a=!0;else if((l==="upstream"||l==="tracking")&&u?.startsWith("refs/heads/"))s.push(u.slice(11));else if(l!=="nothing")s.push(null)}if(e.allBranches)s.push(...r.heads);if(a){for(let l of r.heads)if(r.remoteHeads.has(l))s.push(l)}for(let l of i)s.push(...wC(t,l));return s},xC=(e)=>{if(!/[$`]/.test(e))return[e];let t=e.replace(/\$\{\w+:?[-=]([^}$`]*)\}/g,"$1").replace(/\$\{\w+\}|\$\w+/g,"");return/[$`]/.test(t)||!t?[]:[t]},SC=(e,t)=>{for(let n of xC(t)){if(Ki(e,n))return n;let r=n.startsWith("heads/")?n.slice(6):null;if(r&&Ki(e,r))return r}return null},ob=(e,t)=>e.tags.has(t)&&!e.heads.has(t),_C=(e,t,n)=>{let r=[...e.tags??[],...e.targets.filter((i)=>i!==null&&ob(t,i))];if(!r.length&&!e.allTags)return null;let o=`${Oa(n)}<version>`,s=r.length?r.join(" --release "):o;return`workit: raw ${V(`git push${e.allTags?" --tags":""}`)} of ${r.length?`tag ${r.join(", ")}`:"tags"} bypasses the release grant. Push a release tag with ${V(`workit git push --release ${s}`)} (${o} tags whose commit the production branch already has; a tag never moves), under the ${V("release")} grant (if refused, ask the user to run ${V("workit grant set <workspace> release=true")}).`},RC=(e,t)=>{let n=Ao("git",["ls-remote","--heads",t],{cwd:e.dir,encoding:"utf8",timeout:3000,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});if(n.status!==0)return null;return new Set((n.stdout??"").split(`
206
206
  `).map((r)=>r.split("\t")[1]??"").filter((r)=>r.startsWith("refs/heads/")).map((r)=>r.slice(11)))},zw=(e,t,n,r)=>{let o=e.allBranches?[...n.heads]:e.targets.map((a)=>a??t.branch),s,i=(a)=>(s===void 0?s=RC(t,r):s)?.has(a)??!0;for(let a of o){if(!a||/[$`]/.test(a))continue;if(e.deleted?.includes(a)||ob(n,a))continue;if(n.remoteHeads.has(a))continue;let c=Us(t.dir,a);if(c.ok||c.rule!=="allowed_pattern"||i(a))continue;return`workit: raw ${V("git push")} onto ${a}: ${c.error}`}return null},$C=(e,t,n)=>{switch(e.kind){case"commit":{let r=t==="cursor"&&n?`workit --session ${n}`:"workit";return e.amend?`workit: raw ${V("git commit --amend")} is recorded for this session; for new commits prefer ${V(`${r} git commit -m '<msg>'`)} (adds the Workit-Session trailer and checks branch and commit policy).`:`workit: prefer ${V(`${r} git commit -m '<msg>' [--all | -- <paths>]`)}: it adds the Workit-Session trailer and checks branch and commit policy.`}case"push":return e.blindForce?`workit: ${V("git push --force")} overwrites without a lease; use ${V("workit git push --force-with-lease")}.`:`workit: prefer ${V("workit git push")}: it refuses protected branches and verifies the remote tip.`;case"pr-create":return`workit: prefer ${V("workit pr create --fill")} (or --title/--body): it records the PR the merge gate checks.`;case"pr-read":case"merge":return null}},IC=(e,t,n)=>{if(!yC(t,e.remote,n))return null;if(e.mirror)return`workit: raw ${V("git push --mirror")} rewrites and deletes every remote ref, protected branches and tags included. Push one branch with ${V("workit git push")}.`;let r=e.remote??nb(n,t.branch)??"origin",o=vC(t,r),s=bC(e,t,n,o,r),i={...e,targets:s},a=e.allBranches?zw(i,t,o,r):null;if(a)return a;for(let c of s){let l=SC(t.dir,c??t.branch??"");if(l)return rb(e,l,t.dir)}return _C(i,o,t.dir)??(e.deletes?null:zw(i,t,o,r))},Ji=(e,t,n,r=new Map)=>{let o=[],s=new Map,i=(a)=>{let c=Je.resolve(e,a??".");if(!s.has(c)){let l=Du(c);s.set(c,l&&Yw(l)?l:null)}return s.get(c)??null};for(let a of Yt(t,n)){if(a.dir===void 0)continue;let c=a.tool!=="git"||eb.has(a.args[0]??"");if(!c&&!i(a.dir))continue;for(let l of c?[a]:qi(e,a,r)){if(l.dir===void 0)continue;let u=uC(l),d=u?i(l.dir):null;if(u&&d)o.push({action:u,repo:d,invocation:l})}}return o},lt=(e)=>{let t=Du(e);return t!==null&&Yw(t)},sb=(e,t,n)=>TC(t)&&Ji(e,t,n).some(({action:r})=>r.kind!=="commit"&&r.kind!=="pr-read"),TC=(e)=>/\b(?:git|gh|glab)\b/i.test(e),ju=(e)=>(e.event.kind==="shell.pre"||e.event.kind==="shell.post"?e.event.dialect:void 0)??"posix",Nw=(e)=>e.kind==="commit"&&e.amend?"commit-amend":e.kind==="push"&&e.blindForce?"push-force":e.kind,OC=(e,t,n)=>{let r=e.session.id,o=r?Cn(e,r,n):null;if(!o)return[...t.values()];let s=Gn(o),i=e.session.agentId?`${e.session.agentId}:`:"",a=[...t.keys()].filter((c)=>!s.raw.includes(i+c));if(a.length)To(o,{...s,raw:[...s.raw,...a.map((c)=>i+c)]});return a.map((c)=>t.get(c))};function No(e,t,n={}){try{let r=ju(e),o=new Map,s=null,i=new Map;for(let{action:c,repo:l,invocation:u}of Ji(e.cwd,t,r,i)){if(s??=l.location.dir,c.kind==="merge")return Lw(rb(c,null));if(c.kind==="push"){let p=IC(c,l,Qw(l.dir,u,i));if(p)return Lw(p)}let d=$C(c,e.host,e.session.id);if(d&&!o.has(Nw(c)))o.set(Nw(c),d)}if(n.nudge===!1||!s||o.size===0)return Fi;if(Qt(t,r).length>0)return Fi;let a=OC(e,o,s);return a.length?{kind:"context",text:a.join(`
207
207
  `)}:Fi}catch(r){return r instanceof ct?Wu(r):Fi}}var Lw=(e)=>({kind:"deny",reason:e,unblock:null}),Dw="Split it into simpler commands (no deeply nested substitutions or huge brace lists) and run them one at a time.",Wu=(e)=>({kind:"deny",reason:`workit: the shell hook could not analyze this command (${e.message}), so it does not run. ${Dw}`,unblock:Dw}),Mu="next",EC=3600,Fu=(e,t,n)=>Je.join(e.location.dir,"hooks",`commit-${jw("sha256").update(`${t}\x00${n}`).digest("hex").slice(0,32)}.json`),Gi=(e,t)=>e??`cmd:${jw("sha256").update(t).digest("hex")}`;function Bu(e,t,n){try{if(!e.session.id||!/\bcommit\b/.test(t))return;let r=Math.floor(Date.now()/1000);for(let{action:o,repo:s}of Ji(e.cwd,t,ju(e))){if(o.kind!=="commit")continue;let i=Fu(s,e.session.id,n);Et.mkdirSync(Je.dirname(i),{recursive:!0}),Et.writeFileSync(i,`${JSON.stringify({head:dC(s),at:r})}
208
- `)}}catch{}}var CC=(e)=>{let t=Ao("git",["log","-1","--format=%H%x1f%ct%x1f%s%x1f%(trailers:key=Workit-Session,valueonly,separator=%x2c)"],{cwd:e,encoding:"utf8",timeout:5000,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0",LC_ALL:"C"}}),[n,r,o="",s=""]=(t.status===0?t.stdout.trim():"").split("\x1F");return n&&/^[0-9a-f]{40,64}$/.test(n)?{sha:n,committed:Number(r),subject:o,trailer:s.trim()||null}:null},ib=(e,t,n)=>{let r;try{r=JSON.parse(Et.readFileSync(n,"utf8"))}catch{return}Et.rmSync(n,{force:!0});let o=e.session.id,s=Date.now()/1000;if(typeof r.at!=="number"||s-r.at>EC)return;if(!o||!t.branch)return;let i=CC(t.dir);if(!i||i.sha===r.head||i.committed<r.at)return;if(i.trailer&&i.trailer!==o)return;let a=it(t.dir);if(!a.ok)return;if(a.value.rows.some((l)=>l.type==="commit.recorded"&&(l.sha===i.sha||l.head===i.sha)))return;Rn(t.dir,{type:"commit.recorded",actor:{host:e.host,session:o,agentId:e.session.agentId},branch:t.branch,head:i.sha,sha:i.sha,session:o,agentId:e.session.agentId,subject:i.subject.slice(0,200),files:[],fileCount:null,via:"raw_shell"})};function Hu(e,t,n){try{if(!e.session.id||!/\bcommit\b/.test(t))return;for(let{action:r,repo:o}of Ji(e.cwd,t,ju(e)))if(r.kind==="commit")ib(e,o,Fu(o,e.session.id,n))}catch{}}function ab(e){try{if(!e.session.id)return;let t=Du(e.cwd);if(!t)return;let n=Fu(t,e.session.id,Mu);if(Et.existsSync(n))ib(e,t,n)}catch{}}var NC=/[$`*?[\]{}~]/u,LC=new Set(["-c","--create","-C","--force-create","--orphan"]),DC=new Set(["-b","-B","--orphan"]),jC=new Set(["-b","-B"]),WC=new Set(["-b","--branch"]),cb=new Set(["-d","-D","--delete","-l","--list","-a","--all","-r","--remotes","--show-current"].concat(["-v","-vv","--verbose","--contains","--no-contains","--merged","--no-merged"]).concat(["--points-at","--sort","--format","--column","--no-column","-u"]).concat(["--set-upstream-to","--unset-upstream","--edit-description","-i","--ignore-case"])),lb=new Set(["-m","-M","--move","-c","-C","--copy"]),Zu=(e,t)=>t.has(e)||e.length>=3&&[...t].some((n)=>n.startsWith("--")&&n.startsWith(e)),MC=(e)=>[...e].filter((t)=>/^-[^-]$/u.test(t)).join("").replaceAll("-",""),Vi=(e,t)=>{let n=MC(t);for(let r=1;r<e.length;r++){let o=e[r];if(o==="--")return null;if(o.startsWith("--")){let s=o.indexOf("=");if(!Zu(s>0?o.slice(0,s):o,t))continue;return s>0?o.slice(s+1):e[r+1]??null}if(!o.startsWith("-")||o.length<2)continue;for(let s=1;s<o.length;s++)if(n.includes(o[s]))return s+1<o.length?o.slice(s+1):e[r+1]??null}return null},FC=new Set(["--reason"]),BC=(e)=>{let t=Vi(e,jC);if(t!==null)return t;let n=[];for(let o=1;o<e.length;o++){let s=e[o];if(s==="--detach"||s==="-d")return null;if(FC.has(s))o++;else if(!s.startsWith("-"))n.push(s)}if(n.length!==1)return null;let r=n[0].split(/[\\/]/u).findLast(Boolean)??"";return r&&r!=="."&&r!==".."?r:null},HC=(e)=>{let t=!1,n=[];for(let r=1;r<e.length;r++){let o=e[r];if(o==="--"){n.push(...e.slice(r+1));break}if(o.startsWith("--")){let s=o.split("=",1)[0];if(Zu(s,cb))return null;if(Zu(s,lb))t=!0}else if(o.startsWith("-")&&o.length>1){let s=o.slice(1).split("");if(s.some((i)=>cb.has(`-${i}`)))return null;if(s.some((i)=>lb.has(`-${i}`)))t=!0}else n.push(o)}if(n.length<1||n.length>2)return null;return t?n.at(-1)??null:n[0]},Yi=(e,t,n=new Set)=>{let r=[];for(let o=t;o<e.length;o++){let s=e[o];if(s==="--")return[...r,...e.slice(o+1)];if(n.has(s))o++;else if(!s.startsWith("-")||s==="-")r.push(s)}return r},Xi=(e)=>e.startsWith("refs/heads/")?e.slice(11):null,ZC=(e,t)=>{if(e.some((o)=>o==="-d"||o==="--delete"))return[];if(e.includes("--stdin"))return(t??"").split(/[\n\0]/u).map((o)=>/^\s*(?:create|update)\s+(\S+)/u.exec(o)?.[1]??"").map(Xi).filter((o)=>o!==null);let[n]=Yi(e,1,new Set(["-m"])),r=n?Xi(n):null;return r?[r]:[]},UC=(e)=>{if(e.some((n)=>n==="-d"||n==="--delete"))return null;let[,t]=Yi(e,1,new Set(["-m"]));return t?Xi(t):null},KC=new Set(["--depth","--deepen","--shallow-since","--shallow-exclude","--refmap","-j","--jobs"].concat(["--upload-pack","-o","--server-option","--negotiation-tip","--filter"]).concat(["--recurse-submodules-default","--submodule-prefix","-s","--strategy","-X"]).concat(["--strategy-option"])),qC=(e,t)=>{if(e.includes("--all")||e.includes("--multiple"))return[];let n=e.includes("--stdin")?(t??"").split(/\s+/u).filter(Boolean):Yi(e,1,KC).slice(1),r=[];for(let o of n){let s=o.indexOf(":"),i=s>=0?o.slice(s+1):"";if(!i||i.includes("*"))continue;let a=i.startsWith("refs/")?Xi(i):i;if(a)r.push(a)}return r},JC=(e)=>{let t=Co(e);if(t?.kind!=="push"||t.remote!=="."||t.deletes)return[];return t.targets.filter((n)=>n!==null)},GC=(e,t)=>{let[n,r]=e;return(n==="switch"?[Vi(e,LC)]:n==="checkout"?[Vi(e,DC)]:n==="branch"?[HC(e)]:n==="worktree"&&r==="add"?[BC(e.slice(1))]:n==="stash"&&r==="branch"?Yi(e,2).slice(0,1):n==="update-ref"?ZC(e,t):n==="symbolic-ref"?[UC(e)]:n==="fetch"||n==="pull"?qC(e,t):n==="push"?JC(e):n==="subtree"&&r==="split"?[Vi(e.slice(1),WC)]:[]).filter((s)=>s!==null&&s!==""&&!s.startsWith("-")&&!NC.test(s))},VC=(e)=>e.flatMap((t)=>t.tool==="git"?GC(t.args,t.stdin).map((n)=>({branch:n,dir:t.dir})):[]);var XC=(e,t)=>AC("git",["show-ref","--verify","--quiet",`refs/heads/${t}`],{cwd:e,stdio:"ignore",timeout:5000}).status===0,ub=(e,t)=>{if(t===void 0)return null;if(t===null)return e;let n=zC.resolve(e,t);return PC(n)&&lt(n)?n:null},db=(e,t,n="posix")=>{let r=!1,o=new Map;for(let s of Yt(t,n)){if(s.tool!=="git"||ub(e,s.dir)===null)continue;for(let i of VC(qi(e,s,o))){let a=ub(e,i.dir);if(a===null||XC(a,i.branch))continue;r=!0;let c=Us(a,i.branch);if(!c.ok)return c}}return r?{ok:!0}:null};var Uu=(e,t,n="posix")=>{let r;try{r=db(e,t,n)}catch(o){if(o instanceof ct)return Wu(o);throw o}return r&&!r.ok?{kind:"deny",reason:`branch_policy_denied: ${r.error}`,unblock:null}:{kind:"none"}};var Qi=["git","pr","ci","stack","release","task","ledger","evidence","finding","decision","worker","verify-delivery","policy","doctor","help"],Ku=["--unverified","--overwrite-unintegrated"],JF=new Set(Qi),YC=(e)=>Ku.some((t)=>e===t||e.startsWith(`${t}=`)),QC=(e)=>/^(?:.*[\\/])?workit(?:-cli)?$/u.test(e);var pb=(e)=>`Workit: \`${e}\` overrides a Workit gate, so the user decides this call (no allow rule covers it).`,fb=(e,t="posix")=>{for(let n of $e(e,t)){if(n.unanalyzable){let a=e.replaceAll(/['"\\`]/gu,"");if(!/\bworkit\b/u.test(a))return null;let c=Ku.find((l)=>a.includes(l));return c?pb(c):null}let r=n.words.findIndex(QC);if(r<0)continue;let o=n.words.slice(r+1),s=o.indexOf("--"),i=(s<0?o:o.slice(0,s)).find(YC);if(i)return pb(i.split("=")[0]??i)}return null};import Ju from"node:fs";import eA from"node:os";import le from"node:path";var ea=()=>({deny:[],allow:[]}),ta=(e)=>{try{return Ju.readFileSync(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}},en=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function gb(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==='"'){let o=/"(?:[^"\\]|\\.)*"/y;o.lastIndex=n;let s=o.exec(e);if(!s)throw Error("unterminated string");t+=s[0],n+=s[0].length-1}else if(r==="/"&&e[n+1]==="/"){while(n<e.length&&e[n]!==`
208
+ `)}}catch{}}var CC=(e)=>{let t=Ao("git",["log","-1","--format=%H%x1f%ct%x1f%s%x1f%(trailers:key=Workit-Session,valueonly,separator=%x2c)"],{cwd:e,encoding:"utf8",timeout:5000,windowsHide:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0",LC_ALL:"C"}}),[n,r,o="",s=""]=(t.status===0?t.stdout.trim():"").split("\x1F");return n&&/^[0-9a-f]{40,64}$/.test(n)?{sha:n,committed:Number(r),subject:o,trailer:s.trim()||null}:null},ib=(e,t,n)=>{let r;try{r=JSON.parse(Et.readFileSync(n,"utf8"))}catch{return}Et.rmSync(n,{force:!0});let o=e.session.id,s=Date.now()/1000;if(typeof r.at!=="number"||s-r.at>EC)return;if(!o||!t.branch)return;let i=CC(t.dir);if(!i||i.sha===r.head||i.committed<r.at)return;if(i.trailer&&i.trailer!==o)return;let a=it(t.dir);if(!a.ok)return;if(a.value.rows.some((l)=>l.type==="commit.recorded"&&(l.sha===i.sha||l.head===i.sha)))return;Rn(t.dir,{type:"commit.recorded",actor:{host:e.host,session:o,agentId:e.session.agentId},branch:t.branch,head:i.sha,sha:i.sha,session:o,agentId:e.session.agentId,subject:i.subject.slice(0,200),files:[],fileCount:null,via:"raw_shell"})};function Hu(e,t,n){try{if(!e.session.id||!/\bcommit\b/.test(t))return;for(let{action:r,repo:o}of Ji(e.cwd,t,ju(e)))if(r.kind==="commit")ib(e,o,Fu(o,e.session.id,n))}catch{}}function ab(e){try{if(!e.session.id)return;let t=Du(e.cwd);if(!t)return;let n=Fu(t,e.session.id,Mu);if(Et.existsSync(n))ib(e,t,n)}catch{}}var NC=/[$`*?[\]{}~]/u,LC=new Set(["-c","--create","-C","--force-create","--orphan"]),DC=new Set(["-b","-B","--orphan"]),jC=new Set(["-b","-B"]),WC=new Set(["-b","--branch"]),cb=new Set(["-d","-D","--delete","-l","--list","-a","--all","-r","--remotes","--show-current"].concat(["-v","-vv","--verbose","--contains","--no-contains","--merged","--no-merged"]).concat(["--points-at","--sort","--format","--column","--no-column","-u"]).concat(["--set-upstream-to","--unset-upstream","--edit-description","-i","--ignore-case"])),lb=new Set(["-m","-M","--move","-c","-C","--copy"]),Zu=(e,t)=>t.has(e)||e.length>=3&&[...t].some((n)=>n.startsWith("--")&&n.startsWith(e)),MC=(e)=>[...e].filter((t)=>/^-[^-]$/u.test(t)).join("").replaceAll("-",""),Vi=(e,t)=>{let n=MC(t);for(let r=1;r<e.length;r++){let o=e[r];if(o==="--")return null;if(o.startsWith("--")){let s=o.indexOf("=");if(!Zu(s>0?o.slice(0,s):o,t))continue;return s>0?o.slice(s+1):e[r+1]??null}if(!o.startsWith("-")||o.length<2)continue;for(let s=1;s<o.length;s++)if(n.includes(o[s]))return s+1<o.length?o.slice(s+1):e[r+1]??null}return null},FC=new Set(["--reason"]),BC=(e)=>{let t=Vi(e,jC);if(t!==null)return t;let n=[];for(let o=1;o<e.length;o++){let s=e[o];if(s==="--detach"||s==="-d")return null;if(FC.has(s))o++;else if(!s.startsWith("-"))n.push(s)}if(n.length!==1)return null;let r=n[0].split(/[\\/]/u).findLast(Boolean)??"";return r&&r!=="."&&r!==".."?r:null},HC=(e)=>{let t=!1,n=[];for(let r=1;r<e.length;r++){let o=e[r];if(o==="--"){n.push(...e.slice(r+1));break}if(o.startsWith("--")){let s=o.split("=",1)[0];if(Zu(s,cb))return null;if(Zu(s,lb))t=!0}else if(o.startsWith("-")&&o.length>1){let s=o.slice(1).split("");if(s.some((i)=>cb.has(`-${i}`)))return null;if(s.some((i)=>lb.has(`-${i}`)))t=!0}else n.push(o)}if(n.length<1||n.length>2)return null;return t?n.at(-1)??null:n[0]},Yi=(e,t,n=new Set)=>{let r=[];for(let o=t;o<e.length;o++){let s=e[o];if(s==="--")return[...r,...e.slice(o+1)];if(n.has(s))o++;else if(!s.startsWith("-")||s==="-")r.push(s)}return r},Xi=(e)=>e.startsWith("refs/heads/")?e.slice(11):null,ZC=(e,t)=>{if(e.some((o)=>o==="-d"||o==="--delete"))return[];if(e.includes("--stdin"))return(t??"").split(/[\n\0]/u).map((o)=>/^\s*(?:create|update)\s+(\S+)/u.exec(o)?.[1]??"").map(Xi).filter((o)=>o!==null);let[n]=Yi(e,1,new Set(["-m"])),r=n?Xi(n):null;return r?[r]:[]},UC=(e)=>{if(e.some((n)=>n==="-d"||n==="--delete"))return null;let[,t]=Yi(e,1,new Set(["-m"]));return t?Xi(t):null},KC=new Set(["--depth","--deepen","--shallow-since","--shallow-exclude","--refmap","-j","--jobs"].concat(["--upload-pack","-o","--server-option","--negotiation-tip","--filter"]).concat(["--recurse-submodules-default","--submodule-prefix","-s","--strategy","-X"]).concat(["--strategy-option"])),qC=(e,t)=>{if(e.includes("--all")||e.includes("--multiple"))return[];let n=e.includes("--stdin")?(t??"").split(/\s+/u).filter(Boolean):Yi(e,1,KC).slice(1),r=[];for(let o of n){let s=o.indexOf(":"),i=s>=0?o.slice(s+1):"";if(!i||i.includes("*"))continue;let a=i.startsWith("refs/")?Xi(i):i;if(a)r.push(a)}return r},JC=(e)=>{let t=Co(e);if(t?.kind!=="push"||t.remote!=="."||t.deletes)return[];return t.targets.filter((n)=>n!==null)},GC=(e,t)=>{let[n,r]=e;return(n==="switch"?[Vi(e,LC)]:n==="checkout"?[Vi(e,DC)]:n==="branch"?[HC(e)]:n==="worktree"&&r==="add"?[BC(e.slice(1))]:n==="stash"&&r==="branch"?Yi(e,2).slice(0,1):n==="update-ref"?ZC(e,t):n==="symbolic-ref"?[UC(e)]:n==="fetch"||n==="pull"?qC(e,t):n==="push"?JC(e):n==="subtree"&&r==="split"?[Vi(e.slice(1),WC)]:[]).filter((s)=>s!==null&&s!==""&&!s.startsWith("-")&&!NC.test(s))},VC=(e)=>e.flatMap((t)=>t.tool==="git"?GC(t.args,t.stdin).map((n)=>({branch:n,dir:t.dir})):[]);var XC=(e,t)=>AC("git",["show-ref","--verify","--quiet",`refs/heads/${t}`],{cwd:e,stdio:"ignore",timeout:5000}).status===0,ub=(e,t)=>{if(t===void 0)return null;if(t===null)return e;let n=zC.resolve(e,t);return PC(n)&&lt(n)?n:null},db=(e,t,n="posix")=>{let r=!1,o=new Map;for(let s of Yt(t,n)){if(s.tool!=="git"||ub(e,s.dir)===null)continue;for(let i of VC(qi(e,s,o))){let a=ub(e,i.dir);if(a===null||XC(a,i.branch))continue;r=!0;let c=Us(a,i.branch);if(!c.ok)return c}}return r?{ok:!0}:null};var Uu=(e,t,n="posix")=>{let r;try{r=db(e,t,n)}catch(o){if(o instanceof ct)return Wu(o);throw o}return r&&!r.ok?{kind:"deny",reason:`branch_policy_denied: ${r.error}`,unblock:null}:{kind:"none"}};var Qi=["git","pr","ci","stack","release","task","ledger","evidence","finding","decision","worker","verify-delivery","policy","doctor","help"],Ku=["--unverified","--overwrite-unintegrated"],JF=new Set(Qi),YC=(e)=>Ku.some((t)=>e===t||e.startsWith(`${t}=`)),QC=(e)=>/^(?:.*[\\/])?workit(?:-cli)?$/u.test(e);var pb=(e)=>`Workit: \`${e}\` overrides a Workit gate, so the user decides this call (no allow rule covers it).`,fb=(e,t="posix")=>{for(let n of $e(e,t)){if(n.unanalyzable){let a=e.replaceAll(/['"\\`]/gu,"");if(!/\bworkit\b/u.test(a))return null;let c=Ku.find((l)=>a.includes(l));return c?pb(c):null}let r=n.words.findIndex(QC);if(r<0)continue;let o=n.words.slice(r+1),s=o.indexOf("--"),i=(s<0?o:o.slice(0,s)).find(YC);if(i)return pb(i.split("=")[0]??i)}return null};import Ju from"node:fs";import eA from"node:os";import ue from"node:path";var ea=()=>({deny:[],allow:[]}),ta=(e)=>{try{return Ju.readFileSync(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}},en=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function gb(e){let t="";for(let n=0;n<e.length;n+=1){let r=e[n];if(r==='"'){let o=/"(?:[^"\\]|\\.)*"/y;o.lastIndex=n;let s=o.exec(e);if(!s)throw Error("unterminated string");t+=s[0],n+=s[0].length-1}else if(r==="/"&&e[n+1]==="/"){while(n<e.length&&e[n]!==`
209
209
  `)n+=1;t+=`
210
- `}else if(r==="/"&&e[n+1]==="*"){let o=e.indexOf("*/",n+2);if(o<0)throw Error("unterminated comment");n=o+1}else t+=r}return JSON.parse(t.replace(/,(\s*[}\]])/gu,"$1"))}function Xn(e){for(let t=le.resolve(e);;t=le.dirname(t)){if(Ju.existsSync(le.join(t,".git")))return t;if(le.dirname(t)===t)return null}}var tA=(e)=>{let t=Xn(e),n=[];for(let r=le.resolve(e);;r=le.dirname(r))if(n.push(r),!t||r===t||le.dirname(r)===r)return n},na=(e)=>e.HOME||eA.homedir(),hb={linux:"/etc/claude-code/managed-settings.json",darwin:"/Library/Application Support/ClaudeCode/managed-settings.json",win32:"C:\\Program Files\\ClaudeCode\\managed-settings.json"};function nA(e,t,n=process.platform){let r=t.CLAUDE_PROJECT_DIR||Xn(e)||e,o=t.CLAUDE_CONFIG_DIR||le.join(na(t),".claude");return[...hb[n]?[hb[n]]:[],le.join(o,"settings.json"),le.join(r,".claude","settings.json"),le.join(r,".claude","settings.local.json")]}var rA=(e)=>{let t=/^Bash(?:\((.*)\))?$/su.exec(e.trim());return t?t[1]??"":null};function vb(e,t=process.env){let n=ea();try{for(let r of nA(e,t)){let o=ta(r);if(o===null)continue;let s=JSON.parse(o);if(!en(s))return"unreadable";let i=s.permissions;if(i===void 0)continue;if(!en(i))return"unreadable";for(let[a,c]of[["deny",n.deny],["ask",n.deny],["allow",n.allow]]){let l=i[a];if(l===void 0)continue;if(!Array.isArray(l))return"unreadable";for(let u of l){if(typeof u!=="string")return"unreadable";let d=rA(u);if(d!==null)c.push(d)}}}}catch{return"unreadable"}return n}var mb=["opencode.json","opencode.jsonc"],kb=(e,t)=>{if(e===void 0)return!0;if(typeof e==="string")return(e==="allow"?t.allow:t.deny).push(""),["allow","ask","deny"].includes(e);if(!en(e))return!1;for(let n of["bash","shell"]){let r=e[n];if(r===void 0)continue;if(typeof r==="string"){if(!["allow","ask","deny"].includes(r))return!1;(r==="allow"?t.allow:t.deny).push("");continue}if(!en(r))return!1;for(let[o,s]of Object.entries(r)){if(s!=="allow"&&s!=="ask"&&s!=="deny")return!1;(s==="allow"?t.allow:t.deny).push(o)}}return!0},yb=(e,t)=>{if(!en(e))return!1;if(!kb(e.permission,t))return!1;if(e.agent===void 0)return!0;if(!en(e.agent))return!1;return Object.values(e.agent).every((n)=>en(n)&&kb(n.permission,t))};function wb(e,t=process.env){let n=ea();try{let r=t.XDG_CONFIG_HOME||le.join(na(t),".config"),o=[...mb.map((s)=>le.join(r,"opencode",s)),...tA(e).flatMap((s)=>mb.flatMap((i)=>[le.join(s,i),le.join(s,".opencode",i)])),...t.OPENCODE_CONFIG?[t.OPENCODE_CONFIG]:[]];for(let s of o){let i=ta(s);if(i!==null&&!yb(gb(i),n))return"unreadable"}if(t.OPENCODE_CONFIG_CONTENT&&!yb(gb(t.OPENCODE_CONFIG_CONTENT),n))return"unreadable"}catch{return"unreadable"}return n}var oA=(e)=>{let t=/\bpattern\s*=\s*\[/u.exec(e);if(!t)return null;let n=[],r=t.index+t[0].length;for(;;){while(/[\s,]/u.test(e[r]??""))r+=1;if(e[r]==="]")break;if(e[r]!=='"')return null;let s=/"((?:[^"\\]|\\.)*)"/y;s.lastIndex=r;let i=s.exec(e);if(!i)return null;n.push(JSON.parse(`"${i[1]}"`)),r=s.lastIndex}let o=/\bdecision\s*=\s*"(\w+)"/u.exec(e)?.[1];if(!n.length||!o||!["allow","prompt","forbidden"].includes(o))return null;return{pattern:n.join(" "),decision:o}};function bb(e,t=process.env){let n=ea();try{let r=t.CODEX_HOME||le.join(na(t),".codex"),o=Xn(e)??e;for(let s of[le.join(r,"rules"),le.join(o,".codex","rules")]){let i;try{i=Ju.readdirSync(s).filter((a)=>a.endsWith(".rules"))}catch(a){if(a.code==="ENOENT")continue;return"unreadable"}for(let a of i){let c=ta(le.join(s,a))??"";for(let l of c.split(/\bprefix_rule\s*\(/u).slice(1)){let u=oA(l);if(!u)return"unreadable";(u.decision==="allow"?n.allow:n.deny).push(u.pattern)}}}}catch{return"unreadable"}return n}function xb(e,t=process.env){let n=ea();try{let r=Xn(e)??e;for(let o of[le.join(na(t),".cursor","cli-config.json"),le.join(r,".cursor","cli.json")]){let s=ta(o);if(s===null)continue;let i=JSON.parse(s);if(!en(i))return"unreadable";if(i.permissions===void 0)continue;if(!en(i.permissions))return"unreadable";for(let[a,c]of[["deny",n.deny],["allow",n.allow]]){let l=i.permissions[a];if(l===void 0)continue;if(!Array.isArray(l))return"unreadable";for(let u of l){if(typeof u!=="string")return"unreadable";let d=/^Shell(?:\((.*)\))?$/su.exec(u.trim());if(d)c.push(d[1]??"")}}}}catch{return"unreadable"}return n}var qu=(e)=>(e.split(/[\\/]/u).at(-1)??"").toLowerCase().replace(/\.(?:exe|cmd|bat)$/u,""),Sb=(e)=>e.trim().split(/[:\s]/u)[0]??"";function sA(e,t){let n=Sb(e);if(!n||n==="*"||n.includes("*"))return!0;let r=qu(n);return t.some((o)=>qu(o)===r)}var _b=(e)=>e.trim().replace(/(?::\*| \*|\*)$/u,""),iA=(e)=>{let t=Sb(e);if(!t||t.includes("*"))return!0;let n=_b(e).split(/\s+/u);if(qu(n[0])!=="workit")return!1;return["check","--heavy"].slice(0,n.length-1).every((r,o)=>{let s=n[o+1];return s===r||r.startsWith(s)})},aA=(e,t)=>{let n=_b(e);if(!n)return!0;return!n.includes("*")&&t.trim().startsWith(n)};function Rb(e,t,n,r={}){if(e==="unreadable")return{ok:!1,why:"named"};if(e.deny.some((o)=>sA(o,t)))return{ok:!1,why:"named"};if(!r.bypass&&e.allow.some(iA)&&!e.allow.some((o)=>aA(o,n)))return{ok:!1,why:"allowlisted"};return{ok:!0}}import Gu from"node:fs";import cA from"node:os";import tn from"node:path";function lA(e,t=process.platform){if(e.WORKFLOW_TOOLKIT_STATE)return e.WORKFLOW_TOOLKIT_STATE;if(e.XDG_STATE_HOME)return tn.join(e.XDG_STATE_HOME,"workit");let n=e.HOME||cA.homedir();if(t==="darwin")return tn.join(n,"Library","Application Support","workit");if(t==="win32")return tn.join(e.LOCALAPPDATA??tn.join(n,"AppData","Local"),"workit");return tn.join(n,".local","state","workit")}var uA="heavy-commands.json",dA=(e)=>tn.join(lA(e),uA),An=/^(?:test|tests|t|tst|unit|integration|e2e|coverage|cov|lint|eslint|typecheck|type-check|types|tsc|check|verify|validate|build|compile|bundle|ci|sonar|cypress|playwright|jest|vitest|mocha|bench|benchmark|all)(?:$|[:_.-])/iu,pA=new Set(["--version","-v","-V","--help","-h","help","version"]),fA=/^(?:--watch(?:All)?(?:=.*)?|-w|--serve)$/u,Pr=/(?:^|[:_.-])(?:watch|dev|serve|start|storybook)(?:$|[:_.-])/iu,H=(...e)=>new Set(e),gA={jest:"any",vitest:"any",mocha:"any",ava:"any",tap:"any",karma:"any",jasmine:"any",nyc:"any",c8:"any",tsc:"any","vue-tsc":"any","svelte-check":"any",eslint:"any",stylelint:"any",tslint:"any",webpack:"any","webpack-cli":"any",rollup:"any",parcel:"any",tsup:"any",vite:H("build","optimize"),next:H("build","lint"),nuxt:H("build","generate"),nuxi:H("build","generate"),astro:H("build","check"),ng:H("build","b","test","t","e2e","lint"),"react-scripts":H("build","test"),playwright:H("test","install"),cypress:H("run"),wdio:"any",testcafe:"any",turbo:"any",lerna:H("run","exec","bootstrap"),"sonar-scanner":"any",sonarless:H("scan"),"sonarless-mcp":H("scan"),go:H("test","build","vet","install","generate"),"golangci-lint":H("run"),gotestsum:"any",staticcheck:"any",cargo:H("build","b","test","t","check","c","clippy","bench","nextest","doc","install","tarpaulin","llvm-cov"),mvn:"any",mvnw:"any",gradle:"any",gradlew:"any",ant:"any",sbt:"any",bazel:H("build","test","run","coverage"),bazelisk:H("build","test","run","coverage"),buck2:H("build","test","run"),dotnet:H("build","test","publish","restore","pack","msbuild"),msbuild:"any",pytest:"any","py.test":"any",tox:"any",nox:"any",mypy:"any",pyright:"any",pylint:"any",coverage:H("run"),maturin:H("build","develop"),pip:H("install","wheel"),pip3:H("install","wheel"),rspec:"any",rails:H("test","assets:precompile"),phpunit:"any",pest:"any",phpstan:"any",psalm:"any",composer:H("install","update","require","test"),mix:H("test","compile","deps.get","dialyzer","credo"),swift:H("build","test"),xcodebuild:"any",flutter:H("build","test"),dart:H("test","compile"),pod:H("install"),cmake:H("--build"),ninja:"any",meson:H("compile","test"),ctest:"any",scons:"any","docker-compose":H("build"),buildah:H("bud","build"),earthly:"any"},hA=new Set(["--prefix","-w","--workspace","-C","--dir","--filter","-F","--cwd","-p","--package","--cache","--registry"]);function Ge(e,t,n=hA){let r=t;while(r<e.length&&e[r].startsWith("-")){if(e[r]==="--")return r+1;r+=n.has(e[r])?2:1}return r}var Vu=(e)=>(e?.split(/[\\/]/u).at(-1)??"").toLowerCase().replace(/\.(?:exe|cmd|bat|ps1)$/u,""),Ib=/^(?:workit|@brainervirus\/workit-cli(?:@.*)?)$/u,mA=/^(?:python[\d.]*|py)$/u,kA=new Set(["ci","clean-install","cit","install-test","it","install","i","in","add","rebuild","update","up"]),yA=new Set(["run","run-script","rum","urn"]),vA=new Set(["test","t","tst"]),wA=new Set(["exec","x","dlx"]);function Tb(e,t=0){if(t>6||!e.length)return null;let n=Vu(e[0]),r=()=>e.slice(0,3).join(" "),o=(a)=>Tb(e.slice(a),t+1);if(Ib.test(n))return null;if(pA.has(e[1]??"")&&e.length===2)return null;if(e.some((a)=>a==="--watch"||a.startsWith("--watch=")||a==="--watchAll"))return null;if(n==="npx"||n==="bunx"||n==="pnpx")return o(Ge(e,1));if(n==="corepack")return o(1);if(n==="npm"||n==="pnpm"||n==="yarn"||n==="bun"||n==="deno"){let a=Ge(e,1),c=e[a];if(c===void 0)return n==="yarn"?"yarn (install)":null;if(n==="deno"){if(["test","bench","check","compile","lint"].includes(c))return r();if(c==="task"&&An.test(e[a+1]??""))return r();return null}if(kA.has(c)||vA.has(c))return r();if(n==="bun"&&c==="build")return r();if(wA.has(c))return o(Ge(e,a+1));if(n==="yarn"&&c==="workspace")return o(a+2);if(n==="yarn"&&c==="workspaces")return e.slice(a+1).some((l)=>An.test(l))?r():null;if(yA.has(c)){let l=e[Ge(e,a+1)];if(l===void 0||Pr.test(l))return null;if(An.test(l))return r();return n==="bun"?o(Ge(e,a+1)):null}if(n==="npm")return null;if(Pr.test(c))return null;if(An.test(c)&&!/\.[cm]?[jt]sx?$/u.test(c))return r();return o(a)}if(mA.test(n)){let a=e.indexOf("-m");return a>0&&e[a+1]?o(a+1):null}if(["uv","poetry","pdm","pipenv","hatch","rye"].includes(n)){let a=Ge(e,1),c=e[a];if(c==="run")return o(Ge(e,a+1));if(c==="pip")return o(a);return["sync","install","build","test","add"].includes(c??"")?r():null}if(n==="bundle"){let a=e[Ge(e,1)];if(a==="exec")return o(Ge(e,2));return a==="install"||a===void 0?r():null}if(n==="make"||n==="gmake"){let a=e.slice(1).filter((c)=>!c.startsWith("-")&&!c.includes("="));if(a.some((c)=>Pr.test(c)))return null;return!a.length||a.some((c)=>An.test(c))?r():null}if(n==="rake")return e.slice(1).filter((c)=>!c.startsWith("-")&&!c.includes("=")).some((c)=>An.test(c)||/^spec(?:$|:)/u.test(c))?r():null;if(n==="nx"){let a=Ge(e,1),c=e[a]??"";if(["run-many","affected"].includes(c))return e.some((l)=>/^(?:-t|--targets?)(?:=|$)/u.test(l))&&!e.some((l)=>Pr.test(l.replace(/^--?targets?=/u,"")))?r():null;if(c==="run"){let l=(e[a+1]??"").split(":")[1]??"";return An.test(l)&&!Pr.test(l)?r():null}return An.test(c)&&!Pr.test(c)?r():null}if(n==="docker"||n==="podman"||n==="nerdctl"){let a=Ge(e,1,new Set(["-H","--host","--context","-c","--config"])),c=e[a];if(c==="build")return r();if(c==="buildx"||c==="image"||c==="builder")return e[Ge(e,a+1)]==="build"?r():null;if(c==="compose"){let l=Ge(e,a+1,new Set(["-f","--file","-p"])),u=e[l];if(u==="build")return r();return u==="up"&&e.slice(l+1).includes("--build")?r():null}return null}let s=gA[n];if(!s)return null;if(e.slice(1).some((a)=>fA.test(a)||a==="watch"||a==="dev"))return null;if(s==="any")return r();let i=e.slice(1).find((a)=>!a.startsWith("-")&&!a.startsWith("+")||s.has(a));return i!==void 0&&s.has(i)?r():null}var bA=(e)=>new RegExp(`^${e.replace(/[.+?^${}()|[\]\\]/gu,"\\$&").replaceAll("*",".*")}$`,"u");function xA(e){let t=e.trim().split(/\s+/u).filter(Boolean);return t.length?t.map(bA):null}var SA=(e,t)=>e.length<=t.length&&e.every((n,r)=>r===0?n.test(t[0])||n.test(Vu(t[0])):n.test(t[r])),_A=(e)=>{try{return JSON.parse(Gu.readFileSync(e,"utf8"))}catch{return}},RA=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),$A=(e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string"):[];function IA(e){let t=_A(dA(e));return RA(t)?$A(t.patterns):[]}function TA(e){return ti(Xn(e)??tn.resolve(e))}function $b(e,t){let n=[],r=null;for(let o of e){let s=Tb(o);if(s){n.push({line:o,source:"catalog",reason:s});continue}r??=(t.patterns??[...IA(t.env??process.env).map((a)=>({pattern:a,from:"machine"})),...TA(t.cwd).map((a)=>({pattern:a,from:"repo"}))]).flatMap((a)=>{let c=xA(a.pattern);return c?[{...a,matchers:c}]:[]});let i=r.find((a)=>SA(a.matchers,o));if(i)n.push({line:o,source:{pattern:i.pattern,from:i.from},reason:`${i.from} pattern "${i.pattern}"`})}return n}var OA=(e,t)=>{try{return Jw(e,t)}catch{return null}};var EA=(e)=>/^[\w@%+=:,./-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`,CA=(e)=>`workit check --heavy -- ${e.map(EA).join(" ")}`;function Ob(e,t){let n=t.dialect??"posix";if(n!=="posix"||!Xn(t.cwd))return{kind:"none"};let r=OA(e,n);if(!r)return{kind:"none"};let o=$b(r,t);if(!o.length)return{kind:"none"};let s=Ui(e,n,0,!0),i=s&&!Ib.test(Vu(s[0]))&&$b([s],t)[0],a=i?[{words:r.flat(),text:e}]:o.map((l)=>({words:l.line,text:l.line.join(" ")}));if(t.rules!==null){for(let{words:l,text:u}of a)if(!Rb(t.rules,l,u,{bypass:t.bypass}).ok)return{kind:"passthrough",note:""}}if(i){let l=PA(e);return l?{kind:"rewrite",command:l,reason:i.reason}:{kind:"none"}}let c=o.map((l)=>CA(l.line));return{kind:"split",reason:`heavy_command: \`${e.trim()}\` chains heavy work (${o.map((l)=>l.reason).join("; ")}) with other commands, and a chain cannot run under the machine-wide heavy-check lease. Run the heavy part alone, now: \`${c[0]}\`; then run the other parts as their own commands${c.length>1?", each heavy one the same way":""}.`,unblock:c[0]??null}}function Eb(e=process.env){let t=process.platform==="win32"?["workit.exe","workit.cmd","workit"]:["workit"];for(let n of(e.PATH??"").split(tn.delimiter))for(let r of t){if(!n)continue;try{return Gu.accessSync(tn.join(n,r),Gu.constants.X_OK),!0}catch{}}return!1}var AA=/^\s*((?:[A-Za-z_]\w*=(?:'[^']*'|"(?:[^"\\]|\\.)*"|[^\s'"])*\s+)*)/u;function PA(e){let t=e.trim(),n=AA.exec(t)?.[1]??"",r=t.slice(n.length).trim();if(!r)return null;return`${n}workit check --heavy -- ${r}`}import Cb from"node:fs";import zA from"node:os";import At from"node:path";var NA=new Set("npm npx pnpm pnpx yarn bun bunx deno corepack make gmake docker podman nerdctl python python3 py uv poetry pdm pipenv hatch rye bundle rake nx jest vitest mocha ava tap karma jasmine nyc c8 tsc vue-tsc svelte-check eslint stylelint tslint webpack webpack-cli rollup parcel tsup vite next nuxt nuxi astro ng react-scripts playwright cypress wdio testcafe turbo lerna sonar-scanner sonarless sonarless-mcp go golangci-lint gotestsum staticcheck cargo mvn mvnw gradle gradlew ant sbt bazel bazelisk buck2 dotnet msbuild pytest py.test tox nox mypy pyright pylint coverage maturin pip pip3 rspec rails phpunit pest phpstan psalm composer mix swift xcodebuild flutter dart pod cmake ninja meson ctest scons docker-compose buildah earthly".split(" ")),Ab=(e)=>e.split(/[\s;&|()<>`'"]+/u).map((t)=>(t.split(/[\\/]/u).at(-1)??"").toLowerCase().replace(/\.(?:exe|cmd|bat)$/u,"")).filter(Boolean),LA=(e)=>{if(e.WORKFLOW_TOOLKIT_STATE)return e.WORKFLOW_TOOLKIT_STATE;if(e.XDG_STATE_HOME)return At.join(e.XDG_STATE_HOME,"workit");let t=e.HOME||zA.homedir();if(process.platform==="darwin")return At.join(t,"Library","Application Support","workit");if(process.platform==="win32")return At.join(e.LOCALAPPDATA??At.join(t,"AppData","Local"),"workit");return At.join(t,".local","state","workit")},DA=(e)=>{try{return JSON.parse(Cb.readFileSync(e,"utf8"))}catch{return}},jA=(e,t)=>{let n=[],r=DA(At.join(LA(t),"heavy-commands.json"));if(Array.isArray(r?.patterns))n.push(...r.patterns);for(let s=At.resolve(e);;s=At.dirname(s)){if(Cb.existsSync(At.join(s,".git"))){n.push(...ti(s));break}if(At.dirname(s)===s)break}let o=new Set;for(let s of n){if(typeof s!=="string")continue;let i=Ab(s)[0];if(!i||i.includes("*"))return null;o.add(i)}return o};function Pb(e,t,n=process.env){try{let r=Ab(e);if(r.some((s)=>NA.has(s)||/^python[\d.]*$/u.test(s)))return!0;let o=jA(t,n);return o===null||r.some((s)=>o.has(s))}catch{return!0}}var WA=(e,t,n)=>{switch(e){case"claude_code":return vb(t,n);case"opencode":return wb(t,n);case"codex_cli":case"codex_desktop":return bb(t,n);case"cursor":return xb(t,n);case"pi":return null}};function Xu(e,t,n){let r=n.env??process.env;try{if(r.WORKIT_HEAVY_GATE==="0"||!Pb(t,e,r)||!Eb(r))return{kind:"none"};return Ob(t,{cwd:e,env:r,dialect:n.dialect??"posix",rules:WA(n.host,e,r),bypass:n.permissionMode==="bypassPermissions"})}catch{return{kind:"none"}}}var zb=(e)=>`workit: this heavy command (${e.reason}) runs under the machine-wide heavy-check lease as \`${e.command}\`: it waits while another heavy check holds the lease (\`workit lock status\` shows who). Run heavy commands that way yourself; \`workit help lock\` explains the lease.`,Yu=(e,t)=>({kind:"deny",reason:`heavy_command: \`${e.trim()}\` is heavy (${t.reason}) and must run under the machine-wide heavy-check lease, so parallel agents cannot exhaust this machine's memory and CPU. Run exactly: ${t.command}`,unblock:t.command}),Qu=(e)=>({kind:"deny",reason:e.reason,unblock:e.unblock});import{existsSync as GA,realpathSync as VA}from"node:fs";import Kb from"node:os";import U from"node:path";import{spawnSync as MA}from"node:child_process";import{createHash as FA}from"node:crypto";import yt from"node:fs";import td from"node:os";import Pt from"node:path";var BA=900000,HA=30000,Yn={platform:process.platform,run:(e)=>MA("ps",e,{encoding:"utf8",timeout:2000}).stdout??"",start:(e)=>go(e)},ed=(e)=>e.split(":")[0].replace(/-w-.*$/su,"")||e,Nb=(e)=>e.replace(/_(?:cli|desktop)$/u,""),ZA=(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},UA=(e)=>{try{if(Yn.platform==="linux"){let n=yt.readFileSync(`/proc/${e}/stat`,"utf8"),r=Number(n.slice(n.lastIndexOf(")")+2).split(" ")[1]),o=yt.readFileSync(`/proc/${e}/cmdline`,"utf8").replaceAll("\x00"," ");return Number.isInteger(r)?{ppid:r,command:o.trim()}:null}if(Yn.platform==="win32")return null;let t=/^\s*(\d+)\s+(.*)$/su.exec(Yn.run(["-o","ppid=,command=","-p",String(e)]));return t?{ppid:Number(t[1]),command:t[2].trim()}:null}catch{return null}},KA=/^(?:\S*\/)?(?:sh|bash|dash|zsh|ash|ksh|fish|env|timeout|npx|npm|bunx|cmd\.exe|pwsh|powershell)(?:\s|$)|launch\.mjs|npx-cli\.js/u,ra=new Map,qA=(e)=>{if(e!=="hook-process")return process.pid;let t=`${Yn.platform}\x00${process.ppid}`;if(ra.has(t))return ra.get(t)??null;if(Yn.platform==="win32")return ra.set(t,null),null;let n=process.ppid;for(let r=0;r<4;r++){let o=UA(n);if(!o||!KA.test(o.command)||o.ppid<=1)break;n=o.ppid}return ra.set(t,n),n},oa=(e)=>e.replace(/[^A-Za-z0-9_.:@/+-]/gu,"-"),ia=(e,t,n=process.env)=>{let r=e.session.id?.trim();if(!r)return null;let o=new Set([ed(oa(r))]);if(e.session.parentId)o.add(ed(oa(e.session.parentId)));if(n.WORKIT_PI_WORKER_SESSION&&n.WORKIT_SESSION_ID)o.add(ed(oa(n.WORKIT_SESSION_ID)));return{host:e.host,session:oa(r),leads:[...o],pid:()=>qA(t)}},Lb=(e)=>{let t=Pt.resolve(e);while(!yt.existsSync(t)&&Pt.dirname(t)!==t)t=Pt.dirname(t);if(yt.existsSync(t)&&!yt.statSync(t).isDirectory())t=Pt.dirname(t);let n=t.split(Pt.sep),r=n.lastIndexOf(".git");if(r>0)t=n.slice(0,r).join(Pt.sep)||Pt.sep;let o=_e(t);if(o instanceof Error||!o.shared||!o.top)return null;let s=o.top;try{s=yt.realpathSync.native(s)}catch{}return s},Db=(e)=>Pt.join(Le(),"live-sessions",`${FA("sha256").update(JA(e)).digest("hex").slice(0,32)}.json`),JA=(e,t=process.platform)=>{let n=Pt.resolve(e);try{n=yt.realpathSync.native(n)}catch{}return t==="win32"?n.replaceAll("/","\\").toLowerCase():n},jb=(e)=>{try{let t=JSON.parse(yt.readFileSync(e,"utf8"));if(t?.version!==1||typeof t.session!=="string"||typeof t.host!=="string"||typeof t.heartbeatAt!=="string"||Number.isNaN(Date.parse(t.heartbeatAt)))return null;return{version:1,session:t.session,leads:Array.isArray(t.leads)?t.leads.filter((n)=>typeof n==="string"):[],host:t.host,pid:typeof t.pid==="number"?t.pid:null,pidStart:typeof t.pidStart==="string"?t.pidStart:null,machine:typeof t.machine==="string"?t.machine:"",checkout:typeof t.checkout==="string"?t.checkout:"",heartbeatAt:t.heartbeatAt}}catch{return null}},nd=(e,t)=>t.getTime()-Date.parse(e.heartbeatAt),Wb=(e,t)=>{if(nd(e,t.now??new Date)>(t.ttlMs??BA))return!1;if(e.machine!==(t.machine??td.hostname())||e.pid===null)return!0;if(!(t.alive??ZA)(e.pid))return!1;if(e.pidStart===null)return!0;let r=Yn.start(e.pid);return r===null||r===e.pidStart},sa=(e,t)=>e.session===t.session||t.leads.some((n)=>n===e.session||e.leads.includes(n)),Mb=(e,t,n)=>{if(sa(e,t))return!0;if(e.machine!==n)return!1;let r=t.pid();if(r===null||e.pid===null||e.pidStart===null)return Nb(e.host)===Nb(t.host);return e.pid===r},Fb=(e,t,n={})=>{try{let r=Lb(e);if(!r)return null;let o=Db(r),s=jb(o);if(!s||sa(s,t)||!Wb(s,n))return null;if(Mb(s,t,n.machine??td.hostname()))return null;return{marker:s,file:o,ageMs:nd(s,n.now??new Date),checkout:r}}catch{return null}},Bb=(e,t,n={})=>{try{let r=Lb(e);if(!r)return;let o=Db(r),s=n.now??new Date,i=n.machine??td.hostname(),a=jb(o);if(a){let d=nd(a,s);if(sa(a,t)&&d>=0&&d<HA)return;if(!sa(a,t)&&Wb(a,n)&&!Mb(a,t,i))return}let c=t.pid(),l={version:1,session:t.session,leads:t.leads,host:t.host,pid:c,pidStart:c===null?null:Yn.start(c),machine:i,checkout:r,heartbeatAt:s.toISOString()};yt.mkdirSync(Pt.dirname(o),{recursive:!0});let u=`${o}.${process.pid}.tmp`;yt.writeFileSync(u,JSON.stringify(l)),yt.renameSync(u,o)}catch{}};var Do={kind:"none"},XA=process.platform==="darwin"||process.platform==="win32",rd=(e)=>{let t="";for(let n=U.resolve(e);;n=U.dirname(n))try{return U.join(VA.native(n),t)}catch{if(U.dirname(n)===n)return U.resolve(e);t=t?U.join(U.basename(n),t):U.basename(n)}},YA=(e,t,n,r)=>{let o=(c)=>XA?c.toLowerCase():c,s=U.relative(o(rd(t)),o(rd(U.resolve(e,n))));if(s.startsWith("..")||U.isAbsolute(s))return!0;let i=s.split(U.sep).join("/"),a=i.split("/");return/\.mdx?$/i.test(i)||a[0]==="docs"||a.includes("plans")||[...r].some((c)=>o(c)===i)},ca=new Set(["sudo","command","env","nohup","time","exec","xargs","busybox"]),Qn=(e)=>e.filter((t)=>!t.startsWith("-")),qb=new Set(["sh","bash","zsh","dash","ksh"]),Jb=(e)=>{let t=e;while(t.length&&(ca.has(t[0])||/^\w+=/.test(t[0])))t=t.slice(1);let n=Lu(t);if(!n)return null;if("script"in n)return n.script;let r=id(n.argv);if(qb.has((n.argv[0]?.split(/[\\/]/).at(-1)??"").toLowerCase())&&r)return r;return n.argv.map(ad).join(" ")},sd=(e)=>{let t=e;while(t.length&&(ca.has(t[0])||/^\w+=/.test(t[0])))t=t.slice(1);let[n,...r]=t,o=(n?.split(/[\\/]/).at(-1)??"").toLowerCase();if(!o||o==="workit"||o==="npx"&&r.some((s)=>/workit/.test(s)))return[];switch(o){case"touch":case"mkdir":case"rm":case"rmdir":case"tee":case"mv":case"truncate":return Qn(r);case"cp":case"ln":case"install":{let s=r.indexOf("-t");if(s>=0)return r[s+1]?[r[s+1]]:null;let i=Qn(r).at(-1);return i?[i]:null}case"dd":return r.filter((s)=>s.startsWith("of=")).map((s)=>s.slice(3));case"sed":case"perl":{if(!r.some((a)=>/^-[a-zA-Z]*i|^--in-place/.test(a)))return[];let s=r.some((a)=>a==="-e"||a==="-f"),i=[];for(let a=0;a<r.length;a++)if(r[a]==="-e"||r[a]==="-f")a++;else if(!r[a].startsWith("-"))i.push(r[a]);return s?i:i.slice(1)}case"patch":return null;case"set-content":case"add-content":case"out-file":case"new-item":case"ni":case"remove-item":case"del":case"copy-item":case"move-item":{let s=r.findIndex((c)=>/^-(?:path|filepath|literalpath|destination)$/i.test(c));if(s>=0)return r[s+1]?[r[s+1]]:null;let i=Qn(r);if(o==="move-item")return i.length?i:null;let a=o==="copy-item"?i.at(-1):i[0];return a?[a]:null}case"git":{let s=Qn(r)[0];if(s==="apply")return null;if(s==="restore"||s==="mv"||s==="rm")return Qn(r).slice(1);if(s==="checkout"&&r.includes("--"))return r.slice(r.indexOf("--")+1);return[]}default:return[]}},id=(e)=>{if(!qb.has((e[0]?.split(/[\\/]/).at(-1)??"").toLowerCase()))return null;for(let t=1;t<e.length;t++){let n=e[t];if(/^-[a-z]*c$/.test(n))return e[t+1]??null;if(/^[-+][oO]$/.test(n))t++;else if(!/^[-+]/.test(n))return null}return null},QA=/^-[IinLPdsEa]$/,Hb=(e)=>{let t=[...e.filter((r)=>r!=="{}"&&r!==";"&&r!=="+"),"x"],n=sd(t);return n===null||n.length>0||Gb(t)!==null},Gb=(e)=>{let t=e;while(t.length&&(ca.has(t[0])||/^\w+=/.test(t[0]))){if(t[0]==="xargs"){let c=1;while(t[c]?.startsWith("-"))c+=QA.test(t[c])?2:1;return Hb(t.slice(c))?["."]:null}t=t.slice(1)}let[n,...r]=t,o=(n?.split(/[\\/]/).at(-1)??"").toLowerCase(),s=Qn(r),i=(c)=>r.some((l)=>c.test(l)),a=(c)=>c.length?c:["."];if(o==="unlink"||o==="shred")return a(s);if(/^(?:chmod|chown|chgrp|chattr)$/.test(o))return a(i(/^--reference/)?s:s.slice(1));if(o==="rsync"){let c=s.at(-1),l=/^[\w.@-]*:/.test(c??"")&&!/^[A-Za-z]:[\\/]/.test(c??"");return c===void 0?["."]:l?[]:[c]}if(o==="find"){let c=r.findIndex((d)=>/^-(?:exec|execdir|ok|okdir)$/.test(d)),l=i(/^-(?:delete|fprint\w*|fls)$/)||c>=0&&Hb(r.slice(c+1)),u=r.findIndex((d)=>/^[-(!]/.test(d));return l?a(u<0?r:r.slice(0,u)):null}if(/^g?awk$/.test(o)){if(!i(/^-i|^--include/))return null;let c=[],l=!i(/^-f$|^--file/);for(let u=0;u<r.length;u++)if(/^(?:-[ifvF]|--(?:include|file|assign|field-separator))$/.test(r[u]))u++;else if(r[u].startsWith("-"))continue;else if(l)l=!1;else c.push(r[u]);return a(c)}if(o==="perl")return i(/^-[a-zA-Z]*[eE]/)?["."]:null;if(/^(?:python[\d.]*|node|bun|deno|ruby|php)$/.test(o))return i(/^-[a-zA-Z]*[ce]$|^--eval$|^-p$/)?["."]:null;return id(t)===null?null:["."]},eP=(e,t)=>{let n=Qn([...e]),r=e.indexOf("-t"),o=r>=0?e[r+1]:n.length>1?n.at(-1):".",s=n.filter((l,u)=>r>=0?l!==o:u<n.length-1||n.length===1),i=o===void 0?null:t(o),a=e.some((l)=>/^-[a-zA-Z]*s|^--symbolic$/.test(l)),c=i===null?null:r>=0||s.length>1||GA(i)||/[\\/]$/.test(o??"")?i:U.dirname(i);return s.flatMap((l)=>{if(a&&c!==null&&!U.isAbsolute(Wo(l)))return[U.resolve(c,l)];let u=t(l);return u?[u]:[]})},la=(e,t=0)=>{let n=[],r=!1;for(let o of $e(e)){let s=t<4?Jb(o.words):null;if(s!==null){let a=la(s,t+1);if(a.writes&&a.targets===null)r=!0;else if(a.targets)n.push(...a.targets)}n.push(...o.redirects.filter((a)=>!/^\/dev\/(?:null|stdout|stderr|tty)$/.test(a)));let i=sd(o.words);if(i===null)r=!0;else n.push(...i)}if(!r&&n.length===0)return{writes:!1,targets:null};return{writes:!0,targets:r?null:n}},Lo=new Map,Zb=(e,t)=>[...t].map((n)=>bn(U.resolve(e,n))??"-").join("\x00"),tP=(e)=>{let t=new xn(e),n=t.listTaskIndex();if(!n.ok)return null;let r=t.currentKey();if(!r.ok)return null;let o=n.data.filter((f)=>f.key===r.data.key&&f.status!=="closed").toSorted((f,g)=>g.updatedAt.localeCompare(f.updatedAt))[0];if(!o)return{blockers:[],root:t.root,plans:new Set};let s=Sr(t.root),i=`${o.id}\x00${o.revision}\x00${s.ok&&bn(s.value)||"-"}`,a=Lo.get(t.root);if(a&&a.key===i&&a.planKey===Zb(t.root,a.plans))return a;let c=t.readTask(o.id);if(!c.ok)return null;let l=t.readWorkspace(),u=new Set((Kt(c.data)?.refs??[]).flatMap((f)=>f.kind==="file"?[f.path]:[])),p={blockers:wv(c.data,t.root).filter((f)=>{let g=c.data.policy?.requirements.find((h)=>h.ruleId===f.ruleId&&h.before==="write");return!(g?.acceptanceAllowed&&l.ok&&l.data&&$i(c.data,l.data,g,t.root).length>0)}),root:t.root,plans:u,key:i,planKey:Zb(t.root,u)};if(Lo.set(t.root,p),Lo.size>32)Lo.delete(Lo.keys().next().value);return p},nP=new Set(["add","am","apply","checkout","cherry-pick","clean","commit","merge","mv","pull","rebase","reset","restore","revert","rm","stash","switch"]),rP=new Set(["add","clean","rm","mv"]),oP=new Set(["commit","branch"]),jo=".workit-live-target",Vb="WORKIT_LIVE_SESSION=override",Xb=(e,t)=>e.some((n)=>n==="--help"||n==="-h"||n==="--dry-run"||rP.has(t)&&/^-[a-zA-Z]*n[a-zA-Z]*$/.test(n)&&!n.startsWith("--")),sP=(e,t,n)=>{let r;try{r=Yt(t,n)}catch{return[]}return r.flatMap((o)=>{if(o.tool!=="git"||o.dir===void 0)return[];let s=o.args.findIndex((c)=>!c.startsWith("-")),i=o.args[s]??"",a=o.args.slice(s+1);if(!nP.has(i)||Xb(a,i))return[];if(i==="stash"&&["list","show"].includes(a[0]??""))return[];return[U.resolve(e,o.dir??".")]})},iP=new Set(["cd","chdir","set-location","sl"]),aP=new Set(["pushd","push-location"]),cP=new Set(["popd","pop-location"]),ua=U.resolve(U.parse(process.cwd()).root,".workit-unknown-dir"),Ub=(e,t,n=!1)=>{let r=n?ua:void 0,o=t.slice(1).find((i)=>!i.startsWith("-")||i==="-"),s=o===void 0?void 0:Wo(o);if(s==="-"||s&&/^~|[$`*?]/.test(s))return r;if(e===void 0)return r;return s===void 0?Kb.homedir():U.resolve(e,s)},ad=(e)=>/^[\w@%+=:,./-]+$/.test(e)?e:`'${e.replaceAll("'","'\\''")}'`,Wo=(e)=>{let t=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)/.exec(e);return t?(process.env.HOME||Kb.homedir())+e.slice(t[0].length):e},aa=(e,t,n,r=0,o=!1)=>{let s=[],i=e,a=[],c=[],l=(u)=>{let d=Wo(u);return U.isAbsolute(d)?d:i===void 0?null:U.resolve(i,d)};for(let u of $e(t,n)){if(u.group==="open"){c.push({dir:i,stack:[...a]});continue}if(u.group==="close"){let v=c.pop();if(v)({dir:i,stack:a}=v);continue}let d=u.words.findIndex((v)=>!/^\w+=/.test(v)),p=d<0?[]:u.words.slice(d),f=(p[0]?.split(/[\\/]/).at(-1)??"").toLowerCase();if(iP.has(f)){i=Ub(i,p,o);continue}if(aP.has(f)){a.push(i),i=Ub(i,p,o);continue}if(cP.has(f)){i=a.length?a.pop():o?ua:void 0;continue}let g=r<4?Jb(p)??(o?id(p):null):null;if(g!==null&&i!==void 0)s.push(...aa(lP(i,p),g,"posix",r+1,o));if(o&&i!==void 0){let v=i;for(let w of r<4?u.subs??[]:[])s.push(...aa(v,w,n,r+1,!0));let m=u.unanalyzable?["."]:g===null?Gb(p):null;for(let w of m??[]){let b=l(w);if(b)s.push(w==="."?U.join(b,jo):b)}let y=p.findIndex((w)=>/^ln$/i.test(w.split(/[\\/]/).at(-1)??""));if(y>=0&&p.slice(0,y).every((w)=>ca.has(w)))s.push(...eP(p.slice(y+1),l))}for(let v of u.redirects)if(!/^\/dev\/(?:null|stdout|stderr|tty)$/.test(v)){let m=l(v);if(m)s.push(m)}let h=sd(u.words);if(h===null){if(i!==void 0)s.push(U.join(i,jo))}else for(let v of h){let m=l(v);if(m)s.push(m)}if(i!==void 0)for(let v of Qt(u.words.map(ad).join(" "),"posix")){let{at:m,args:y}=Yb(i,v);if(y[0]==="git"&&oP.has(y[1]??"")&&!Xb(y.slice(2),""))s.push(U.join(m,jo))}}return s},lP=(e,t)=>{for(let n of Qt(t.map(ad).join(" "),"posix")){let{at:r,args:o}=Yb(e,n);if(o[0]==="check"||o[0]==="lock"&&o[1]==="run")return r}return e},Yb=(e,t)=>{let{rest:n,cwd:r}=zo(t);return{at:r===null?e:U.resolve(e,Wo(r)),args:n}},cd=(e,t,n="posix",r=!1)=>{try{return[...aa(e,t,n,0,r),...sP(e,t,n).map((o)=>U.join(o,jo))]}catch{return[]}},uP=(e,t)=>{let n=$e(e,t);if(n.length!==1||n[0].group||n[0].subs?.length)return!1;let r=n[0].words,o=r.findIndex((s)=>!/^\w+=/.test(s));return o>0&&r.slice(0,o).includes(Vb)},dP={claude_code:"Claude Code",opencode:"OpenCode",codex_cli:"Codex CLI",codex_desktop:"Codex Desktop",cursor:"Cursor",pi:"Pi"},pP=(e)=>{let t=Math.max(0,Math.round(e/1000));return t<120?`${t}s`:`${Math.round(t/60)} min`},fP=({marker:e,checkout:t,ageMs:n,file:r})=>{let o=`Work in your own worktree (\`git worktree add <path> -b <branch>\`, or \`workit fanout worktree create <slice>\`). Only if the user confirms that session is finished: release it with \`rm '${r}'\`, or prefix one command with ${Vb}.`;return{kind:"deny",reason:`workit live-session guard: ${t} belongs to another live agent session, ${dP[e.host]??e.host} session ${e.session}${e.pid===null?"":` (pid ${e.pid})`}, last active ${pP(n)} ago. Do not edit a checkout another session is working in; read-only commands stay allowed. ${o}`,unblock:o}},Qb=(e)=>{let t=new Set;return e.filter((n)=>{let r=U.dirname(n);if(t.has(r))return!1;return t.add(r),!0})},ex=(e,t,n)=>{try{for(let r of Qb(t)){let o=Fb(r,e,n);if(o&&Am(o.checkout))return fP(o)}}catch{}return Do},tx=(e,t,n)=>{for(let r of Qb(t))Bb(r,e,n)},ld=(e,t)=>t?.length?t.map((n)=>U.resolve(e,n)):[U.join(e,jo)],nx=(e,t)=>{let n=Le();return t.find((o)=>gP(n,e,Wo(o),process.platform,rd))??null},gP=(e,t,n,r=process.platform,o=(s)=>s)=>{let s=r==="win32",i=s?U.win32:U.posix,a=(u)=>s||r==="darwin"?u.toLowerCase():u,c=s?n.replace(/^\/([a-zA-Z])(?=\/|$)/,"$1:"):n,l=i.relative(a(o(i.resolve(e))),a(o(i.resolve(t,c))));if(l.startsWith("..")||i.isAbsolute(l))return!1;return l.split(i.sep)[0].startsWith("issued")},hP=(e)=>{if(process.platform!=="win32"||!e.includes("\\"))return!1;let t=(n)=>n.replaceAll("\\","/").toLowerCase();return t(e).includes(`${t(Le())}/issued`)&&la(e).writes},rx=(e)=>({kind:"deny",reason:`workit issued-registry guard: ${e} is under Workit's issued-session state. Issued ids and tokens are written only by Workit's SubagentStart hook. Run the verifier or reviewer agent so the host issues its own session; never edit the issued registries by hand.`,unblock:"Issued ids and tokens are written only by Workit's SubagentStart hook. Run the verifier or reviewer agent so the host issues its own session; never edit the issued registries by hand."});function ud(e,t,n,r){let o=t?.length?nx(e,t):null;if(o)return rx(o);if(!n)return od(e,t);let s=ld(e,t),i=ex(n,s,r);if(i.kind!=="none")return i;let a=od(e,t);if(a.kind==="none")tx(n,s,r);return a}function dd(e,t,n,r="posix",o){try{let c=nx(e,aa(e,t,r))??(hP(t)?"the issued registry":null);if(c)return rx(c)}catch{}let s=la(t),i=[];if(n)i=cd(e,t,r);if(n&&i.length){let c=ex(n,i,o);if(c.kind!=="none"){if(!uP(t,r))return c;mP(e,n,t)}}let a=s.writes?od(e,s.targets):Do;if(n&&i.length&&a.kind==="none")tx(n,i,o);return a}var mP=(e,t,n)=>{try{if(!lt(e))return;Rn(e,{type:"live_session.override",actor:{host:t.host,session:t.session,agentId:null},session:t.session,command:n.slice(0,200)})}catch{}};function od(e,t){try{let n=tP(e);if(!n||n.blockers.length===0)return Do;if(t?.length&&t.every((o)=>YA(e,n.root,o,n.plans)))return Do;return{kind:"deny",reason:`workit before-write gate: ${n.blockers.map((o)=>`${o.ruleId}: ${o.reason}`).join("; ")}. Markdown, docs/, plans/ and files outside the checkout stay writable.`,unblock:n.blockers[0].reason}}catch{return Do}}import{spawnSync as kP}from"node:child_process";function ox(e){try{let t=new xn(e),n=t.listTaskIndex(),r=t.currentKey();if(!n.ok||!r.ok)return null;let o=n.data.filter((i)=>i.key===r.data.key&&i.status!=="closed").toSorted((i,a)=>a.updatedAt.localeCompare(i.updatedAt))[0],s=o?t.readTask(o.id):null;return s?.ok===!0?Kt(s.data):null}catch{return null}}var Mo={kind:"none"},yP=/[??؟](?=[\s*_`"')\]>]*(?:\s|$))|¿/,vP=/\b(?:let me know|want me to|should I|shall I|would you like|do you want|if you(?:'d| would) like|may I|can I go ahead)\b/i,wP=/[[(]\s*y(?:es)?\s*\/\s*n(?:o)?\s*[\])]/i,bP=/^\s*(?:[-*+•]|\d+[.)]|[a-z][.)])\s+/i,ix=(e)=>{if(!e)return!1;let t=e.replace(/```[\s\S]*?(?:```|$)/g,`
210
+ `}else if(r==="/"&&e[n+1]==="*"){let o=e.indexOf("*/",n+2);if(o<0)throw Error("unterminated comment");n=o+1}else t+=r}return JSON.parse(t.replace(/,(\s*[}\]])/gu,"$1"))}function Xn(e){for(let t=ue.resolve(e);;t=ue.dirname(t)){if(Ju.existsSync(ue.join(t,".git")))return t;if(ue.dirname(t)===t)return null}}var tA=(e)=>{let t=Xn(e),n=[];for(let r=ue.resolve(e);;r=ue.dirname(r))if(n.push(r),!t||r===t||ue.dirname(r)===r)return n},na=(e)=>e.HOME||eA.homedir(),hb={linux:"/etc/claude-code/managed-settings.json",darwin:"/Library/Application Support/ClaudeCode/managed-settings.json",win32:"C:\\Program Files\\ClaudeCode\\managed-settings.json"};function nA(e,t,n=process.platform){let r=t.CLAUDE_PROJECT_DIR||Xn(e)||e,o=t.CLAUDE_CONFIG_DIR||ue.join(na(t),".claude");return[...hb[n]?[hb[n]]:[],ue.join(o,"settings.json"),ue.join(r,".claude","settings.json"),ue.join(r,".claude","settings.local.json")]}var rA=(e)=>{let t=/^Bash(?:\((.*)\))?$/su.exec(e.trim());return t?t[1]??"":null};function vb(e,t=process.env){let n=ea();try{for(let r of nA(e,t)){let o=ta(r);if(o===null)continue;let s=JSON.parse(o);if(!en(s))return"unreadable";let i=s.permissions;if(i===void 0)continue;if(!en(i))return"unreadable";for(let[a,c]of[["deny",n.deny],["ask",n.deny],["allow",n.allow]]){let l=i[a];if(l===void 0)continue;if(!Array.isArray(l))return"unreadable";for(let u of l){if(typeof u!=="string")return"unreadable";let d=rA(u);if(d!==null)c.push(d)}}}}catch{return"unreadable"}return n}var mb=["opencode.json","opencode.jsonc"],kb=(e,t)=>{if(e===void 0)return!0;if(typeof e==="string")return(e==="allow"?t.allow:t.deny).push(""),["allow","ask","deny"].includes(e);if(!en(e))return!1;for(let n of["bash","shell"]){let r=e[n];if(r===void 0)continue;if(typeof r==="string"){if(!["allow","ask","deny"].includes(r))return!1;(r==="allow"?t.allow:t.deny).push("");continue}if(!en(r))return!1;for(let[o,s]of Object.entries(r)){if(s!=="allow"&&s!=="ask"&&s!=="deny")return!1;(s==="allow"?t.allow:t.deny).push(o)}}return!0},yb=(e,t)=>{if(!en(e))return!1;if(!kb(e.permission,t))return!1;if(e.agent===void 0)return!0;if(!en(e.agent))return!1;return Object.values(e.agent).every((n)=>en(n)&&kb(n.permission,t))};function wb(e,t=process.env){let n=ea();try{let r=t.XDG_CONFIG_HOME||ue.join(na(t),".config"),o=[...mb.map((s)=>ue.join(r,"opencode",s)),...tA(e).flatMap((s)=>mb.flatMap((i)=>[ue.join(s,i),ue.join(s,".opencode",i)])),...t.OPENCODE_CONFIG?[t.OPENCODE_CONFIG]:[]];for(let s of o){let i=ta(s);if(i!==null&&!yb(gb(i),n))return"unreadable"}if(t.OPENCODE_CONFIG_CONTENT&&!yb(gb(t.OPENCODE_CONFIG_CONTENT),n))return"unreadable"}catch{return"unreadable"}return n}var oA=(e)=>{let t=/\bpattern\s*=\s*\[/u.exec(e);if(!t)return null;let n=[],r=t.index+t[0].length;for(;;){while(/[\s,]/u.test(e[r]??""))r+=1;if(e[r]==="]")break;if(e[r]!=='"')return null;let s=/"((?:[^"\\]|\\.)*)"/y;s.lastIndex=r;let i=s.exec(e);if(!i)return null;n.push(JSON.parse(`"${i[1]}"`)),r=s.lastIndex}let o=/\bdecision\s*=\s*"(\w+)"/u.exec(e)?.[1];if(!n.length||!o||!["allow","prompt","forbidden"].includes(o))return null;return{pattern:n.join(" "),decision:o}};function bb(e,t=process.env){let n=ea();try{let r=t.CODEX_HOME||ue.join(na(t),".codex"),o=Xn(e)??e;for(let s of[ue.join(r,"rules"),ue.join(o,".codex","rules")]){let i;try{i=Ju.readdirSync(s).filter((a)=>a.endsWith(".rules"))}catch(a){if(a.code==="ENOENT")continue;return"unreadable"}for(let a of i){let c=ta(ue.join(s,a))??"";for(let l of c.split(/\bprefix_rule\s*\(/u).slice(1)){let u=oA(l);if(!u)return"unreadable";(u.decision==="allow"?n.allow:n.deny).push(u.pattern)}}}}catch{return"unreadable"}return n}function xb(e,t=process.env){let n=ea();try{let r=Xn(e)??e;for(let o of[ue.join(na(t),".cursor","cli-config.json"),ue.join(r,".cursor","cli.json")]){let s=ta(o);if(s===null)continue;let i=JSON.parse(s);if(!en(i))return"unreadable";if(i.permissions===void 0)continue;if(!en(i.permissions))return"unreadable";for(let[a,c]of[["deny",n.deny],["allow",n.allow]]){let l=i.permissions[a];if(l===void 0)continue;if(!Array.isArray(l))return"unreadable";for(let u of l){if(typeof u!=="string")return"unreadable";let d=/^Shell(?:\((.*)\))?$/su.exec(u.trim());if(d)c.push(d[1]??"")}}}}catch{return"unreadable"}return n}var qu=(e)=>(e.split(/[\\/]/u).at(-1)??"").toLowerCase().replace(/\.(?:exe|cmd|bat)$/u,""),Sb=(e)=>e.trim().split(/[:\s]/u)[0]??"";function sA(e,t){let n=Sb(e);if(!n||n==="*"||n.includes("*"))return!0;let r=qu(n);return t.some((o)=>qu(o)===r)}var _b=(e)=>e.trim().replace(/(?::\*| \*|\*)$/u,""),iA=(e)=>{let t=Sb(e);if(!t||t.includes("*"))return!0;let n=_b(e).split(/\s+/u);if(qu(n[0])!=="workit")return!1;return["check","--heavy"].slice(0,n.length-1).every((r,o)=>{let s=n[o+1];return s===r||r.startsWith(s)})},aA=(e,t)=>{let n=_b(e);if(!n)return!0;return!n.includes("*")&&t.trim().startsWith(n)};function Rb(e,t,n,r={}){if(e==="unreadable")return{ok:!1,why:"named"};if(e.deny.some((o)=>sA(o,t)))return{ok:!1,why:"named"};if(!r.bypass&&e.allow.some(iA)&&!e.allow.some((o)=>aA(o,n)))return{ok:!1,why:"allowlisted"};return{ok:!0}}import Gu from"node:fs";import cA from"node:os";import tn from"node:path";function lA(e,t=process.platform){if(e.WORKFLOW_TOOLKIT_STATE)return e.WORKFLOW_TOOLKIT_STATE;if(e.XDG_STATE_HOME)return tn.join(e.XDG_STATE_HOME,"workit");let n=e.HOME||cA.homedir();if(t==="darwin")return tn.join(n,"Library","Application Support","workit");if(t==="win32")return tn.join(e.LOCALAPPDATA??tn.join(n,"AppData","Local"),"workit");return tn.join(n,".local","state","workit")}var uA="heavy-commands.json",dA=(e)=>tn.join(lA(e),uA),An=/^(?:test|tests|t|tst|unit|integration|e2e|coverage|cov|lint|eslint|typecheck|type-check|types|tsc|check|verify|validate|build|compile|bundle|ci|sonar|cypress|playwright|jest|vitest|mocha|bench|benchmark|all)(?:$|[:_.-])/iu,pA=new Set(["--version","-v","-V","--help","-h","help","version"]),fA=/^(?:--watch(?:All)?(?:=.*)?|-w|--serve)$/u,Pr=/(?:^|[:_.-])(?:watch|dev|serve|start|storybook)(?:$|[:_.-])/iu,H=(...e)=>new Set(e),gA={jest:"any",vitest:"any",mocha:"any",ava:"any",tap:"any",karma:"any",jasmine:"any",nyc:"any",c8:"any",tsc:"any","vue-tsc":"any","svelte-check":"any",eslint:"any",stylelint:"any",tslint:"any",webpack:"any","webpack-cli":"any",rollup:"any",parcel:"any",tsup:"any",vite:H("build","optimize"),next:H("build","lint"),nuxt:H("build","generate"),nuxi:H("build","generate"),astro:H("build","check"),ng:H("build","b","test","t","e2e","lint"),"react-scripts":H("build","test"),playwright:H("test","install"),cypress:H("run"),wdio:"any",testcafe:"any",turbo:"any",lerna:H("run","exec","bootstrap"),"sonar-scanner":"any",sonarless:H("scan"),"sonarless-mcp":H("scan"),go:H("test","build","vet","install","generate"),"golangci-lint":H("run"),gotestsum:"any",staticcheck:"any",cargo:H("build","b","test","t","check","c","clippy","bench","nextest","doc","install","tarpaulin","llvm-cov"),mvn:"any",mvnw:"any",gradle:"any",gradlew:"any",ant:"any",sbt:"any",bazel:H("build","test","run","coverage"),bazelisk:H("build","test","run","coverage"),buck2:H("build","test","run"),dotnet:H("build","test","publish","restore","pack","msbuild"),msbuild:"any",pytest:"any","py.test":"any",tox:"any",nox:"any",mypy:"any",pyright:"any",pylint:"any",coverage:H("run"),maturin:H("build","develop"),pip:H("install","wheel"),pip3:H("install","wheel"),rspec:"any",rails:H("test","assets:precompile"),phpunit:"any",pest:"any",phpstan:"any",psalm:"any",composer:H("install","update","require","test"),mix:H("test","compile","deps.get","dialyzer","credo"),swift:H("build","test"),xcodebuild:"any",flutter:H("build","test"),dart:H("test","compile"),pod:H("install"),cmake:H("--build"),ninja:"any",meson:H("compile","test"),ctest:"any",scons:"any","docker-compose":H("build"),buildah:H("bud","build"),earthly:"any"},hA=new Set(["--prefix","-w","--workspace","-C","--dir","--filter","-F","--cwd","-p","--package","--cache","--registry"]);function Ge(e,t,n=hA){let r=t;while(r<e.length&&e[r].startsWith("-")){if(e[r]==="--")return r+1;r+=n.has(e[r])?2:1}return r}var Vu=(e)=>(e?.split(/[\\/]/u).at(-1)??"").toLowerCase().replace(/\.(?:exe|cmd|bat|ps1)$/u,""),Ib=/^(?:workit|@brainervirus\/workit-cli(?:@.*)?)$/u,mA=/^(?:python[\d.]*|py)$/u,kA=new Set(["ci","clean-install","cit","install-test","it","install","i","in","add","rebuild","update","up"]),yA=new Set(["run","run-script","rum","urn"]),vA=new Set(["test","t","tst"]),wA=new Set(["exec","x","dlx"]);function Tb(e,t=0){if(t>6||!e.length)return null;let n=Vu(e[0]),r=()=>e.slice(0,3).join(" "),o=(a)=>Tb(e.slice(a),t+1);if(Ib.test(n))return null;if(pA.has(e[1]??"")&&e.length===2)return null;if(e.some((a)=>a==="--watch"||a.startsWith("--watch=")||a==="--watchAll"))return null;if(n==="npx"||n==="bunx"||n==="pnpx")return o(Ge(e,1));if(n==="corepack")return o(1);if(n==="npm"||n==="pnpm"||n==="yarn"||n==="bun"||n==="deno"){let a=Ge(e,1),c=e[a];if(c===void 0)return n==="yarn"?"yarn (install)":null;if(n==="deno"){if(["test","bench","check","compile","lint"].includes(c))return r();if(c==="task"&&An.test(e[a+1]??""))return r();return null}if(kA.has(c)||vA.has(c))return r();if(n==="bun"&&c==="build")return r();if(wA.has(c))return o(Ge(e,a+1));if(n==="yarn"&&c==="workspace")return o(a+2);if(n==="yarn"&&c==="workspaces")return e.slice(a+1).some((l)=>An.test(l))?r():null;if(yA.has(c)){let l=e[Ge(e,a+1)];if(l===void 0||Pr.test(l))return null;if(An.test(l))return r();return n==="bun"?o(Ge(e,a+1)):null}if(n==="npm")return null;if(Pr.test(c))return null;if(An.test(c)&&!/\.[cm]?[jt]sx?$/u.test(c))return r();return o(a)}if(mA.test(n)){let a=e.indexOf("-m");return a>0&&e[a+1]?o(a+1):null}if(["uv","poetry","pdm","pipenv","hatch","rye"].includes(n)){let a=Ge(e,1),c=e[a];if(c==="run")return o(Ge(e,a+1));if(c==="pip")return o(a);return["sync","install","build","test","add"].includes(c??"")?r():null}if(n==="bundle"){let a=e[Ge(e,1)];if(a==="exec")return o(Ge(e,2));return a==="install"||a===void 0?r():null}if(n==="make"||n==="gmake"){let a=e.slice(1).filter((c)=>!c.startsWith("-")&&!c.includes("="));if(a.some((c)=>Pr.test(c)))return null;return!a.length||a.some((c)=>An.test(c))?r():null}if(n==="rake")return e.slice(1).filter((c)=>!c.startsWith("-")&&!c.includes("=")).some((c)=>An.test(c)||/^spec(?:$|:)/u.test(c))?r():null;if(n==="nx"){let a=Ge(e,1),c=e[a]??"";if(["run-many","affected"].includes(c))return e.some((l)=>/^(?:-t|--targets?)(?:=|$)/u.test(l))&&!e.some((l)=>Pr.test(l.replace(/^--?targets?=/u,"")))?r():null;if(c==="run"){let l=(e[a+1]??"").split(":")[1]??"";return An.test(l)&&!Pr.test(l)?r():null}return An.test(c)&&!Pr.test(c)?r():null}if(n==="docker"||n==="podman"||n==="nerdctl"){let a=Ge(e,1,new Set(["-H","--host","--context","-c","--config"])),c=e[a];if(c==="build")return r();if(c==="buildx"||c==="image"||c==="builder")return e[Ge(e,a+1)]==="build"?r():null;if(c==="compose"){let l=Ge(e,a+1,new Set(["-f","--file","-p"])),u=e[l];if(u==="build")return r();return u==="up"&&e.slice(l+1).includes("--build")?r():null}return null}let s=gA[n];if(!s)return null;if(e.slice(1).some((a)=>fA.test(a)||a==="watch"||a==="dev"))return null;if(s==="any")return r();let i=e.slice(1).find((a)=>!a.startsWith("-")&&!a.startsWith("+")||s.has(a));return i!==void 0&&s.has(i)?r():null}var bA=(e)=>new RegExp(`^${e.replace(/[.+?^${}()|[\]\\]/gu,"\\$&").replaceAll("*",".*")}$`,"u");function xA(e){let t=e.trim().split(/\s+/u).filter(Boolean);return t.length?t.map(bA):null}var SA=(e,t)=>e.length<=t.length&&e.every((n,r)=>r===0?n.test(t[0])||n.test(Vu(t[0])):n.test(t[r])),_A=(e)=>{try{return JSON.parse(Gu.readFileSync(e,"utf8"))}catch{return}},RA=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),$A=(e)=>Array.isArray(e)?e.filter((t)=>typeof t==="string"):[];function IA(e){let t=_A(dA(e));return RA(t)?$A(t.patterns):[]}function TA(e){return ti(Xn(e)??tn.resolve(e))}function $b(e,t){let n=[],r=null;for(let o of e){let s=Tb(o);if(s){n.push({line:o,source:"catalog",reason:s});continue}r??=(t.patterns??[...IA(t.env??process.env).map((a)=>({pattern:a,from:"machine"})),...TA(t.cwd).map((a)=>({pattern:a,from:"repo"}))]).flatMap((a)=>{let c=xA(a.pattern);return c?[{...a,matchers:c}]:[]});let i=r.find((a)=>SA(a.matchers,o));if(i)n.push({line:o,source:{pattern:i.pattern,from:i.from},reason:`${i.from} pattern "${i.pattern}"`})}return n}var OA=(e,t)=>{try{return Jw(e,t)}catch{return null}};var EA=(e)=>/^[\w@%+=:,./-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`,CA=(e)=>`workit check --heavy -- ${e.map(EA).join(" ")}`;function Ob(e,t){let n=t.dialect??"posix";if(n!=="posix"||!Xn(t.cwd))return{kind:"none"};let r=OA(e,n);if(!r)return{kind:"none"};let o=$b(r,t);if(!o.length)return{kind:"none"};let s=Ui(e,n,0,!0),i=s&&!Ib.test(Vu(s[0]))&&$b([s],t)[0],a=i?[{words:r.flat(),text:e}]:o.map((l)=>({words:l.line,text:l.line.join(" ")}));if(t.rules!==null){for(let{words:l,text:u}of a)if(!Rb(t.rules,l,u,{bypass:t.bypass}).ok)return{kind:"passthrough",note:""}}if(i){let l=PA(e);return l?{kind:"rewrite",command:l,reason:i.reason}:{kind:"none"}}let c=o.map((l)=>CA(l.line));return{kind:"split",reason:`heavy_command: \`${e.trim()}\` chains heavy work (${o.map((l)=>l.reason).join("; ")}) with other commands, and a chain cannot run under the machine-wide heavy-check lease. Run the heavy part alone, now: \`${c[0]}\`; then run the other parts as their own commands${c.length>1?", each heavy one the same way":""}.`,unblock:c[0]??null}}function Eb(e=process.env){let t=process.platform==="win32"?["workit.exe","workit.cmd","workit"]:["workit"];for(let n of(e.PATH??"").split(tn.delimiter))for(let r of t){if(!n)continue;try{return Gu.accessSync(tn.join(n,r),Gu.constants.X_OK),!0}catch{}}return!1}var AA=/^\s*((?:[A-Za-z_]\w*=(?:'[^']*'|"(?:[^"\\]|\\.)*"|[^\s'"])*\s+)*)/u;function PA(e){let t=e.trim(),n=AA.exec(t)?.[1]??"",r=t.slice(n.length).trim();if(!r)return null;return`${n}workit check --heavy -- ${r}`}import Cb from"node:fs";import zA from"node:os";import At from"node:path";var NA=new Set("npm npx pnpm pnpx yarn bun bunx deno corepack make gmake docker podman nerdctl python python3 py uv poetry pdm pipenv hatch rye bundle rake nx jest vitest mocha ava tap karma jasmine nyc c8 tsc vue-tsc svelte-check eslint stylelint tslint webpack webpack-cli rollup parcel tsup vite next nuxt nuxi astro ng react-scripts playwright cypress wdio testcafe turbo lerna sonar-scanner sonarless sonarless-mcp go golangci-lint gotestsum staticcheck cargo mvn mvnw gradle gradlew ant sbt bazel bazelisk buck2 dotnet msbuild pytest py.test tox nox mypy pyright pylint coverage maturin pip pip3 rspec rails phpunit pest phpstan psalm composer mix swift xcodebuild flutter dart pod cmake ninja meson ctest scons docker-compose buildah earthly".split(" ")),Ab=(e)=>e.split(/[\s;&|()<>`'"]+/u).map((t)=>(t.split(/[\\/]/u).at(-1)??"").toLowerCase().replace(/\.(?:exe|cmd|bat)$/u,"")).filter(Boolean),LA=(e)=>{if(e.WORKFLOW_TOOLKIT_STATE)return e.WORKFLOW_TOOLKIT_STATE;if(e.XDG_STATE_HOME)return At.join(e.XDG_STATE_HOME,"workit");let t=e.HOME||zA.homedir();if(process.platform==="darwin")return At.join(t,"Library","Application Support","workit");if(process.platform==="win32")return At.join(e.LOCALAPPDATA??At.join(t,"AppData","Local"),"workit");return At.join(t,".local","state","workit")},DA=(e)=>{try{return JSON.parse(Cb.readFileSync(e,"utf8"))}catch{return}},jA=(e,t)=>{let n=[],r=DA(At.join(LA(t),"heavy-commands.json"));if(Array.isArray(r?.patterns))n.push(...r.patterns);for(let s=At.resolve(e);;s=At.dirname(s)){if(Cb.existsSync(At.join(s,".git"))){n.push(...ti(s));break}if(At.dirname(s)===s)break}let o=new Set;for(let s of n){if(typeof s!=="string")continue;let i=Ab(s)[0];if(!i||i.includes("*"))return null;o.add(i)}return o};function Pb(e,t,n=process.env){try{let r=Ab(e);if(r.some((s)=>NA.has(s)||/^python[\d.]*$/u.test(s)))return!0;let o=jA(t,n);return o===null||r.some((s)=>o.has(s))}catch{return!0}}var WA=(e,t,n)=>{switch(e){case"claude_code":return vb(t,n);case"opencode":return wb(t,n);case"codex_cli":case"codex_desktop":return bb(t,n);case"cursor":return xb(t,n);case"pi":return null}};function Xu(e,t,n){let r=n.env??process.env;try{if(r.WORKIT_HEAVY_GATE==="0"||!Pb(t,e,r)||!Eb(r))return{kind:"none"};return Ob(t,{cwd:e,env:r,dialect:n.dialect??"posix",rules:WA(n.host,e,r),bypass:n.permissionMode==="bypassPermissions"})}catch{return{kind:"none"}}}var zb=(e)=>`workit: this heavy command (${e.reason}) runs under the machine-wide heavy-check lease as \`${e.command}\`: it waits while another heavy check holds the lease (\`workit lock status\` shows who). Run heavy commands that way yourself; \`workit help lock\` explains the lease.`,Yu=(e,t)=>({kind:"deny",reason:`heavy_command: \`${e.trim()}\` is heavy (${t.reason}) and must run under the machine-wide heavy-check lease, so parallel agents cannot exhaust this machine's memory and CPU. Run exactly: ${t.command}`,unblock:t.command}),Qu=(e)=>({kind:"deny",reason:e.reason,unblock:e.unblock});import{existsSync as GA,realpathSync as VA}from"node:fs";import Kb from"node:os";import U from"node:path";import{spawnSync as MA}from"node:child_process";import{createHash as FA}from"node:crypto";import yt from"node:fs";import td from"node:os";import Pt from"node:path";var BA=900000,HA=30000,Yn={platform:process.platform,run:(e)=>MA("ps",e,{encoding:"utf8",timeout:2000}).stdout??"",start:(e)=>go(e)},ed=(e)=>e.split(":")[0].replace(/-w-.*$/su,"")||e,Nb=(e)=>e.replace(/_(?:cli|desktop)$/u,""),ZA=(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},UA=(e)=>{try{if(Yn.platform==="linux"){let n=yt.readFileSync(`/proc/${e}/stat`,"utf8"),r=Number(n.slice(n.lastIndexOf(")")+2).split(" ")[1]),o=yt.readFileSync(`/proc/${e}/cmdline`,"utf8").replaceAll("\x00"," ");return Number.isInteger(r)?{ppid:r,command:o.trim()}:null}if(Yn.platform==="win32")return null;let t=/^\s*(\d+)\s+(.*)$/su.exec(Yn.run(["-o","ppid=,command=","-p",String(e)]));return t?{ppid:Number(t[1]),command:t[2].trim()}:null}catch{return null}},KA=/^(?:\S*\/)?(?:sh|bash|dash|zsh|ash|ksh|fish|env|timeout|npx|npm|bunx|cmd\.exe|pwsh|powershell)(?:\s|$)|launch\.mjs|npx-cli\.js/u,ra=new Map,qA=(e)=>{if(e!=="hook-process")return process.pid;let t=`${Yn.platform}\x00${process.ppid}`;if(ra.has(t))return ra.get(t)??null;if(Yn.platform==="win32")return ra.set(t,null),null;let n=process.ppid;for(let r=0;r<4;r++){let o=UA(n);if(!o||!KA.test(o.command)||o.ppid<=1)break;n=o.ppid}return ra.set(t,n),n},oa=(e)=>e.replace(/[^A-Za-z0-9_.:@/+-]/gu,"-"),ia=(e,t,n=process.env)=>{let r=e.session.id?.trim();if(!r)return null;let o=new Set([ed(oa(r))]);if(e.session.parentId)o.add(ed(oa(e.session.parentId)));if(n.WORKIT_PI_WORKER_SESSION&&n.WORKIT_SESSION_ID)o.add(ed(oa(n.WORKIT_SESSION_ID)));return{host:e.host,session:oa(r),leads:[...o],pid:()=>qA(t)}},Lb=(e)=>{let t=Pt.resolve(e);while(!yt.existsSync(t)&&Pt.dirname(t)!==t)t=Pt.dirname(t);if(yt.existsSync(t)&&!yt.statSync(t).isDirectory())t=Pt.dirname(t);let n=t.split(Pt.sep),r=n.lastIndexOf(".git");if(r>0)t=n.slice(0,r).join(Pt.sep)||Pt.sep;let o=_e(t);if(o instanceof Error||!o.shared||!o.top)return null;let s=o.top;try{s=yt.realpathSync.native(s)}catch{}return s},Db=(e)=>Pt.join(Le(),"live-sessions",`${FA("sha256").update(JA(e)).digest("hex").slice(0,32)}.json`),JA=(e,t=process.platform)=>{let n=Pt.resolve(e);try{n=yt.realpathSync.native(n)}catch{}return t==="win32"?n.replaceAll("/","\\").toLowerCase():n},jb=(e)=>{try{let t=JSON.parse(yt.readFileSync(e,"utf8"));if(t?.version!==1||typeof t.session!=="string"||typeof t.host!=="string"||typeof t.heartbeatAt!=="string"||Number.isNaN(Date.parse(t.heartbeatAt)))return null;return{version:1,session:t.session,leads:Array.isArray(t.leads)?t.leads.filter((n)=>typeof n==="string"):[],host:t.host,pid:typeof t.pid==="number"?t.pid:null,pidStart:typeof t.pidStart==="string"?t.pidStart:null,machine:typeof t.machine==="string"?t.machine:"",checkout:typeof t.checkout==="string"?t.checkout:"",heartbeatAt:t.heartbeatAt}}catch{return null}},nd=(e,t)=>t.getTime()-Date.parse(e.heartbeatAt),Wb=(e,t)=>{if(nd(e,t.now??new Date)>(t.ttlMs??BA))return!1;if(e.machine!==(t.machine??td.hostname())||e.pid===null)return!0;if(!(t.alive??ZA)(e.pid))return!1;if(e.pidStart===null)return!0;let r=Yn.start(e.pid);return r===null||r===e.pidStart},sa=(e,t)=>e.session===t.session||t.leads.some((n)=>n===e.session||e.leads.includes(n)),Mb=(e,t,n)=>{if(sa(e,t))return!0;if(e.machine!==n)return!1;let r=t.pid();if(r===null||e.pid===null||e.pidStart===null)return Nb(e.host)===Nb(t.host);return e.pid===r},Fb=(e,t,n={})=>{try{let r=Lb(e);if(!r)return null;let o=Db(r),s=jb(o);if(!s||sa(s,t)||!Wb(s,n))return null;if(Mb(s,t,n.machine??td.hostname()))return null;return{marker:s,file:o,ageMs:nd(s,n.now??new Date),checkout:r}}catch{return null}},Bb=(e,t,n={})=>{try{let r=Lb(e);if(!r)return;let o=Db(r),s=n.now??new Date,i=n.machine??td.hostname(),a=jb(o);if(a){let d=nd(a,s);if(sa(a,t)&&d>=0&&d<HA)return;if(!sa(a,t)&&Wb(a,n)&&!Mb(a,t,i))return}let c=t.pid(),l={version:1,session:t.session,leads:t.leads,host:t.host,pid:c,pidStart:c===null?null:Yn.start(c),machine:i,checkout:r,heartbeatAt:s.toISOString()};yt.mkdirSync(Pt.dirname(o),{recursive:!0});let u=`${o}.${process.pid}.tmp`;yt.writeFileSync(u,JSON.stringify(l)),yt.renameSync(u,o)}catch{}};var Do={kind:"none"},XA=process.platform==="darwin"||process.platform==="win32",rd=(e)=>{let t="";for(let n=U.resolve(e);;n=U.dirname(n))try{return U.join(VA.native(n),t)}catch{if(U.dirname(n)===n)return U.resolve(e);t=t?U.join(U.basename(n),t):U.basename(n)}},YA=(e,t,n,r)=>{let o=(c)=>XA?c.toLowerCase():c,s=U.relative(o(rd(t)),o(rd(U.resolve(e,n))));if(s.startsWith("..")||U.isAbsolute(s))return!0;let i=s.split(U.sep).join("/"),a=i.split("/");return/\.mdx?$/i.test(i)||a[0]==="docs"||a.includes("plans")||[...r].some((c)=>o(c)===i)},ca=new Set(["sudo","command","env","nohup","time","exec","xargs","busybox"]),Qn=(e)=>e.filter((t)=>!t.startsWith("-")),qb=new Set(["sh","bash","zsh","dash","ksh"]),Jb=(e)=>{let t=e;while(t.length&&(ca.has(t[0])||/^\w+=/.test(t[0])))t=t.slice(1);let n=Lu(t);if(!n)return null;if("script"in n)return n.script;let r=id(n.argv);if(qb.has((n.argv[0]?.split(/[\\/]/).at(-1)??"").toLowerCase())&&r)return r;return n.argv.map(ad).join(" ")},sd=(e)=>{let t=e;while(t.length&&(ca.has(t[0])||/^\w+=/.test(t[0])))t=t.slice(1);let[n,...r]=t,o=(n?.split(/[\\/]/).at(-1)??"").toLowerCase();if(!o||o==="workit"||o==="npx"&&r.some((s)=>/workit/.test(s)))return[];switch(o){case"touch":case"mkdir":case"rm":case"rmdir":case"tee":case"mv":case"truncate":return Qn(r);case"cp":case"ln":case"install":{let s=r.indexOf("-t");if(s>=0)return r[s+1]?[r[s+1]]:null;let i=Qn(r).at(-1);return i?[i]:null}case"dd":return r.filter((s)=>s.startsWith("of=")).map((s)=>s.slice(3));case"sed":case"perl":{if(!r.some((a)=>/^-[a-zA-Z]*i|^--in-place/.test(a)))return[];let s=r.some((a)=>a==="-e"||a==="-f"),i=[];for(let a=0;a<r.length;a++)if(r[a]==="-e"||r[a]==="-f")a++;else if(!r[a].startsWith("-"))i.push(r[a]);return s?i:i.slice(1)}case"patch":return null;case"set-content":case"add-content":case"out-file":case"new-item":case"ni":case"remove-item":case"del":case"copy-item":case"move-item":{let s=r.findIndex((c)=>/^-(?:path|filepath|literalpath|destination)$/i.test(c));if(s>=0)return r[s+1]?[r[s+1]]:null;let i=Qn(r);if(o==="move-item")return i.length?i:null;let a=o==="copy-item"?i.at(-1):i[0];return a?[a]:null}case"git":{let s=Qn(r)[0];if(s==="apply")return null;if(s==="restore"||s==="mv"||s==="rm")return Qn(r).slice(1);if(s==="checkout"&&r.includes("--"))return r.slice(r.indexOf("--")+1);return[]}default:return[]}},id=(e)=>{if(!qb.has((e[0]?.split(/[\\/]/).at(-1)??"").toLowerCase()))return null;for(let t=1;t<e.length;t++){let n=e[t];if(/^-[a-z]*c$/.test(n))return e[t+1]??null;if(/^[-+][oO]$/.test(n))t++;else if(!/^[-+]/.test(n))return null}return null},QA=/^-[IinLPdsEa]$/,Hb=(e)=>{let t=[...e.filter((r)=>r!=="{}"&&r!==";"&&r!=="+"),"x"],n=sd(t);return n===null||n.length>0||Gb(t)!==null},Gb=(e)=>{let t=e;while(t.length&&(ca.has(t[0])||/^\w+=/.test(t[0]))){if(t[0]==="xargs"){let c=1;while(t[c]?.startsWith("-"))c+=QA.test(t[c])?2:1;return Hb(t.slice(c))?["."]:null}t=t.slice(1)}let[n,...r]=t,o=(n?.split(/[\\/]/).at(-1)??"").toLowerCase(),s=Qn(r),i=(c)=>r.some((l)=>c.test(l)),a=(c)=>c.length?c:["."];if(o==="unlink"||o==="shred")return a(s);if(/^(?:chmod|chown|chgrp|chattr)$/.test(o))return a(i(/^--reference/)?s:s.slice(1));if(o==="rsync"){let c=s.at(-1),l=/^[\w.@-]*:/.test(c??"")&&!/^[A-Za-z]:[\\/]/.test(c??"");return c===void 0?["."]:l?[]:[c]}if(o==="find"){let c=r.findIndex((d)=>/^-(?:exec|execdir|ok|okdir)$/.test(d)),l=i(/^-(?:delete|fprint\w*|fls)$/)||c>=0&&Hb(r.slice(c+1)),u=r.findIndex((d)=>/^[-(!]/.test(d));return l?a(u<0?r:r.slice(0,u)):null}if(/^g?awk$/.test(o)){if(!i(/^-i|^--include/))return null;let c=[],l=!i(/^-f$|^--file/);for(let u=0;u<r.length;u++)if(/^(?:-[ifvF]|--(?:include|file|assign|field-separator))$/.test(r[u]))u++;else if(r[u].startsWith("-"))continue;else if(l)l=!1;else c.push(r[u]);return a(c)}if(o==="perl")return i(/^-[a-zA-Z]*[eE]/)?["."]:null;if(/^(?:python[\d.]*|node|bun|deno|ruby|php)$/.test(o))return i(/^-[a-zA-Z]*[ce]$|^--eval$|^-p$/)?["."]:null;return id(t)===null?null:["."]},eP=(e,t)=>{let n=Qn([...e]),r=e.indexOf("-t"),o=r>=0?e[r+1]:n.length>1?n.at(-1):".",s=n.filter((l,u)=>r>=0?l!==o:u<n.length-1||n.length===1),i=o===void 0?null:t(o),a=e.some((l)=>/^-[a-zA-Z]*s|^--symbolic$/.test(l)),c=i===null?null:r>=0||s.length>1||GA(i)||/[\\/]$/.test(o??"")?i:U.dirname(i);return s.flatMap((l)=>{if(a&&c!==null&&!U.isAbsolute(Wo(l)))return[U.resolve(c,l)];let u=t(l);return u?[u]:[]})},la=(e,t=0)=>{let n=[],r=!1;for(let o of $e(e)){let s=t<4?Jb(o.words):null;if(s!==null){let a=la(s,t+1);if(a.writes&&a.targets===null)r=!0;else if(a.targets)n.push(...a.targets)}n.push(...o.redirects.filter((a)=>!/^\/dev\/(?:null|stdout|stderr|tty)$/.test(a)));let i=sd(o.words);if(i===null)r=!0;else n.push(...i)}if(!r&&n.length===0)return{writes:!1,targets:null};return{writes:!0,targets:r?null:n}},Lo=new Map,Zb=(e,t)=>[...t].map((n)=>bn(U.resolve(e,n))??"-").join("\x00"),tP=(e)=>{let t=new xn(e),n=t.listTaskIndex();if(!n.ok)return null;let r=t.currentKey();if(!r.ok)return null;let o=n.data.filter((f)=>f.key===r.data.key&&f.status!=="closed").toSorted((f,g)=>g.updatedAt.localeCompare(f.updatedAt))[0];if(!o)return{blockers:[],root:t.root,plans:new Set};let s=Sr(t.root),i=`${o.id}\x00${o.revision}\x00${s.ok&&bn(s.value)||"-"}`,a=Lo.get(t.root);if(a&&a.key===i&&a.planKey===Zb(t.root,a.plans))return a;let c=t.readTask(o.id);if(!c.ok)return null;let l=t.readWorkspace(),u=new Set((Kt(c.data)?.refs??[]).flatMap((f)=>f.kind==="file"?[f.path]:[])),p={blockers:wv(c.data,t.root).filter((f)=>{let g=c.data.policy?.requirements.find((h)=>h.ruleId===f.ruleId&&h.before==="write");return!(g?.acceptanceAllowed&&l.ok&&l.data&&$i(c.data,l.data,g,t.root).length>0)}),root:t.root,plans:u,key:i,planKey:Zb(t.root,u)};if(Lo.set(t.root,p),Lo.size>32)Lo.delete(Lo.keys().next().value);return p},nP=new Set(["add","am","apply","checkout","cherry-pick","clean","commit","merge","mv","pull","rebase","reset","restore","revert","rm","stash","switch"]),rP=new Set(["add","clean","rm","mv"]),oP=new Set(["commit","branch"]),jo=".workit-live-target",Vb="WORKIT_LIVE_SESSION=override",Xb=(e,t)=>e.some((n)=>n==="--help"||n==="-h"||n==="--dry-run"||rP.has(t)&&/^-[a-zA-Z]*n[a-zA-Z]*$/.test(n)&&!n.startsWith("--")),sP=(e,t,n)=>{let r;try{r=Yt(t,n)}catch{return[]}return r.flatMap((o)=>{if(o.tool!=="git"||o.dir===void 0)return[];let s=o.args.findIndex((c)=>!c.startsWith("-")),i=o.args[s]??"",a=o.args.slice(s+1);if(!nP.has(i)||Xb(a,i))return[];if(i==="stash"&&["list","show"].includes(a[0]??""))return[];return[U.resolve(e,o.dir??".")]})},iP=new Set(["cd","chdir","set-location","sl"]),aP=new Set(["pushd","push-location"]),cP=new Set(["popd","pop-location"]),ua=U.resolve(U.parse(process.cwd()).root,".workit-unknown-dir"),Ub=(e,t,n=!1)=>{let r=n?ua:void 0,o=t.slice(1).find((i)=>!i.startsWith("-")||i==="-"),s=o===void 0?void 0:Wo(o);if(s==="-"||s&&/^~|[$`*?]/.test(s))return r;if(e===void 0)return r;return s===void 0?Kb.homedir():U.resolve(e,s)},ad=(e)=>/^[\w@%+=:,./-]+$/.test(e)?e:`'${e.replaceAll("'","'\\''")}'`,Wo=(e)=>{let t=/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)/.exec(e);return t?(process.env.HOME||Kb.homedir())+e.slice(t[0].length):e},aa=(e,t,n,r=0,o=!1)=>{let s=[],i=e,a=[],c=[],l=(u)=>{let d=Wo(u);return U.isAbsolute(d)?d:i===void 0?null:U.resolve(i,d)};for(let u of $e(t,n)){if(u.group==="open"){c.push({dir:i,stack:[...a]});continue}if(u.group==="close"){let v=c.pop();if(v)({dir:i,stack:a}=v);continue}let d=u.words.findIndex((v)=>!/^\w+=/.test(v)),p=d<0?[]:u.words.slice(d),f=(p[0]?.split(/[\\/]/).at(-1)??"").toLowerCase();if(iP.has(f)){i=Ub(i,p,o);continue}if(aP.has(f)){a.push(i),i=Ub(i,p,o);continue}if(cP.has(f)){i=a.length?a.pop():o?ua:void 0;continue}let g=r<4?Jb(p)??(o?id(p):null):null;if(g!==null&&i!==void 0)s.push(...aa(lP(i,p),g,"posix",r+1,o));if(o&&i!==void 0){let v=i;for(let w of r<4?u.subs??[]:[])s.push(...aa(v,w,n,r+1,!0));let m=u.unanalyzable?["."]:g===null?Gb(p):null;for(let w of m??[]){let b=l(w);if(b)s.push(w==="."?U.join(b,jo):b)}let y=p.findIndex((w)=>/^ln$/i.test(w.split(/[\\/]/).at(-1)??""));if(y>=0&&p.slice(0,y).every((w)=>ca.has(w)))s.push(...eP(p.slice(y+1),l))}for(let v of u.redirects)if(!/^\/dev\/(?:null|stdout|stderr|tty)$/.test(v)){let m=l(v);if(m)s.push(m)}let h=sd(u.words);if(h===null){if(i!==void 0)s.push(U.join(i,jo))}else for(let v of h){let m=l(v);if(m)s.push(m)}if(i!==void 0)for(let v of Qt(u.words.map(ad).join(" "),"posix")){let{at:m,args:y}=Yb(i,v);if(y[0]==="git"&&oP.has(y[1]??"")&&!Xb(y.slice(2),""))s.push(U.join(m,jo))}}return s},lP=(e,t)=>{for(let n of Qt(t.map(ad).join(" "),"posix")){let{at:r,args:o}=Yb(e,n);if(o[0]==="check"||o[0]==="lock"&&o[1]==="run")return r}return e},Yb=(e,t)=>{let{rest:n,cwd:r}=zo(t);return{at:r===null?e:U.resolve(e,Wo(r)),args:n}},cd=(e,t,n="posix",r=!1)=>{try{return[...aa(e,t,n,0,r),...sP(e,t,n).map((o)=>U.join(o,jo))]}catch{return[]}},uP=(e,t)=>{let n=$e(e,t);if(n.length!==1||n[0].group||n[0].subs?.length)return!1;let r=n[0].words,o=r.findIndex((s)=>!/^\w+=/.test(s));return o>0&&r.slice(0,o).includes(Vb)},dP={claude_code:"Claude Code",opencode:"OpenCode",codex_cli:"Codex CLI",codex_desktop:"Codex Desktop",cursor:"Cursor",pi:"Pi"},pP=(e)=>{let t=Math.max(0,Math.round(e/1000));return t<120?`${t}s`:`${Math.round(t/60)} min`},fP=({marker:e,checkout:t,ageMs:n,file:r})=>{let o=`Work in your own worktree (\`git worktree add <path> -b <branch>\`, or \`workit fanout worktree create <slice>\`). Only if the user confirms that session is finished: release it with \`rm '${r}'\`, or prefix one command with ${Vb}.`;return{kind:"deny",reason:`workit live-session guard: ${t} belongs to another live agent session, ${dP[e.host]??e.host} session ${e.session}${e.pid===null?"":` (pid ${e.pid})`}, last active ${pP(n)} ago. Do not edit a checkout another session is working in; read-only commands stay allowed. ${o}`,unblock:o}},Qb=(e)=>{let t=new Set;return e.filter((n)=>{let r=U.dirname(n);if(t.has(r))return!1;return t.add(r),!0})},ex=(e,t,n)=>{try{for(let r of Qb(t)){let o=Fb(r,e,n);if(o&&Am(o.checkout))return fP(o)}}catch{}return Do},tx=(e,t,n)=>{for(let r of Qb(t))Bb(r,e,n)},ld=(e,t)=>t?.length?t.map((n)=>U.resolve(e,n)):[U.join(e,jo)],nx=(e,t)=>{let n=Le();return t.find((o)=>gP(n,e,Wo(o),process.platform,rd))??null},gP=(e,t,n,r=process.platform,o=(s)=>s)=>{let s=r==="win32",i=s?U.win32:U.posix,a=(u)=>s||r==="darwin"?u.toLowerCase():u,c=s?n.replace(/^\/([a-zA-Z])(?=\/|$)/,"$1:"):n,l=i.relative(a(o(i.resolve(e))),a(o(i.resolve(t,c))));if(l.startsWith("..")||i.isAbsolute(l))return!1;return l.split(i.sep)[0].startsWith("issued")},hP=(e)=>{if(process.platform!=="win32"||!e.includes("\\"))return!1;let t=(n)=>n.replaceAll("\\","/").toLowerCase();return t(e).includes(`${t(Le())}/issued`)&&la(e).writes},rx=(e)=>({kind:"deny",reason:`workit issued-registry guard: ${e} is under Workit's issued-session state. Issued ids and tokens are written only by Workit's SubagentStart hook. Run the verifier or reviewer agent so the host issues its own session; never edit the issued registries by hand.`,unblock:"Issued ids and tokens are written only by Workit's SubagentStart hook. Run the verifier or reviewer agent so the host issues its own session; never edit the issued registries by hand."});function ud(e,t,n,r){let o=t?.length?nx(e,t):null;if(o)return rx(o);if(!n)return od(e,t);let s=ld(e,t),i=ex(n,s,r);if(i.kind!=="none")return i;let a=od(e,t);if(a.kind==="none")tx(n,s,r);return a}function dd(e,t,n,r="posix",o){try{let c=nx(e,aa(e,t,r))??(hP(t)?"the issued registry":null);if(c)return rx(c)}catch{}let s=la(t),i=[];if(n)i=cd(e,t,r);if(n&&i.length){let c=ex(n,i,o);if(c.kind!=="none"){if(!uP(t,r))return c;mP(e,n,t)}}let a=s.writes?od(e,s.targets):Do;if(n&&i.length&&a.kind==="none")tx(n,i,o);return a}var mP=(e,t,n)=>{try{if(!lt(e))return;Rn(e,{type:"live_session.override",actor:{host:t.host,session:t.session,agentId:null},session:t.session,command:n.slice(0,200)})}catch{}};function od(e,t){try{let n=tP(e);if(!n||n.blockers.length===0)return Do;if(t?.length&&t.every((o)=>YA(e,n.root,o,n.plans)))return Do;return{kind:"deny",reason:`workit before-write gate: ${n.blockers.map((o)=>`${o.ruleId}: ${o.reason}`).join("; ")}. Markdown, docs/, plans/ and files outside the checkout stay writable.`,unblock:n.blockers[0].reason}}catch{return Do}}import{spawnSync as kP}from"node:child_process";function ox(e){try{let t=new xn(e),n=t.listTaskIndex(),r=t.currentKey();if(!n.ok||!r.ok)return null;let o=n.data.filter((i)=>i.key===r.data.key&&i.status!=="closed").toSorted((i,a)=>a.updatedAt.localeCompare(i.updatedAt))[0],s=o?t.readTask(o.id):null;return s?.ok===!0?Kt(s.data):null}catch{return null}}var Mo={kind:"none"},yP=/[??؟](?=[\s*_`"')\]>]*(?:\s|$))|¿/,vP=/\b(?:let me know|want me to|should I|shall I|would you like|do you want|if you(?:'d| would) like|may I|can I go ahead)\b/i,wP=/[[(]\s*y(?:es)?\s*\/\s*n(?:o)?\s*[\])]/i,bP=/^\s*(?:[-*+•]|\d+[.)]|[a-z][.)])\s+/i,ix=(e)=>{if(!e)return!1;let t=e.replace(/```[\s\S]*?(?:```|$)/g,`
211
211
 
212
212
  `).split(/\n\s*\n/).map((r)=>r.trim()).filter(Boolean);while(t.length>1&&t.at(-1).split(`
213
213
  `).every((r)=>bP.test(r)))t.pop();let n=t.slice(-2).join(`