@intentius/chant 0.124.33 → 0.124.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/cli/handlers/promote.d.ts.map +1 -1
  2. package/dist/cli/handlers/promote.js +261 -73
  3. package/dist/cli/main.d.ts.map +1 -1
  4. package/dist/cli/main.js +18 -1
  5. package/dist/cli/parse-args.d.ts.map +1 -1
  6. package/dist/cli/parse-args.js +7 -0
  7. package/dist/cli/registry.d.ts +3 -1
  8. package/dist/cli/registry.d.ts.map +1 -1
  9. package/dist/components/promote-rounds.d.ts +102 -0
  10. package/dist/components/promote-rounds.d.ts.map +1 -0
  11. package/dist/components/promote-rounds.js +174 -0
  12. package/dist/components/release-gate.d.ts +30 -0
  13. package/dist/components/release-gate.d.ts.map +1 -1
  14. package/dist/components/release-gate.js +92 -42
  15. package/dist/graph-declared.d.ts +4 -0
  16. package/dist/graph-declared.d.ts.map +1 -1
  17. package/dist/graph-declared.js +11 -1
  18. package/dist/wave-runtime.mjs +39 -39
  19. package/dist/workspace/__fixtures__/contract-repo.d.ts.map +1 -1
  20. package/dist/workspace/__fixtures__/contract-repo.js +13 -2
  21. package/dist/workspace/check.schema.json +20 -2
  22. package/dist/workspace/checks/ci-workflow.d.ts +17 -0
  23. package/dist/workspace/checks/ci-workflow.d.ts.map +1 -0
  24. package/dist/workspace/checks/ci-workflow.js +123 -0
  25. package/dist/workspace/checks/security.d.ts +16 -1
  26. package/dist/workspace/checks/security.d.ts.map +1 -1
  27. package/dist/workspace/checks/security.js +4 -4
  28. package/dist/workspace/checks.d.ts +1 -1
  29. package/dist/workspace/checks.d.ts.map +1 -1
  30. package/dist/workspace/checks.js +4 -1
  31. package/dist/workspace/ci-init.d.ts +100 -0
  32. package/dist/workspace/ci-init.d.ts.map +1 -0
  33. package/dist/workspace/ci-init.js +434 -0
  34. package/dist/workspace/ci-workflow.d.ts +91 -0
  35. package/dist/workspace/ci-workflow.d.ts.map +1 -0
  36. package/dist/workspace/ci-workflow.js +33 -0
  37. package/dist/workspace/declaration.d.ts +18 -0
  38. package/dist/workspace/declaration.d.ts.map +1 -1
  39. package/dist/workspace/declaration.js +9 -2
  40. package/dist/workspace/declaration.schema.json +28 -0
  41. package/dist/workspace/init.js +2 -2
  42. package/dist/workspace/reason-codes.d.ts +9 -0
  43. package/dist/workspace/reason-codes.d.ts.map +1 -1
  44. package/dist/workspace/reason-codes.js +10 -0
  45. package/dist/workspace/release-workflow.d.ts +31 -0
  46. package/dist/workspace/release-workflow.d.ts.map +1 -0
  47. package/dist/workspace/release-workflow.js +150 -0
  48. package/package.json +1 -1
  49. package/src/cli/handlers/promote.ts +280 -83
  50. package/src/cli/main.ts +18 -1
  51. package/src/cli/parse-args.ts +5 -0
  52. package/src/cli/registry.ts +3 -1
  53. package/src/components/promote-rounds.test.ts +220 -0
  54. package/src/components/promote-rounds.ts +232 -0
  55. package/src/components/release-gate.test.ts +47 -0
  56. package/src/components/release-gate.ts +111 -46
  57. package/src/graph-declared-exports.test.ts +40 -0
  58. package/src/graph-declared.ts +9 -1
  59. package/src/workspace/__fixtures__/contract-repo.ts +11 -2
  60. package/src/workspace/check-contract.test.ts +3 -2
  61. package/src/workspace/check.schema.json +20 -2
  62. package/src/workspace/checks/ci-workflow.test.ts +150 -0
  63. package/src/workspace/checks/ci-workflow.ts +129 -0
  64. package/src/workspace/checks/security.ts +4 -4
  65. package/src/workspace/checks.ts +4 -1
  66. package/src/workspace/ci-init.test.ts +159 -0
  67. package/src/workspace/ci-init.ts +445 -0
  68. package/src/workspace/ci-report-url.test.ts +6 -1
  69. package/src/workspace/ci-workflow.ts +71 -0
  70. package/src/workspace/declaration.schema.json +28 -0
  71. package/src/workspace/declaration.ts +32 -3
  72. package/src/workspace/init.ts +2 -2
  73. package/src/workspace/reason-codes.test.ts +2 -0
  74. package/src/workspace/reason-codes.ts +10 -0
  75. package/src/workspace/release-workflow.ts +167 -0
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- // @intentius/chant 0.124.33 wave-job runtime (#3896): run wave, run resume, approve, workspace points.
2
+ // @intentius/chant 0.124.34 wave-job runtime (#3896): run wave, run resume, approve, workspace points.
3
3
  import { createRequire as __chantCreateRequire } from "node:module";
4
4
  const require = __chantCreateRequire(import.meta.url);
5
5
  var Lie=Object.create;var MS=Object.defineProperty;var Mie=Object.getOwnPropertyDescriptor;var Fie=Object.getOwnPropertyNames;var Gie=Object.getPrototypeOf,Wie=Object.prototype.hasOwnProperty;var v=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(i){throw n=[i],i}};var ae=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},_e=(e,t)=>{for(var n in t)MS(e,n,{get:t[n],enumerable:!0})},Bie=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Fie(t))!Wie.call(e,r)&&r!==n&&MS(e,r,{get:()=>t[r],enumerable:!(i=Mie(t,r))||i.enumerable});return e};var Ye=(e,t,n)=>(n=e!=null?Lie(Gie(e)):{},Bie(t||!e||!e.__esModule?MS(n,"default",{value:e,enumerable:!0}):n,e));function nW(e,t=new Set){let n=[];for(let i of e)if(i.startsWith("--")&&i.includes("=")){let r=i.indexOf("="),o=i.slice(0,r),s=i.slice(r+1);if(t.has(o))throw new Error(`${i} \u2014 ${o} is a boolean flag and does not take a value. Pass ${o} on its own.`);n.push(o,s)}else n.push(i);return n}var FS,GS=v(()=>{"use strict";FS=new Set(["build","lint","list","describe","import","audit","migrate","carve","init","update","doctor","dev","run","graph","vendor","lifecycle","lc","components","emulator","serve","operator","approve","workspace"])});function Vie(){return!process.env.NO_COLOR&&process.stdout.isTTY!==!1}function Xs(e,t){return Vie()?`${t}${e}${ps.reset}`:e}function we(e){let t=[];if(e.file){let n=e.file;e.line!==void 0&&(n+=`:${e.line}`,e.column!==void 0&&(n+=`:${e.column}`)),t.push(Xs(n,ps.cyan)),t.push(" - ")}return t.push(Xs("error",ps.red)),t.push(": "),t.push(e.message),e.hint&&(t.push(`
6
6
  `),t.push(Xs(e.hint,ps.gray))),t.join("")}function si(e){let t=[];if(e.file){let n=e.file;e.line!==void 0&&(n+=`:${e.line}`,e.column!==void 0&&(n+=`:${e.column}`)),t.push(Xs(n,ps.cyan)),t.push(" - ")}return t.push(Xs("warning",ps.yellow)),t.push(": "),t.push(e.message),e.hint&&(t.push(`
7
- `),t.push(Xs(e.hint,ps.gray))),t.join("")}function xf(e){return Xs(e,ps.green)}function Qn(e){return Xs(e,ps.gray)}var ps,ur=v(()=>{"use strict";ps={red:"\x1B[31m",yellow:"\x1B[33m",green:"\x1B[32m",cyan:"\x1B[36m",gray:"\x1B[90m",reset:"\x1B[0m",bold:"\x1B[1m"}});var pw,BS=v(()=>{"use strict";pw="0.124.33"});function F(e,t,n){function i(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let p=u[d];p in a||(a[p]=l[p].bind(a))}}let r=n?.Parent??Object;class o extends r{}Object.defineProperty(o,"name",{value:e});function s(a){var c;let l=n?.Parent?new o:this;i(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function sn(e){return e&&Object.assign($f,e),$f}var zS,fw,Ni,Qs,$f,bu=v(()=>{zS=Object.freeze({status:"aborted"});fw=Symbol("zod_brand"),Ni=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Qs=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}},$f={}});var fe={};_e(fe,{BIGINT_FORMAT_RANGES:()=>QS,Class:()=>VS,NUMBER_FORMAT_RANGES:()=>XS,aborted:()=>ra,allowsEval:()=>KS,assert:()=>Yie,assertEqual:()=>qie,assertIs:()=>Jie,assertNever:()=>Zie,assertNotEqual:()=>Kie,assignProp:()=>ta,base64ToUint8Array:()=>lW,base64urlToUint8Array:()=>moe,cached:()=>ku,captureStackTrace:()=>gw,cleanEnum:()=>foe,cleanRegex:()=>Ef,clone:()=>dr,cloneDef:()=>Qie,createTransparentProxy:()=>ooe,defineLazy:()=>st,esc:()=>mw,escapeRegex:()=>ai,extend:()=>coe,finalizeIssue:()=>Or,floatSafeRemainder:()=>HS,getElementAtPath:()=>eoe,getEnumValues:()=>Sf,getLengthableOrigin:()=>Pf,getParsedType:()=>ioe,getSizableOrigin:()=>Af,hexToUint8Array:()=>hoe,isObject:()=>Fc,isPlainObject:()=>na,issue:()=>xu,joinValues:()=>Z,jsonStringifyReplacer:()=>vu,merge:()=>uoe,mergeDefs:()=>fs,normalizeParams:()=>me,nullish:()=>ea,numKeys:()=>roe,objectClone:()=>Xie,omit:()=>aoe,optionalKeys:()=>YS,parsedType:()=>pe,partial:()=>doe,pick:()=>soe,prefixIssues:()=>qr,primitiveTypes:()=>ZS,promiseAllObject:()=>toe,propertyKeyTypes:()=>Of,randomString:()=>noe,required:()=>poe,safeExtend:()=>loe,shallowClone:()=>JS,slugify:()=>qS,stringifyPrimitive:()=>le,uint8ArrayToBase64:()=>uW,uint8ArrayToBase64url:()=>goe,uint8ArrayToHex:()=>yoe,unwrapMessage:()=>Rf});function qie(e){return e}function Kie(e){return e}function Jie(e){}function Zie(e){throw new Error("Unexpected value in exhaustive check")}function Yie(e){}function Sf(e){let t=Object.values(e).filter(i=>typeof i=="number");return Object.entries(e).filter(([i,r])=>t.indexOf(+i)===-1).map(([i,r])=>r)}function Z(e,t="|"){return e.map(n=>le(n)).join(t)}function vu(e,t){return typeof t=="bigint"?t.toString():t}function ku(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function ea(e){return e==null}function Ef(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function HS(e,t){let n=(e.toString().split(".")[1]||"").length,i=t.toString(),r=(i.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(i)){let c=i.match(/\d?e-(\d?)/);c?.[1]&&(r=Number.parseInt(c[1]))}let o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}function st(e,t,n){let i;Object.defineProperty(e,t,{get(){if(i!==cW)return i===void 0&&(i=cW,i=n()),i},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Xie(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function ta(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function fs(...e){let t={};for(let n of e){let i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function Qie(e){return fs(e._zod.def)}function eoe(e,t){return t?t.reduce((n,i)=>n?.[i],e):e}function toe(e){let t=Object.keys(e),n=t.map(i=>e[i]);return Promise.all(n).then(i=>{let r={};for(let o=0;o<t.length;o++)r[t[o]]=i[o];return r})}function noe(e=10){let t="abcdefghijklmnopqrstuvwxyz",n="";for(let i=0;i<e;i++)n+=t[Math.floor(Math.random()*t.length)];return n}function mw(e){return JSON.stringify(e)}function qS(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Fc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function na(e){if(Fc(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(Fc(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function JS(e){return na(e)?{...e}:Array.isArray(e)?[...e]:e}function roe(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function ai(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dr(e,t,n){let i=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(i._zod.parent=e),i}function me(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function ooe(e){let t;return new Proxy({},{get(n,i,r){return t??(t=e()),Reflect.get(t,i,r)},set(n,i,r,o){return t??(t=e()),Reflect.set(t,i,r,o)},has(n,i){return t??(t=e()),Reflect.has(t,i)},deleteProperty(n,i){return t??(t=e()),Reflect.deleteProperty(t,i)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,i){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,i)},defineProperty(n,i,r){return t??(t=e()),Reflect.defineProperty(t,i,r)}})}function le(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function YS(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function soe(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let o=fs(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=n.shape[a])}return ta(this,"shape",s),s},checks:[]});return dr(e,o)}function aoe(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let o=fs(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return ta(this,"shape",s),s},checks:[]});return dr(e,o)}function coe(e,t){if(!na(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=fs(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return ta(this,"shape",o),o}});return dr(e,r)}function loe(e,t){if(!na(t))throw new Error("Invalid input to safeExtend: expected a plain object");let n=fs(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return ta(this,"shape",i),i}});return dr(e,n)}function uoe(e,t){let n=fs(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t._zod.def.shape};return ta(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:[]});return dr(e,n)}function doe(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=fs(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(n)for(let l in n){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return ta(this,"shape",c),c},checks:[]});return dr(t,s)}function poe(e,t,n){let i=fs(t._zod.def,{get shape(){let r=t._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return ta(this,"shape",o),o}});return dr(t,i)}function ra(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function qr(e,t){return t.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function Rf(e){return typeof e=="string"?e:e?.message}function Or(e,t,n){let i={...e,path:e.path??[]};if(!e.message){let r=Rf(e.inst?._zod.def?.error?.(e))??Rf(t?.error?.(e))??Rf(n.customError?.(e))??Rf(n.localeError?.(e))??"Invalid input";i.message=r}return delete i.inst,delete i.continue,t?.reportInput||delete i.input,i}function Af(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Pf(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function pe(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function xu(...e){let[t,n,i]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:i}:{...t}}function foe(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function lW(e){let t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}function uW(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function moe(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return lW(t+n)}function goe(e){return uW(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hoe(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)n[i/2]=Number.parseInt(t.slice(i,i+2),16);return n}function yoe(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var cW,gw,KS,ioe,Of,ZS,XS,QS,VS,Me=v(()=>{cW=Symbol("evaluating");gw="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};KS=ku(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});ioe=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Of=new Set(["string","number","symbol"]),ZS=new Set(["string","number","bigint","boolean","symbol","undefined"]);XS={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},QS={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};VS=class{constructor(...t){}}});function _f(e,t=n=>n.message){let n={},i=[];for(let r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):i.push(t(r));return{formErrors:i,fieldErrors:n}}function Tf(e,t=n=>n.message){let n={_errors:[]},i=r=>{for(let o of r.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>i({issues:s}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)n._errors.push(t(o));else{let s=n,a=0;for(;a<o.path.length;){let c=o.path[a];a===o.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(o))):s[c]=s[c]||{_errors:[]},s=s[c],a++}}};return i(e),n}function eE(e,t=n=>n.message){let n={errors:[]},i=(r,o=[])=>{var s,a;for(let c of r.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>i({issues:l},c.path));else if(c.code==="invalid_key")i({issues:c.issues},c.path);else if(c.code==="invalid_element")i({issues:c.issues},c.path);else{let l=[...o,...c.path];if(l.length===0){n.errors.push(t(c));continue}let u=n,d=0;for(;d<l.length;){let p=l[d],f=d===l.length-1;typeof p=="string"?(u.properties??(u.properties={}),(s=u.properties)[p]??(s[p]={errors:[]}),u=u.properties[p]):(u.items??(u.items=[]),(a=u.items)[p]??(a[p]={errors:[]}),u=u.items[p]),f&&u.errors.push(t(c)),d++}}};return i(e),n}function pW(e){let t=[],n=e.map(i=>typeof i=="object"?i.key:i);for(let i of n)typeof i=="number"?t.push(`[${i}]`):typeof i=="symbol"?t.push(`[${JSON.stringify(String(i))}]`):/[^\w$]/.test(i)?t.push(`[${JSON.stringify(i)}]`):(t.length&&t.push("."),t.push(i));return t.join("")}function tE(e){let t=[],n=[...e.issues].sort((i,r)=>(i.path??[]).length-(r.path??[]).length);for(let i of n)t.push(`\u2716 ${i.message}`),i.path?.length&&t.push(` \u2192 at ${pW(i.path)}`);return t.join(`
7
+ `),t.push(Xs(e.hint,ps.gray))),t.join("")}function xf(e){return Xs(e,ps.green)}function Qn(e){return Xs(e,ps.gray)}var ps,ur=v(()=>{"use strict";ps={red:"\x1B[31m",yellow:"\x1B[33m",green:"\x1B[32m",cyan:"\x1B[36m",gray:"\x1B[90m",reset:"\x1B[0m",bold:"\x1B[1m"}});var pw,BS=v(()=>{"use strict";pw="0.124.34"});function F(e,t,n){function i(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let p=u[d];p in a||(a[p]=l[p].bind(a))}}let r=n?.Parent??Object;class o extends r{}Object.defineProperty(o,"name",{value:e});function s(a){var c;let l=n?.Parent?new o:this;i(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function sn(e){return e&&Object.assign($f,e),$f}var zS,fw,Ni,Qs,$f,bu=v(()=>{zS=Object.freeze({status:"aborted"});fw=Symbol("zod_brand"),Ni=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Qs=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}},$f={}});var fe={};_e(fe,{BIGINT_FORMAT_RANGES:()=>QS,Class:()=>VS,NUMBER_FORMAT_RANGES:()=>XS,aborted:()=>ra,allowsEval:()=>KS,assert:()=>Yie,assertEqual:()=>qie,assertIs:()=>Jie,assertNever:()=>Zie,assertNotEqual:()=>Kie,assignProp:()=>ta,base64ToUint8Array:()=>lW,base64urlToUint8Array:()=>moe,cached:()=>ku,captureStackTrace:()=>gw,cleanEnum:()=>foe,cleanRegex:()=>Ef,clone:()=>dr,cloneDef:()=>Qie,createTransparentProxy:()=>ooe,defineLazy:()=>st,esc:()=>mw,escapeRegex:()=>ai,extend:()=>coe,finalizeIssue:()=>Or,floatSafeRemainder:()=>HS,getElementAtPath:()=>eoe,getEnumValues:()=>Sf,getLengthableOrigin:()=>Pf,getParsedType:()=>ioe,getSizableOrigin:()=>Af,hexToUint8Array:()=>hoe,isObject:()=>Fc,isPlainObject:()=>na,issue:()=>xu,joinValues:()=>Z,jsonStringifyReplacer:()=>vu,merge:()=>uoe,mergeDefs:()=>fs,normalizeParams:()=>me,nullish:()=>ea,numKeys:()=>roe,objectClone:()=>Xie,omit:()=>aoe,optionalKeys:()=>YS,parsedType:()=>pe,partial:()=>doe,pick:()=>soe,prefixIssues:()=>qr,primitiveTypes:()=>ZS,promiseAllObject:()=>toe,propertyKeyTypes:()=>Of,randomString:()=>noe,required:()=>poe,safeExtend:()=>loe,shallowClone:()=>JS,slugify:()=>qS,stringifyPrimitive:()=>le,uint8ArrayToBase64:()=>uW,uint8ArrayToBase64url:()=>goe,uint8ArrayToHex:()=>yoe,unwrapMessage:()=>Rf});function qie(e){return e}function Kie(e){return e}function Jie(e){}function Zie(e){throw new Error("Unexpected value in exhaustive check")}function Yie(e){}function Sf(e){let t=Object.values(e).filter(i=>typeof i=="number");return Object.entries(e).filter(([i,r])=>t.indexOf(+i)===-1).map(([i,r])=>r)}function Z(e,t="|"){return e.map(n=>le(n)).join(t)}function vu(e,t){return typeof t=="bigint"?t.toString():t}function ku(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function ea(e){return e==null}function Ef(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function HS(e,t){let n=(e.toString().split(".")[1]||"").length,i=t.toString(),r=(i.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(i)){let c=i.match(/\d?e-(\d?)/);c?.[1]&&(r=Number.parseInt(c[1]))}let o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}function st(e,t,n){let i;Object.defineProperty(e,t,{get(){if(i!==cW)return i===void 0&&(i=cW,i=n()),i},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Xie(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function ta(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function fs(...e){let t={};for(let n of e){let i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function Qie(e){return fs(e._zod.def)}function eoe(e,t){return t?t.reduce((n,i)=>n?.[i],e):e}function toe(e){let t=Object.keys(e),n=t.map(i=>e[i]);return Promise.all(n).then(i=>{let r={};for(let o=0;o<t.length;o++)r[t[o]]=i[o];return r})}function noe(e=10){let t="abcdefghijklmnopqrstuvwxyz",n="";for(let i=0;i<e;i++)n+=t[Math.floor(Math.random()*t.length)];return n}function mw(e){return JSON.stringify(e)}function qS(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Fc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function na(e){if(Fc(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(Fc(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function JS(e){return na(e)?{...e}:Array.isArray(e)?[...e]:e}function roe(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function ai(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dr(e,t,n){let i=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(i._zod.parent=e),i}function me(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function ooe(e){let t;return new Proxy({},{get(n,i,r){return t??(t=e()),Reflect.get(t,i,r)},set(n,i,r,o){return t??(t=e()),Reflect.set(t,i,r,o)},has(n,i){return t??(t=e()),Reflect.has(t,i)},deleteProperty(n,i){return t??(t=e()),Reflect.deleteProperty(t,i)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,i){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,i)},defineProperty(n,i,r){return t??(t=e()),Reflect.defineProperty(t,i,r)}})}function le(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function YS(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function soe(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let o=fs(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=n.shape[a])}return ta(this,"shape",s),s},checks:[]});return dr(e,o)}function aoe(e,t){let n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let o=fs(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return ta(this,"shape",s),s},checks:[]});return dr(e,o)}function coe(e,t){if(!na(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=fs(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return ta(this,"shape",o),o}});return dr(e,r)}function loe(e,t){if(!na(t))throw new Error("Invalid input to safeExtend: expected a plain object");let n=fs(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return ta(this,"shape",i),i}});return dr(e,n)}function uoe(e,t){let n=fs(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t._zod.def.shape};return ta(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:[]});return dr(e,n)}function doe(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=fs(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(n)for(let l in n){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return ta(this,"shape",c),c},checks:[]});return dr(t,s)}function poe(e,t,n){let i=fs(t._zod.def,{get shape(){let r=t._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return ta(this,"shape",o),o}});return dr(t,i)}function ra(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function qr(e,t){return t.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function Rf(e){return typeof e=="string"?e:e?.message}function Or(e,t,n){let i={...e,path:e.path??[]};if(!e.message){let r=Rf(e.inst?._zod.def?.error?.(e))??Rf(t?.error?.(e))??Rf(n.customError?.(e))??Rf(n.localeError?.(e))??"Invalid input";i.message=r}return delete i.inst,delete i.continue,t?.reportInput||delete i.input,i}function Af(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Pf(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function pe(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function xu(...e){let[t,n,i]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:i}:{...t}}function foe(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function lW(e){let t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n}function uW(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function moe(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return lW(t+n)}function goe(e){return uW(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hoe(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)n[i/2]=Number.parseInt(t.slice(i,i+2),16);return n}function yoe(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var cW,gw,KS,ioe,Of,ZS,XS,QS,VS,Me=v(()=>{cW=Symbol("evaluating");gw="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};KS=ku(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});ioe=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Of=new Set(["string","number","symbol"]),ZS=new Set(["string","number","bigint","boolean","symbol","undefined"]);XS={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},QS={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};VS=class{constructor(...t){}}});function _f(e,t=n=>n.message){let n={},i=[];for(let r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):i.push(t(r));return{formErrors:i,fieldErrors:n}}function Tf(e,t=n=>n.message){let n={_errors:[]},i=r=>{for(let o of r.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>i({issues:s}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)n._errors.push(t(o));else{let s=n,a=0;for(;a<o.path.length;){let c=o.path[a];a===o.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(o))):s[c]=s[c]||{_errors:[]},s=s[c],a++}}};return i(e),n}function eE(e,t=n=>n.message){let n={errors:[]},i=(r,o=[])=>{var s,a;for(let c of r.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>i({issues:l},c.path));else if(c.code==="invalid_key")i({issues:c.issues},c.path);else if(c.code==="invalid_element")i({issues:c.issues},c.path);else{let l=[...o,...c.path];if(l.length===0){n.errors.push(t(c));continue}let u=n,d=0;for(;d<l.length;){let p=l[d],f=d===l.length-1;typeof p=="string"?(u.properties??(u.properties={}),(s=u.properties)[p]??(s[p]={errors:[]}),u=u.properties[p]):(u.items??(u.items=[]),(a=u.items)[p]??(a[p]={errors:[]}),u=u.items[p]),f&&u.errors.push(t(c)),d++}}};return i(e),n}function pW(e){let t=[],n=e.map(i=>typeof i=="object"?i.key:i);for(let i of n)typeof i=="number"?t.push(`[${i}]`):typeof i=="symbol"?t.push(`[${JSON.stringify(String(i))}]`):/[^\w$]/.test(i)?t.push(`[${JSON.stringify(i)}]`):(t.length&&t.push("."),t.push(i));return t.join("")}function tE(e){let t=[],n=[...e.issues].sort((i,r)=>(i.path??[]).length-(r.path??[]).length);for(let i of n)t.push(`\u2716 ${i.message}`),i.path?.length&&t.push(` \u2192 at ${pW(i.path)}`);return t.join(`
8
8
  `)}var dW,Cf,Ar,nE=v(()=>{bu();Me();dW=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,vu,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Cf=F("$ZodError",dW),Ar=F("$ZodError",dW,{Parent:Error})});var $u,hw,Ru,yw,Su,rE,Eu,iE,ww,boe,bw,voe,vw,koe,kw,xoe,xw,$oe,$w,Roe,Rw,Soe,Sw,Eoe,oE=v(()=>{bu();nE();Me();$u=e=>(t,n,i,r)=>{let o=i?Object.assign(i,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Ni;if(s.issues.length){let a=new(r?.Err??e)(s.issues.map(c=>Or(c,o,sn())));throw gw(a,r?.callee),a}return s.value},hw=$u(Ar),Ru=e=>async(t,n,i,r)=>{let o=i?Object.assign(i,{async:!0}):{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(r?.Err??e)(s.issues.map(c=>Or(c,o,sn())));throw gw(a,r?.callee),a}return s.value},yw=Ru(Ar),Su=e=>(t,n,i)=>{let r=i?{...i,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new Ni;return o.issues.length?{success:!1,error:new(e??Cf)(o.issues.map(s=>Or(s,r,sn())))}:{success:!0,data:o.value}},rE=Su(Ar),Eu=e=>async(t,n,i)=>{let r=i?Object.assign(i,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>Or(s,r,sn())))}:{success:!0,data:o.value}},iE=Eu(Ar),ww=e=>(t,n,i)=>{let r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return $u(e)(t,n,r)},boe=ww(Ar),bw=e=>(t,n,i)=>$u(e)(t,n,i),voe=bw(Ar),vw=e=>async(t,n,i)=>{let r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Ru(e)(t,n,r)},koe=vw(Ar),kw=e=>async(t,n,i)=>Ru(e)(t,n,i),xoe=kw(Ar),xw=e=>(t,n,i)=>{let r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Su(e)(t,n,r)},$oe=xw(Ar),$w=e=>(t,n,i)=>Su(e)(t,n,i),Roe=$w(Ar),Rw=e=>async(t,n,i)=>{let r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Eu(e)(t,n,r)},Soe=Rw(Ar),Sw=e=>async(t,n,i)=>Eu(e)(t,n,i),Eoe=Sw(Ar)});var ci={};_e(ci,{base64:()=>kE,base64url:()=>Ew,bigint:()=>OE,boolean:()=>PE,browserEmail:()=>Doe,cidrv4:()=>bE,cidrv6:()=>vE,cuid:()=>sE,cuid2:()=>aE,date:()=>$E,datetime:()=>SE,domain:()=>Loe,duration:()=>pE,e164:()=>xE,email:()=>mE,emoji:()=>gE,extendedDuration:()=>Ooe,guid:()=>fE,hex:()=>Moe,hostname:()=>Noe,html5Email:()=>_oe,idnEmail:()=>Ioe,integer:()=>AE,ipv4:()=>hE,ipv6:()=>yE,ksuid:()=>uE,lowercase:()=>TE,mac:()=>wE,md5_base64:()=>Goe,md5_base64url:()=>Woe,md5_hex:()=>Foe,nanoid:()=>dE,null:()=>CE,number:()=>Ow,rfc5322Email:()=>Toe,sha1_base64:()=>zoe,sha1_base64url:()=>Uoe,sha1_hex:()=>Boe,sha256_base64:()=>Hoe,sha256_base64url:()=>qoe,sha256_hex:()=>Voe,sha384_base64:()=>Joe,sha384_base64url:()=>Zoe,sha384_hex:()=>Koe,sha512_base64:()=>Xoe,sha512_base64url:()=>Qoe,sha512_hex:()=>Yoe,string:()=>EE,time:()=>RE,ulid:()=>cE,undefined:()=>_E,unicodeEmail:()=>fW,uppercase:()=>IE,uuid:()=>Gc,uuid4:()=>Aoe,uuid6:()=>Poe,uuid7:()=>Coe,xid:()=>lE});function gE(){return new RegExp(joe,"u")}function gW(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function RE(e){return new RegExp(`^${gW(e)}$`)}function SE(e){let t=gW({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let i=`${t}(?:${n.join("|")})`;return new RegExp(`^${mW}T(?:${i})$`)}function If(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Df(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var sE,aE,cE,lE,uE,dE,pE,Ooe,fE,Gc,Aoe,Poe,Coe,mE,_oe,Toe,fW,Ioe,Doe,joe,hE,yE,wE,bE,vE,kE,Ew,Noe,Loe,xE,mW,$E,EE,OE,AE,Ow,PE,CE,_E,TE,IE,Moe,Foe,Goe,Woe,Boe,zoe,Uoe,Voe,Hoe,qoe,Koe,Joe,Zoe,Yoe,Xoe,Qoe,Aw=v(()=>{Me();sE=/^[cC][^\s-]{8,}$/,aE=/^[0-9a-z]+$/,cE=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lE=/^[0-9a-vA-V]{20}$/,uE=/^[A-Za-z0-9]{27}$/,dE=/^[a-zA-Z0-9_-]{21}$/,pE=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ooe=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,fE=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Gc=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Aoe=Gc(4),Poe=Gc(6),Coe=Gc(7),mE=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_oe=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Toe=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,fW=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Ioe=fW,Doe=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,joe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";hE=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,yE=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,wE=e=>{let t=ai(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},bE=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,vE=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,kE=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ew=/^[A-Za-z0-9_-]*$/,Noe=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Loe=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,xE=/^\+[1-9]\d{6,14}$/,mW="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",$E=new RegExp(`^${mW}$`);EE=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},OE=/^-?\d+n?$/,AE=/^-?\d+$/,Ow=/^-?\d+(?:\.\d+)?$/,PE=/^(?:true|false)$/i,CE=/^null$/i,_E=/^undefined$/i,TE=/^[^A-Z]*$/,IE=/^[^a-z]*$/,Moe=/^[0-9a-fA-F]*$/;Foe=/^[0-9a-fA-F]{32}$/,Goe=If(22,"=="),Woe=Df(22),Boe=/^[0-9a-fA-F]{40}$/,zoe=If(27,"="),Uoe=Df(27),Voe=/^[0-9a-fA-F]{64}$/,Hoe=If(43,"="),qoe=Df(43),Koe=/^[0-9a-fA-F]{96}$/,Joe=If(64,""),Zoe=Df(64),Yoe=/^[0-9a-fA-F]{128}$/,Xoe=If(86,"=="),Qoe=Df(86)});function hW(e,t,n){e.issues.length&&t.issues.push(...qr(n,e.issues))}var Ft,yW,Pw,Cw,DE,jE,NE,LE,ME,FE,GE,WE,BE,Ou,zE,UE,VE,HE,qE,KE,JE,ZE,YE,_w=v(()=>{bu();Aw();Me();Ft=F("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),yW={number:"number",bigint:"bigint",object:"date"},Pw=F("$ZodCheckLessThan",(e,t)=>{Ft.init(e,t);let n=yW[typeof t.value];e._zod.onattach.push(i=>{let r=i._zod.bag,o=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value<=t.value:i.value<t.value)||i.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Cw=F("$ZodCheckGreaterThan",(e,t)=>{Ft.init(e,t);let n=yW[typeof t.value];e._zod.onattach.push(i=>{let r=i._zod.bag,o=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),DE=F("$ZodCheckMultipleOf",(e,t)=>{Ft.init(e,t),e._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):HS(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),jE=F("$ZodCheckNumberFormat",(e,t)=>{Ft.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),i=n?"int":"number",[r,o]=XS[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=r,a.maximum=o,n&&(a.pattern=AE)}),e._zod.check=s=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});return}}a<r&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),NE=F("$ZodCheckBigIntFormat",(e,t)=>{Ft.init(e,t);let[n,i]=QS[t.format];e._zod.onattach.push(r=>{let o=r._zod.bag;o.format=t.format,o.minimum=n,o.maximum=i}),e._zod.check=r=>{let o=r.value;o<n&&r.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>i&&r.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),LE=F("$ZodCheckMaxSize",(e,t)=>{var n;Ft.init(e,t),(n=e._zod.def).when??(n.when=i=>{let r=i.value;return!ea(r)&&r.size!==void 0}),e._zod.onattach.push(i=>{let r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(i._zod.bag.maximum=t.maximum)}),e._zod.check=i=>{let r=i.value;r.size<=t.maximum||i.issues.push({origin:Af(r),code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ME=F("$ZodCheckMinSize",(e,t)=>{var n;Ft.init(e,t),(n=e._zod.def).when??(n.when=i=>{let r=i.value;return!ea(r)&&r.size!==void 0}),e._zod.onattach.push(i=>{let r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(i._zod.bag.minimum=t.minimum)}),e._zod.check=i=>{let r=i.value;r.size>=t.minimum||i.issues.push({origin:Af(r),code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),FE=F("$ZodCheckSizeEquals",(e,t)=>{var n;Ft.init(e,t),(n=e._zod.def).when??(n.when=i=>{let r=i.value;return!ea(r)&&r.size!==void 0}),e._zod.onattach.push(i=>{let r=i._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=i=>{let r=i.value,o=r.size;if(o===t.size)return;let s=o>t.size;i.issues.push({origin:Af(r),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),GE=F("$ZodCheckMaxLength",(e,t)=>{var n;Ft.init(e,t),(n=e._zod.def).when??(n.when=i=>{let r=i.value;return!ea(r)&&r.length!==void 0}),e._zod.onattach.push(i=>{let r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(i._zod.bag.maximum=t.maximum)}),e._zod.check=i=>{let r=i.value;if(r.length<=t.maximum)return;let s=Pf(r);i.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),WE=F("$ZodCheckMinLength",(e,t)=>{var n;Ft.init(e,t),(n=e._zod.def).when??(n.when=i=>{let r=i.value;return!ea(r)&&r.length!==void 0}),e._zod.onattach.push(i=>{let r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(i._zod.bag.minimum=t.minimum)}),e._zod.check=i=>{let r=i.value;if(r.length>=t.minimum)return;let s=Pf(r);i.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),BE=F("$ZodCheckLengthEquals",(e,t)=>{var n;Ft.init(e,t),(n=e._zod.def).when??(n.when=i=>{let r=i.value;return!ea(r)&&r.length!==void 0}),e._zod.onattach.push(i=>{let r=i._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=i=>{let r=i.value,o=r.length;if(o===t.length)return;let s=Pf(r),a=o>t.length;i.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),Ou=F("$ZodCheckStringFormat",(e,t)=>{var n,i;Ft.init(e,t),e._zod.onattach.push(r=>{let o=r._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(i=e._zod).check??(i.check=()=>{})}),zE=F("$ZodCheckRegex",(e,t)=>{Ou.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),UE=F("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=TE),Ou.init(e,t)}),VE=F("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=IE),Ou.init(e,t)}),HE=F("$ZodCheckIncludes",(e,t)=>{Ft.init(e,t);let n=ai(t.includes),i=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),qE=F("$ZodCheckStartsWith",(e,t)=>{Ft.init(e,t);let n=new RegExp(`^${ai(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=i=>{i.value.startsWith(t.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),KE=F("$ZodCheckEndsWith",(e,t)=>{Ft.init(e,t);let n=new RegExp(`.*${ai(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=i=>{i.value.endsWith(t.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}});JE=F("$ZodCheckProperty",(e,t)=>{Ft.init(e,t),e._zod.check=n=>{let i=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(i instanceof Promise)return i.then(r=>hW(r,n,t.property));hW(i,n,t.property)}}),ZE=F("$ZodCheckMimeType",(e,t)=>{Ft.init(e,t);let n=new Set(t.mime);e._zod.onattach.push(i=>{i._zod.bag.mime=t.mime}),e._zod.check=i=>{n.has(i.value.type)||i.issues.push({code:"invalid_value",values:t.mime,input:i.value.type,inst:e,continue:!t.abort})}}),YE=F("$ZodCheckOverwrite",(e,t)=>{Ft.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}})});var jf,XE=v(()=>{jf=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let i=t.split(`
9
9
  `).filter(s=>s),r=Math.min(...i.map(s=>s.length-s.trimStart().length)),o=i.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let t=Function,n=this?.args,r=[...(this?.content??[""]).map(o=>` ${o}`)];return new t(...n,r.join(`
10
10
  `))}}});var QE,eO=v(()=>{QE={major:4,minor:3,patch:6}});function xO(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function CW(e){if(!Ew.test(e))return!1;let t=e.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return xO(n)}function _W(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[i]=n;if(!i)return!1;let r=JSON.parse(atob(i));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}function bW(e,t,n){e.issues.length&&t.issues.push(...qr(n,e.issues)),t.value[n]=e.value}function Nw(e,t,n,i,r){if(e.issues.length){if(r&&!(n in i))return;t.issues.push(...qr(n,e.issues))}e.value===void 0?n in i&&(t.value[n]=void 0):t.value[n]=e.value}function TW(e){let t=Object.keys(e.shape);for(let i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);let n=YS(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function IW(e,t,n,i,r,o){let s=[],a=r.keySet,c=r.catchall._zod,l=c.def.type,u=c.optout==="optional";for(let d in t){if(a.has(d))continue;if(l==="never"){s.push(d);continue}let p=c.run({value:t[d],issues:[]},i);p instanceof Promise?e.push(p.then(f=>Nw(f,n,d,t,u))):Nw(p,n,d,t,u)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}function vW(e,t,n,i){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let r=e.filter(o=>!ra(o));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Or(s,i,sn())))}),t)}function kW(e,t,n,i){let r=e.filter(o=>o.issues.length===0);return r.length===1?(t.value=r[0].value,t):(r.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Or(s,i,sn())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1}),t)}function tO(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(na(e)&&na(t)){let n=Object.keys(t),i=Object.keys(e).filter(o=>n.indexOf(o)!==-1),r={...e,...t};for(let o of i){let s=tO(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r[o]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<e.length;i++){let r=e[i],o=t[i],s=tO(r,o);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function xW(e,t,n){let i=new Map,r;for(let a of t.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(let c of a.keys)i.has(c)||i.set(c,{}),i.get(c).l=!0}else e.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)i.has(c)||i.set(c,{}),i.get(c).r=!0;else e.issues.push(a);let o=[...i].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(o.length&&r&&e.issues.push({...r,keys:o}),ra(e))return e;let s=tO(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}function Tw(e,t,n){e.issues.length&&t.issues.push(...qr(n,e.issues)),t.value[n]=e.value}function $W(e,t,n,i,r,o,s){e.issues.length&&(Of.has(typeof i)?n.issues.push(...qr(i,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:r,inst:o,issues:e.issues.map(a=>Or(a,s,sn()))})),t.issues.length&&(Of.has(typeof i)?n.issues.push(...qr(i,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:r,inst:o,key:i,issues:t.issues.map(a=>Or(a,s,sn()))})),n.value.set(e.value,t.value)}function RW(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}function SW(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}function EW(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function OW(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function Iw(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}function Dw(e,t,n){if(e.issues.length)return e.aborted=!0,e;if((n.direction||"forward")==="forward"){let r=t.transform(e.value,e);return r instanceof Promise?r.then(o=>jw(e,o,t.out,n)):jw(e,r,t.out,n)}else{let r=t.reverseTransform(e.value,e);return r instanceof Promise?r.then(o=>jw(e,o,t.in,n)):jw(e,r,t.in,n)}}function jw(e,t,n,i){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},i)}function AW(e){return e.value=Object.freeze(e.value),e}function PW(e,t,n,i){if(!e){let r={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(r.params=i._zod.def.params),t.issues.push(xu(r))}}var Je,Wc,It,nO,rO,iO,oO,sO,aO,cO,lO,uO,dO,pO,fO,mO,gO,hO,yO,wO,bO,vO,kO,$O,RO,SO,EO,OO,Lw,AO,Nf,Mw,PO,CO,_O,TO,IO,DO,jO,NO,LO,MO,DW,FO,Lf,GO,WO,BO,Fw,zO,UO,VO,HO,qO,KO,JO,Gw,ZO,YO,XO,QO,eA,tA,nA,rA,iA,Mf,oA,sA,aA,cA,lA,uA,dA=v(()=>{_w();bu();XE();oE();Aw();Me();eO();Me();Je=F("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=QE;let i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(let r of i)for(let o of r._zod.onattach)o(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let r=(s,a,c)=>{let l=ra(s),u;for(let d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(l)continue;let p=s.issues.length,f=d._zod.check(s);if(f instanceof Promise&&c?.async===!1)throw new Ni;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==p&&(l||(l=ra(s,p)))});else{if(s.issues.length===p)continue;l||(l=ra(s,p))}}return u?u.then(()=>s):s},o=(s,a,c)=>{if(ra(s))return s.aborted=!0,s;let l=r(a,i,c);if(l instanceof Promise){if(c.async===!1)throw new Ni;return l.then(u=>e._zod.parse(u,c))}return e._zod.parse(l,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let l=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(u=>o(u,s,a)):o(l,s,a)}let c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new Ni;return c.then(l=>r(l,i,a))}return r(c,i,a)}}st(e,"~standard",()=>({validate:r=>{try{let o=rE(e,r);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return iE(e,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Wc=F("$ZodString",(e,t)=>{Je.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??EE(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),It=F("$ZodStringFormat",(e,t)=>{Ou.init(e,t),Wc.init(e,t)}),nO=F("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=fE),It.init(e,t)}),rO=F("$ZodUUID",(e,t)=>{if(t.version){let i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(i===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Gc(i))}else t.pattern??(t.pattern=Gc());It.init(e,t)}),iO=F("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=mE),It.init(e,t)}),oO=F("$ZodURL",(e,t)=>{It.init(e,t),e._zod.check=n=>{try{let i=n.value.trim(),r=new URL(i);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=r.href:n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),sO=F("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=gE()),It.init(e,t)}),aO=F("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=dE),It.init(e,t)}),cO=F("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=sE),It.init(e,t)}),lO=F("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=aE),It.init(e,t)}),uO=F("$ZodULID",(e,t)=>{t.pattern??(t.pattern=cE),It.init(e,t)}),dO=F("$ZodXID",(e,t)=>{t.pattern??(t.pattern=lE),It.init(e,t)}),pO=F("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=uE),It.init(e,t)}),fO=F("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=SE(t)),It.init(e,t)}),mO=F("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=$E),It.init(e,t)}),gO=F("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=RE(t)),It.init(e,t)}),hO=F("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=pE),It.init(e,t)}),yO=F("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=hE),It.init(e,t),e._zod.bag.format="ipv4"}),wO=F("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=yE),It.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),bO=F("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=wE(t.delimiter)),It.init(e,t),e._zod.bag.format="mac"}),vO=F("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=bE),It.init(e,t)}),kO=F("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=vE),It.init(e,t),e._zod.check=n=>{let i=n.value.split("/");try{if(i.length!==2)throw new Error;let[r,o]=i;if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});$O=F("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=kE),It.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{xO(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});RO=F("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ew),It.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{CW(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),SO=F("$ZodE164",(e,t)=>{t.pattern??(t.pattern=xE),It.init(e,t)});EO=F("$ZodJWT",(e,t)=>{It.init(e,t),e._zod.check=n=>{_W(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),OO=F("$ZodCustomStringFormat",(e,t)=>{It.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),Lw=F("$ZodNumber",(e,t)=>{Je.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ow,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let o=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...o?{received:o}:{}}),n}}),AO=F("$ZodNumberFormat",(e,t)=>{jE.init(e,t),Lw.init(e,t)}),Nf=F("$ZodBoolean",(e,t)=>{Je.init(e,t),e._zod.pattern=PE,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=!!n.value}catch{}let r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),Mw=F("$ZodBigInt",(e,t)=>{Je.init(e,t),e._zod.pattern=OE,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),PO=F("$ZodBigIntFormat",(e,t)=>{NE.init(e,t),Mw.init(e,t)}),CO=F("$ZodSymbol",(e,t)=>{Je.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;return typeof r=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),n}}),_O=F("$ZodUndefined",(e,t)=>{Je.init(e,t),e._zod.pattern=_E,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,i)=>{let r=n.value;return typeof r>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),n}}),TO=F("$ZodNull",(e,t)=>{Je.init(e,t),e._zod.pattern=CE,e._zod.values=new Set([null]),e._zod.parse=(n,i)=>{let r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}}),IO=F("$ZodAny",(e,t)=>{Je.init(e,t),e._zod.parse=n=>n}),DO=F("$ZodUnknown",(e,t)=>{Je.init(e,t),e._zod.parse=n=>n}),jO=F("$ZodNever",(e,t)=>{Je.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),NO=F("$ZodVoid",(e,t)=>{Je.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;return typeof r>"u"||n.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),n}}),LO=F("$ZodDate",(e,t)=>{Je.init(e,t),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}let r=n.value,o=r instanceof Date;return o&&!Number.isNaN(r.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:r,...o?{received:"Invalid Date"}:{},inst:e}),n}});MO=F("$ZodArray",(e,t)=>{Je.init(e,t),e._zod.parse=(n,i)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);let o=[];for(let s=0;s<r.length;s++){let a=r[s],c=t.element._zod.run({value:a,issues:[]},i);c instanceof Promise?o.push(c.then(l=>bW(l,n,s))):bW(c,n,s)}return o.length?Promise.all(o).then(()=>n):n}});DW=F("$ZodObject",(e,t)=>{if(Je.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let i=ku(()=>TW(t));st(e._zod,"propValues",()=>{let a=t.shape,c={};for(let l in a){let u=a[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(let d of u.values)c[l].add(d)}}return c});let r=Fc,o=t.catchall,s;e._zod.parse=(a,c)=>{s??(s=i.value);let l=a.value;if(!r(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;a.value={};let u=[],d=s.shape;for(let p of s.keys){let f=d[p],g=f._zod.optout==="optional",h=f._zod.run({value:l[p],issues:[]},c);h instanceof Promise?u.push(h.then(w=>Nw(w,a,p,l,g))):Nw(h,a,p,l,g)}return o?IW(u,l,a,c,i.value,e):u.length?Promise.all(u).then(()=>a):a}}),FO=F("$ZodObjectJIT",(e,t)=>{DW.init(e,t);let n=e._zod.parse,i=ku(()=>TW(t)),r=p=>{let f=new jf(["shape","payload","ctx"]),g=i.value,h=$=>{let x=mw($);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let w=Object.create(null),b=0;for(let $ of g.keys)w[$]=`key_${b++}`;f.write("const newResult = {};");for(let $ of g.keys){let x=w[$],R=mw($),I=p[$]?._zod?.optout==="optional";f.write(`const ${x} = ${h($)};`),I?f.write(`
@@ -48,10 +48,10 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
48
48
  `)}var $2=v(()=>{"use strict"});import{fork as hce}from"node:child_process";function R2(e){let t="";return{push(n){t+=n.toString();let i=t.indexOf(`
49
49
  `);for(;i!==-1;)e(t.slice(0,i)),t=t.slice(i+1),i=t.indexOf(`
50
50
  `)},flush(){t.length>0&&(e(t),t="")}}}function yce(e,t,n,i,r){let o=i.trim(),s=`${e}: child exited before reporting results (code ${t}, signal ${n})`;if(r.length>0){let a=r.map(c=>c&&typeof c=="object"?`{${Object.keys(c).join(", ")}}`:typeof c).join(", ");return`${s}. It sent ${r.length} message(s) the parent did not recognise (${a}), so the payload shape and the parent's check disagree`+(o?`: ${o}`:"")}return o?`${s}: ${o}`:t!==0||n!==null?s:`${s}. It exited cleanly with nothing on stderr, and no message arrived even after its IPC channel closed, so it never sent one: something it awaited never settled. On the run path the usual cause is a project file with a top-level \`await\` that does not settle. Module scope is arbitrary project source, an import of such a file never completes, and a promise that never settles is not a rejection, so the driver's own \`main().catch\` does not see it either. The config driver has nothing to await that can hang, and a failed send exits non-zero with a reason on stderr, so on the config path this has no known cause: please report it with the command that produced it (chant#2461).`}function bce(e,t,n=wce){e.on("exit",(i,r)=>{let o=!1,s,a=()=>{o||(o=!0,s!==void 0&&clearTimeout(s),t(i,r))};if(!e.connected){a();return}e.once("disconnect",a),s=setTimeout(a,n)})}function S2(e,t){let{bundlePath:n,bundleDir:i,projectRealpath:r,externalReadPaths:o,env:s,timeoutMs:a,label:c,send:l,outputPrefix:u}=e;return new Promise((d,p)=>{let f=[i,r,...o].map(P=>`--allow-fs-read=${P}`),g=hce(n,[],{execArgv:["--permission",...f],env:s,stdio:["ignore","pipe","pipe","ipc"]}),h=!1,w="",b=[],k=setTimeout(()=>{h||(h=!0,g.kill(),p(new Error(`${c} timed out after ${a}ms`)))},a);l!==void 0&&g.send(l,P=>{h||!P||(h=!0,clearTimeout(k),g.kill(),p(new Error(`${c}: failed to send the child its input: ${P.message}`)))});let $=P=>{process.stderr.write(`${u} ${P}
51
- `)},x=R2($),R=R2($);g.stdout?.on("data",P=>{x.push(P)}),g.stdout?.on("end",()=>x.flush()),g.stderr?.on("data",P=>{w+=P.toString(),R.push(P)}),g.stderr?.on("end",()=>R.flush()),g.on("message",P=>{if(!h){if(!t(P)){b.push(P);return}h=!0,clearTimeout(k),g.kill(),d(P)}}),g.on("error",P=>{h||(h=!0,clearTimeout(k),p(P))}),bce(g,(P,I)=>{h||(h=!0,clearTimeout(k),p(new Error(yce(c,P,I,w,b))))})})}var wce,E2=v(()=>{"use strict";wce=2e3});var A2={};_e(A2,{evaluateConfigSandboxed:()=>Rce});import{realpathSync as vce,rmSync as kce}from"node:fs";import{resolve as O2}from"node:path";function $ce(e){return typeof e=="object"&&e!==null&&e.kind==="chant-config"&&typeof e.ok=="boolean"}async function Rce(e,t){let n=v2(e),{bundlePath:i,bundleDir:r,externalReadPaths:o,durationMs:s,bytes:a}=await w2(n);try{let c;try{c=vce(O2(t))}catch{c=O2(t)}let l={PATH:process.env.PATH??""},u=process.env[Yu];u&&(l[Yu]=u);let d=await S2({bundlePath:i,bundleDir:r,projectRealpath:c,externalReadPaths:o,env:l,timeoutMs:xce,label:`sandboxed evaluation of ${e}`,outputPrefix:"[sandbox:config]"},$ce);if(!d.ok)throw d.offenders&&d.offenders.length>0?new Error(x2(e,d.offenders)):new Error(d.error?.message?`Failed to evaluate ${e} inside the --sandbox boundary: ${d.error.message}`:`Failed to evaluate ${e} inside the --sandbox boundary`);return{config:d.config??{},bundleMs:s,bundleBytes:a}}finally{kce(r,{recursive:!0,force:!0})}}var xce,P2=v(()=>{"use strict";b2();k2();$2();E2();um();xce=6e4});import{dirname as Sce}from"node:path";function Oce(e){let t=Jr(e);return t.default??t.config??t}async function C2(e,t=Sce(e)){if(!Ece)return Oce(await u2(e));if(c_.has(e))return c_.get(e);let{evaluateConfigSandboxed:n}=await Promise.resolve().then(()=>(P2(),A2)),{config:i}=await n(e,t);return c_.set(e,i),i}var Ece,c_,l_=v(()=>{"use strict";d2();Jc();Ece=!1,c_=new Map});var f_={};_e(f_,{importLexiconModule:()=>Qc,importLexiconPackage:()=>Eo,lexiconDeclarationName:()=>j2,lexiconModulePath:()=>ys,lexiconModuleRoot:()=>p_,lexiconNames:()=>Gi,lexiconPackagesToInstall:()=>jce,lexiconSourceLabel:()=>Dce,packageNameOf:()=>L2,pathLexiconMap:()=>_ce,pathLexiconRoot:()=>uv,recordedLexiconModules:()=>Tce,registerLexiconDeclarations:()=>ua,resetLexiconModules:()=>Ice,resolveFromProject:()=>dv});import{createRequire as I2}from"node:module";import{dirname as Ace,isAbsolute as Xc,join as Pce,relative as D2,resolve as Xu,sep as Cce}from"node:path";import{pathToFileURL as d_}from"node:url";function j2(e){return typeof e=="string"?e:e.name}function Gi(e){return e?.map(j2)}function u_(e,t){let n=D2(t,e);return n===""||!n.startsWith("..")&&!Xc(n)}function uv(e,t,n="."){let i=Xc(e.module)?e.module:Xu(t,e.module),r=e.root!==void 0,o=r?Xc(e.root)?Xu(e.root):Xu(t,e.root):Ace(i),s=Xu(t),a=Xu(t,n),c;return u_(o,s)?u_(a,o)?c=`${o} contains the project's source directory (${a})`:u_(i,o)||(c=`the module ${i} is not inside ${o}`):c=`${o} is outside the project (${s})`,c===void 0?{root:o}:r?{problem:c}:{}}function ua(e,t,n){let i={};for(let r of e??[]){if(typeof r=="string"){la.delete(r),dm.delete(r);continue}let o=N2(r,t);la.set(r.name,o),i[r.name]=o;let{root:s}=uv(r,t,n);s===void 0?dm.delete(r.name):dm.set(r.name,s)}return i}function N2(e,t){return Xc(e.module)?e.module:Xu(t,e.module)}function _ce(e,t){let n=new Map;for(let i of e)typeof i!="string"&&n.set(i.name,N2(i,t));return n}function Tce(){return new Map(la)}function ys(e){return la.get(e)}function p_(e){return dm.get(e)}function Ice(){la.clear(),dm.clear()}async function Qc(e,t={}){let n=la.get(e);if(n!==void 0)try{return(t.typeScript??!sv(n))&&mr(),Jr(await import(n))}catch(i){throw new Error(`lexicon "${e}" is declared with module ${n}, which could not be loaded: `+(i instanceof Error?i.message:String(i)))}}function Dce(e,t=process.cwd(),n=la){let i=n.get(e);if(i===void 0)return`@intentius/chant-lexicon-${e}`;let r=D2(t,i);return r===""||r.startsWith("..")||Xc(r)?i:`./${r.split(Cce).join("/")}`}function jce(e,t=la){return e.filter(n=>!t.has(n)).map(n=>`@intentius/chant-lexicon-${n}`)}function L2(e){if(e.startsWith(".")||Xc(e)||e.startsWith("file:"))return;let t=e.split("/");return e.startsWith("@")?t.slice(0,2).join("/"):t[0]}function _2(e,t){let n=e?.code;if(n!=="ERR_MODULE_NOT_FOUND"&&n!=="MODULE_NOT_FOUND")return!1;let i=e instanceof Error?e.message:String(e);return i.includes(`'${t}'`)||i.includes(`"${t}"`)||i.includes(`${t}/`)}function dv(e,t=process.cwd()){try{return I2(Pce(t,"package.json")).resolve(e)}catch{return}}function Nce(e){if(Xc(e))return d_(e).href;let t=import.meta.resolve;return typeof t=="function"?t(e):d_(I2(import.meta.url).resolve(e)).href}async function Eo(e,t=process.cwd()){let n=L2(e);if(c2()){let i;try{i=Nce(e)}catch(r){if(n===void 0||!_2(r,n))mr();else return T2(e,t,r)}i!==void 0&&av(i)}try{return Jr(await import(e))}catch(i){if(n===void 0||!_2(i,n))throw i;return T2(e,t,i)}}async function T2(e,t,n){let i=dv(e,t);if(i===void 0)throw n;return av(i),Jr(await import(d_(i).href))}var la,dm,nr=v(()=>{"use strict";So();Jc();Kc();la=new Map,dm=new Map});var Lce,Mce,Fce,Qu,M2,pv=v(()=>{"use strict";$n();Lce=m.strictObject({env:m.string().min(1)}),Mce=m.strictObject({capability:m.string().min(1),member:m.string().min(1).optional(),env:m.string().min(1).optional()}),Fce=m.union([Lce,Mce]),Qu=m.strictObject({url:m.string().min(1),key:Fce.optional(),timeoutMs:m.number().int().positive().optional()}),M2=m.strictObject({backends:m.record(m.string(),Qu).optional()})});var m_,g_,Gce,Wce,Bce,F2,G2=v(()=>{"use strict";$n();m_=m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"an environment variable name"),g_=m.union([m.string().min(1),m.literal(!1)]),Gce=m.object({type:m.literal("npm"),packages:m.array(m.string().min(1)).min(1),registry:m.string().url().optional(),access:m.enum(["public","restricted"]).optional(),sbom:g_.optional()}).strict(),Wce=m.object({type:m.literal("oci"),image:m.string().min(1),repository:m.string().min(1),tags:m.array(m.string().min(1)).optional(),usernameEnv:m_.optional(),passwordEnv:m_.optional(),sbom:g_.optional()}).strict(),Bce=m.object({type:m.literal("forge"),forge:m.enum(["github","gitlab","forgejo"]),repo:m.string().min(1),api:m.string().url().optional(),assets:m.array(m.string().min(1)).min(1),tag:m.string().min(1).optional(),tokenEnv:m_.optional(),sbom:g_.optional()}).strict(),F2=m.discriminatedUnion("type",[Gce,Wce,Bce])});var $_={};_e($_,{ChantConfigSchema:()=>fm,DEFAULT_CHANT_CONFIG:()=>v_,InvalidChantConfigError:()=>ed,environmentEndpoint:()=>H2,environmentName:()=>da,environmentNames:()=>w_,findProjectConfigPastFragments:()=>mm,isEnvironmentPattern:()=>td,isLintOnlyFragment:()=>mv,isOwnershipParamRef:()=>K2,loadChantConfig:()=>nd,loadChantConfigUpward:()=>fv,matchesDeclaredEnvironment:()=>pm,matchesEnvironmentPattern:()=>b_,ownershipEnvDisagreement:()=>Hce,resolveAutoReleaseDisabled:()=>qce,resolveDiscoveryGlobs:()=>gm,resolveFoldEnabled:()=>Z2,resolveKnowledgeDir:()=>Yce,resolveOwnershipEnv:()=>x_,resolveOwnershipMarker:()=>J2,resolveOwnershipStack:()=>k_,resolveSandboxEnabled:()=>Y2,resolveSbomFormat:()=>Kce,resolveSigningDefaults:()=>Jce,resolveVulnPolicy:()=>Zce});import{existsSync as W2,readFileSync as U2}from"fs";import{dirname as V2,join as h_}from"path";function da(e){return typeof e=="string"?e:e.name}function w_(e){return e?.map(da)}function td(e){return e.includes("*")}function b_(e,t){let n=e.split("*");if(n.length===1)return e===t;let i=n[0],r=n[n.length-1];if(!t.startsWith(i))return!1;let o=i.length;for(let s=1;s<n.length-1;s++){let a=n[s];if(a==="")continue;let c=t.indexOf(a,o);if(c===-1)return!1;o=c+a.length}return t.length-o>=r.length&&t.endsWith(r)}function pm(e,t){let n=w_(e)??[];return n.includes(t)?!0:n.some(i=>td(i)&&b_(i,t))}function H2(e,t){let n=e?.find(i=>da(i)===t)??e?.find(i=>td(da(i))&&b_(da(i),t));return n&&typeof n!="string"?n.endpoint:void 0}async function nd(e){let t=h_(e,"chant.config.ts");if(W2(t)){let i=await C2(t,e);return{config:z2(i,t),configPath:t}}let n=h_(e,"chant.config.json");if(W2(n)){let{readFileSync:i}=await import("fs"),r=i(n,"utf-8"),o=JSON.parse(r);return{config:z2(o,n),configPath:n}}return{config:v_}}async function fv(e){let{dir:t,configPath:n}=mm(e);return n&&Vce(n),nd(t)}function mm(e){let{dir:t,configPath:n}=am(e);for(;n&&mv(n);){let i=V2(t);if(i===t)break;({dir:t,configPath:n}=am(i))}return{dir:t,configPath:n}}async function gm(e){let{dir:t,configPath:n}=mm(e);if(!n)return;let i;try{({config:i}=await nd(t))}catch(s){if(s instanceof ed&&(s.key==="exclude"||s.key==="include"))throw s;return}let r=i.exclude??[],o=i.include??[];if(!(r.length===0&&o.length===0))return{root:t,exclude:r,include:o}}function mv(e){if(!e.endsWith("chant.config.json"))return!1;try{let t=JSON.parse(U2(e,"utf-8"));if(typeof t!="object"||t===null||Array.isArray(t))return!1;let n=Object.keys(t).filter(i=>!q2(i));return n.length>0&&n.every(i=>y_.has(i))}catch{return!1}}function Vce(e){if(e.endsWith("chant.config.json"))try{let t=JSON.parse(U2(e,"utf-8"));if(typeof t!="object"||t===null||Array.isArray(t))return;let n=Object.keys(t).filter(i=>!q2(i));if(n.some(i=>!y_.has(i))&&!n.some(i=>B2.has(i))){let i=n.filter(r=>!y_.has(r));console.error(`warning: ${e} is being used as the project config, but declares no project-level key (${[...B2].slice(0,4).join(", ")}, \u2026). ${i.length===1?"The key":"The keys"} ${i.map(r=>`"${r}"`).join(", ")} stopped the walk to the real one \u2014 any config above this file is being ignored. Prefix a comment key with "_", or move the key to the project config. (chant #1711)`)}}catch{}}function K2(e){return typeof e=="object"&&e!==null&&typeof e.param=="string"}function k_(e){let t=e.ownership;if(!(!t||!t.stack||t.enabled===!1))return t.stack}function x_(e,t){let n=e.ownership?.env;if(!K2(n))return n;let i=n.param,r=e.buildParams?.[i];if(!r)throw new Error(`ownership.env references build parameter "${i}", which chant.config.ts's buildParams does not declare`);let o=t?.find(s=>s.name===i);if(!o)throw new Error(`ownership.env references build parameter "${i}", which resolved to no value for this build \u2014 pass --param ${i}=<value>${r.env?`, set ${r.env}`:""}, or give it a default`);return String(o.value)}function J2(e,t){let n=k_(e);if(n!==void 0)return{stack:n,env:x_(e,t)}}function Hce(e,t){let n=e.ownership?.env;if(typeof n!="string"||k_(e)===void 0)return;let i=t?.find(r=>r.name==="env");if(!(!i||String(i.value)===n))return`ownership.env is "${n}" but the env build parameter resolved to ${JSON.stringify(i.value)} (${i.source}) \u2014 the ownership marker and params.env disagree about which environment this build is for. Use ownership: { env: { param: "env" } } so the marker follows the parameter.`}function qce(e,t){return t?!0:e.release?.autoRecord===!1}function Z2(e,t){return t!==void 0?t:e.build?.fold!==void 0?e.build.fold:!0}function Y2(e,t){return t?!0:e.build?.sandbox===!0}function Kce(e,t){return t??e.sbom?.format??li}function Jce(e){let t=e.signing,n=t?.keyless!==!1;return{keyless:n,...!n&&t?.key?{key:{key:t.key}}:{},identityPolicyDefaults:{expectedIssuer:t?.oidcIssuer,expectedIdentity:t?.identity,identityIsRegexp:t?.identityIsRegexp,key:t?.keyless===!1?t?.key:void 0}}}function Zce(e){let t=e.vulnPolicy;if(!t)return{};let n={};return t.failSeverity&&(n.failSeverity=t.failSeverity),t.fixableOnly!==void 0&&(n.fixableOnly=t.fixableOnly),t.warnSeverity&&(n.warnSeverity=t.warnSeverity),t.failOnLicense!==void 0&&(n.failOnLicense=t.failOnLicense),t.failOnUnknownSeverity!==void 0&&(n.failOnUnknownSeverity=t.failOnUnknownSeverity),t.failOnKev!==void 0&&(n.failOnKev=t.failOnKev),t.failEpssAtOrAbove!==void 0&&(n.failEpssAtOrAbove=t.failEpssAtOrAbove),t.warnEpssAtOrAbove!==void 0&&(n.warnEpssAtOrAbove=t.warnEpssAtOrAbove),t.exploitabilityFixableOnly!==void 0&&(n.exploitabilityFixableOnly=t.exploitabilityFixableOnly),t.license&&(n.license=t.license),n}function Yce(e,t){return h_(t,e.knowledge?.dir??"knowledge")}function z2(e,t){if(typeof e!="object"||e===null)return v_;let n=fm.safeParse(e);if(!n.success){let a=n.error.issues[0],c=a.path.length>0?a.path.join("."):void 0,l=t?` in ${t}`:"";throw new ed(`Invalid chant config${l}: ${c?`${c}: `:""}${a.message}`,a.path.length>0?String(a.path[0]):void 0)}let i=e.lexicons,r=t!==void 0?V2(t):process.cwd(),o=e.sourceDir;for(let[a,c]of(i??[]).entries()){if(typeof c=="string"||c.root===void 0)continue;let{problem:l}=uv(c,r,o);if(l!==void 0){let u=t?` in ${t}`:"";throw new ed(`Invalid chant config${u}: lexicons.${a}.root: ${l}`,"lexicons")}}let s=ua(i,r,o);return Object.keys(s).length>0?{...e,lexicons:Gi(i),lexiconModules:s}:e}var zce,Uce,fm,v_,y_,q2,B2,ed,zn=v(()=>{"use strict";$n();hs();Mi();l_();nr();pv();G2();zce=m.union([m.string().min(1),m.object({name:m.string().min(1),endpoint:m.string().min(1).optional(),canary:m.boolean().optional()})]),Uce=m.union([m.string().min(1),m.object({name:m.string().min(1),module:m.string().min(1),root:m.string().min(1).optional()}).strict()]),fm=m.object({lexicons:m.array(Uce).optional(),capabilities:m.array(m.string().min(1)).optional(),environments:m.array(zce).optional(),sourceDir:m.string().min(1).optional(),lint:m.record(m.string(),m.unknown()).optional(),ownership:m.object({stack:m.string().min(1).optional(),env:m.union([m.string().min(1),m.object({param:m.string().min(1)})]).optional(),enabled:m.boolean().optional()}).optional(),build:m.object({fold:m.boolean().optional()}).optional(),buildParams:m.record(m.string(),m.object({type:m.enum(["string","number","boolean"]),default:m.union([m.string(),m.number(),m.boolean()]).optional(),enum:m.array(m.union([m.string(),m.number(),m.boolean()])).optional(),env:m.string().min(1).optional(),required:m.boolean().optional(),description:m.string().optional()})).optional(),release:m.object({autoRecord:m.boolean().optional(),publish:m.array(F2).optional()}).optional(),run:m.object({on:m.string().min(1).optional()}).strict().optional(),sbom:m.object({format:m.enum(["spdx","cyclonedx"]).optional(),enabled:m.boolean().optional()}).optional(),signing:m.object({keyless:m.boolean().optional(),oidcIssuer:m.string().min(1).optional(),identity:m.string().min(1).optional(),identityIsRegexp:m.boolean().optional(),key:m.string().min(1).optional()}).optional(),vulnPolicy:m.object({failSeverity:m.enum(["critical","high","medium","low","negligible","unknown"]).optional(),fixableOnly:m.boolean().optional(),warnSeverity:m.enum(["critical","high","medium","low","negligible","unknown"]).optional(),failOnLicense:m.boolean().optional(),failOnUnknownSeverity:m.boolean().optional(),failOnKev:m.boolean().optional(),failEpssAtOrAbove:m.number().min(0).max(1).optional(),warnEpssAtOrAbove:m.number().min(0).max(1).optional(),exploitabilityFixableOnly:m.boolean().optional(),license:m.object({allow:m.array(m.string()).optional(),deny:m.array(m.string()).optional()}).optional(),scanner:m.enum(["grype","trivy"]).optional(),vexSources:m.array(m.string()).optional()}).optional(),knowledge:m.object({dir:m.string().min(1).optional()}).optional(),codegen:m.object({outDir:m.string().min(1).optional()}).strict().optional(),decide:M2.optional(),exclude:m.array(m.string().min(1)).optional(),include:m.array(m.string().min(1)).optional(),rootOnly:m.boolean().optional()}).passthrough(),v_={};y_=new Set(["$schema","extends","rules","overrides","plugins","policies"]),q2=e=>e.startsWith("_");B2=new Set(Object.keys(fm.shape).filter(e=>e!=="lint"));ed=class extends Error{constructor(n,i){super(n);this.key=i}}});var Yu,um=v(()=>{"use strict";zn();Yu="CHANT_ENV"});var hm=ae((wWe,nV)=>{"use strict";var X2="[^\\\\/]",Xce="(?=.)",Q2="[^/]",R_="(?:\\/|$)",eV="(?:^|\\/)",S_=`\\.{1,2}${R_}`,Qce="(?!\\.)",ele=`(?!${eV}${S_})`,tle=`(?!\\.{0,1}${R_})`,nle=`(?!${S_})`,rle="[^.\\/]",ile=`${Q2}*?`,ole="/",tV={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:Xce,QMARK:Q2,END_ANCHOR:R_,DOTS_SLASH:S_,NO_DOT:Qce,NO_DOTS:ele,NO_DOT_SLASH:tle,NO_DOTS_SLASH:nle,QMARK_NO_DOT:rle,STAR:ile,START_ANCHOR:eV,SEP:ole},sle={...tV,SLASH_LITERAL:"[\\\\/]",QMARK:X2,STAR:`${X2}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},ale={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};nV.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:ale,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===!0?sle:tV}}});var ym=ae(_r=>{"use strict";var{REGEX_BACKSLASH:cle,REGEX_REMOVE_BACKSLASH:lle,REGEX_SPECIAL_CHARS:ule,REGEX_SPECIAL_CHARS_GLOBAL:dle}=hm();_r.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);_r.hasRegexChars=e=>ule.test(e);_r.isRegexChar=e=>e.length===1&&_r.hasRegexChars(e);_r.escapeRegex=e=>e.replace(dle,"\\$1");_r.toPosixSlashes=e=>e.replace(cle,"/");_r.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let e=navigator.platform.toLowerCase();return e==="win32"||e==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};_r.removeBackslashes=e=>e.replace(lle,t=>t==="\\"?"":t);_r.escapeLast=(e,t,n)=>{let i=e.lastIndexOf(t,n);return i===-1?e:e[i-1]==="\\"?_r.escapeLast(e,t,i-1):`${e.slice(0,i)}\\${e.slice(i)}`};_r.removePrefix=(e,t={})=>{let n=e;return n.startsWith("./")&&(n=n.slice(2),t.prefix="./"),n};_r.wrapOutput=(e,t={},n={})=>{let i=n.contains?"":"^",r=n.contains?"":"$",o=`${i}(?:${e})${r}`;return t.negated===!0&&(o=`(?:^(?!${o}).*$)`),o};_r.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:"/"),i=n[n.length-1];return i===""?n[n.length-2]:i}});var uV=ae((vWe,lV)=>{"use strict";var rV=ym(),{CHAR_ASTERISK:E_,CHAR_AT:ple,CHAR_BACKWARD_SLASH:wm,CHAR_COMMA:fle,CHAR_DOT:O_,CHAR_EXCLAMATION_MARK:A_,CHAR_FORWARD_SLASH:cV,CHAR_LEFT_CURLY_BRACE:P_,CHAR_LEFT_PARENTHESES:C_,CHAR_LEFT_SQUARE_BRACKET:mle,CHAR_PLUS:gle,CHAR_QUESTION_MARK:iV,CHAR_RIGHT_CURLY_BRACE:hle,CHAR_RIGHT_PARENTHESES:oV,CHAR_RIGHT_SQUARE_BRACKET:yle}=hm(),sV=e=>e===cV||e===wm,aV=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)},wle=(e,t)=>{let n=t||{},i=e.length-1,r=n.parts===!0||n.scanToEnd===!0,o=[],s=[],a=[],c=e,l=-1,u=0,d=0,p=!1,f=!1,g=!1,h=!1,w=!1,b=!1,k=!1,$=!1,x=!1,R=!1,P=0,I,A,B={value:"",depth:0,isGlob:!1},C=()=>l>=i,q=()=>c.charCodeAt(l+1),L=()=>(I=A,c.charCodeAt(++l));for(;l<i;){A=L();let ve;if(A===wm){k=B.backslashes=!0,A=L(),A===P_&&(b=!0);continue}if(b===!0||A===P_){for(P++;C()!==!0&&(A=L());){if(A===wm){k=B.backslashes=!0,L();continue}if(A===P_){P++;continue}if(b!==!0&&A===O_&&(A=L())===O_){if(p=B.isBrace=!0,g=B.isGlob=!0,R=!0,r===!0)continue;break}if(b!==!0&&A===fle){if(p=B.isBrace=!0,g=B.isGlob=!0,R=!0,r===!0)continue;break}if(A===hle&&(P--,P===0)){b=!1,p=B.isBrace=!0,R=!0;break}}if(r===!0)continue;break}if(A===cV){if(o.push(l),s.push(B),B={value:"",depth:0,isGlob:!1},R===!0)continue;if(I===O_&&l===u+1){u+=2;continue}d=l+1;continue}if(n.noext!==!0&&(A===gle||A===ple||A===E_||A===iV||A===A_)===!0&&q()===C_){if(g=B.isGlob=!0,h=B.isExtglob=!0,R=!0,A===A_&&l===u&&(x=!0),r===!0){for(;C()!==!0&&(A=L());){if(A===wm){k=B.backslashes=!0,A=L();continue}if(A===oV){g=B.isGlob=!0,R=!0;break}}continue}break}if(A===E_){if(I===E_&&(w=B.isGlobstar=!0),g=B.isGlob=!0,R=!0,r===!0)continue;break}if(A===iV){if(g=B.isGlob=!0,R=!0,r===!0)continue;break}if(A===mle){for(;C()!==!0&&(ve=L());){if(ve===wm){k=B.backslashes=!0,L();continue}if(ve===yle){f=B.isBracket=!0,g=B.isGlob=!0,R=!0;break}}if(r===!0)continue;break}if(n.nonegate!==!0&&A===A_&&l===u){$=B.negated=!0,u++;continue}if(n.noparen!==!0&&A===C_){if(g=B.isGlob=!0,r===!0){for(;C()!==!0&&(A=L());){if(A===C_){k=B.backslashes=!0,A=L();continue}if(A===oV){R=!0;break}}continue}break}if(g===!0){if(R=!0,r===!0)continue;break}}n.noext===!0&&(h=!1,g=!1);let M=c,_="",T="";u>0&&(_=c.slice(0,u),c=c.slice(u),d-=u),M&&g===!0&&d>0?(M=c.slice(0,d),T=c.slice(d)):g===!0?(M="",T=c):M=c,M&&M!==""&&M!=="/"&&M!==c&&sV(M.charCodeAt(M.length-1))&&(M=M.slice(0,-1)),n.unescape===!0&&(T&&(T=rV.removeBackslashes(T)),M&&k===!0&&(M=rV.removeBackslashes(M)));let W={prefix:_,input:e,start:u,base:M,glob:T,isBrace:p,isBracket:f,isGlob:g,isExtglob:h,isGlobstar:w,negated:$,negatedExtglob:x};if(n.tokens===!0&&(W.maxDepth=0,sV(A)||s.push(B),W.tokens=s),n.parts===!0||n.tokens===!0){let ve;for(let re=0;re<o.length;re++){let be=ve?ve+1:u,Be=o[re],dt=e.slice(be,Be);n.tokens&&(re===0&&u!==0?(s[re].isPrefix=!0,s[re].value=_):s[re].value=dt,aV(s[re]),W.maxDepth+=s[re].depth),(re!==0||dt!=="")&&a.push(dt),ve=Be}if(ve&&ve+1<e.length){let re=e.slice(ve+1);a.push(re),n.tokens&&(s[s.length-1].value=re,aV(s[s.length-1]),W.maxDepth+=s[s.length-1].depth)}W.slashes=o,W.parts=a}return W};lV.exports=wle});var gV=ae((kWe,mV)=>{"use strict";var bm=hm(),Zr=ym(),{MAX_LENGTH:gv,POSIX_REGEX_SOURCE:ble,REGEX_NON_SPECIAL_CHARS:vle,REGEX_SPECIAL_CHARS_BACKREF:kle,REPLACEMENTS:dV}=bm,xle=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let n=`[${e.join("-")}]`;try{new RegExp(n)}catch{return e.map(r=>Zr.escapeRegex(r)).join("..")}return n},rd=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,pV=e=>{let t=[],n=0,i=0,r=0,o="",s=!1;for(let a of e){if(s===!0){o+=a,s=!1;continue}if(a==="\\"){o+=a,s=!0;continue}if(a==='"'){r=r===1?0:1,o+=a;continue}if(r===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")i++;else if(a===")"&&i>0)i--;else if(a==="|"&&i===0){t.push(o),o="";continue}}}o+=a}return t.push(o),t},$le=e=>{let t=!1;for(let n of e){if(t===!0){t=!1;continue}if(n==="\\"){t=!0;continue}if(/[?*+@!()[\]{}]/.test(n))return!1}return!0},fV=e=>{let t=e.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),n=!0);if($le(t))return t.replace(/\\(.)/g,"$1")},Rle=e=>{let t=e.map(fV).filter(Boolean);for(let n=0;n<t.length;n++)for(let i=n+1;i<t.length;i++){let r=t[n],o=t[i],s=r[0];if(!(!s||r!==s.repeat(r.length)||o!==s.repeat(o.length))&&(r===o||r.startsWith(o)||o.startsWith(r)))return!0}return!1},__=(e,t=!0)=>{if(e[0]!=="+"&&e[0]!=="*"||e[1]!=="(")return;let n=0,i=0,r=0,o=!1;for(let s=1;s<e.length;s++){let a=e[s];if(o===!0){o=!1;continue}if(a==="\\"){o=!0;continue}if(a==='"'){r=r===1?0:1;continue}if(r!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){i++;continue}if(a===")"&&(i--,i===0))return t===!0&&s!==e.length-1?void 0:{type:e[0],body:e.slice(2,s),end:s}}}}},Sle=e=>{let t=0,n=[];for(;t<e.length;){let r=__(e.slice(t),!1);if(!r||r.type!=="*")return;let o=pV(r.body).map(a=>a.trim());if(o.length!==1)return;let s=fV(o[0]);if(!s||s.length!==1)return;n.push(s),t+=r.end+1}return n.length<1?void 0:`${n.length===1?Zr.escapeRegex(n[0]):`[${n.map(r=>Zr.escapeRegex(r)).join("")}]`}*`},Ele=e=>{let t=0,n=e.trim(),i=__(n);for(;i;)t++,n=i.body.trim(),i=__(n);return t},Ole=(e,t)=>{if(t.maxExtglobRecursion===!1)return{risky:!1};let n=typeof t.maxExtglobRecursion=="number"?t.maxExtglobRecursion:bm.DEFAULT_MAX_EXTGLOB_RECURSION,i=pV(e).map(r=>r.trim());if(i.length>1&&(i.some(r=>r==="")||i.some(r=>/^[*?]+$/.test(r))||Rle(i)))return{risky:!0};for(let r of i){let o=Sle(r);if(o)return{risky:!0,safeOutput:o};if(Ele(r)>n)return{risky:!0}}return{risky:!1}},T_=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=dV[e]||e;let n={...t},i=typeof n.maxLength=="number"?Math.min(gv,n.maxLength):gv,r=e.length;if(r>i)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${i}`);let o={type:"bos",value:"",output:n.prepend||""},s=[o],a=n.capture?"":"?:",c=bm.globChars(n.windows),l=bm.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:p,ONE_CHAR:f,DOTS_SLASH:g,NO_DOT:h,NO_DOT_SLASH:w,NO_DOTS_SLASH:b,QMARK:k,QMARK_NO_DOT:$,STAR:x,START_ANCHOR:R}=c,P=te=>`(${a}(?:(?!${R}${te.dot?g:u}).)*?)`,I=n.dot?"":h,A=n.dot?k:$,B=n.bash===!0?P(n):x;n.capture&&(B=`(${B})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let C={input:e,index:-1,start:0,dot:n.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:s};e=Zr.removePrefix(e,C),r=e.length;let q=[],L=[],M=[],_=o,T,W=()=>C.index===r-1,ve=C.peek=(te=1)=>e[C.index+te],re=C.advance=()=>e[++C.index]||"",be=()=>e.slice(C.index+1),Be=(te="",Ve=0)=>{C.consumed+=te,C.index+=Ve},dt=te=>{C.output+=te.output!=null?te.output:te.value,Be(te.value)},ne=()=>{let te=1;for(;ve()==="!"&&(ve(2)!=="("||ve(3)==="?");)re(),C.start++,te++;return te%2===0?!1:(C.negated=!0,C.start++,!0)},ye=te=>{C[te]++,M.push(te)},ge=te=>{C[te]--,M.pop()},oe=te=>{if(_.type==="globstar"){let Ve=C.braces>0&&(te.type==="comma"||te.type==="brace"),z=te.extglob===!0||q.length&&(te.type==="pipe"||te.type==="paren");te.type!=="slash"&&te.type!=="paren"&&!Ve&&!z&&(C.output=C.output.slice(0,-_.output.length),_.type="star",_.value="*",_.output=B,C.output+=_.output)}if(q.length&&te.type!=="paren"&&(q[q.length-1].inner+=te.value),(te.value||te.output)&&dt(te),_&&_.type==="text"&&te.type==="text"){_.output=(_.output||_.value)+te.value,_.value+=te.value;return}te.prev=_,s.push(te),_=te},Se=(te,Ve)=>{let z={...l[Ve],conditions:1,inner:""};z.prev=_,z.parens=C.parens,z.output=C.output,z.startIndex=C.index,z.tokensIndex=s.length;let $e=(n.capture?"(":"")+z.open;ye("parens"),oe({type:te,value:Ve,output:C.output?"":f}),oe({type:"paren",extglob:!0,value:re(),output:$e}),q.push(z)},Ne=te=>{let Ve=e.slice(te.startIndex,C.index+1),z=e.slice(te.startIndex+2,C.index),$e=Ole(z,n);if((te.type==="plus"||te.type==="star")&&$e.risky){let ct=$e.safeOutput?(te.output?"":f)+(n.capture?`(${$e.safeOutput})`:$e.safeOutput):void 0,Vt=s[te.tokensIndex];Vt.type="text",Vt.value=Ve,Vt.output=ct||Zr.escapeRegex(Ve);for(let U=te.tokensIndex+1;U<s.length;U++)s[U].value="",s[U].output="",delete s[U].suffix;C.output=te.output+Vt.output,C.backtrack=!0,oe({type:"paren",extglob:!0,value:T,output:""}),ge("parens");return}let Ie=te.close+(n.capture?")":""),et;if(te.type==="negate"){let ct=B;if(te.inner&&te.inner.length>1&&te.inner.includes("/")&&(ct=P(n)),(ct!==B||W()||/^\)+$/.test(be()))&&(Ie=te.close=`)$))${ct}`),te.inner.includes("*")&&(et=be())&&/^\.[^\\/.]+$/.test(et)){let Vt=T_(et,{...t,fastpaths:!1}).output;Ie=te.close=`)${Vt})${ct})`}te.prev.type==="bos"&&(C.negatedExtglob=!0)}oe({type:"paren",extglob:!0,value:T,output:Ie}),ge("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let te=!1,Ve=e.replace(kle,(z,$e,Ie,et,ct,Vt)=>et==="\\"?(te=!0,z):et==="?"?$e?$e+et+(ct?k.repeat(ct.length):""):Vt===0?A+(ct?k.repeat(ct.length):""):k.repeat(Ie.length):et==="."?u.repeat(Ie.length):et==="*"?$e?$e+et+(ct?B:""):B:$e?z:`\\${z}`);return te===!0&&(n.unescape===!0?Ve=Ve.replace(/\\/g,""):Ve=Ve.replace(/\\+/g,z=>z.length%2===0?"\\\\":z?"\\":"")),Ve===e&&n.contains===!0?(C.output=e,C):(C.output=Zr.wrapOutput(Ve,C,t),C)}for(;!W();){if(T=re(),T==="\0")continue;if(T==="\\"){let z=ve();if(z==="/"&&n.bash!==!0||z==="."||z===";")continue;if(!z){T+="\\",oe({type:"text",value:T});continue}let $e=/^\\+/.exec(be()),Ie=0;if($e&&$e[0].length>2&&(Ie=$e[0].length,C.index+=Ie,Ie%2!==0&&(T+="\\")),n.unescape===!0?T=re():T+=re(),C.brackets===0){oe({type:"text",value:T});continue}}if(C.brackets>0&&(T!=="]"||_.value==="["||_.value==="[^")){if(n.posix!==!1&&T===":"){let z=_.value.slice(1);if(z.includes("[")&&(_.posix=!0,z.includes(":"))){let $e=_.value.lastIndexOf("["),Ie=_.value.slice(0,$e),et=_.value.slice($e+2),ct=ble[et];if(ct){_.value=Ie+ct,C.backtrack=!0,re(),!o.output&&s.indexOf(_)===1&&(o.output=f);continue}}}(T==="["&&ve()!==":"||T==="-"&&ve()==="]")&&(T=`\\${T}`),T==="]"&&(_.value==="["||_.value==="[^")&&(T=`\\${T}`),n.posix===!0&&T==="!"&&_.value==="["&&(T="^"),_.value+=T,dt({value:T});continue}if(C.quotes===1&&T!=='"'){T=Zr.escapeRegex(T),_.value+=T,dt({value:T});continue}if(T==='"'){C.quotes=C.quotes===1?0:1,n.keepQuotes===!0&&oe({type:"text",value:T});continue}if(T==="("){ye("parens"),oe({type:"paren",value:T});continue}if(T===")"){if(C.parens===0&&n.strictBrackets===!0)throw new SyntaxError(rd("opening","("));let z=q[q.length-1];if(z&&C.parens===z.parens+1){Ne(q.pop());continue}oe({type:"paren",value:T,output:C.parens?")":"\\)"}),ge("parens");continue}if(T==="["){if(n.nobracket===!0||!be().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(rd("closing","]"));T=`\\${T}`}else ye("brackets");oe({type:"bracket",value:T});continue}if(T==="]"){if(n.nobracket===!0||_&&_.type==="bracket"&&_.value.length===1){oe({type:"text",value:T,output:`\\${T}`});continue}if(C.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(rd("opening","["));oe({type:"text",value:T,output:`\\${T}`});continue}ge("brackets");let z=_.value.slice(1);if(_.posix!==!0&&z[0]==="^"&&!z.includes("/")&&(T=`/${T}`),_.value+=T,dt({value:T}),n.literalBrackets===!1||Zr.hasRegexChars(z))continue;let $e=Zr.escapeRegex(_.value);if(C.output=C.output.slice(0,-_.value.length),n.literalBrackets===!0){C.output+=$e,_.value=$e;continue}_.value=`(${a}${$e}|${_.value})`,C.output+=_.value;continue}if(T==="{"&&n.nobrace!==!0){ye("braces");let z={type:"brace",value:T,output:"(",outputIndex:C.output.length,tokensIndex:C.tokens.length};L.push(z),oe(z);continue}if(T==="}"){let z=L[L.length-1];if(n.nobrace===!0||!z){oe({type:"text",value:T,output:T});continue}let $e=")";if(z.dots===!0){let Ie=s.slice(),et=[];for(let ct=Ie.length-1;ct>=0&&(s.pop(),Ie[ct].type!=="brace");ct--)Ie[ct].type!=="dots"&&et.unshift(Ie[ct].value);$e=xle(et,n),C.backtrack=!0}if(z.comma!==!0&&z.dots!==!0){let Ie=C.output.slice(0,z.outputIndex),et=C.tokens.slice(z.tokensIndex);z.value=z.output="\\{",T=$e="\\}",C.output=Ie;for(let ct of et)C.output+=ct.output||ct.value}oe({type:"brace",value:T,output:$e}),ge("braces"),L.pop();continue}if(T==="|"){q.length>0&&q[q.length-1].conditions++,oe({type:"text",value:T});continue}if(T===","){let z=T,$e=L[L.length-1];$e&&M[M.length-1]==="braces"&&($e.comma=!0,z="|"),oe({type:"comma",value:T,output:z});continue}if(T==="/"){if(_.type==="dot"&&C.index===C.start+1){C.start=C.index+1,C.consumed="",C.output="",s.pop(),_=o;continue}oe({type:"slash",value:T,output:p});continue}if(T==="."){if(C.braces>0&&_.type==="dot"){_.value==="."&&(_.output=u);let z=L[L.length-1];_.type="dots",_.output+=T,_.value+=T,z.dots=!0;continue}if(C.braces+C.parens===0&&_.type!=="bos"&&_.type!=="slash"){oe({type:"text",value:T,output:u});continue}oe({type:"dot",value:T,output:u});continue}if(T==="?"){if(!(_&&_.value==="(")&&n.noextglob!==!0&&ve()==="("&&ve(2)!=="?"){Se("qmark",T);continue}if(_&&_.type==="paren"){let $e=ve(),Ie=T;(_.value==="("&&!/[!=<:]/.test($e)||$e==="<"&&!/<([!=]|\w+>)/.test(be()))&&(Ie=`\\${T}`),oe({type:"text",value:T,output:Ie});continue}if(n.dot!==!0&&(_.type==="slash"||_.type==="bos")){oe({type:"qmark",value:T,output:$});continue}oe({type:"qmark",value:T,output:k});continue}if(T==="!"){if(n.noextglob!==!0&&ve()==="("&&(ve(2)!=="?"||!/[!=<:]/.test(ve(3)))){Se("negate",T);continue}if(n.nonegate!==!0&&C.index===0){ne();continue}}if(T==="+"){if(n.noextglob!==!0&&ve()==="("&&ve(2)!=="?"){Se("plus",T);continue}if(_&&_.value==="("||n.regex===!1){oe({type:"plus",value:T,output:d});continue}if(_&&(_.type==="bracket"||_.type==="paren"||_.type==="brace")||C.parens>0){oe({type:"plus",value:T});continue}oe({type:"plus",value:d});continue}if(T==="@"){if(n.noextglob!==!0&&ve()==="("&&ve(2)!=="?"){oe({type:"at",extglob:!0,value:T,output:""});continue}oe({type:"text",value:T});continue}if(T!=="*"){(T==="$"||T==="^")&&(T=`\\${T}`);let z=vle.exec(be());z&&(T+=z[0],C.index+=z[0].length),oe({type:"text",value:T});continue}if(_&&(_.type==="globstar"||_.star===!0)){_.type="star",_.star=!0,_.value+=T,_.output=B,C.backtrack=!0,C.globstar=!0,Be(T);continue}let te=be();if(n.noextglob!==!0&&/^\([^?]/.test(te)){Se("star",T);continue}if(_.type==="star"){if(n.noglobstar===!0){Be(T);continue}let z=_.prev,$e=z.prev,Ie=z.type==="slash"||z.type==="bos",et=$e&&($e.type==="star"||$e.type==="globstar");if(n.bash===!0&&(!Ie||te[0]&&te[0]!=="/")){oe({type:"star",value:T,output:""});continue}let ct=C.braces>0&&(z.type==="comma"||z.type==="brace"),Vt=q.length&&(z.type==="pipe"||z.type==="paren");if(!Ie&&z.type!=="paren"&&!ct&&!Vt){oe({type:"star",value:T,output:""});continue}for(;te.slice(0,3)==="/**";){let U=e[C.index+4];if(U&&U!=="/")break;te=te.slice(3),Be("/**",3)}if(z.type==="bos"&&W()){_.type="globstar",_.value+=T,_.output=P(n),C.output=_.output,C.globstar=!0,Be(T);continue}if(z.type==="slash"&&z.prev.type!=="bos"&&!et&&W()){C.output=C.output.slice(0,-(z.output+_.output).length),z.output=`(?:${z.output}`,_.type="globstar",_.output=P(n)+(n.strictSlashes?")":"|$)"),_.value+=T,C.globstar=!0,C.output+=z.output+_.output,Be(T);continue}if(z.type==="slash"&&z.prev.type!=="bos"&&te[0]==="/"){let U=te[1]!==void 0?"|$":"";C.output=C.output.slice(0,-(z.output+_.output).length),z.output=`(?:${z.output}`,_.type="globstar",_.output=`${P(n)}${p}|${p}${U})`,_.value+=T,C.output+=z.output+_.output,C.globstar=!0,Be(T+re()),oe({type:"slash",value:"/",output:""});continue}if(z.type==="bos"&&te[0]==="/"){_.type="globstar",_.value+=T,_.output=`(?:^|${p}|${P(n)}${p})`,C.output=_.output,C.globstar=!0,Be(T+re()),oe({type:"slash",value:"/",output:""});continue}C.output=C.output.slice(0,-_.output.length),_.type="globstar",_.output=P(n),_.value+=T,C.output+=_.output,C.globstar=!0,Be(T);continue}let Ve={type:"star",value:T,output:B};if(n.bash===!0){Ve.output=".*?",(_.type==="bos"||_.type==="slash")&&(Ve.output=I+Ve.output),oe(Ve);continue}if(_&&(_.type==="bracket"||_.type==="paren")&&n.regex===!0){Ve.output=T,oe(Ve);continue}(C.index===C.start||_.type==="slash"||_.type==="dot")&&(_.type==="dot"?(C.output+=w,_.output+=w):n.dot===!0?(C.output+=b,_.output+=b):(C.output+=I,_.output+=I),ve()!=="*"&&(C.output+=f,_.output+=f)),oe(Ve)}for(;C.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(rd("closing","]"));C.output=Zr.escapeLast(C.output,"["),ge("brackets")}for(;C.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(rd("closing",")"));C.output=Zr.escapeLast(C.output,"("),ge("parens")}for(;C.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(rd("closing","}"));C.output=Zr.escapeLast(C.output,"{"),ge("braces")}if(n.strictSlashes!==!0&&(_.type==="star"||_.type==="bracket")&&oe({type:"maybe_slash",value:"",output:`${p}?`}),C.backtrack===!0){C.output="";for(let te of C.tokens)C.output+=te.output!=null?te.output:te.value,te.suffix&&(C.output+=te.suffix)}return C};T_.fastpaths=(e,t)=>{let n={...t},i=typeof n.maxLength=="number"?Math.min(gv,n.maxLength):gv,r=e.length;if(r>i)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${i}`);e=dV[e]||e;let{DOT_LITERAL:o,SLASH_LITERAL:s,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:u,NO_DOTS_SLASH:d,STAR:p,START_ANCHOR:f}=bm.globChars(n.windows),g=n.dot?u:l,h=n.dot?d:l,w=n.capture?"":"?:",b={negated:!1,prefix:""},k=n.bash===!0?".*?":p;n.capture&&(k=`(${k})`);let $=I=>I.noglobstar===!0?k:`(${w}(?:(?!${f}${I.dot?c:o}).)*?)`,x=I=>{switch(I){case"*":return`${g}${a}${k}`;case".*":return`${o}${a}${k}`;case"*.*":return`${g}${k}${o}${a}${k}`;case"*/*":return`${g}${k}${s}${a}${h}${k}`;case"**":return g+$(n);case"**/*":return`(?:${g}${$(n)}${s})?${h}${a}${k}`;case"**/*.*":return`(?:${g}${$(n)}${s})?${h}${k}${o}${a}${k}`;case"**/.*":return`(?:${g}${$(n)}${s})?${o}${a}${k}`;default:{let A=/^(.*?)\.(\w+)$/.exec(I);if(!A)return;let B=x(A[1]);return B?B+o+A[2]:void 0}}},R=Zr.removePrefix(e,b),P=x(R);return P&&n.strictSlashes!==!0&&(P+=`${s}?`),P};mV.exports=T_});var wV=ae((xWe,yV)=>{"use strict";var Ale=uV(),I_=gV(),hV=ym(),Ple=hm(),Cle=e=>e&&typeof e=="object"&&!Array.isArray(e),cn=(e,t,n=!1)=>{if(Array.isArray(e)){let u=e.map(p=>cn(p,t,n));return p=>{for(let f of u){let g=f(p);if(g)return g}return!1}}let i=Cle(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!i)throw new TypeError("Expected pattern to be a non-empty string");let r=t||{},o=r.windows,s=i?cn.compileRe(e,t):cn.makeRe(e,t,!1,!0),a=s.state;delete s.state;let c=()=>!1;if(r.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};c=cn(r.ignore,u,n)}let l=(u,d=!1)=>{let{isMatch:p,match:f,output:g}=cn.test(u,s,t,{glob:e,posix:o}),h={glob:e,state:a,regex:s,posix:o,input:u,output:g,match:f,isMatch:p};return typeof r.onResult=="function"&&r.onResult(h),p===!1?(h.isMatch=!1,d?h:!1):c(u)?(typeof r.onIgnore=="function"&&r.onIgnore(h),h.isMatch=!1,d?h:!1):(typeof r.onMatch=="function"&&r.onMatch(h),d?h:!0)};return n&&(l.state=a),l};cn.test=(e,t,n,{glob:i,posix:r}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return{isMatch:!1,output:""};let o=n||{},s=o.format||(r?hV.toPosixSlashes:null),a=e===i,c=a&&s?s(e):e;return a===!1&&(c=s?s(e):e,a=c===i),(a===!1||o.capture===!0)&&(o.matchBase===!0||o.basename===!0?a=cn.matchBase(e,t,n,r):a=t.exec(c)),{isMatch:!!a,match:a,output:c}};cn.matchBase=(e,t,n)=>(t instanceof RegExp?t:cn.makeRe(t,n)).test(hV.basename(e));cn.isMatch=(e,t,n)=>cn(t,n)(e);cn.parse=(e,t)=>Array.isArray(e)?e.map(n=>cn.parse(n,t)):I_(e,{...t,fastpaths:!1});cn.scan=(e,t)=>Ale(e,t);cn.compileRe=(e,t,n=!1,i=!1)=>{if(n===!0)return e.output;let r=t||{},o=r.contains?"":"^",s=r.contains?"":"$",a=`${o}(?:${e.output})${s}`;e&&e.negated===!0&&(a=`^(?!${a}).*$`);let c=cn.toRegex(a,t);return i===!0&&(c.state=e),c};cn.makeRe=(e,t={},n=!1,i=!1)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let r={negated:!1,fastpaths:!0};return t.fastpaths!==!1&&(e[0]==="."||e[0]==="*")&&(r.output=I_.fastpaths(e,t)),r.output||(r=I_(e,t)),cn.compileRe(r,t,n,i)};cn.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?"i":""))}catch(n){if(t&&t.debug===!0)throw n;return/$^/}};cn.constants=Ple;yV.exports=cn});var vm=ae(($We,kV)=>{"use strict";var bV=wV(),_le=ym();function vV(e,t,n=!1){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:_le.isWindows()}),bV(e,t,n)}Object.assign(vV,bV);kV.exports=vV});import{dirname as Tle}from"path";import{fileURLToPath as Ile}from"url";import{createHash as Dle}from"crypto";import{execFile as jle}from"child_process";function j_(){return hv=new D_,hv}function bt(){return hv||j_()}function N_(e){return Tle(Ile(e))}var xV,D_,hv,Oo=v(()=>{"use strict";xV=Ye(vm(),1),D_=class{constructor(){this.name="node";this.hashAlgorithm="sha256";this.commands={runner:"node",exec:"npx",packCmd:["npm","pack"]}}hash(t){return Dle("sha256").update(t).digest("hex")}globMatch(t,n){return(0,xV.default)(t)(n)}async spawn(t,n){return new Promise(i=>{let r=jle(t[0],t.slice(1),{cwd:n?.cwd,maxBuffer:10485760,...n?.env?{env:{...process.env,...n.env}}:{}},(o,s,a)=>{i({stdout:s??"",stderr:a??"",exitCode:o?o.code??1:0})});r.stdin&&(r.stdin.on("error",()=>{}),r.stdin.end(n?.stdin??""))})}}});import{createHmac as Nle,timingSafeEqual as CWe}from"node:crypto";function L_(e=yv){let t=e.toLowerCase();return{signature:`${t}-signature`,timestamp:`${t}-timestamp`,event:`${t}-event`,delivery:`${t}-delivery`}}function M_(e,t,n){return`sha256=${Nle("sha256",e).update(`${String(t)}.${n}`,"utf8").digest("hex")}`}var yv,F_=v(()=>{"use strict";yv="x-chant"});import{createHash as Lle,randomUUID as Mle}from"node:crypto";function Gle(e){let t={};e.CI_JOB_URL?t.url=e.CI_JOB_URL:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?t.url=`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:e.CI_PIPELINE_URL&&(t.url=e.CI_PIPELINE_URL),e.GITLAB_CI==="true"?t.forge="gitlab":e.GITEA_ACTIONS==="true"||e.FORGEJO_ACTIONS==="true"?t.forge="forgejo":e.GITHUB_ACTIONS==="true"&&(t.forge="github");let n=e.GITHUB_REPOSITORY||e.CI_PROJECT_PATH;n&&(t.repository=n);let i=e.GITHUB_SHA||e.CI_COMMIT_SHA;return i&&(t.commit=i),t}function SV(e,t={}){let n=t.env??process.env,{id:i,project:r,targets:o,run:s,...a}=e,c={...Gle(n),...s??{}},l=r??c.repository??"this project",u=e.digest??e.drift?.fingerprint??c.commit,d=i??(u?Lle("sha256").update(JSON.stringify([e.source,l,e.event,e.wave?.number??null,e.environment??null,u])).digest("hex"):Mle());return{schema:Fle,id:d,at:(t.now??new Date).toISOString(),...a,project:l,targets:o??[],...Object.keys(c).length>0?{run:c}:{}}}function EV(e){if(e.summary)return`${e.source}: ${e.summary}`;let t=e.wave?`wave ${e.wave.number}${e.wave.name?` (${e.wave.name})`:""} of ${e.project}`:e.environment?`${e.environment} in ${e.project}`:e.project;return`${e.source}: ${t} ${Wle[e.event]}`}function OV(e){let t=[];return e.approve?.review&&t.push({title:"Review and approve",value:`pull request ${e.approve.review.pr}, then run it again`,link:e.approve.review.url}),e.drift?(e.drift.changed.length>0&&t.push({title:"Drifted",value:e.drift.changed.join(", ")}),e.drift.missing?.length&&t.push({title:"Missing",value:e.drift.missing.join(", ")}),e.drift.failed?.length&&t.push({title:"Not refreshed",value:e.drift.failed.join(", ")})):e.targets.length>0&&t.push({title:"Targets",value:e.targets.join(", ")}),e.digest&&t.push({title:"Digest",value:e.digest}),e.approve&&t.push({title:e.approve.review?"Or approve":"Approve",value:e.approve.command}),e.reason&&t.push({title:"Reason",value:e.reason}),e.run?.url&&t.push({title:"Run",value:e.run.url,link:e.run.url}),e.reportUrl&&t.push({title:"Report",value:e.reportUrl,link:e.reportUrl}),t}function Ble(e){let t=[`*${EV(e)}*`];for(let n of OV(e))n.title==="Review and approve"?t.push(`${n.title}: <${n.link}|pull request ${e.approve.review.pr}>, then run it again`):n.title==="Approve"||n.title==="Or approve"||n.title==="Digest"?t.push(`${n.title}: \`${n.value}\``):n.link?t.push(`${n.title}: <${n.link}>`):t.push(`${n.title}: ${n.value}`);return{text:t.join(`
51
+ `)},x=R2($),R=R2($);g.stdout?.on("data",P=>{x.push(P)}),g.stdout?.on("end",()=>x.flush()),g.stderr?.on("data",P=>{w+=P.toString(),R.push(P)}),g.stderr?.on("end",()=>R.flush()),g.on("message",P=>{if(!h){if(!t(P)){b.push(P);return}h=!0,clearTimeout(k),g.kill(),d(P)}}),g.on("error",P=>{h||(h=!0,clearTimeout(k),p(P))}),bce(g,(P,I)=>{h||(h=!0,clearTimeout(k),p(new Error(yce(c,P,I,w,b))))})})}var wce,E2=v(()=>{"use strict";wce=2e3});var A2={};_e(A2,{evaluateConfigSandboxed:()=>Rce});import{realpathSync as vce,rmSync as kce}from"node:fs";import{resolve as O2}from"node:path";function $ce(e){return typeof e=="object"&&e!==null&&e.kind==="chant-config"&&typeof e.ok=="boolean"}async function Rce(e,t){let n=v2(e),{bundlePath:i,bundleDir:r,externalReadPaths:o,durationMs:s,bytes:a}=await w2(n);try{let c;try{c=vce(O2(t))}catch{c=O2(t)}let l={PATH:process.env.PATH??""},u=process.env[Yu];u&&(l[Yu]=u);let d=await S2({bundlePath:i,bundleDir:r,projectRealpath:c,externalReadPaths:o,env:l,timeoutMs:xce,label:`sandboxed evaluation of ${e}`,outputPrefix:"[sandbox:config]"},$ce);if(!d.ok)throw d.offenders&&d.offenders.length>0?new Error(x2(e,d.offenders)):new Error(d.error?.message?`Failed to evaluate ${e} inside the --sandbox boundary: ${d.error.message}`:`Failed to evaluate ${e} inside the --sandbox boundary`);return{config:d.config??{},bundleMs:s,bundleBytes:a}}finally{kce(r,{recursive:!0,force:!0})}}var xce,P2=v(()=>{"use strict";b2();k2();$2();E2();um();xce=6e4});import{dirname as Sce}from"node:path";function Oce(e){let t=Jr(e);return t.default??t.config??t}async function C2(e,t=Sce(e)){if(!Ece)return Oce(await u2(e));if(c_.has(e))return c_.get(e);let{evaluateConfigSandboxed:n}=await Promise.resolve().then(()=>(P2(),A2)),{config:i}=await n(e,t);return c_.set(e,i),i}var Ece,c_,l_=v(()=>{"use strict";d2();Jc();Ece=!1,c_=new Map});var f_={};_e(f_,{importLexiconModule:()=>Qc,importLexiconPackage:()=>Eo,lexiconDeclarationName:()=>j2,lexiconModulePath:()=>ys,lexiconModuleRoot:()=>p_,lexiconNames:()=>Gi,lexiconPackagesToInstall:()=>jce,lexiconSourceLabel:()=>Dce,packageNameOf:()=>L2,pathLexiconMap:()=>_ce,pathLexiconRoot:()=>uv,recordedLexiconModules:()=>Tce,registerLexiconDeclarations:()=>ua,resetLexiconModules:()=>Ice,resolveFromProject:()=>dv});import{createRequire as I2}from"node:module";import{dirname as Ace,isAbsolute as Xc,join as Pce,relative as D2,resolve as Xu,sep as Cce}from"node:path";import{pathToFileURL as d_}from"node:url";function j2(e){return typeof e=="string"?e:e.name}function Gi(e){return e?.map(j2)}function u_(e,t){let n=D2(t,e);return n===""||!n.startsWith("..")&&!Xc(n)}function uv(e,t,n="."){let i=Xc(e.module)?e.module:Xu(t,e.module),r=e.root!==void 0,o=r?Xc(e.root)?Xu(e.root):Xu(t,e.root):Ace(i),s=Xu(t),a=Xu(t,n),c;return u_(o,s)?u_(a,o)?c=`${o} contains the project's source directory (${a})`:u_(i,o)||(c=`the module ${i} is not inside ${o}`):c=`${o} is outside the project (${s})`,c===void 0?{root:o}:r?{problem:c}:{}}function ua(e,t,n){let i={};for(let r of e??[]){if(typeof r=="string"){la.delete(r),dm.delete(r);continue}let o=N2(r,t);la.set(r.name,o),i[r.name]=o;let{root:s}=uv(r,t,n);s===void 0?dm.delete(r.name):dm.set(r.name,s)}return i}function N2(e,t){return Xc(e.module)?e.module:Xu(t,e.module)}function _ce(e,t){let n=new Map;for(let i of e)typeof i!="string"&&n.set(i.name,N2(i,t));return n}function Tce(){return new Map(la)}function ys(e){return la.get(e)}function p_(e){return dm.get(e)}function Ice(){la.clear(),dm.clear()}async function Qc(e,t={}){let n=la.get(e);if(n!==void 0)try{return(t.typeScript??!sv(n))&&mr(),Jr(await import(n))}catch(i){throw new Error(`lexicon "${e}" is declared with module ${n}, which could not be loaded: `+(i instanceof Error?i.message:String(i)))}}function Dce(e,t=process.cwd(),n=la){let i=n.get(e);if(i===void 0)return`@intentius/chant-lexicon-${e}`;let r=D2(t,i);return r===""||r.startsWith("..")||Xc(r)?i:`./${r.split(Cce).join("/")}`}function jce(e,t=la){return e.filter(n=>!t.has(n)).map(n=>`@intentius/chant-lexicon-${n}`)}function L2(e){if(e.startsWith(".")||Xc(e)||e.startsWith("file:"))return;let t=e.split("/");return e.startsWith("@")?t.slice(0,2).join("/"):t[0]}function _2(e,t){let n=e?.code;if(n!=="ERR_MODULE_NOT_FOUND"&&n!=="MODULE_NOT_FOUND")return!1;let i=e instanceof Error?e.message:String(e);return i.includes(`'${t}'`)||i.includes(`"${t}"`)||i.includes(`${t}/`)}function dv(e,t=process.cwd()){try{return I2(Pce(t,"package.json")).resolve(e)}catch{return}}function Nce(e){if(Xc(e))return d_(e).href;let t=import.meta.resolve;return typeof t=="function"?t(e):d_(I2(import.meta.url).resolve(e)).href}async function Eo(e,t=process.cwd()){let n=L2(e);if(c2()){let i;try{i=Nce(e)}catch(r){if(n===void 0||!_2(r,n))mr();else return T2(e,t,r)}i!==void 0&&av(i)}try{return Jr(await import(e))}catch(i){if(n===void 0||!_2(i,n))throw i;return T2(e,t,i)}}async function T2(e,t,n){let i=dv(e,t);if(i===void 0)throw n;return av(i),Jr(await import(d_(i).href))}var la,dm,nr=v(()=>{"use strict";So();Jc();Kc();la=new Map,dm=new Map});var Lce,Mce,Fce,Qu,M2,pv=v(()=>{"use strict";$n();Lce=m.strictObject({env:m.string().min(1)}),Mce=m.strictObject({capability:m.string().min(1),member:m.string().min(1).optional(),env:m.string().min(1).optional()}),Fce=m.union([Lce,Mce]),Qu=m.strictObject({url:m.string().min(1),key:Fce.optional(),timeoutMs:m.number().int().positive().optional()}),M2=m.strictObject({backends:m.record(m.string(),Qu).optional()})});var m_,g_,Gce,Wce,Bce,F2,G2=v(()=>{"use strict";$n();m_=m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"an environment variable name"),g_=m.union([m.string().min(1),m.literal(!1)]),Gce=m.object({type:m.literal("npm"),packages:m.array(m.string().min(1)).min(1),registry:m.string().url().optional(),access:m.enum(["public","restricted"]).optional(),sbom:g_.optional()}).strict(),Wce=m.object({type:m.literal("oci"),image:m.string().min(1),repository:m.string().min(1),tags:m.array(m.string().min(1)).optional(),usernameEnv:m_.optional(),passwordEnv:m_.optional(),sbom:g_.optional()}).strict(),Bce=m.object({type:m.literal("forge"),forge:m.enum(["github","gitlab","forgejo"]),repo:m.string().min(1),api:m.string().url().optional(),assets:m.array(m.string().min(1)).min(1),tag:m.string().min(1).optional(),tokenEnv:m_.optional(),sbom:g_.optional()}).strict(),F2=m.discriminatedUnion("type",[Gce,Wce,Bce])});var $_={};_e($_,{ChantConfigSchema:()=>fm,DEFAULT_CHANT_CONFIG:()=>v_,InvalidChantConfigError:()=>ed,environmentEndpoint:()=>H2,environmentName:()=>da,environmentNames:()=>w_,findProjectConfigPastFragments:()=>mm,isEnvironmentPattern:()=>td,isLintOnlyFragment:()=>mv,isOwnershipParamRef:()=>K2,loadChantConfig:()=>nd,loadChantConfigUpward:()=>fv,matchesDeclaredEnvironment:()=>pm,matchesEnvironmentPattern:()=>b_,ownershipEnvDisagreement:()=>Hce,resolveAutoReleaseDisabled:()=>qce,resolveDiscoveryGlobs:()=>gm,resolveFoldEnabled:()=>Z2,resolveKnowledgeDir:()=>Yce,resolveOwnershipEnv:()=>x_,resolveOwnershipMarker:()=>J2,resolveOwnershipStack:()=>k_,resolveSandboxEnabled:()=>Y2,resolveSbomFormat:()=>Kce,resolveSigningDefaults:()=>Jce,resolveVulnPolicy:()=>Zce});import{existsSync as W2,readFileSync as U2}from"fs";import{dirname as V2,join as h_}from"path";function da(e){return typeof e=="string"?e:e.name}function w_(e){return e?.map(da)}function td(e){return e.includes("*")}function b_(e,t){let n=e.split("*");if(n.length===1)return e===t;let i=n[0],r=n[n.length-1];if(!t.startsWith(i))return!1;let o=i.length;for(let s=1;s<n.length-1;s++){let a=n[s];if(a==="")continue;let c=t.indexOf(a,o);if(c===-1)return!1;o=c+a.length}return t.length-o>=r.length&&t.endsWith(r)}function pm(e,t){let n=w_(e)??[];return n.includes(t)?!0:n.some(i=>td(i)&&b_(i,t))}function H2(e,t){let n=e?.find(i=>da(i)===t)??e?.find(i=>td(da(i))&&b_(da(i),t));return n&&typeof n!="string"?n.endpoint:void 0}async function nd(e){let t=h_(e,"chant.config.ts");if(W2(t)){let i=await C2(t,e);return{config:z2(i,t),configPath:t}}let n=h_(e,"chant.config.json");if(W2(n)){let{readFileSync:i}=await import("fs"),r=i(n,"utf-8"),o=JSON.parse(r);return{config:z2(o,n),configPath:n}}return{config:v_}}async function fv(e){let{dir:t,configPath:n}=mm(e);return n&&Vce(n),nd(t)}function mm(e){let{dir:t,configPath:n}=am(e);for(;n&&mv(n);){let i=V2(t);if(i===t)break;({dir:t,configPath:n}=am(i))}return{dir:t,configPath:n}}async function gm(e){let{dir:t,configPath:n}=mm(e);if(!n)return;let i;try{({config:i}=await nd(t))}catch(s){if(s instanceof ed&&(s.key==="exclude"||s.key==="include"))throw s;return}let r=i.exclude??[],o=i.include??[];if(!(r.length===0&&o.length===0))return{root:t,exclude:r,include:o}}function mv(e){if(!e.endsWith("chant.config.json"))return!1;try{let t=JSON.parse(U2(e,"utf-8"));if(typeof t!="object"||t===null||Array.isArray(t))return!1;let n=Object.keys(t).filter(i=>!q2(i));return n.length>0&&n.every(i=>y_.has(i))}catch{return!1}}function Vce(e){if(e.endsWith("chant.config.json"))try{let t=JSON.parse(U2(e,"utf-8"));if(typeof t!="object"||t===null||Array.isArray(t))return;let n=Object.keys(t).filter(i=>!q2(i));if(n.some(i=>!y_.has(i))&&!n.some(i=>B2.has(i))){let i=n.filter(r=>!y_.has(r));console.error(`warning: ${e} is being used as the project config, but declares no project-level key (${[...B2].slice(0,4).join(", ")}, \u2026). ${i.length===1?"The key":"The keys"} ${i.map(r=>`"${r}"`).join(", ")} stopped the walk to the real one \u2014 any config above this file is being ignored. Prefix a comment key with "_", or move the key to the project config. (chant #1711)`)}}catch{}}function K2(e){return typeof e=="object"&&e!==null&&typeof e.param=="string"}function k_(e){let t=e.ownership;if(!(!t||!t.stack||t.enabled===!1))return t.stack}function x_(e,t){let n=e.ownership?.env;if(!K2(n))return n;let i=n.param,r=e.buildParams?.[i];if(!r)throw new Error(`ownership.env references build parameter "${i}", which chant.config.ts's buildParams does not declare`);let o=t?.find(s=>s.name===i);if(!o)throw new Error(`ownership.env references build parameter "${i}", which resolved to no value for this build \u2014 pass --param ${i}=<value>${r.env?`, set ${r.env}`:""}, or give it a default`);return String(o.value)}function J2(e,t){let n=k_(e);if(n!==void 0)return{stack:n,env:x_(e,t)}}function Hce(e,t){let n=e.ownership?.env;if(typeof n!="string"||k_(e)===void 0)return;let i=t?.find(r=>r.name==="env");if(!(!i||String(i.value)===n))return`ownership.env is "${n}" but the env build parameter resolved to ${JSON.stringify(i.value)} (${i.source}) \u2014 the ownership marker and params.env disagree about which environment this build is for. Use ownership: { env: { param: "env" } } so the marker follows the parameter.`}function qce(e,t){return t?!0:e.release?.autoRecord===!1}function Z2(e,t){return t!==void 0?t:e.build?.fold!==void 0?e.build.fold:!0}function Y2(e,t){return t?!0:e.build?.sandbox===!0}function Kce(e,t){return t??e.sbom?.format??li}function Jce(e){let t=e.signing,n=t?.keyless!==!1;return{keyless:n,...!n&&t?.key?{key:{key:t.key}}:{},identityPolicyDefaults:{expectedIssuer:t?.oidcIssuer,expectedIdentity:t?.identity,identityIsRegexp:t?.identityIsRegexp,key:t?.keyless===!1?t?.key:void 0}}}function Zce(e){let t=e.vulnPolicy;if(!t)return{};let n={};return t.failSeverity&&(n.failSeverity=t.failSeverity),t.fixableOnly!==void 0&&(n.fixableOnly=t.fixableOnly),t.warnSeverity&&(n.warnSeverity=t.warnSeverity),t.failOnLicense!==void 0&&(n.failOnLicense=t.failOnLicense),t.failOnUnknownSeverity!==void 0&&(n.failOnUnknownSeverity=t.failOnUnknownSeverity),t.failOnKev!==void 0&&(n.failOnKev=t.failOnKev),t.failEpssAtOrAbove!==void 0&&(n.failEpssAtOrAbove=t.failEpssAtOrAbove),t.warnEpssAtOrAbove!==void 0&&(n.warnEpssAtOrAbove=t.warnEpssAtOrAbove),t.exploitabilityFixableOnly!==void 0&&(n.exploitabilityFixableOnly=t.exploitabilityFixableOnly),t.license&&(n.license=t.license),n}function Yce(e,t){return h_(t,e.knowledge?.dir??"knowledge")}function z2(e,t){if(typeof e!="object"||e===null)return v_;let n=fm.safeParse(e);if(!n.success){let a=n.error.issues[0],c=a.path.length>0?a.path.join("."):void 0,l=t?` in ${t}`:"";throw new ed(`Invalid chant config${l}: ${c?`${c}: `:""}${a.message}`,a.path.length>0?String(a.path[0]):void 0)}let i=e.lexicons,r=t!==void 0?V2(t):process.cwd(),o=e.sourceDir;for(let[a,c]of(i??[]).entries()){if(typeof c=="string"||c.root===void 0)continue;let{problem:l}=uv(c,r,o);if(l!==void 0){let u=t?` in ${t}`:"";throw new ed(`Invalid chant config${u}: lexicons.${a}.root: ${l}`,"lexicons")}}let s=ua(i,r,o);return Object.keys(s).length>0?{...e,lexicons:Gi(i),lexiconModules:s}:e}var zce,Uce,fm,v_,y_,q2,B2,ed,zn=v(()=>{"use strict";$n();hs();Mi();l_();nr();pv();G2();zce=m.union([m.string().min(1),m.object({name:m.string().min(1),endpoint:m.string().min(1).optional(),canary:m.boolean().optional()})]),Uce=m.union([m.string().min(1),m.object({name:m.string().min(1),module:m.string().min(1),root:m.string().min(1).optional()}).strict()]),fm=m.object({lexicons:m.array(Uce).optional(),capabilities:m.array(m.string().min(1)).optional(),environments:m.array(zce).optional(),sourceDir:m.string().min(1).optional(),lint:m.record(m.string(),m.unknown()).optional(),ownership:m.object({stack:m.string().min(1).optional(),env:m.union([m.string().min(1),m.object({param:m.string().min(1)})]).optional(),enabled:m.boolean().optional()}).optional(),build:m.object({fold:m.boolean().optional()}).optional(),buildParams:m.record(m.string(),m.object({type:m.enum(["string","number","boolean"]),default:m.union([m.string(),m.number(),m.boolean()]).optional(),enum:m.array(m.union([m.string(),m.number(),m.boolean()])).optional(),env:m.string().min(1).optional(),required:m.boolean().optional(),description:m.string().optional()})).optional(),release:m.object({autoRecord:m.boolean().optional(),publish:m.array(F2).optional()}).optional(),run:m.object({on:m.string().min(1).optional()}).strict().optional(),sbom:m.object({format:m.enum(["spdx","cyclonedx"]).optional(),enabled:m.boolean().optional()}).optional(),signing:m.object({keyless:m.boolean().optional(),oidcIssuer:m.string().min(1).optional(),identity:m.string().min(1).optional(),identityIsRegexp:m.boolean().optional(),key:m.string().min(1).optional()}).optional(),vulnPolicy:m.object({failSeverity:m.enum(["critical","high","medium","low","negligible","unknown"]).optional(),fixableOnly:m.boolean().optional(),warnSeverity:m.enum(["critical","high","medium","low","negligible","unknown"]).optional(),failOnLicense:m.boolean().optional(),failOnUnknownSeverity:m.boolean().optional(),failOnKev:m.boolean().optional(),failEpssAtOrAbove:m.number().min(0).max(1).optional(),warnEpssAtOrAbove:m.number().min(0).max(1).optional(),exploitabilityFixableOnly:m.boolean().optional(),license:m.object({allow:m.array(m.string()).optional(),deny:m.array(m.string()).optional()}).optional(),scanner:m.enum(["grype","trivy"]).optional(),vexSources:m.array(m.string()).optional()}).optional(),knowledge:m.object({dir:m.string().min(1).optional()}).optional(),codegen:m.object({outDir:m.string().min(1).optional()}).strict().optional(),decide:M2.optional(),exclude:m.array(m.string().min(1)).optional(),include:m.array(m.string().min(1)).optional(),rootOnly:m.boolean().optional()}).passthrough(),v_={};y_=new Set(["$schema","extends","rules","overrides","plugins","policies"]),q2=e=>e.startsWith("_");B2=new Set(Object.keys(fm.shape).filter(e=>e!=="lint"));ed=class extends Error{constructor(n,i){super(n);this.key=i}}});var Yu,um=v(()=>{"use strict";zn();Yu="CHANT_ENV"});var hm=ae((wWe,nV)=>{"use strict";var X2="[^\\\\/]",Xce="(?=.)",Q2="[^/]",R_="(?:\\/|$)",eV="(?:^|\\/)",S_=`\\.{1,2}${R_}`,Qce="(?!\\.)",ele=`(?!${eV}${S_})`,tle=`(?!\\.{0,1}${R_})`,nle=`(?!${S_})`,rle="[^.\\/]",ile=`${Q2}*?`,ole="/",tV={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:Xce,QMARK:Q2,END_ANCHOR:R_,DOTS_SLASH:S_,NO_DOT:Qce,NO_DOTS:ele,NO_DOT_SLASH:tle,NO_DOTS_SLASH:nle,QMARK_NO_DOT:rle,STAR:ile,START_ANCHOR:eV,SEP:ole},sle={...tV,SLASH_LITERAL:"[\\\\/]",QMARK:X2,STAR:`${X2}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},ale={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};nV.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:ale,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===!0?sle:tV}}});var ym=ae(_r=>{"use strict";var{REGEX_BACKSLASH:cle,REGEX_REMOVE_BACKSLASH:lle,REGEX_SPECIAL_CHARS:ule,REGEX_SPECIAL_CHARS_GLOBAL:dle}=hm();_r.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);_r.hasRegexChars=e=>ule.test(e);_r.isRegexChar=e=>e.length===1&&_r.hasRegexChars(e);_r.escapeRegex=e=>e.replace(dle,"\\$1");_r.toPosixSlashes=e=>e.replace(cle,"/");_r.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let e=navigator.platform.toLowerCase();return e==="win32"||e==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};_r.removeBackslashes=e=>e.replace(lle,t=>t==="\\"?"":t);_r.escapeLast=(e,t,n)=>{let i=e.lastIndexOf(t,n);return i===-1?e:e[i-1]==="\\"?_r.escapeLast(e,t,i-1):`${e.slice(0,i)}\\${e.slice(i)}`};_r.removePrefix=(e,t={})=>{let n=e;return n.startsWith("./")&&(n=n.slice(2),t.prefix="./"),n};_r.wrapOutput=(e,t={},n={})=>{let i=n.contains?"":"^",r=n.contains?"":"$",o=`${i}(?:${e})${r}`;return t.negated===!0&&(o=`(?:^(?!${o}).*$)`),o};_r.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:"/"),i=n[n.length-1];return i===""?n[n.length-2]:i}});var uV=ae((vWe,lV)=>{"use strict";var rV=ym(),{CHAR_ASTERISK:E_,CHAR_AT:ple,CHAR_BACKWARD_SLASH:wm,CHAR_COMMA:fle,CHAR_DOT:O_,CHAR_EXCLAMATION_MARK:A_,CHAR_FORWARD_SLASH:cV,CHAR_LEFT_CURLY_BRACE:P_,CHAR_LEFT_PARENTHESES:C_,CHAR_LEFT_SQUARE_BRACKET:mle,CHAR_PLUS:gle,CHAR_QUESTION_MARK:iV,CHAR_RIGHT_CURLY_BRACE:hle,CHAR_RIGHT_PARENTHESES:oV,CHAR_RIGHT_SQUARE_BRACKET:yle}=hm(),sV=e=>e===cV||e===wm,aV=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)},wle=(e,t)=>{let n=t||{},i=e.length-1,r=n.parts===!0||n.scanToEnd===!0,o=[],s=[],a=[],c=e,l=-1,u=0,d=0,p=!1,f=!1,g=!1,h=!1,w=!1,b=!1,k=!1,$=!1,x=!1,R=!1,P=0,I,A,B={value:"",depth:0,isGlob:!1},C=()=>l>=i,q=()=>c.charCodeAt(l+1),L=()=>(I=A,c.charCodeAt(++l));for(;l<i;){A=L();let ke;if(A===wm){k=B.backslashes=!0,A=L(),A===P_&&(b=!0);continue}if(b===!0||A===P_){for(P++;C()!==!0&&(A=L());){if(A===wm){k=B.backslashes=!0,L();continue}if(A===P_){P++;continue}if(b!==!0&&A===O_&&(A=L())===O_){if(p=B.isBrace=!0,g=B.isGlob=!0,R=!0,r===!0)continue;break}if(b!==!0&&A===fle){if(p=B.isBrace=!0,g=B.isGlob=!0,R=!0,r===!0)continue;break}if(A===hle&&(P--,P===0)){b=!1,p=B.isBrace=!0,R=!0;break}}if(r===!0)continue;break}if(A===cV){if(o.push(l),s.push(B),B={value:"",depth:0,isGlob:!1},R===!0)continue;if(I===O_&&l===u+1){u+=2;continue}d=l+1;continue}if(n.noext!==!0&&(A===gle||A===ple||A===E_||A===iV||A===A_)===!0&&q()===C_){if(g=B.isGlob=!0,h=B.isExtglob=!0,R=!0,A===A_&&l===u&&(x=!0),r===!0){for(;C()!==!0&&(A=L());){if(A===wm){k=B.backslashes=!0,A=L();continue}if(A===oV){g=B.isGlob=!0,R=!0;break}}continue}break}if(A===E_){if(I===E_&&(w=B.isGlobstar=!0),g=B.isGlob=!0,R=!0,r===!0)continue;break}if(A===iV){if(g=B.isGlob=!0,R=!0,r===!0)continue;break}if(A===mle){for(;C()!==!0&&(ke=L());){if(ke===wm){k=B.backslashes=!0,L();continue}if(ke===yle){f=B.isBracket=!0,g=B.isGlob=!0,R=!0;break}}if(r===!0)continue;break}if(n.nonegate!==!0&&A===A_&&l===u){$=B.negated=!0,u++;continue}if(n.noparen!==!0&&A===C_){if(g=B.isGlob=!0,r===!0){for(;C()!==!0&&(A=L());){if(A===C_){k=B.backslashes=!0,A=L();continue}if(A===oV){R=!0;break}}continue}break}if(g===!0){if(R=!0,r===!0)continue;break}}n.noext===!0&&(h=!1,g=!1);let M=c,_="",T="";u>0&&(_=c.slice(0,u),c=c.slice(u),d-=u),M&&g===!0&&d>0?(M=c.slice(0,d),T=c.slice(d)):g===!0?(M="",T=c):M=c,M&&M!==""&&M!=="/"&&M!==c&&sV(M.charCodeAt(M.length-1))&&(M=M.slice(0,-1)),n.unescape===!0&&(T&&(T=rV.removeBackslashes(T)),M&&k===!0&&(M=rV.removeBackslashes(M)));let W={prefix:_,input:e,start:u,base:M,glob:T,isBrace:p,isBracket:f,isGlob:g,isExtglob:h,isGlobstar:w,negated:$,negatedExtglob:x};if(n.tokens===!0&&(W.maxDepth=0,sV(A)||s.push(B),W.tokens=s),n.parts===!0||n.tokens===!0){let ke;for(let re=0;re<o.length;re++){let be=ke?ke+1:u,Be=o[re],dt=e.slice(be,Be);n.tokens&&(re===0&&u!==0?(s[re].isPrefix=!0,s[re].value=_):s[re].value=dt,aV(s[re]),W.maxDepth+=s[re].depth),(re!==0||dt!=="")&&a.push(dt),ke=Be}if(ke&&ke+1<e.length){let re=e.slice(ke+1);a.push(re),n.tokens&&(s[s.length-1].value=re,aV(s[s.length-1]),W.maxDepth+=s[s.length-1].depth)}W.slashes=o,W.parts=a}return W};lV.exports=wle});var gV=ae((kWe,mV)=>{"use strict";var bm=hm(),Zr=ym(),{MAX_LENGTH:gv,POSIX_REGEX_SOURCE:ble,REGEX_NON_SPECIAL_CHARS:vle,REGEX_SPECIAL_CHARS_BACKREF:kle,REPLACEMENTS:dV}=bm,xle=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let n=`[${e.join("-")}]`;try{new RegExp(n)}catch{return e.map(r=>Zr.escapeRegex(r)).join("..")}return n},rd=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,pV=e=>{let t=[],n=0,i=0,r=0,o="",s=!1;for(let a of e){if(s===!0){o+=a,s=!1;continue}if(a==="\\"){o+=a,s=!0;continue}if(a==='"'){r=r===1?0:1,o+=a;continue}if(r===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")i++;else if(a===")"&&i>0)i--;else if(a==="|"&&i===0){t.push(o),o="";continue}}}o+=a}return t.push(o),t},$le=e=>{let t=!1;for(let n of e){if(t===!0){t=!1;continue}if(n==="\\"){t=!0;continue}if(/[?*+@!()[\]{}]/.test(n))return!1}return!0},fV=e=>{let t=e.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),n=!0);if($le(t))return t.replace(/\\(.)/g,"$1")},Rle=e=>{let t=e.map(fV).filter(Boolean);for(let n=0;n<t.length;n++)for(let i=n+1;i<t.length;i++){let r=t[n],o=t[i],s=r[0];if(!(!s||r!==s.repeat(r.length)||o!==s.repeat(o.length))&&(r===o||r.startsWith(o)||o.startsWith(r)))return!0}return!1},__=(e,t=!0)=>{if(e[0]!=="+"&&e[0]!=="*"||e[1]!=="(")return;let n=0,i=0,r=0,o=!1;for(let s=1;s<e.length;s++){let a=e[s];if(o===!0){o=!1;continue}if(a==="\\"){o=!0;continue}if(a==='"'){r=r===1?0:1;continue}if(r!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){i++;continue}if(a===")"&&(i--,i===0))return t===!0&&s!==e.length-1?void 0:{type:e[0],body:e.slice(2,s),end:s}}}}},Sle=e=>{let t=0,n=[];for(;t<e.length;){let r=__(e.slice(t),!1);if(!r||r.type!=="*")return;let o=pV(r.body).map(a=>a.trim());if(o.length!==1)return;let s=fV(o[0]);if(!s||s.length!==1)return;n.push(s),t+=r.end+1}return n.length<1?void 0:`${n.length===1?Zr.escapeRegex(n[0]):`[${n.map(r=>Zr.escapeRegex(r)).join("")}]`}*`},Ele=e=>{let t=0,n=e.trim(),i=__(n);for(;i;)t++,n=i.body.trim(),i=__(n);return t},Ole=(e,t)=>{if(t.maxExtglobRecursion===!1)return{risky:!1};let n=typeof t.maxExtglobRecursion=="number"?t.maxExtglobRecursion:bm.DEFAULT_MAX_EXTGLOB_RECURSION,i=pV(e).map(r=>r.trim());if(i.length>1&&(i.some(r=>r==="")||i.some(r=>/^[*?]+$/.test(r))||Rle(i)))return{risky:!0};for(let r of i){let o=Sle(r);if(o)return{risky:!0,safeOutput:o};if(Ele(r)>n)return{risky:!0}}return{risky:!1}},T_=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=dV[e]||e;let n={...t},i=typeof n.maxLength=="number"?Math.min(gv,n.maxLength):gv,r=e.length;if(r>i)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${i}`);let o={type:"bos",value:"",output:n.prepend||""},s=[o],a=n.capture?"":"?:",c=bm.globChars(n.windows),l=bm.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:p,ONE_CHAR:f,DOTS_SLASH:g,NO_DOT:h,NO_DOT_SLASH:w,NO_DOTS_SLASH:b,QMARK:k,QMARK_NO_DOT:$,STAR:x,START_ANCHOR:R}=c,P=te=>`(${a}(?:(?!${R}${te.dot?g:u}).)*?)`,I=n.dot?"":h,A=n.dot?k:$,B=n.bash===!0?P(n):x;n.capture&&(B=`(${B})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let C={input:e,index:-1,start:0,dot:n.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:s};e=Zr.removePrefix(e,C),r=e.length;let q=[],L=[],M=[],_=o,T,W=()=>C.index===r-1,ke=C.peek=(te=1)=>e[C.index+te],re=C.advance=()=>e[++C.index]||"",be=()=>e.slice(C.index+1),Be=(te="",Ve=0)=>{C.consumed+=te,C.index+=Ve},dt=te=>{C.output+=te.output!=null?te.output:te.value,Be(te.value)},ne=()=>{let te=1;for(;ke()==="!"&&(ke(2)!=="("||ke(3)==="?");)re(),C.start++,te++;return te%2===0?!1:(C.negated=!0,C.start++,!0)},ye=te=>{C[te]++,M.push(te)},ge=te=>{C[te]--,M.pop()},oe=te=>{if(_.type==="globstar"){let Ve=C.braces>0&&(te.type==="comma"||te.type==="brace"),z=te.extglob===!0||q.length&&(te.type==="pipe"||te.type==="paren");te.type!=="slash"&&te.type!=="paren"&&!Ve&&!z&&(C.output=C.output.slice(0,-_.output.length),_.type="star",_.value="*",_.output=B,C.output+=_.output)}if(q.length&&te.type!=="paren"&&(q[q.length-1].inner+=te.value),(te.value||te.output)&&dt(te),_&&_.type==="text"&&te.type==="text"){_.output=(_.output||_.value)+te.value,_.value+=te.value;return}te.prev=_,s.push(te),_=te},Se=(te,Ve)=>{let z={...l[Ve],conditions:1,inner:""};z.prev=_,z.parens=C.parens,z.output=C.output,z.startIndex=C.index,z.tokensIndex=s.length;let $e=(n.capture?"(":"")+z.open;ye("parens"),oe({type:te,value:Ve,output:C.output?"":f}),oe({type:"paren",extglob:!0,value:re(),output:$e}),q.push(z)},Ne=te=>{let Ve=e.slice(te.startIndex,C.index+1),z=e.slice(te.startIndex+2,C.index),$e=Ole(z,n);if((te.type==="plus"||te.type==="star")&&$e.risky){let ct=$e.safeOutput?(te.output?"":f)+(n.capture?`(${$e.safeOutput})`:$e.safeOutput):void 0,Vt=s[te.tokensIndex];Vt.type="text",Vt.value=Ve,Vt.output=ct||Zr.escapeRegex(Ve);for(let U=te.tokensIndex+1;U<s.length;U++)s[U].value="",s[U].output="",delete s[U].suffix;C.output=te.output+Vt.output,C.backtrack=!0,oe({type:"paren",extglob:!0,value:T,output:""}),ge("parens");return}let Ie=te.close+(n.capture?")":""),et;if(te.type==="negate"){let ct=B;if(te.inner&&te.inner.length>1&&te.inner.includes("/")&&(ct=P(n)),(ct!==B||W()||/^\)+$/.test(be()))&&(Ie=te.close=`)$))${ct}`),te.inner.includes("*")&&(et=be())&&/^\.[^\\/.]+$/.test(et)){let Vt=T_(et,{...t,fastpaths:!1}).output;Ie=te.close=`)${Vt})${ct})`}te.prev.type==="bos"&&(C.negatedExtglob=!0)}oe({type:"paren",extglob:!0,value:T,output:Ie}),ge("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let te=!1,Ve=e.replace(kle,(z,$e,Ie,et,ct,Vt)=>et==="\\"?(te=!0,z):et==="?"?$e?$e+et+(ct?k.repeat(ct.length):""):Vt===0?A+(ct?k.repeat(ct.length):""):k.repeat(Ie.length):et==="."?u.repeat(Ie.length):et==="*"?$e?$e+et+(ct?B:""):B:$e?z:`\\${z}`);return te===!0&&(n.unescape===!0?Ve=Ve.replace(/\\/g,""):Ve=Ve.replace(/\\+/g,z=>z.length%2===0?"\\\\":z?"\\":"")),Ve===e&&n.contains===!0?(C.output=e,C):(C.output=Zr.wrapOutput(Ve,C,t),C)}for(;!W();){if(T=re(),T==="\0")continue;if(T==="\\"){let z=ke();if(z==="/"&&n.bash!==!0||z==="."||z===";")continue;if(!z){T+="\\",oe({type:"text",value:T});continue}let $e=/^\\+/.exec(be()),Ie=0;if($e&&$e[0].length>2&&(Ie=$e[0].length,C.index+=Ie,Ie%2!==0&&(T+="\\")),n.unescape===!0?T=re():T+=re(),C.brackets===0){oe({type:"text",value:T});continue}}if(C.brackets>0&&(T!=="]"||_.value==="["||_.value==="[^")){if(n.posix!==!1&&T===":"){let z=_.value.slice(1);if(z.includes("[")&&(_.posix=!0,z.includes(":"))){let $e=_.value.lastIndexOf("["),Ie=_.value.slice(0,$e),et=_.value.slice($e+2),ct=ble[et];if(ct){_.value=Ie+ct,C.backtrack=!0,re(),!o.output&&s.indexOf(_)===1&&(o.output=f);continue}}}(T==="["&&ke()!==":"||T==="-"&&ke()==="]")&&(T=`\\${T}`),T==="]"&&(_.value==="["||_.value==="[^")&&(T=`\\${T}`),n.posix===!0&&T==="!"&&_.value==="["&&(T="^"),_.value+=T,dt({value:T});continue}if(C.quotes===1&&T!=='"'){T=Zr.escapeRegex(T),_.value+=T,dt({value:T});continue}if(T==='"'){C.quotes=C.quotes===1?0:1,n.keepQuotes===!0&&oe({type:"text",value:T});continue}if(T==="("){ye("parens"),oe({type:"paren",value:T});continue}if(T===")"){if(C.parens===0&&n.strictBrackets===!0)throw new SyntaxError(rd("opening","("));let z=q[q.length-1];if(z&&C.parens===z.parens+1){Ne(q.pop());continue}oe({type:"paren",value:T,output:C.parens?")":"\\)"}),ge("parens");continue}if(T==="["){if(n.nobracket===!0||!be().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(rd("closing","]"));T=`\\${T}`}else ye("brackets");oe({type:"bracket",value:T});continue}if(T==="]"){if(n.nobracket===!0||_&&_.type==="bracket"&&_.value.length===1){oe({type:"text",value:T,output:`\\${T}`});continue}if(C.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(rd("opening","["));oe({type:"text",value:T,output:`\\${T}`});continue}ge("brackets");let z=_.value.slice(1);if(_.posix!==!0&&z[0]==="^"&&!z.includes("/")&&(T=`/${T}`),_.value+=T,dt({value:T}),n.literalBrackets===!1||Zr.hasRegexChars(z))continue;let $e=Zr.escapeRegex(_.value);if(C.output=C.output.slice(0,-_.value.length),n.literalBrackets===!0){C.output+=$e,_.value=$e;continue}_.value=`(${a}${$e}|${_.value})`,C.output+=_.value;continue}if(T==="{"&&n.nobrace!==!0){ye("braces");let z={type:"brace",value:T,output:"(",outputIndex:C.output.length,tokensIndex:C.tokens.length};L.push(z),oe(z);continue}if(T==="}"){let z=L[L.length-1];if(n.nobrace===!0||!z){oe({type:"text",value:T,output:T});continue}let $e=")";if(z.dots===!0){let Ie=s.slice(),et=[];for(let ct=Ie.length-1;ct>=0&&(s.pop(),Ie[ct].type!=="brace");ct--)Ie[ct].type!=="dots"&&et.unshift(Ie[ct].value);$e=xle(et,n),C.backtrack=!0}if(z.comma!==!0&&z.dots!==!0){let Ie=C.output.slice(0,z.outputIndex),et=C.tokens.slice(z.tokensIndex);z.value=z.output="\\{",T=$e="\\}",C.output=Ie;for(let ct of et)C.output+=ct.output||ct.value}oe({type:"brace",value:T,output:$e}),ge("braces"),L.pop();continue}if(T==="|"){q.length>0&&q[q.length-1].conditions++,oe({type:"text",value:T});continue}if(T===","){let z=T,$e=L[L.length-1];$e&&M[M.length-1]==="braces"&&($e.comma=!0,z="|"),oe({type:"comma",value:T,output:z});continue}if(T==="/"){if(_.type==="dot"&&C.index===C.start+1){C.start=C.index+1,C.consumed="",C.output="",s.pop(),_=o;continue}oe({type:"slash",value:T,output:p});continue}if(T==="."){if(C.braces>0&&_.type==="dot"){_.value==="."&&(_.output=u);let z=L[L.length-1];_.type="dots",_.output+=T,_.value+=T,z.dots=!0;continue}if(C.braces+C.parens===0&&_.type!=="bos"&&_.type!=="slash"){oe({type:"text",value:T,output:u});continue}oe({type:"dot",value:T,output:u});continue}if(T==="?"){if(!(_&&_.value==="(")&&n.noextglob!==!0&&ke()==="("&&ke(2)!=="?"){Se("qmark",T);continue}if(_&&_.type==="paren"){let $e=ke(),Ie=T;(_.value==="("&&!/[!=<:]/.test($e)||$e==="<"&&!/<([!=]|\w+>)/.test(be()))&&(Ie=`\\${T}`),oe({type:"text",value:T,output:Ie});continue}if(n.dot!==!0&&(_.type==="slash"||_.type==="bos")){oe({type:"qmark",value:T,output:$});continue}oe({type:"qmark",value:T,output:k});continue}if(T==="!"){if(n.noextglob!==!0&&ke()==="("&&(ke(2)!=="?"||!/[!=<:]/.test(ke(3)))){Se("negate",T);continue}if(n.nonegate!==!0&&C.index===0){ne();continue}}if(T==="+"){if(n.noextglob!==!0&&ke()==="("&&ke(2)!=="?"){Se("plus",T);continue}if(_&&_.value==="("||n.regex===!1){oe({type:"plus",value:T,output:d});continue}if(_&&(_.type==="bracket"||_.type==="paren"||_.type==="brace")||C.parens>0){oe({type:"plus",value:T});continue}oe({type:"plus",value:d});continue}if(T==="@"){if(n.noextglob!==!0&&ke()==="("&&ke(2)!=="?"){oe({type:"at",extglob:!0,value:T,output:""});continue}oe({type:"text",value:T});continue}if(T!=="*"){(T==="$"||T==="^")&&(T=`\\${T}`);let z=vle.exec(be());z&&(T+=z[0],C.index+=z[0].length),oe({type:"text",value:T});continue}if(_&&(_.type==="globstar"||_.star===!0)){_.type="star",_.star=!0,_.value+=T,_.output=B,C.backtrack=!0,C.globstar=!0,Be(T);continue}let te=be();if(n.noextglob!==!0&&/^\([^?]/.test(te)){Se("star",T);continue}if(_.type==="star"){if(n.noglobstar===!0){Be(T);continue}let z=_.prev,$e=z.prev,Ie=z.type==="slash"||z.type==="bos",et=$e&&($e.type==="star"||$e.type==="globstar");if(n.bash===!0&&(!Ie||te[0]&&te[0]!=="/")){oe({type:"star",value:T,output:""});continue}let ct=C.braces>0&&(z.type==="comma"||z.type==="brace"),Vt=q.length&&(z.type==="pipe"||z.type==="paren");if(!Ie&&z.type!=="paren"&&!ct&&!Vt){oe({type:"star",value:T,output:""});continue}for(;te.slice(0,3)==="/**";){let U=e[C.index+4];if(U&&U!=="/")break;te=te.slice(3),Be("/**",3)}if(z.type==="bos"&&W()){_.type="globstar",_.value+=T,_.output=P(n),C.output=_.output,C.globstar=!0,Be(T);continue}if(z.type==="slash"&&z.prev.type!=="bos"&&!et&&W()){C.output=C.output.slice(0,-(z.output+_.output).length),z.output=`(?:${z.output}`,_.type="globstar",_.output=P(n)+(n.strictSlashes?")":"|$)"),_.value+=T,C.globstar=!0,C.output+=z.output+_.output,Be(T);continue}if(z.type==="slash"&&z.prev.type!=="bos"&&te[0]==="/"){let U=te[1]!==void 0?"|$":"";C.output=C.output.slice(0,-(z.output+_.output).length),z.output=`(?:${z.output}`,_.type="globstar",_.output=`${P(n)}${p}|${p}${U})`,_.value+=T,C.output+=z.output+_.output,C.globstar=!0,Be(T+re()),oe({type:"slash",value:"/",output:""});continue}if(z.type==="bos"&&te[0]==="/"){_.type="globstar",_.value+=T,_.output=`(?:^|${p}|${P(n)}${p})`,C.output=_.output,C.globstar=!0,Be(T+re()),oe({type:"slash",value:"/",output:""});continue}C.output=C.output.slice(0,-_.output.length),_.type="globstar",_.output=P(n),_.value+=T,C.output+=_.output,C.globstar=!0,Be(T);continue}let Ve={type:"star",value:T,output:B};if(n.bash===!0){Ve.output=".*?",(_.type==="bos"||_.type==="slash")&&(Ve.output=I+Ve.output),oe(Ve);continue}if(_&&(_.type==="bracket"||_.type==="paren")&&n.regex===!0){Ve.output=T,oe(Ve);continue}(C.index===C.start||_.type==="slash"||_.type==="dot")&&(_.type==="dot"?(C.output+=w,_.output+=w):n.dot===!0?(C.output+=b,_.output+=b):(C.output+=I,_.output+=I),ke()!=="*"&&(C.output+=f,_.output+=f)),oe(Ve)}for(;C.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(rd("closing","]"));C.output=Zr.escapeLast(C.output,"["),ge("brackets")}for(;C.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(rd("closing",")"));C.output=Zr.escapeLast(C.output,"("),ge("parens")}for(;C.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(rd("closing","}"));C.output=Zr.escapeLast(C.output,"{"),ge("braces")}if(n.strictSlashes!==!0&&(_.type==="star"||_.type==="bracket")&&oe({type:"maybe_slash",value:"",output:`${p}?`}),C.backtrack===!0){C.output="";for(let te of C.tokens)C.output+=te.output!=null?te.output:te.value,te.suffix&&(C.output+=te.suffix)}return C};T_.fastpaths=(e,t)=>{let n={...t},i=typeof n.maxLength=="number"?Math.min(gv,n.maxLength):gv,r=e.length;if(r>i)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${i}`);e=dV[e]||e;let{DOT_LITERAL:o,SLASH_LITERAL:s,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:u,NO_DOTS_SLASH:d,STAR:p,START_ANCHOR:f}=bm.globChars(n.windows),g=n.dot?u:l,h=n.dot?d:l,w=n.capture?"":"?:",b={negated:!1,prefix:""},k=n.bash===!0?".*?":p;n.capture&&(k=`(${k})`);let $=I=>I.noglobstar===!0?k:`(${w}(?:(?!${f}${I.dot?c:o}).)*?)`,x=I=>{switch(I){case"*":return`${g}${a}${k}`;case".*":return`${o}${a}${k}`;case"*.*":return`${g}${k}${o}${a}${k}`;case"*/*":return`${g}${k}${s}${a}${h}${k}`;case"**":return g+$(n);case"**/*":return`(?:${g}${$(n)}${s})?${h}${a}${k}`;case"**/*.*":return`(?:${g}${$(n)}${s})?${h}${k}${o}${a}${k}`;case"**/.*":return`(?:${g}${$(n)}${s})?${o}${a}${k}`;default:{let A=/^(.*?)\.(\w+)$/.exec(I);if(!A)return;let B=x(A[1]);return B?B+o+A[2]:void 0}}},R=Zr.removePrefix(e,b),P=x(R);return P&&n.strictSlashes!==!0&&(P+=`${s}?`),P};mV.exports=T_});var wV=ae((xWe,yV)=>{"use strict";var Ale=uV(),I_=gV(),hV=ym(),Ple=hm(),Cle=e=>e&&typeof e=="object"&&!Array.isArray(e),cn=(e,t,n=!1)=>{if(Array.isArray(e)){let u=e.map(p=>cn(p,t,n));return p=>{for(let f of u){let g=f(p);if(g)return g}return!1}}let i=Cle(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!i)throw new TypeError("Expected pattern to be a non-empty string");let r=t||{},o=r.windows,s=i?cn.compileRe(e,t):cn.makeRe(e,t,!1,!0),a=s.state;delete s.state;let c=()=>!1;if(r.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};c=cn(r.ignore,u,n)}let l=(u,d=!1)=>{let{isMatch:p,match:f,output:g}=cn.test(u,s,t,{glob:e,posix:o}),h={glob:e,state:a,regex:s,posix:o,input:u,output:g,match:f,isMatch:p};return typeof r.onResult=="function"&&r.onResult(h),p===!1?(h.isMatch=!1,d?h:!1):c(u)?(typeof r.onIgnore=="function"&&r.onIgnore(h),h.isMatch=!1,d?h:!1):(typeof r.onMatch=="function"&&r.onMatch(h),d?h:!0)};return n&&(l.state=a),l};cn.test=(e,t,n,{glob:i,posix:r}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return{isMatch:!1,output:""};let o=n||{},s=o.format||(r?hV.toPosixSlashes:null),a=e===i,c=a&&s?s(e):e;return a===!1&&(c=s?s(e):e,a=c===i),(a===!1||o.capture===!0)&&(o.matchBase===!0||o.basename===!0?a=cn.matchBase(e,t,n,r):a=t.exec(c)),{isMatch:!!a,match:a,output:c}};cn.matchBase=(e,t,n)=>(t instanceof RegExp?t:cn.makeRe(t,n)).test(hV.basename(e));cn.isMatch=(e,t,n)=>cn(t,n)(e);cn.parse=(e,t)=>Array.isArray(e)?e.map(n=>cn.parse(n,t)):I_(e,{...t,fastpaths:!1});cn.scan=(e,t)=>Ale(e,t);cn.compileRe=(e,t,n=!1,i=!1)=>{if(n===!0)return e.output;let r=t||{},o=r.contains?"":"^",s=r.contains?"":"$",a=`${o}(?:${e.output})${s}`;e&&e.negated===!0&&(a=`^(?!${a}).*$`);let c=cn.toRegex(a,t);return i===!0&&(c.state=e),c};cn.makeRe=(e,t={},n=!1,i=!1)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let r={negated:!1,fastpaths:!0};return t.fastpaths!==!1&&(e[0]==="."||e[0]==="*")&&(r.output=I_.fastpaths(e,t)),r.output||(r=I_(e,t)),cn.compileRe(r,t,n,i)};cn.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?"i":""))}catch(n){if(t&&t.debug===!0)throw n;return/$^/}};cn.constants=Ple;yV.exports=cn});var vm=ae(($We,kV)=>{"use strict";var bV=wV(),_le=ym();function vV(e,t,n=!1){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:_le.isWindows()}),bV(e,t,n)}Object.assign(vV,bV);kV.exports=vV});import{dirname as Tle}from"path";import{fileURLToPath as Ile}from"url";import{createHash as Dle}from"crypto";import{execFile as jle}from"child_process";function j_(){return hv=new D_,hv}function bt(){return hv||j_()}function N_(e){return Tle(Ile(e))}var xV,D_,hv,Oo=v(()=>{"use strict";xV=Ye(vm(),1),D_=class{constructor(){this.name="node";this.hashAlgorithm="sha256";this.commands={runner:"node",exec:"npx",packCmd:["npm","pack"]}}hash(t){return Dle("sha256").update(t).digest("hex")}globMatch(t,n){return(0,xV.default)(t)(n)}async spawn(t,n){return new Promise(i=>{let r=jle(t[0],t.slice(1),{cwd:n?.cwd,maxBuffer:10485760,...n?.env?{env:{...process.env,...n.env}}:{}},(o,s,a)=>{i({stdout:s??"",stderr:a??"",exitCode:o?o.code??1:0})});r.stdin&&(r.stdin.on("error",()=>{}),r.stdin.end(n?.stdin??""))})}}});import{createHmac as Nle,timingSafeEqual as CWe}from"node:crypto";function L_(e=yv){let t=e.toLowerCase();return{signature:`${t}-signature`,timestamp:`${t}-timestamp`,event:`${t}-event`,delivery:`${t}-delivery`}}function M_(e,t,n){return`sha256=${Nle("sha256",e).update(`${String(t)}.${n}`,"utf8").digest("hex")}`}var yv,F_=v(()=>{"use strict";yv="x-chant"});import{createHash as Lle,randomUUID as Mle}from"node:crypto";function Gle(e){let t={};e.CI_JOB_URL?t.url=e.CI_JOB_URL:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?t.url=`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:e.CI_PIPELINE_URL&&(t.url=e.CI_PIPELINE_URL),e.GITLAB_CI==="true"?t.forge="gitlab":e.GITEA_ACTIONS==="true"||e.FORGEJO_ACTIONS==="true"?t.forge="forgejo":e.GITHUB_ACTIONS==="true"&&(t.forge="github");let n=e.GITHUB_REPOSITORY||e.CI_PROJECT_PATH;n&&(t.repository=n);let i=e.GITHUB_SHA||e.CI_COMMIT_SHA;return i&&(t.commit=i),t}function SV(e,t={}){let n=t.env??process.env,{id:i,project:r,targets:o,run:s,...a}=e,c={...Gle(n),...s??{}},l=r??c.repository??"this project",u=e.digest??e.drift?.fingerprint??c.commit,d=i??(u?Lle("sha256").update(JSON.stringify([e.source,l,e.event,e.wave?.number??null,e.environment??null,u])).digest("hex"):Mle());return{schema:Fle,id:d,at:(t.now??new Date).toISOString(),...a,project:l,targets:o??[],...Object.keys(c).length>0?{run:c}:{}}}function EV(e){if(e.summary)return`${e.source}: ${e.summary}`;let t=e.wave?`wave ${e.wave.number}${e.wave.name?` (${e.wave.name})`:""} of ${e.project}`:e.environment?`${e.environment} in ${e.project}`:e.project;return`${e.source}: ${t} ${Wle[e.event]}`}function OV(e){let t=[];return e.approve?.review&&t.push({title:"Review and approve",value:`pull request ${e.approve.review.pr}, then run it again`,link:e.approve.review.url}),e.drift?(e.drift.changed.length>0&&t.push({title:"Drifted",value:e.drift.changed.join(", ")}),e.drift.missing?.length&&t.push({title:"Missing",value:e.drift.missing.join(", ")}),e.drift.failed?.length&&t.push({title:"Not refreshed",value:e.drift.failed.join(", ")})):e.targets.length>0&&t.push({title:"Targets",value:e.targets.join(", ")}),e.digest&&t.push({title:"Digest",value:e.digest}),e.approve&&t.push({title:e.approve.review?"Or approve":"Approve",value:e.approve.command}),e.reason&&t.push({title:"Reason",value:e.reason}),e.run?.url&&t.push({title:"Run",value:e.run.url,link:e.run.url}),e.reportUrl&&t.push({title:"Report",value:e.reportUrl,link:e.reportUrl}),t}function Ble(e){let t=[`*${EV(e)}*`];for(let n of OV(e))n.title==="Review and approve"?t.push(`${n.title}: <${n.link}|pull request ${e.approve.review.pr}>, then run it again`):n.title==="Approve"||n.title==="Or approve"||n.title==="Digest"?t.push(`${n.title}: \`${n.value}\``):n.link?t.push(`${n.title}: <${n.link}>`):t.push(`${n.title}: ${n.value}`);return{text:t.join(`
52
52
  `)}}function zle(e){let t=OV(e),n=[...e.approve?.review?[{type:"Action.OpenUrl",title:"Review and approve",url:e.approve.review.url}]:[],...e.run?.url?[{type:"Action.OpenUrl",title:"Open the run",url:e.run.url}]:[]];return{type:"message",attachments:[{contentType:"application/vnd.microsoft.card.adaptive",contentUrl:null,content:{$schema:"http://adaptivecards.io/schemas/adaptive-card.json",type:"AdaptiveCard",version:"1.4",body:[{type:"TextBlock",text:EV(e),weight:"Bolder",wrap:!0},{type:"FactSet",facts:t.map(i=>({title:i.title,value:i.link&&i.title==="Review and approve"?`${i.value}: ${i.link}`:i.value}))}],...n.length>0?{actions:n}:{}}}]}}function wv(e,t="notify"){if(typeof e!="object"||e===null||Array.isArray(e))return`${t}: expected { webhook, key, slack, teams, events }`;let n=e;for(let i of Object.keys(n))if(!RV.includes(i))return`${t}.${i}: unknown setting (expected ${RV.join(", ")})`;for(let i of["webhook","key","slack","teams"]){let r=n[i];if(r!==void 0&&(typeof r!="string"||!Ule.test(r)))return`${t}.${i}: the name of the environment variable that holds the ${i==="key"?"signing key":"URL"}, never the ${i==="key"?"key":"URL"} itself`}if(n.webhook!==void 0&&n.key===void 0)return`${t}.key: a webhook needs a signing key; name the variable that holds it`;if(n.key!==void 0&&n.webhook===void 0)return`${t}.webhook: a key is for a webhook; name the variable that holds its URL`;if(n.webhook===void 0&&n.slack===void 0&&n.teams===void 0)return`${t}: name a webhook (with its key), a slack or a teams URL variable`;if(n.events!==void 0&&!(Array.isArray(n.events)&&n.events.every(i=>$V.includes(i))))return`${t}.events: a list of ${$V.join(", ")}`}function Vle(e,t,n={}){let i=JSON.stringify(e),r=n.now??Math.floor(Date.now()/1e3),o=L_(n.prefix??yv);return{body:i,headers:{"content-type":"application/json","user-agent":n.userAgent??e.source,[o.event]:e.event,[o.delivery]:e.id,[o.timestamp]:String(r),[o.signature]:M_(t,r,i)}}}function AV(e,t){let n=e;for(let i of t)i&&(n=n.split(i).join("<url>"));return n.replace(/https?:\/\/\S+/g,"<url>")}async function Hle(e,t,n,i,r){let o="not attempted";for(let s=0;s<i;s++){s>0&&await r(500*s);try{let a=await e(t,{method:"POST",...n,signal:AbortSignal.timeout(1e4)});if(a.ok)return;if(o=`HTTP ${String(a.status)}`,a.status<500)return o}catch(a){o=AV(a instanceof Error?a.message:String(a),[t])}}return o}async function PV(e,t,n={}){if(!e||!t)return[];if(e.events&&!e.events.includes(t.event))return[];let i=n.env??process.env,r=n.fetch??((d,p)=>globalThis.fetch(d,p)),o=Math.max(1,n.attempts??3),s=n.sleep??(d=>new Promise(p=>setTimeout(p,d))),a=n.log??(d=>process.stderr.write(d+`
53
53
  `)),c=[],l=async(d,p,f)=>{let g;try{let h=i[p];if(!h)g={target:d,ok:!1,detail:`${p} is not set`};else{let w=f();if(typeof w=="string")g={target:d,ok:!1,detail:w};else{let b=await Hle(r,h,w,o,s);g={target:d,ok:b===void 0,detail:b??"delivered"}}}}catch(h){g={target:d,ok:!1,detail:AV(h instanceof Error?h.message:String(h),[i[p]??""])}}g.ok||a(`notify: the ${t.event} event was not delivered to ${qle[d]}: ${g.detail}`),c.push(g)},u=d=>({headers:{"content-type":"application/json"},body:JSON.stringify(d)});return e.webhook&&await l("webhook",e.webhook,()=>{let d=e.key?i[e.key]:void 0;return d?Vle(t,d,{...n.now!==void 0?{now:n.now}:{},...n.prefix?{prefix:n.prefix}:{},...n.userAgent?{userAgent:n.userAgent}:{}}):`${e.key??"the key variable"} is not set, and an event is never sent unsigned`}),e.slack&&await l("slack",e.slack,()=>u((n.render?.slack??Ble)(t))),e.teams&&await l("teams",e.teams,()=>u((n.render?.teams??zle)(t))),c}var Fle,$V,Wle,Ule,RV,qle,bv=v(()=>{"use strict";F_();F_();Fle="chant.notify/v1",$V=["waiting","refused","failed","drift"];Wle={waiting:"waits for an approval",refused:"was refused",failed:"failed",drift:"drifted"};Ule=/^[A-Za-z_][A-Za-z0-9_]*$/,RV=["webhook","key","slack","teams","events"];qle={webhook:"the webhook",slack:"Slack",teams:"Teams"}});function CV(e,t,n,i={}){let o=e.waves[t-1]?.name,s=`wave ${t}${o?` (${o})`:""} of ${e.name}`;if(n.error!==void 0)return{source:"chant",event:"failed",summary:`${s} failed`,wave:{number:t,...o?{name:o}:{}},targets:[],reason:n.error,exitCode:1};let{result:a}=n,c=a.decision,l={source:"chant",wave:{number:t,...o?{name:o}:{},...c?.gate?{gate:c.gate}:{}},...c?.digest?{digest:c.digest}:{},exitCode:a.exitCode};if(a.exitCode===3){if(!c)return;let u=a.hooks.filter(p=>p.outcome==="held");if((i.share!==void 0||i.group!==void 0)&&u.length===0)return;let d=c.review?.pr!==void 0&&c.review.url?{review:{pr:c.review.pr,url:c.review.url}}:{};return{...l,event:"waiting",status:"waiting",summary:`${s} waits for an approval`,targets:c.members.map(p=>p.member),approve:{command:c.approve??`chant approve ${c.op} ${c.gate} --plan ${c.digest}`,...d},...c.heldOn?{reason:`held on ${c.heldOn.op} / ${c.heldOn.gate} by ${c.heldOn.hook}`}:c.heldBy?.length?{reason:`held by ${c.heldBy.join(", ")}`}:c.review?.reason?{reason:c.review.reason}:{}}}if(a.exitCode===8&&c?.refused?.reason==="point")return{...l,event:"refused",status:"point",summary:`${s} refused: decision point ${c.point?.name??""} answered ${JSON.stringify(c.point?.answer?.answer??null)}`,targets:c.refused.runs,...c.refused.message?{reason:c.refused.message}:{}};if(a.exitCode===7&&c?.refused)return{...l,event:"refused",status:c.refused.reason==="override-moved"?"override-moved":"denied",summary:`${s} refused: the policy denied ${c.refused.runs.join(", ")}`,targets:c.refused.runs,reason:c.refused.reason==="override-moved"?"an override stands for an earlier plan or other rules, so it counts for nothing":"the policy denied these runs, and no override counts for them"};if(!(a.exitCode===6&&a.outcome?.outcome==="stood-down")){if(a.exitCode===5&&a.outcome?.outcome==="held"){let u=a.outcome.holder;return{...l,event:"refused",status:"held",summary:`${s} applied nothing: another run${u?` (${u.run})`:""} holds what it changes`,targets:c?.members.map(d=>d.member)??[],reason:a.outcome.reason??`another run${u?`, ${u.run},`:""} holds what the apply changes; apply again once it is done`}}if(a.exitCode===4)return{...l,event:"refused",status:"moved",summary:`${s}${Kle(i)} refused ${a.moved.length} run${a.moved.length===1?"":"s"} whose plan moved since the wave was decided`,targets:a.moved,reason:"their plans moved since the wave was decided, so they were not applied"};if(a.exitCode!==0){let u=a.hooks.filter(d=>d.outcome==="failed").map(d=>`${d.moment} hook ${d.name}${d.target?` (${d.target})`:""}`);return a.failed.length===0&&u.length>0?{...l,event:"failed",status:"failed",summary:`${s} failed: ${u.join(", ")} failed`,targets:[],reason:`${u.join(", ")} exited non-zero`}:{...l,event:"failed",status:"failed",summary:`${s} failed: ${a.failed.length>0?`${a.failed.join(", ")} did not apply`:`exit ${a.exitCode}`}`,targets:a.failed,...a.failed.length>0?{reason:`the apply command failed for ${a.failed.join(", ")}`}:{}}}}}function Kle(e){return e.group!==void 0?`, ${e.share!==void 0?`share ${e.share} of `:""}job group ${e.group},`:e.share!==void 0?`, share ${e.share},`:""}async function vv(e,t,n,i={},r={}){if(!e.notify||wv(e.notify)!==void 0)return[];try{let o=CV(e,t,n,i);return o?await PV(e.notify,SV(o,{...r.env?{env:r.env}:{}}),r):[]}catch(o){return(r.log??(s=>process.stderr.write(s+`
54
- `)))(`notify: nothing was sent: ${o instanceof Error?o.message:String(o)}`),[]}}var G_=v(()=>{"use strict";bv()});var TV={};_e(TV,{DEPRECATED_GATE_KEY_WARNING:()=>_V,FAN_OUT_GATE_OP:()=>id,OVERRIDE_GATE_OP:()=>pa,RELEASE_GATE_OP:()=>ui,WORKSPACE_UPGRADE_GATE_OP:()=>od,gateName:()=>fa,isNeverOverMcpGateOp:()=>W_,opUsesDeprecatedGateKey:()=>Zle,usesDeprecatedGateKey:()=>B_});function W_(e){return e===id||e===od||e===pa||e===ui||Jle.test(e)}function fa(e){return e.gate??e.signalName??""}function B_(e){return e.gate===void 0&&typeof e.signalName=="string"}function Zle(e){let t=i=>i.kind==="gate"?B_(i):i.kind==="effect"?i.steps.some(t):!1,n=i=>(i??[]).some(r=>r.steps.some(t));return n(e.phases)||n(e.onFailure)}var id,od,pa,ui,Jle,_V,Yr=v(()=>{"use strict";id="fan-out",od="workspace-upgrade",pa="policy-override",ui="release",Jle=/^pr-\d+(?:-[a-z0-9][a-z0-9-]*)?$/;_V='Gate steps still using "signalName": the key is now "gate" (chant #2202). "signalName" is accepted through 0.59.0 and removed in 0.60.0.'});function sd(e){return typeof e=="object"&&e!==null&&ma in e&&e[ma]===!0}var ma,ws=v(()=>{"use strict";ma=Symbol.for("chant.intrinsic")});var IV,ga,ad=v(()=>{"use strict";ws();ga=class{constructor(t,n){this[IV]=!0;this.parent=new WeakRef(t),this.attribute=n}_setLogicalName(t){this.logicalName=t}getLogicalName(){return this.logicalName}toString(){let t=this.logicalName?`${this.logicalName}.${this.attribute}`:`.${this.attribute}`;throw new Error(`A resource attribute reference (${t}) has no string form: it stands for a value the build resolves later, and interpolating it into a plain template literal would produce "[object Object]". Use the lexicon's own intrinsic, whose interior handles references \u2014 \`Sub\`\${\u2026}\`\` for CloudFormation \u2014 or move the reference out of the template.`)}[(IV=ma,Symbol.toPrimitive)](){return this.toString()}toJSON(){if(!this.logicalName)throw new Error(`Cannot serialize AttrRef for attribute "${this.attribute}": logical name not set`);return{__attrRef:{entity:this.logicalName,attribute:this.attribute}}}}});function Wi(e){return e instanceof ga?!0:typeof e=="object"&&e!==null&&"parent"in e&&"attribute"in e&&"_setLogicalName"in e&&typeof e.parent=="object"&&typeof e.attribute=="string"}function Gt(e,t){return t&&typeof t=="object"&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([n],[i])=>n.localeCompare(i))):t}var Wt=v(()=>{"use strict";ad()});function di(e){return e!==void 0&&Yle.has(e)}function bs(){if(z_!=="cli")return z_;let e=process.env[Xle];return e==="mcp"||e==="acp"?e:z_}function DV(e,t){if(di(t)&&e===t)return`the gate was reached over ${t} and this resolution arrived over ${t} too, so the same caller wrote both halves`}var Yle,kv,z_,Xle,el=v(()=>{"use strict";Yle=new Set(["mcp","acp"]);kv="unattested",z_="cli",Xle="CHANT_GATE_ORIGIN"});var jV,U_=v(()=>{"use strict";jV=["changeSets","releases","runEvents"]});import{dirname as KWe,isAbsolute as Qle,join as JWe}from"node:path";import{fileURLToPath as eue}from"node:url";function NV(e,t="--report-url"){let n=e.trim();if(n.startsWith("file://")){let r;try{r=eue(n)}catch(o){return{error:`${t} ${n}: ${o instanceof Error?o.message:String(o)}`}}return Qle(r)?{scheme:"file",url:n.replace(/\/+$/,""),dir:r}:{error:`${t} ${n}: a file URL names an absolute directory`}}let i=/^s3:\/\/([^/]+)\/?(.*)$/.exec(n);if(i){let r=i[2].replace(/\/+$/,"");return{scheme:"s3",url:`s3://${i[1]}${r?`/${r}`:""}`,bucket:i[1],prefix:r}}return{error:`${t} ${n}: takes an s3://<bucket>/<prefix> or file://<directory> URL`}}var LV=v(()=>{"use strict"});var V_,MV=v(()=>{V_={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://intentius.io/chant/schemas/workspace/declaration/v1/chant.workspace.schema.json",title:"chant.workspace.json",description:"A workspace declaration, schema 1 (#2524 D1, D2; ws-051). Only this file makes a directory a workspace. It may also be named chant.workspace.jsonc, which allows comments and trailing commas; having both is an error. Unknown fields are refused, except fields whose names start with x-. A field added later within schema 1 is optional, and a declaration that uses one sets minReader to the first chant that knows it, so an older chant says so instead of misreading the file. Uniqueness of names and the placement rules are checked in code, since JSON Schema cannot say them.",type:"object",required:["name","schema","members"],properties:{$schema:{type:"string",description:"An editor hint. chant ignores it."},$comment:{type:"string",description:"A note for people. chant ignores it."},name:{$ref:"#/$defs/name",description:"The workspace's name. With a git revision it identifies the workspace to readers (#2524 D15)."},schema:{const:1,description:"The declaration format version."},minReader:{$ref:"#/$defs/version",description:"The oldest chant that may read this declaration. An older chant refuses it with reader-too-old."},members:{type:"array",description:"Members and example groups, in the order readers list them.",items:{$ref:"#/$defs/entry"}},pins:{type:"array",description:"The toolchain and plugins that read this workspace, pinned (#2524 D3, threat model). Member kinds come only from pinned packages, read as data from their ./workspace-kinds subpath (#2535).",items:{$ref:"#/$defs/pin"}},quorum:{type:"integer",minimum:0,description:"How many agree verdicts besides the decider's a record needs, for every record kind with a reviews list (#2671). chant workspace records reports each record's quorum against it. Two when absent. Added in schema 1 by chant 0.86.0, so a declaration that sets it sets minReader to 0.86.0 or newer. A per-kind quorum comes later (#2650 C14)."},records:{type:"array",description:"The workspace's own record kinds, each a kind file relative to the workspace root (#2680): the kinds whose records belong to no one member, such as a decisions directory at the root. A member names its own in its records. chant workspace ls lists them, and chant workspace records and graph --intent read every declared kind when --kind is not given. Added in schema 1 by chant 0.86.0, so a declaration that uses it sets minReader to 0.86.0 or newer.",items:{$ref:"#/$defs/recordKind"}},hosts:{type:"array",description:"The hosts boxes run on (#2727). A host is one machine reached under one hostname: boxes on it share its ports, its state root and, in a browser, its cookie jar, so chant workspace check compares the boxes on one host and never boxes on different hosts. A member's box block names its host. Added in schema 1 by chant 0.91.0, so a declaration that uses it sets minReader to 0.91.0 or newer.",items:{$ref:"#/$defs/host"}},diagrams:{type:"array",description:"The workspace's own diagram artifacts (#2764): the diagrams that belong to no one member, such as a diagrams directory at the root. A member names its own in its diagrams. chant workspace ls lists every declared diagram, and chant workspace check reports one whose render is stale for its source when the entry records a sourceHash. Added in schema 1 by chant 0.91.0, so a declaration that uses it sets minReader to 0.91.0 or newer.",items:{$ref:"#/$defs/diagram"}},checks:{type:"object",description:"Severity for the declaration checks that allow it, keyed by WSP id (#2535, ws-028): error, warning, info or off. chant workspace check refuses an id it does not know, and one whose severity is fixed.",propertyNames:{pattern:"^WSP[0-9]{3}$"},additionalProperties:{$ref:"#/$defs/severity"}},changes:{type:"object",additionalProperties:!1,description:"The forward coverage check, chant workspace check --changes <base>..<head> (#2773): each path a diff changes is mapped to the current records whose constrains cover it. severity says what a finding does: off reports none, warn (the default) reports them and passes, fail reports them and fails. ignore lists globs over files whose changes need no record, such as lockfiles and generated output. Added in schema 1 by chant 0.92.0, so a declaration that uses it sets minReader to 0.92.0 or newer.",properties:{severity:{enum:["off","warn","fail"],description:"What a change-uncovered or change-out-of-scope finding does. warn when absent."},ignore:{type:"array",description:"Globs over file paths from the workspace root: * and ? within one segment, ** across segments. A changed path one matches is listed as ignored and never reported.",items:{$ref:"#/$defs/fileGlob"}}}},writeScope:{type:"object",propertyNames:{$ref:"#/$defs/className"},additionalProperties:{$ref:"#/$defs/classScope",description:"A domain class a pinned package supplies at its ./workspace-principals subpath (#3080, ws-079): principals holding the role the class names in the trust policy at base, and none of the agent, runner and service roles. A key no pinned package supplies fails chant workspace check with WSP003, and a writer judged human is refused with write-scope-class-unknown, since it may be in that class. Added in schema 1 by chant 0.102.0, so a declaration that uses one sets minReader to 0.102.0 or newer."},description:"Who may write what (#2524 D5, #2548, ws-067): for each principal class, the members whose files it may write and the record kinds it may write, with which verbs. A class is human, agent, runner or service, or a domain class a pinned package supplies (#3080). A class with no entry is not restricted. An agent is always bound to its session's member (agents); its entry can only narrow the record kinds and verbs. chant workspace records new, amend, review and close and the MCP record tools refuse a write outside the writer's scope with write-scope-member or write-scope-kind, and chant workspace check --changes reports each commit that writes outside its author's scope, read from the declaration and the trust policy at the range's base, and a write to a path the class's protected list covers with write-scope-protected (#3146). Added in schema 1 by chant 0.101.0, so a declaration that uses it sets minReader to 0.101.0 or newer.",properties:{human:{$ref:"#/$defs/classScope",description:"Principals holding none of the agent, runner and service roles, and none of the roles a domain class names, in the trust policy at base."},agent:{$ref:"#/$defs/agentScope",description:"An agent session (agents), or a principal holding the agent role in the trust policy at base."},runner:{$ref:"#/$defs/classScope",description:"Principals holding the runner role in the trust policy at base, such as a CI job's signing identity."},service:{$ref:"#/$defs/classScope",description:"Principals holding the service role in the trust policy at base."}}},agents:{type:"array",description:"The agent sessions the workspace declares (#2524 D20, #2548, ws-067, ws-101). Each is bound to the members it names, one with member or several with members: it writes the files of any of them and the records of kinds any of them or the workspace declares, as writeScope.agent allows. A session resumes from chant workspace agent <name> --json, which prints its member, its scope and the spec, read from the repository alone. A write names its session with the CHANT_AGENT environment variable, or a commit with a Chant-Agent trailer. Added in schema 1 by chant 0.101.0, so a declaration that uses it sets minReader to 0.101.0 or newer.",items:{$ref:"#/$defs/agent"}},identity:{type:"object",additionalProperties:!1,description:"Who a person-attributed record or gate approval may name, and which gates need a signed approval (#3163, ws-080). Read from the declaration at base, like writeScope, so a change can't loosen its own rule. A person is named by a forge identity (github:<login>, gitlab:<login>, or <forge>@<host>:<login> for forgejo, gitea or a self-hosted github or gitlab) that the surface which signed them in maps their session to, or by a principal .chant/allowed_signers lists at base. chant never authenticates a person: a forge identity is recorded as the surface gives it, and only a seal verified against the signers at base attests it. Added in schema 1 by chant 0.102.0, so a declaration that uses it sets minReader to 0.102.0 or newer.",properties:{attribution:{enum:["any","identified"],description:"any (the default): a record's by, decided_by, reviewer or answerer and a gate approval's actor may be any name, such as a roster name. identified: each must be a forge identity, a principal the signers file at base lists, or a principal holding the agent, runner or service role at base or listed by a declared agent session; chant workspace records new and review, points answer and chant approve refuse any other name with principal-unidentified."},gates:{type:"object",description:"Gates, by name, that pass only on a signed approval: chant approve --sign with a key the signers file at base lists for the approver. The rule applies to a gate of that name in every member, Op and component. An unsigned approval, or one whose signer is not in class, is recorded nowhere and never counts toward the gate.",propertyNames:{type:"string",minLength:1},additionalProperties:{type:"object",additionalProperties:!1,properties:{class:{$ref:"#/$defs/className",description:"The principal class the signer must be in, read from the role grants at base (#3080, ws-079): human, runner, service, or a domain class a pinned package supplies. A class no pinned package supplies lets no approval through (fail closed). Absent: any signer the signers file lists."}}}}}},ci:{type:"object",additionalProperties:!1,patternProperties:{"^x-":!0},description:"What the workspace's CI decides about its commits (#3573, ws-103). Added in schema 1 by chant 0.108.0, so a declaration that uses it sets minReader to 0.108.0 or newer.",properties:{green:{$ref:"#/$defs/ciGreen"},reportUrl:{type:"string",minLength:1,description:"Where the pull-request jobs copy their reports and events, and where chant ci run keeps the run index, <reportUrl>/runs/index.json (#4160): an s3://<bucket>/<prefix> or file://<directory> URL, as --report-url takes. chant build --pr-loop, chant ci run, chant ci serve and chant ci runs use it when --report-url is not given, and the flag wins. Readers find it in chant workspace ls --json as ci.reportUrl. Added in schema 1 by chant 0.124.32, so a declaration that uses it sets minReader to 0.124.32 or newer."}}},retention:{type:"object",additionalProperties:!1,patternProperties:{"^x-":!0},description:"How long chant lifecycle gc keeps each kind of stored record (#4036). A kind or field left out keeps its default: changeSets 14 days; releases 14 days and the newest 10 of each member; runEvents 14 days and the newest 100. Whatever the policy, gc never prunes a release an environment runs, what a pending gate binds, or a change set a gate names with a kept release. Read from the declaration at base. Added in schema 1 by chant 0.124.29, so a declaration that uses it sets minReader to 0.124.29 or newer.",properties:{changeSets:{type:"object",additionalProperties:!1,description:"Stored change sets, _change-sets/<digest>.json on chant/lifecycle.",properties:{days:{$ref:"#/$defs/retentionDays"}}},releases:{type:"object",additionalProperties:!1,description:"Releases, _releases/<digest>.json on chant/lifecycle, with the template bytes only they name. A release stays promotable for days after its newest cut, and the newest keep releases of each member stay promotable at any age, unless their commit is revoked.",properties:{days:{$ref:"#/$defs/retentionDays"},keep:{$ref:"#/$defs/retentionKeep"}}},runEvents:{type:"object",additionalProperties:!1,description:"Run event files, <git-common-dir>/chant/run-events/<run>.jsonl on each host. A file is kept for days after its last write, and the newest keep files at any age.",properties:{days:{$ref:"#/$defs/retentionDays"},keep:{$ref:"#/$defs/retentionKeep"}}}}},metrics:{type:"object",additionalProperties:!1,patternProperties:{"^x-":!0},description:"How chant workspace metrics counts the DORA metrics (#4039). Added in schema 1 by chant 0.124.29, so a declaration that uses it sets minReader to 0.124.29 or newer.",properties:{failureWindowDays:{type:"integer",minimum:1,maximum:365,description:"A deploy counts as failed when, within this many days after it, the commit it deployed is revoked or the environment is rolled back from it. The default is 7."}}},security:{type:"array",uniqueItems:!0,description:"The security groups the workspace opts into (#4168), for every member; a member's own security adds to them. With none, a security feature the workspace has not turned on never refuses, warns or hides anything. verified-releases: release publish and promote --release take only a verified release. supply-chain: a publish without OIDC provenance warns, and a target with no SBOM source is refused. who-ran-it: ci tick needs a runner key. review-rules: pr-apply requires a forge review. isolated-runners: an apply job requires a runner-start statement. workspace check reports what a declared group lacks (WSP161 to WSP165). Added in schema 1 by chant 0.124.33, so a declaration that uses it sets minReader to 0.124.33 or newer.",items:{enum:["verified-releases","supply-chain","who-ran-it","review-rules","isolated-runners"]}}},patternProperties:{"^x-":!0},additionalProperties:!1,$defs:{retentionDays:{type:"integer",minimum:0,maximum:36500,description:"Days a record is kept past its last write or use. 0 lets every record go that no never-prune rule keeps."},retentionKeep:{type:"integer",minimum:0,maximum:1e5,description:"How many of the newest are kept at any age."},name:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,39}$",description:"Lowercase letters, digits and hyphens, starting with a letter or digit, at most 40 characters. _workspace and _members are reserved; the pattern already rules them out."},kindName:{type:"string",pattern:"^[a-z][a-z0-9-]{0,39}$"},className:{type:"string",pattern:"^(?!x-)[a-z][a-z0-9-]{0,39}$",description:"A principal class: human, agent, runner, service, or a domain class a pinned package supplies (#3080)."},version:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?$"},dir:{type:"string",description:'A directory relative to the workspace root, with / separators: "." for the root itself, otherwise no leading /, no . or .. segments and no trailing /.',pattern:"^(\\.|(?!\\.\\.?(/|$))[^/\\\\]+(/(?!\\.\\.?(/|$))[^/\\\\]+)*)$"},glob:{type:"string",description:"A glob over directories, relative to the workspace root: * and ? within one segment, ** across segments, [...] classes. No leading /, no . or .. segments.",pattern:"^(?!\\.\\.?(/|$))[^/\\\\]+(/(?!\\.\\.?(/|$))[^/\\\\]+)*$"},severity:{enum:["error","warning","info","off"]},suppress:{type:"array",description:"Declaration checks suppressed for this entry (#2535). Each names a WSP id and says why. A suppressed finding is still reported, as suppressed, and never fails check.",items:{type:"object",required:["check","because"],properties:{check:{type:"string",pattern:"^WSP[0-9]{3}$"},because:{type:"string",minLength:1}},patternProperties:{"^x-":!0},additionalProperties:!1}},outputName:{type:"string",minLength:1,maxLength:255,pattern:"^[^\\u0000-\\u001f]+$",description:"An output's name, compared exactly."},link:{type:"object",description:"A member link: this member reads output of member (#2539), or sends its telemetry to a pipeline of its collector (#2558).",required:["member","output"],properties:{member:{$ref:"#/$defs/name",description:"The producer: another member of this workspace."},output:{$ref:"#/$defs/outputName",description:"The producer's output, matched exactly. It must be one the producer's kind exposes. For a telemetry link, the id of a pipeline or an exporter in the producer's collector."},kind:{$ref:"#/$defs/kindName",description:"The link kind. output, the default: the consumer reads the named output. telemetry (#2558): the consumer sends its telemetry to the named pipeline or exporter of the producer's collector, and chant workspace graph checks that it exists and, when protocol is given, that it speaks it. A declaration that uses telemetry sets minReader to 0.101.0 or newer."},protocol:{enum:["grpc","http/protobuf","http/json"],description:"For a telemetry link, the OTLP protocol the consumer sends, as OTEL_EXPORTER_OTLP_PROTOCOL names it. Refused on any other kind. Added in schema 1 by chant 0.101.0."}},patternProperties:{"^x-":!0},additionalProperties:!1},entry:{description:"A member, or an example group when kind is examples (ws-051).",type:"object",required:["kind"],properties:{kind:{$ref:"#/$defs/kindName"}},if:{type:"object",properties:{kind:{const:"examples"}},required:["kind"]},then:{$ref:"#/$defs/group"},else:{$ref:"#/$defs/member"}},member:{type:"object",description:"A member (#2524 D2). Its directory leaves the root project, and it gets its own build, lint and ledger.",required:["name","dir","kind"],properties:{name:{$ref:"#/$defs/name",description:"Frozen once the member deploys; a rename is an alias record."},dir:{$ref:"#/$defs/dir"},kind:{$ref:"#/$defs/kindName",description:"How to read the member: chant, workspace, other, or a kind a pinned plugin supplies (#2535)."},roles:{type:"array",description:"Roles the member plays. A role may point at a path inside the member.",items:{oneOf:[{$ref:"#/$defs/kindName"},{type:"object",required:["name"],properties:{name:{$ref:"#/$defs/kindName"},path:{$ref:"#/$defs/dir",description:"Relative to the member's directory."}},patternProperties:{"^x-":!0},additionalProperties:!1}]}},generated:{type:"array",description:"Files in the member's directory that a command writes (#2524 D14, #2541). chant workspace check fails when one differs from what its generator writes, unless the entry is marked handWritten with a reason. The lineage lock classes the same files as generated. skills/*/SKILL.md, which chant update writes, is listed implicitly for a chant member.",items:{$ref:"#/$defs/generatedFile"}},outputs:{type:"array",uniqueItems:!0,description:"The outputs this member exposes as link targets (#2539), for a member whose kind takes them from the entry: other, or a kind a pinned package supplies. A chant member's outputs are read from its source, and a nested workspace exposes none.",items:{$ref:"#/$defs/outputName"}},fields:{$ref:"#/$defs/memberFields"},links:{type:"array",description:"Member links (#2524 D6, #2539): the outputs of other members this member reads. A link is stated once, here on the consumer, and matched exactly against the producer's outputs. chant workspace check resolves it in source.",items:{$ref:"#/$defs/link"}},records:{type:"array",description:"The record kinds this member holds, each a kind file relative to the member's directory (#2680). chant workspace ls lists them, and chant workspace records and graph --intent read every declared kind when --kind is not given. Added in schema 1 by chant 0.86.0, so a declaration that uses it sets minReader to 0.86.0 or newer.",items:{$ref:"#/$defs/recordKind"}},diagrams:{type:"array",description:"The diagram artifacts this member holds (#2764). chant workspace ls lists every declared diagram, and chant workspace check reports one whose render is stale for its source when the entry records a sourceHash. Added in schema 1 by chant 0.91.0, so a declaration that uses it sets minReader to 0.91.0 or newer.",items:{$ref:"#/$defs/diagram"}},box:{$ref:"#/$defs/box"},upstream:{type:"string",minLength:1,description:"Where an embedded member's files come from. Versions live in the lock."},travel:{type:"boolean",description:"Whether the member goes with an export (#2524 D10, #2552). chant workspace export writes only members that set travel to true into the export member, and refuses to name one that does not. Added in schema 1 by chant 0.101.0, so a declaration that uses it sets minReader to 0.101.0 or newer."},security:{type:"array",uniqueItems:!0,description:"The security groups this member opts into, added to the declaration's top-level security (#4168). A release, publish or pull-request job of this member runs under both lists. Added in schema 1 by chant 0.124.33, so a declaration that uses it sets minReader to 0.124.33 or newer.",items:{enum:["verified-releases","supply-chain","who-ran-it","review-rules","isolated-runners"]}},because:{type:"string",minLength:1,description:"Why the member is there. Required for kind other."},suppress:{$ref:"#/$defs/suppress"}},patternProperties:{"^x-":!0},additionalProperties:!1,if:{type:"object",properties:{kind:{const:"other"}},required:["kind"]},then:{type:"object",properties:{because:{type:"string"}},required:["because"]}},memberFields:{type:"object",description:"Values for the fields the member's kind declares (#3151), such as an app member's scripts, env and health. Each is a string, integer or boolean, or an object of those for a field the kind declares as an object. chant workspace check fails when the kind declares no such field or a value is of the wrong type (WSP005), and chant workspace status --json prints every field the kind declares with its defaults filled in. Added in schema 1 by chant 0.103.0, so a declaration that uses it sets minReader to 0.103.0 or newer.",propertyNames:{pattern:"^[a-z][A-Za-z0-9]{0,39}$"},additionalProperties:{oneOf:[{type:"string"},{type:"integer"},{type:"boolean"},{type:"object",propertyNames:{pattern:"^[a-z][A-Za-z0-9]{0,39}$"},additionalProperties:{oneOf:[{type:"string"},{type:"integer"},{type:"boolean"}]}}]}},group:{type:"object",description:"An example group (ws-051): every directory the glob matches that holds a chant project is built and linted. A group has no ledger, releases or links, and its matches are never members. A match may sit inside a member's directory; that member leaves it to the group.",required:["name","kind","glob"],properties:{name:{$ref:"#/$defs/name"},kind:{const:"examples"},glob:{oneOf:[{$ref:"#/$defs/glob"},{type:"array",minItems:1,uniqueItems:!0,items:{$ref:"#/$defs/glob"}}]},suppress:{$ref:"#/$defs/suppress"}},patternProperties:{"^x-":!0},additionalProperties:!1},path:{type:"string",description:"A file or directory path with / separators: no leading /, no . or .. segments and no trailing /.",pattern:"^(?!\\.\\.?(/|$))[^/\\\\]+(/(?!\\.\\.?(/|$))[^/\\\\]+)*$"},box:{type:"object",description:"The member is a box, or holds a box's declarations (#2726). A box holds no credential: each capability it needs outside itself is reached through a broker, a runtime such as a lobby or a door, which holds the credential and enforces the scope. chant workspace check fails when a file in the member's directory carries a literal secret (WSP121) and when a capability names no broker (WSP122). chant workspace status --json lists the capabilities, so a broker can read the scopes. Its host, slot, ports, state and cookies state the box's isolation (#2727): chant derives each value from the box's identity, its host, the member's name and its slot, and prints them in chant workspace status --json, so a runtime reads them instead of choosing its own. chant workspace check fails when two boxes on a host resolve to the same value (WSP123) and when a box hard-codes a machine path (WSP124). A member that builds the fountain lexicon's Box declares the callback token fountain gives its sandbox as the capability fountain-callback, brokered by fountain, with scope owner, or chant workspace check fails (WSP125, #2780). Its intent names the decision record that says what the box is for (#2850): chant workspace status --json reports the record's state and answer, and chant workspace check fails when no decision record has the id (WSP126) and warns when the record constrains no member or path of this workspace (WSP127, #2857). Its services list what the box runs under its supervisor (#2880), which the fly lexicon observes, restarts and applies through sprite-env, and which chant workspace status --json prints. Its factory declares what the box builds, how a build is checked, which member declares the builder agents and where a finished build is published (#3146, ws-077), its listing what the box shows of itself (#3146), and its replicate where the box's work in progress is pushed so a lost box loses none of it (#3172, ws-085). Added in schema 1 by chant 0.91.0, so a declaration that uses it sets minReader to 0.91.0 or newer.",properties:{intent:{type:"string",minLength:1,description:"The id of the decision record that says what the box is for (#2850), a record of a declared kind named decision. A new box starts as a question: the record is proposed with a null choice until the person who answers it decides it. The record constrains a member or path of this workspace, with member:<a member's name> or a path: entry at, above or inside a member's directory. It need not be this member: the intent can constrain the app the box runs when that app is another member (#2857). When it constrains this member, chant workspace graph --intent shows it for the box's files. Added by chant 0.94.0, so a declaration that uses it sets minReader to 0.94.0 or newer."},services:{type:"array",description:"The services the box runs under its supervisor, sprite-env on a sprite (#2880). Each name is given once, every needs entry names a service of this list, the needs form no cycle, and at most one service sets httpPort; a declaration that breaks one of these can't be read (declaration-invalid). The fly lexicon's spriteServicesObserve and spriteServiceRestart read the list with box: true, and spriteApplyServices with box: true creates and replaces the services through sprite-env. None when omitted. Added by chant 0.95.0, so a declaration that uses it sets minReader to 0.95.0 or newer.",items:{$ref:"#/$defs/boxService"}},factory:{$ref:"#/$defs/boxFactory"},listing:{$ref:"#/$defs/boxListing"},publisher:{type:"string",minLength:1,pattern:"\\S",description:"The command that publishes the box's work (#3165, ws-088): it applies a built work item to the box's checkout and, when factory.publish names a target, pushes it and opens the pull request, and it sends the records a person kept uncommitted. It is run from the workspace root by chant workspace box publish, split into words as a shell splits plain words (quotes group, a backslash escapes) but never given to a shell, with a JSON request on stdin; box-publish.schema.json says what it reads and prints. An orchestrator such as studio supplies it. chant workspace status --json prints it under the member's box, so a surface offers a publish only when a box names one. Added in schema 1 by chant 0.103.0, so a declaration that uses it sets minReader to 0.103.0 or newer."},replicate:{$ref:"#/$defs/boxReplicate"},ship:{$ref:"#/$defs/boxShip"},capabilities:{type:"array",description:"Each capability the box reaches outside itself, named once. None when omitted.",items:{$ref:"#/$defs/capability"}},host:{$ref:"#/$defs/name",description:"The host the box runs on, one of the top-level hosts (#2727). The box's name is the member's name."},slot:{type:"integer",minimum:0,description:"The box's number on its host (#2727). Its ports come from the slot's block of the host's range."},ports:{type:"object",description:"The ports the box listens on, each a name and its offset in the box's block (#2727). The port is the block's first port plus the offset.",propertyNames:{$ref:"#/$defs/kindName"},additionalProperties:{type:"integer",minimum:0,maximum:65534}},state:{type:"object",description:"State the box keeps outside its checkout, such as hud's identity and database, each a name and a path relative to the box's state directory (#2727). The name is usually the environment variable the runtime sets, such as HUD_IDENTITY_PATH. A path that is absolute, starts with ~ or an environment reference, or has a .. segment is a WSP124 finding.",propertyNames:{type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_-]{0,63}$"},additionalProperties:{type:"string",minLength:1}},cookies:{type:"array",description:"Session cookie names the box's runtimes set, such as hud_session (#2727). A browser scopes a cookie to a host, not a port, so each resolves to <cookie>_<member name>.",uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"}}},dependentRequired:{host:["slot"],slot:["host"],ports:["host"],state:["host"],cookies:["host"]},patternProperties:{"^x-":!0},additionalProperties:!1},boxFactory:{type:"object",description:"What the box builds and how (#3146, ws-077), replacing studio's x-factory. Opt-in: a box block without it declares no factory, and nothing here is required of a workspace that doesn't build with agents (#3174). At most one box block in a declaration declares a factory. builds and builders name declared members, or the declaration can't be read (declaration-invalid). chant workspace status --json and chant workspace graph --json print it under the member's box. The factory need not build an app: builds may name any member kind, such as chant or terraform, and the check may be a plan, a lint or a conformance run. Added in schema 1 by chant 0.102.0, so a declaration that uses it sets minReader to 0.102.0 or newer.",required:["builds"],properties:{builds:{type:"array",minItems:1,uniqueItems:!0,description:"The members the factory builds, each a declared member of any kind. A work item a person asks for here constrains member:<the first>.",items:{$ref:"#/$defs/name"}},check:{description:"The command whose exit code is a build's verdict, run from the workspace root after the work item's own checks: a command, or { run, kind } saying what it is. kind is test when omitted.",oneOf:[{type:"string",minLength:1},{type:"object",required:["run"],properties:{run:{type:"string",minLength:1,description:"The command, run from the workspace root."},kind:{enum:["test","build","lint","plan","conformance"],description:"What the command is: an app's tests, a build, a lint, a lifecycle plan or a conformance run. test when omitted."}},patternProperties:{"^x-":!0},additionalProperties:!1}]},checks:{$ref:"#/$defs/path",description:"The directory, from the workspace root, where a work item's builder writes the check for its item. When omitted the orchestrator chooses, such as <the first member of builds>/checks."},builders:{$ref:"#/$defs/name",description:"The member that declares the builder agents, such as the one whose agents/ holds them. tiers says which of them builds at which tier (#3152)."},tiers:{type:"array",minItems:1,description:"Which builder agent builds at which tier (#3152, ws-094), replacing studio's studio/role and studio/tier Agent metadata. Each entry names a tier, in the vocabulary of the work kind's work.tier.tiers (#3147), and an agent the builders member declares, by its name. An entry with kinds builds only members of those kinds, so an infra builder and an app builder can share a tier; an entry without kinds builds the tier for every other kind. A tier has at most one entry without kinds and at most one per kind, tiers needs builders, and a session names a declared agent session, or the declaration can't be read (declaration-invalid). chant workspace status --json prints builderFor, the agent for each built member and tier. Added in schema 1 by chant 0.103.0, so a declaration that uses it sets minReader to 0.103.0 or newer.",items:{type:"object",required:["tier","agent"],properties:{tier:{$ref:"#/$defs/kindName",description:"The tier, such as small, medium or large: a word of the work kind's work.tier.tiers, which a work item's tier or the slice-tier decision point answers."},agent:{type:"string",minLength:1,pattern:"^[^\\u0000-\\u001f]+$",description:"The builder agent's name, as the builders member declares it (such as an Agent of the fountain lexicon in its agents/)."},kinds:{type:"array",minItems:1,uniqueItems:!0,items:{$ref:"#/$defs/kindName"},description:"The member kinds this agent builds at the tier, such as app or terraform. Without it, every kind no other entry of the tier names."},session:{$ref:"#/$defs/name",description:"The declared agent session (agents) the builder writes as, so its write scope is that session's. Optional: without it the orchestrator chooses."}},patternProperties:{"^x-":!0},additionalProperties:!1}},publish:{type:"object",description:"Where a finished build is published: its branch is pushed and a pull request opened against repo's base. The repo is the record, so an orchestrator reads this instead of being told the target in its environment.",required:["repo"],properties:{forge:{enum:["github"],description:"The forge repo is on. github when omitted."},repo:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}$",description:"The repository the pull request is opened on, as owner/name."},base:{type:"string",minLength:1,description:"The branch the pull request targets. The repository's default branch when omitted."},branchPrefix:{type:"string",minLength:1,pattern:"^[A-Za-z0-9._/-]+$",description:"What the published branch's name starts with; the work item's id follows, as in box/ and then box/work-012. chant/work/ when omitted, the work lease's own branch."},head:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}$",description:"The repository the branch is pushed to when it isn't repo, as owner/name: a fork, so the pull request comes from <head owner>:<branch>. A runtime that publishes for one contributor's fork supplies that per contributor instead (arugula-salad/studio#242); this names a fork the whole workspace publishes from."}},patternProperties:{"^x-":!0},additionalProperties:!1}},patternProperties:{"^x-":!0},additionalProperties:!1},boxListing:{type:"object",description:"What the box shows of itself on a home site that lists boxes (#3146, #3154): whether it is listed, its title and one line, and a cover image kept as a file in the repo. A box's listing is configuration, so changing it is a reviewed change (ws-074). chant workspace status --json and chant workspace graph --json print it under the member's box, with the cover's sha256. Added in schema 1 by chant 0.102.0, so a declaration that uses it sets minReader to 0.102.0 or newer.",properties:{published:{type:"boolean",description:"Whether the box is listed. true when omitted: a box is listed unless its owner takes it out."},title:{type:"string",maxLength:60,pattern:"^[^\\u0000-\\u001f\\u007f-\\u009f]*$",description:"The box's title, one line of at most 60 characters. Empty when omitted, and a reader then shows a name of its own."},line:{type:"string",maxLength:140,pattern:"^[^\\u0000-\\u001f\\u007f-\\u009f]*$",description:"One line saying what the box is, at most 140 characters. Empty when omitted."},cover:{$ref:"#/$defs/path",description:"A PNG, JPEG or WebP picture of the box, as a file from the workspace root. None when omitted."}},patternProperties:{"^x-":!0},additionalProperties:!1},boxReplicate:{type:"object",description:"Where the box's work in progress is replicated, so a box that is lost, reclaimed or corrupted before anyone commits loses nothing (#3172, ws-085). Work in progress is the work branches (chant/work/...), the kept attempts (refs/chant/kept/..., #3147), the snapshots chant workspace wip save takes of each branch's working tree, uncommitted records included (refs/chant/wip/<branch>), and the ledger branch, chant/lifecycle. chant pushes them to remote under their own names and never forces a push. Opt-in: a box block without it replicates nothing. At most one box block in a declaration declares one, or the declaration can't be read (declaration-invalid). chant workspace status --json prints it under the member's box, with every default filled in, and reports in replication how far each ref is from the remote. Added in schema 1 by chant 0.103.0, so a declaration that uses it sets minReader to 0.103.0 or newer.",properties:{remote:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",description:"The git remote to push to, by name: the repository's own remote, such as origin, or a mirror the host adds to the box's checkout with its credential, since a box holds none (#2726). origin when omitted."},refs:{type:"array",minItems:1,uniqueItems:!0,description:"What is replicated: work (the branches under chant/work/), kept (the kept attempts under refs/chant/kept/), wip (the snapshots under refs/chant/wip/) and ledger (the chant/lifecycle branch). All four when omitted.",items:{enum:["work","kept","wip","ledger"]}},on:{type:"array",uniqueItems:!0,description:"When chant pushes on its own: save, after each chant workspace wip save, and release, after a work lease is released (chant workspace work release, or a run of an Op under a work lease ending, which is when a kept attempt is written). Both when omitted; an empty list leaves every push to chant workspace wip push. A record write never pushes, because chant's record writes never run git (ws-074).",items:{enum:["save","release"]}},every:{type:"string",pattern:"^[1-9][0-9]*(s|m|h)$",description:"How often the host runs chant workspace wip push on a schedule of its own, such as 10m, beside the pushes on save and release. chant runs no scheduler; it only states the interval. None when omitted."}},patternProperties:{"^x-":!0},additionalProperties:!1},boxShip:{type:"object",description:"How the box ships its staged work to its own site (ws-100): the people working on a box see the working tree at once, everyone else sees the last release, and a person ships. op is the Op in the box member that does it: its own steps commit the staged tree as one commit by the person shipping (named to it in CHANT_SHIP_BY) with a Chant-Record trailer for each work item it lands, then release that commit to the box's site, stopping at gate, and record the release in env's release ledger. chant runs none of it; a surface runs chant run <op> in the member's directory and approves the gate as for any Op. chant workspace status --json prints it under the member's box with the commit the site serves (the latest release in env's ledger) and what is waiting to ship (the files changed between that commit and the working tree, bookkeeping left out). Added in schema 1 by chant 0.104.0, so a declaration that uses it sets minReader to 0.104.0 or newer.",required:["op"],properties:{op:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",description:"The name of the Op in the box member that ships, as chant run takes it."},gate:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",description:"The gate the Op stops at for a person's approval. ship when omitted."},env:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",description:"The environment whose release ledger, under the box member, the Op records each release in. box when omitted."},bookkeeping:{type:"array",uniqueItems:!0,description:"Path prefixes from the workspace root whose changes are bookkeeping, such as the record directories, and never count as waiting to ship. None when omitted.",items:{type:"string",minLength:1,pattern:"^(?!/)(?!.*(^|/)\\.\\.(/|$))[^\\n]+$"}}},patternProperties:{"^x-":!0},additionalProperties:!1},boxService:{type:"object",description:"A service a box runs under its supervisor (#2880).",required:["name","cmd"],properties:{name:{$ref:"#/$defs/kindName",description:"The service's name in the supervisor. Unique within the box."},cmd:{type:"string",minLength:1,description:"The command the supervisor runs (sprite-env services create --cmd). ${HOME} and other ${VAR} references are expanded from the environment of the process that applies the list, so the declaration holds no machine path."},needs:{type:"array",uniqueItems:!0,description:"Names of services of the same box that start before this one (sprite-env services create --needs).",items:{$ref:"#/$defs/kindName"}},httpPort:{$ref:"#/$defs/port",description:"The port the supervisor routes the sprite's URL to (sprite-env services create --http-port). At most one service of a box sets it."},duration:{type:"string",pattern:"^[0-9]+(\\.[0-9]+)?(ms|s|m)$",description:"How long the service must stay up after it is created or started, such as 3s (sprite-env services create --duration)."},health:{type:"string",pattern:"^https?://",description:"A URL that answers 200 while the service works. spriteServicesObserve probes it, and spriteServiceRestart waits for it after a restart. Without it, the supervisor's state decides."},optional:{type:"boolean",description:"True for a service something else creates by name, such as a site a release Op makes: spriteApplyServices creates it only when its only names it, and spriteServicesObserve skips it while the supervisor has no such service."}},patternProperties:{"^x-":!0},additionalProperties:!1},capability:{type:"object",description:"A capability a box needs and does not hold the credential for, such as inference, fountain or a third-party API (#2726).",required:["name"],properties:{name:{$ref:"#/$defs/kindName",description:"The capability, such as inference or fountain. Unique within the box."},broker:{type:"string",minLength:1,description:"What brokers the capability: the runtime that holds the credential and swaps the box's own token for it, such as lobby or door. It may name a member of this workspace, or a runtime outside it. Without it the capability is unbrokered, and chant workspace check fails with WSP122."},scope:{type:"array",uniqueItems:!0,description:"What of the box's own the broker lets it reach, which the broker enforces. For Fountain: agent (start conversations with its own agent), vault (attach its own vault), conversations and sandboxes (its own). The words are the broker's; chant records them.",items:{type:"string",minLength:1,pattern:"^[^\\u0000-\\u001f]+$"}}},patternProperties:{"^x-":!0},additionalProperties:!1},recordKind:{type:"object",description:"A record kind the workspace declares (#2680): a kind file that exports recordKind. chant workspace check fails (WSP115) when the file is missing or does not load as a record kind.",required:["kind"],properties:{kind:{$ref:"#/$defs/path",description:"The kind file, relative to the member's directory, or to the workspace root for the workspace's own records. A path is listed once across the declaration."},name:{$ref:"#/$defs/kindName",description:"The name readers show for the kind. Without it, the kind file's own recordKind.name. Unique across the declaration."}},patternProperties:{"^x-":!0},additionalProperties:!1},diagram:{type:"object",description:"A diagram artifact the workspace declares (#2764): a rendered image with a source, pinned to the renderer that made it. A mermaid or excalidraw diagram may name no render: a reader draws it from its source. chant never runs the renderer.",required:["name","title","renderer"],if:{type:"object",properties:{renderer:{type:"object",properties:{tool:{enum:["mermaid","excalidraw"]}},required:["tool"]}},required:["renderer"]},then:{type:"object",properties:{source:{$ref:"#/$defs/path"}},required:["source"]},else:{type:"object",properties:{render:{$ref:"#/$defs/path"}},required:["render"]},properties:{name:{$ref:"#/$defs/name",description:"Unique across the declaration."},title:{type:"string",minLength:1,description:"Shown above the diagram."},source:{oneOf:[{$ref:"#/$defs/path"},{type:"null"}],description:"The source file, from the workspace root, with / separators. Null for an SVG with no source. Default null."},render:{oneOf:[{$ref:"#/$defs/path"},{type:"null"}],description:"The rendered image, from the workspace root, with / separators. Required for d2 and graphviz. A mermaid or excalidraw diagram needs a source instead and may leave render out or null, from chant 0.96.0: a reader such as hud draws it from the source (an excalidraw diagram may still commit an exported SVG for docs)."},renderer:{$ref:"#/$defs/diagramRenderer"},sourceHash:{type:["string","null"],pattern:"^[0-9a-f]{64}$",description:"sha256 hex of the source's bytes when render was last produced from it, or for a mermaid or excalidraw diagram without a render, when the source was last pinned. chant workspace check compares this against the source in the tree read and reports drift (WSP133) on a mismatch; without it, or without a source, the render is never checked for drift. Default null."}},patternProperties:{"^x-":!0},additionalProperties:!1},diagramRenderer:{type:"object",description:"The renderer a diagram's render was made with. chant records the pin; it never installs or runs the renderer (ws-052).",required:["tool","version"],properties:{tool:{enum:["d2","mermaid","graphviz","excalidraw"]},version:{$ref:"#/$defs/version",description:"The exact release the render was made with, such as 0.9.0. For mermaid or excalidraw, the release of the library a reader draws the source with, such as 11.4.1."},args:{type:"array",description:'Passed before the input and output paths, in order, such as ["--layout=elk", "--theme=0", "--pad=40", "--omit-version"]. Empty when absent.',items:{type:"string"}}},patternProperties:{"^x-":!0},additionalProperties:!1},generatedFile:{type:"object",description:"One generated file of a member (#2524 D14, #2541).",required:["path","generator"],properties:{path:{$ref:"#/$defs/path",description:"The file, relative to the member's directory."},generator:{type:"string",minLength:1,description:"The command line that writes the file, run in the member's directory with the member's own node_modules/.bin first on PATH, such as chant build ci --lexicon github -o ci.yml. When it passes -o or --output with this file's path, chant workspace check --generated points that flag at a temporary file. Otherwise the generator writes in place and check restores the tree afterwards."},sources:{type:"array",description:"The files or directories the generator reads, relative to the workspace root, since a generator often reads other members.",items:{$ref:"#/$defs/path"}},handWritten:{type:"object",description:"The file is kept by hand instead of regenerated. chant workspace check reports it with the reason and never runs its generator, and the lock classes it owned.",required:["because"],properties:{because:{type:"string",minLength:1}},patternProperties:{"^x-":!0},additionalProperties:!1}},patternProperties:{"^x-":!0},additionalProperties:!1},pin:{description:"An npm package at an exact version, or a local plugin by path. integrity is a Subresource Integrity digest.",oneOf:[{type:"object",required:["package","version"],properties:{package:{type:"string",pattern:"^(@[a-z0-9-~][a-z0-9-._~]*/)?[a-z0-9-~][a-z0-9-._~]*$"},version:{$ref:"#/$defs/version"},integrity:{type:"string",pattern:"^sha(256|384|512)-[A-Za-z0-9+/]+={0,2}$"}},patternProperties:{"^x-":!0},additionalProperties:!1},{type:"object",required:["path"],properties:{path:{$ref:"#/$defs/dir"},integrity:{type:"string",pattern:"^sha(256|384|512)-[A-Za-z0-9+/]+={0,2}$"}},patternProperties:{"^x-":!0},additionalProperties:!1}]},host:{type:"object",description:"A host boxes run on (#2727).",required:["name","ports"],properties:{name:{$ref:"#/$defs/name",description:"The host's name, unique among hosts. A box block names it in host."},ports:{type:"object",description:"The TCP ports boxes on this host take theirs from. Slot n owns the block from + n * perBox to from + (n + 1) * perBox - 1, which must end at or before to.",required:["from","to","perBox"],properties:{from:{$ref:"#/$defs/port",description:"The first port of the range."},to:{$ref:"#/$defs/port",description:"The last port of the range, inclusive."},perBox:{type:"integer",minimum:1,maximum:65535,description:"How many ports each box's block holds. A box's port offsets are below it."}},additionalProperties:!1},stateRoot:{type:"string",minLength:1,description:"Where boxes on this host keep state, as an environment reference such as ${XDG_STATE_HOME}/chant/boxes, which the runtime expands on the machine. A box's state directory is <stateRoot>/<member name>. A literal machine path, such as /Users/... or anything under $HOME, is a WSP124 finding. Default ${XDG_STATE_HOME}/chant/boxes."}},patternProperties:{"^x-":!0},additionalProperties:!1},port:{type:"integer",minimum:1,maximum:65535},fileGlob:{type:"string",description:"A glob over file paths, relative to the workspace root: * and ? within one segment, ** across segments, [...] classes and {a,b} alternatives. No leading /, no . or .. segments.",pattern:"^(?!\\.\\.?(/|$))[^/\\\\]+(/(?!\\.\\.?(/|$))[^/\\\\]+)*$"},recordScope:{type:"object",description:"Record kind names, as the kind file's recordKind.name or the name the declaration gives it, each with the verbs the class may write it with: new, amend, review and close (a review session). A kind left out may not be written at all. A record file a commit deletes is never in scope.",propertyNames:{$ref:"#/$defs/kindName"},additionalProperties:{type:"array",uniqueItems:!0,items:{enum:["new","amend","review","close"]}}},protectedPath:{description:"A protected path: a glob from the workspace root, or { path, except } for a JSON file whose listed top-level keys, or the values JSON Pointers name, may still change.",oneOf:[{$ref:"#/$defs/fileGlob"},{type:"object",required:["path"],properties:{path:{$ref:"#/$defs/fileGlob"},except:{type:"array",minItems:1,uniqueItems:!0,description:"What a write may change in the JSON file: a top-level key, or, for an entry starting with /, the values a JSON Pointer matches, where a * token matches every key or array index at its level, such as /members/*/box/listing for every box's listing (#3308). A change anywhere else in the file, or to a file that doesn't parse as a JSON object before and after, is still outside the scope.",items:{type:"string",minLength:1}}},patternProperties:{"^x-":!0},additionalProperties:!1}]},classScope:{type:"object",description:"A principal class's write scope.",properties:{members:{description:"The members whose files the class may write, by name, or * for every path. Without it, every path. A path in no member is in scope only under *.",oneOf:[{const:"*"},{type:"array",uniqueItems:!0,items:{$ref:"#/$defs/name"}}]},protected:{type:"array",description:"Paths the class may not write, even inside a member it may (#3146, ws-077): each a glob from the workspace root, or { path, except } for a JSON file the class may change only in the top-level keys except names. An entry protects the files it matches and everything under a directory it matches. A record file is judged by records, not here. Added in schema 1 by chant 0.102.0, so a declaration that uses it sets minReader to 0.102.0 or newer.",items:{$ref:"#/$defs/protectedPath"}},records:{$ref:"#/$defs/recordScope",description:"The record kinds the class may write, and how. Without it, every kind in reach, with every verb. A kind a member declares is in reach when that member is; the workspace's own kinds always are."}},patternProperties:{"^x-":!0},additionalProperties:!1},agentScope:{type:"object",description:"The agent class's write scope. Its members are always the members its session is bound to, so only the record kinds and the protected paths can be set.",properties:{protected:{type:"array",description:"Paths the class may not write, even inside a member it may (#3146, ws-077): each a glob from the workspace root, or { path, except } for a JSON file the class may change only in the top-level keys except names. An entry protects the files it matches and everything under a directory it matches. A record file is judged by records, not here. Added in schema 1 by chant 0.102.0, so a declaration that uses it sets minReader to 0.102.0 or newer.",items:{$ref:"#/$defs/protectedPath"}},records:{$ref:"#/$defs/recordScope",description:"The record kinds an agent may write, and how. Without it, every kind in reach of its member, with every verb."}},patternProperties:{"^x-":!0},additionalProperties:!1},agent:{type:"object",description:"An agent session (#2548). It names its members with exactly one of member and members (ws-101).",required:["name"],oneOf:[{properties:{member:!0},required:["member"]},{properties:{members:!0},required:["members"]}],properties:{name:{$ref:"#/$defs/name",description:"The session's name, unique among agents: what CHANT_AGENT and a Chant-Agent trailer give."},member:{$ref:"#/$defs/name",description:"The one member the session is bound to. It must be a declared member, not an example group. A session bound to several names them with members instead."},members:{type:"array",minItems:1,uniqueItems:!0,items:{$ref:"#/$defs/name"},description:"The members the session is bound to, when it writes in more than one, such as a factory that builds an app and writes its evidence records in a design member (ws-101, arugula-salad/studio#402). Each must be a declared member, not an example group. The session may write the files of any of them and the records of kinds any of them or the workspace declares, and the write scope is judged against all of them together. Added in schema 1 by chant 0.105.0, so a declaration that uses it sets minReader to 0.105.0 or newer."},principals:{type:"array",uniqueItems:!0,items:{type:"string",minLength:1},description:"Principals that write only as this session: a commit attested by one, or a write whose by names one, is judged as the session. A principal is listed by one session at most."}},patternProperties:{"^x-":!0},additionalProperties:!1},ciGreen:{type:"object",description:"Which commits passed CI (#3573, ws-103). chant ci tick tags each first-parent commit of branch, within window, whose required phases all passed with ci/green/<sha>, and a green commit that later fails a required phase with ci/revoked/<sha>. Both are annotated tags made once and never moved or deleted by chant. chant ci last-green prints the newest commit with a green tag and no revoked tag.",required:["branch","phases","require"],properties:{branch:{type:"string",minLength:1,pattern:"^[^\\s~^:?*\\[\\\\]+$",description:"The branch whose commits are tagged, such as main. Only its first-parent commits count."},window:{type:"string",pattern:"^[1-9][0-9]*(m|h|d)$",description:"How far back a tick looks, by committer time, such as 24h, 90m or 7d. 24h when absent."},phases:{type:"object",minProperties:1,description:"The phases, by name. Each is a list of check-run name patterns, or { runs, skipped }. A pattern matches a check run's whole name, with * standing for any run of characters. A phase passes when every check run its patterns match finished with success, judged by each run's latest attempt.",propertyNames:{$ref:"#/$defs/ciPhaseName"},additionalProperties:{$ref:"#/$defs/ciPhase"}},require:{type:"array",minItems:1,uniqueItems:!0,description:"The phases a commit must pass to be tagged green, by name. Each must be a declared phase.",items:{$ref:"#/$defs/ciPhaseName"}},signedSince:{type:"string",pattern:"^[0-9a-f]{40}([0-9a-f]{24})?$",description:"Added by #4031, read by chant 0.124.28 and newer. The full sha of the first commit on branch whose ci/green and ci/revoked tags must carry a DSSE statement in their annotation, signed by a key .chant/trust.json at base lists under runners for a principal holding the runner role. A tag on a strict first-parent ancestor of this commit counts unsigned, so existing tags keep working; a tag on any other commit, this one included, needs a statement. Position in history decides, never a date, which whoever makes a commit or a tag sets. A reader refuses a sha that names no commit in its clone with declaration-invalid. Absent, no tag needs a statement. Since chant 0.124.32 (#4156) it covers Op run records the same way, when ci.green.source is runs: an unsigned run counts on a strict first-parent ancestor of this commit and needs a statement on any other, ci serve refuses to start without a runner key trusted at the target's head, and ci run and chant run warn about a run they leave unsigned. Absent, an unsigned run counts and nothing asks for a key."},source:{enum:["checks","runs"],description:"Added by #4044, read by chant 0.124.28 and newer, so a declaration that sets it sets minReader to 0.124.28 or newer. Where chant ci tick reads each phase's results. checks (the default): the forge's check runs, whose names the phases' patterns match. runs: chant's own Op runs, read from the run ledger on chant/lifecycle, for a project whose pipelines run as chant Ops, such as one on GitLab or Forgejo. A phase's patterns then match Op names, a run counts for the commit its record names as gitSha, and the latest run of each Op decides. A run counts only when its record carries a statement signed by a key .chant/trust.json at base lists under runners for a principal holding the runner role; the tick ignores and reports any other. A tick from runs signs every tag it makes, so it needs a runner key."}},patternProperties:{"^x-":!0},additionalProperties:!1},ciPhaseName:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$"},ciPhase:{oneOf:[{$ref:"#/$defs/ciRunPatterns"},{type:"object",required:["runs"],properties:{runs:{$ref:"#/$defs/ciRunPatterns"},skipped:{enum:["pass","fail"],description:"What a check run that finished as skipped counts as. fail (the default): it never passes. pass: it passes, for a job a path filter runs only on some commits."},build:{enum:["every","newest"],description:"Added by #4169, read by chant 0.124.33 and newer. Which first-parent commits of the branch the phase runs on. every (the default): each one. newest: only the newest commit when a runner frees. Under either, a run that was cancelled leaves the commit unbuilt rather than red. Under newest, a commit a newer run superseded is unbuilt too, and a red commit starts a bisect over the unbuilt commits back to the last one the phase passed on. chant ci workflow writes the triggers and concurrency of the workflows holding a phase that sets build, and leaves them alone for a phase that does not."}},patternProperties:{"^x-":!0},additionalProperties:!1}]},ciRunPatterns:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1,description:"A check run's name, such as lint, or a pattern with *, such as e2e (*)."}}}}});var q_={};_e(q_,{gitTop:()=>vs,gitTree:()=>cd,joinPath:()=>qe,resolveCommit:()=>H_,skippedDir:()=>Bi,workingTree:()=>Rn});import{execFileSync as WV}from"node:child_process";import{readdirSync as nue,readFileSync as FV,statSync as GV}from"node:fs";import{join as km}from"node:path";function qe(...e){return e.filter(t=>t!==""&&t!==".").join("/")}function Rn(e){return{label:"",stat(t){try{let n=GV(km(e,t));return n.isDirectory()?"dir":n.isFile()?"file":void 0}catch{return}},list(t){let n;try{n=nue(km(e,t),{withFileTypes:!0})}catch{return}let i=[];for(let r of n){let o=r.isDirectory()?"dir":r.isFile()?"file":void 0;if(!o&&r.isSymbolicLink())try{let s=GV(km(e,t,r.name));o=s.isDirectory()?"dir":s.isFile()?"file":void 0}catch{}o&&i.push({name:r.name,type:o})}return i},read(t){return FV(km(e,t),"utf-8")},bytes(t){return FV(km(e,t))}}}function xv(e,t){return WV("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],maxBuffer:512*1024*1024})}function vs(e){try{return xv(e,["rev-parse","--show-toplevel"]).trim()}catch{return}}function H_(e,t){if(!t.startsWith("-"))try{return xv(e,["rev-parse","--verify","--quiet",`${t}^{commit}`]).trim()}catch{return}}function cd(e,t,n=""){let i=new Map([["","dir"]]),r=new Map([["",[]]]),o=xv(e,["ls-tree","-r","-t","-z","--full-tree",t]);for(let s of o.split("\0")){if(!s)continue;let a=s.indexOf(" "),c=s.slice(0,a).split(" ")[1],l=s.slice(a+1),u;if(n==="")u=l;else if(l.startsWith(`${n}/`))u=l.slice(n.length+1);else continue;let d=c==="tree"?"dir":c==="blob"?"file":void 0;if(!d)continue;i.set(u,d);let p=u.lastIndexOf("/"),f=p<0?"":u.slice(0,p);r.has(f)||r.set(f,[]),r.get(f).push({name:u.slice(p+1),type:d}),d==="dir"&&!r.has(u)&&r.set(u,[])}return{label:` at ${t.slice(0,8)}`,stat:s=>i.get(s),list:s=>i.get(s)==="dir"?[...r.get(s)??[]]:void 0,read(s){if(i.get(s)!=="file")throw new Error(`${s} is not a file${` at ${t.slice(0,8)}`}`);return xv(e,["cat-file","blob",`${t}:${qe(n,s)}`])},bytes(s){if(i.get(s)!=="file")throw new Error(`${s} is not a file${` at ${t.slice(0,8)}`}`);return WV("git",["cat-file","blob",`${t}:${qe(n,s)}`],{cwd:e,stdio:["ignore","pipe","pipe"],maxBuffer:512*1024*1024})}}}function Bi(e){return e==="node_modules"||e.startsWith(".")}var on=v(()=>{"use strict"});function zV(e,t){let i=t.split("/").map(a=>a==="**"?"**":rue(a)?a:(0,BV.default)(a,{dot:!1})),r=new Set,o=a=>(e.list(a)??[]).filter(c=>c.type==="dir"&&!Bi(c.name)).map(c=>c.name),s=(a,c)=>{if(c===i.length){a!==""&&r.add(a);return}let l=i[c];if(l==="**"){s(a,c+1);for(let u of o(a))s(qe(a,u),c);return}if(typeof l=="string"){let u=qe(a,l);e.stat(u)==="dir"&&s(u,c+1);return}for(let u of o(a))l(u)&&s(qe(a,u),c+1)};return s("",0),[...r].sort()}var BV,rue,UV=v(()=>{"use strict";BV=Ye(vm(),1);on();rue=e=>!/[*?[\]{}()!+@]/.test(e)});var K_,VV=v(()=>{K_={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://intentius.io/chant/schemas/workspace/kinds/v1/workspace-kinds.schema.json",title:"workspace-kinds.json",description:"Member kinds a plugin supplies (#2524 D3, #2535, ws-031). A package publishes this file as data at its ./workspace-kinds subpath. chant reads it with the file system and never imports the package, so reading kinds never loads a lexicon.",type:"object",required:["schema","kinds"],properties:{$schema:{type:"string",description:"An editor hint. chant ignores it."},$comment:{type:"string",description:"A note for people. chant ignores it."},schema:{const:1,description:"The kinds format version."},kinds:{type:"array",minItems:1,items:{$ref:"#/$defs/kind"}}},patternProperties:{"^x-":!0},additionalProperties:!1,$defs:{kind:{type:"object",required:["name","description","precedence","probe"],properties:{name:{type:"string",pattern:"^[a-z][a-z0-9-]{0,39}$",description:"The kind's name, as a member's kind field names it. chant, workspace, other and examples are built in and can't be supplied."},description:{type:"string",minLength:1,description:"One line saying what the member's directory holds, for listings and error messages."},precedence:{type:"integer",minimum:1,maximum:999,description:"When the probes of several kinds claim one directory, the highest precedence decides. Two claiming kinds with the same highest precedence are a tie, and a tie fails. The built-in chant kind has 500 and workspace has 1000."},probe:{$ref:"#/$defs/probe"},outputs:{type:"array",uniqueItems:!0,description:"The outputs every member of this kind exposes as link targets (#2524 D6, #2539). A member entry of the kind may list more in its own outputs field. Without this field the kind exposes only what each entry lists.",items:{type:"string",minLength:1,maxLength:255,pattern:"^[^\\u0000-\\u001f]+$"}},graph:{$ref:"#/$defs/graph"},fields:{$ref:"#/$defs/fields"},reader:{type:"string",pattern:"^[a-z][a-z0-9-]{0,39}$",description:"A link reader chant ships, by name, that derives a member's links from the member's own files (#3932): dbt-project reads a dbt project's sources. The reader is chant's code and runs offline, parsing files as data; the package supplies only the name. A name this chant doesn't have keeps the kind without a reader, and the load reports it. A chant older than this field fails a kinds file that uses it."}},patternProperties:{"^x-":!0},additionalProperties:!1},probe:{type:"object",description:"What the probe checks in a member's directory. It runs no code. It passes when any of its clauses does, and it needs at least one.",minProperties:1,properties:{anyFile:{type:"array",minItems:1,uniqueItems:!0,description:"The directory passes when a file matching one of these names sits directly in it. A * in a name matches any run of characters, so *.tf matches every Terraform file.",items:{$ref:"#/$defs/fileName"}},anyBlock:{type:"object",description:"The directory passes when a file directly in it, whose name matches one of in, has a line opening an unlabelled block named in blocks: leading space, the name, optional space, then {. No file is parsed.",required:["in","blocks"],properties:{in:{type:"array",minItems:1,uniqueItems:!0,items:{$ref:"#/$defs/fileName"}},blocks:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_-]{0,63}$"}}},additionalProperties:!1},anyJsonKey:{type:"object",description:"The directory passes when a file directly in it, whose name matches one of in, parses as JSON and has a value at one of pointers, each a JSON Pointer such as /scripts/start (#3151). A file that is not JSON is no evidence either way. Added by chant 0.103.0.",required:["in","pointers"],properties:{in:{type:"array",minItems:1,uniqueItems:!0,items:{$ref:"#/$defs/fileName"}},pointers:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",pattern:"^(/[^/]+)+$"}}},additionalProperties:!1}},additionalProperties:!1},fileName:{type:"string",description:"A file name, with no directory part. A * matches any run of characters.",pattern:"^(?!\\.\\.?$)[^/\\\\]+$"},graph:{type:"object",description:"How chant workspace graph reads a member of this kind (#2874). chant writes a reader project of its own outside the workspace, with a chant.config.json that declares lexicon and puts config under that lexicon's key, and runs the member's chant graph there. In every string key and value of config, {member} becomes the member's name, {dir} its absolute directory and {workspace} the absolute workspace root. Without this field a member of the kind is listed with kind-not-run.",required:["lexicon","config"],properties:{lexicon:{type:"string",pattern:"^[a-z][a-z0-9-]{0,39}$",description:"The lexicon that reads the member, by name. The package that supplies the kind must be @intentius/chant-lexicon-<lexicon>, so the lexicon chant loads is the one the declaration pins."},config:{type:"object",description:"The lexicon's config namespace for the reader project, such as terraform's roots. Placeholders are substituted; nothing else is interpreted."}},patternProperties:{"^x-":!0},additionalProperties:!1},fields:{type:"object",description:"The fields a member entry of this kind may set under its own fields block, each with a type and, optionally, a default (#3151). chant workspace check fails a member whose fields name one the kind doesn't declare or give a value of the wrong type (WSP005), and chant workspace status --json prints every declared field with the defaults filled in. Added by chant 0.103.0; an older chant can't read a kinds file that uses it.",minProperties:1,propertyNames:{$ref:"#/$defs/fieldName"},additionalProperties:{oneOf:[{$ref:"#/$defs/scalarField"},{$ref:"#/$defs/objectField"}]}},fieldName:{type:"string",pattern:"^[a-z][A-Za-z0-9]{0,39}$"},scalarField:{type:"object",required:["type","description"],properties:{type:{enum:["string","integer","boolean"]},description:{type:"string",minLength:1},default:{oneOf:[{type:"string"},{type:"integer"},{type:"boolean"}],description:"The value a member that doesn't set the field gets. Its type is the field's. Without it the field reads as null when unset."},pattern:{type:"string",minLength:1,description:"For a string field: a regular expression the value must match."}},additionalProperties:!1},objectField:{type:"object",required:["type","description","properties"],properties:{type:{const:"object"},description:{type:"string",minLength:1},properties:{type:"object",minProperties:1,propertyNames:{$ref:"#/$defs/fieldName"},additionalProperties:{$ref:"#/$defs/scalarField"},description:"The object's own fields, each a string, integer or boolean field. A member sets any of them; the rest take their defaults."}},additionalProperties:!1}}}});function HV(e){return e===$v||e.endsWith(`/${$v}`)}var $v,oBe,J_=v(()=>{"use strict";$v=".chant/work",oBe=`/${$v}/`});import{createHash as Z_}from"node:crypto";import{lstatSync as oue,readdirSync as sue,readFileSync as qV}from"node:fs";import{join as KV}from"node:path";function cue(e){let t=aue.exec(e);return t?{algorithm:t[1],digest:t[2]}:void 0}function JV(e,t,n){for(let i of sue(e,{withFileTypes:!0})){let r=t===""?i.name:`${t}/${i.name}`;if(i.isSymbolicLink())throw new ld(`${r} is a symbolic link, which a pinned plugin may not contain`);i.isDirectory()?!lue.has(i.name)&&!HV(r)&&JV(KV(e,i.name),r,n):i.isFile()&&n.push(r)}}function uue(e){let t=[];return JV(e,"",t),t.sort((n,i)=>n<i?-1:n>i?1:0)}function due(e,t="sha256"){let n;try{n=oue(e)}catch{throw new ld("it does not exist")}if(n.isSymbolicLink())throw new ld("it is a symbolic link, which a pinned plugin may not be");if(n.isFile())return{integrity:`${t}-${Z_(t).update(qV(e)).digest("base64")}`,files:1};let i=uue(e),r=i.map(o=>`${Z_(t).update(qV(KV(e,...o.split("/")))).digest("hex")} ${o}
54
+ `)))(`notify: nothing was sent: ${o instanceof Error?o.message:String(o)}`),[]}}var G_=v(()=>{"use strict";bv()});var TV={};_e(TV,{DEPRECATED_GATE_KEY_WARNING:()=>_V,FAN_OUT_GATE_OP:()=>id,OVERRIDE_GATE_OP:()=>pa,RELEASE_GATE_OP:()=>ui,WORKSPACE_UPGRADE_GATE_OP:()=>od,gateName:()=>fa,isNeverOverMcpGateOp:()=>W_,opUsesDeprecatedGateKey:()=>Zle,usesDeprecatedGateKey:()=>B_});function W_(e){return e===id||e===od||e===pa||e===ui||Jle.test(e)}function fa(e){return e.gate??e.signalName??""}function B_(e){return e.gate===void 0&&typeof e.signalName=="string"}function Zle(e){let t=i=>i.kind==="gate"?B_(i):i.kind==="effect"?i.steps.some(t):!1,n=i=>(i??[]).some(r=>r.steps.some(t));return n(e.phases)||n(e.onFailure)}var id,od,pa,ui,Jle,_V,Yr=v(()=>{"use strict";id="fan-out",od="workspace-upgrade",pa="policy-override",ui="release",Jle=/^pr-\d+(?:-[a-z0-9][a-z0-9-]*)?$/;_V='Gate steps still using "signalName": the key is now "gate" (chant #2202). "signalName" is accepted through 0.59.0 and removed in 0.60.0.'});function sd(e){return typeof e=="object"&&e!==null&&ma in e&&e[ma]===!0}var ma,ws=v(()=>{"use strict";ma=Symbol.for("chant.intrinsic")});var IV,ga,ad=v(()=>{"use strict";ws();ga=class{constructor(t,n){this[IV]=!0;this.parent=new WeakRef(t),this.attribute=n}_setLogicalName(t){this.logicalName=t}getLogicalName(){return this.logicalName}toString(){let t=this.logicalName?`${this.logicalName}.${this.attribute}`:`.${this.attribute}`;throw new Error(`A resource attribute reference (${t}) has no string form: it stands for a value the build resolves later, and interpolating it into a plain template literal would produce "[object Object]". Use the lexicon's own intrinsic, whose interior handles references \u2014 \`Sub\`\${\u2026}\`\` for CloudFormation \u2014 or move the reference out of the template.`)}[(IV=ma,Symbol.toPrimitive)](){return this.toString()}toJSON(){if(!this.logicalName)throw new Error(`Cannot serialize AttrRef for attribute "${this.attribute}": logical name not set`);return{__attrRef:{entity:this.logicalName,attribute:this.attribute}}}}});function Wi(e){return e instanceof ga?!0:typeof e=="object"&&e!==null&&"parent"in e&&"attribute"in e&&"_setLogicalName"in e&&typeof e.parent=="object"&&typeof e.attribute=="string"}function Gt(e,t){return t&&typeof t=="object"&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([n],[i])=>n.localeCompare(i))):t}var Wt=v(()=>{"use strict";ad()});function di(e){return e!==void 0&&Yle.has(e)}function bs(){if(z_!=="cli")return z_;let e=process.env[Xle];return e==="mcp"||e==="acp"?e:z_}function DV(e,t){if(di(t)&&e===t)return`the gate was reached over ${t} and this resolution arrived over ${t} too, so the same caller wrote both halves`}var Yle,kv,z_,Xle,el=v(()=>{"use strict";Yle=new Set(["mcp","acp"]);kv="unattested",z_="cli",Xle="CHANT_GATE_ORIGIN"});var jV,U_=v(()=>{"use strict";jV=["changeSets","releases","runEvents"]});import{dirname as KWe,isAbsolute as Qle,join as JWe}from"node:path";import{fileURLToPath as eue}from"node:url";function NV(e,t="--report-url"){let n=e.trim();if(n.startsWith("file://")){let r;try{r=eue(n)}catch(o){return{error:`${t} ${n}: ${o instanceof Error?o.message:String(o)}`}}return Qle(r)?{scheme:"file",url:n.replace(/\/+$/,""),dir:r}:{error:`${t} ${n}: a file URL names an absolute directory`}}let i=/^s3:\/\/([^/]+)\/?(.*)$/.exec(n);if(i){let r=i[2].replace(/\/+$/,"");return{scheme:"s3",url:`s3://${i[1]}${r?`/${r}`:""}`,bucket:i[1],prefix:r}}return{error:`${t} ${n}: takes an s3://<bucket>/<prefix> or file://<directory> URL`}}var LV=v(()=>{"use strict"});var V_,MV=v(()=>{V_={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://intentius.io/chant/schemas/workspace/declaration/v1/chant.workspace.schema.json",title:"chant.workspace.json",description:"A workspace declaration, schema 1 (#2524 D1, D2; ws-051). Only this file makes a directory a workspace. It may also be named chant.workspace.jsonc, which allows comments and trailing commas; having both is an error. Unknown fields are refused, except fields whose names start with x-. A field added later within schema 1 is optional, and a declaration that uses one sets minReader to the first chant that knows it, so an older chant says so instead of misreading the file. Uniqueness of names and the placement rules are checked in code, since JSON Schema cannot say them.",type:"object",required:["name","schema","members"],properties:{$schema:{type:"string",description:"An editor hint. chant ignores it."},$comment:{type:"string",description:"A note for people. chant ignores it."},name:{$ref:"#/$defs/name",description:"The workspace's name. With a git revision it identifies the workspace to readers (#2524 D15)."},schema:{const:1,description:"The declaration format version."},minReader:{$ref:"#/$defs/version",description:"The oldest chant that may read this declaration. An older chant refuses it with reader-too-old."},members:{type:"array",description:"Members and example groups, in the order readers list them.",items:{$ref:"#/$defs/entry"}},pins:{type:"array",description:"The toolchain and plugins that read this workspace, pinned (#2524 D3, threat model). Member kinds come only from pinned packages, read as data from their ./workspace-kinds subpath (#2535).",items:{$ref:"#/$defs/pin"}},quorum:{type:"integer",minimum:0,description:"How many agree verdicts besides the decider's a record needs, for every record kind with a reviews list (#2671). chant workspace records reports each record's quorum against it. Two when absent. Added in schema 1 by chant 0.86.0, so a declaration that sets it sets minReader to 0.86.0 or newer. A per-kind quorum comes later (#2650 C14)."},records:{type:"array",description:"The workspace's own record kinds, each a kind file relative to the workspace root (#2680): the kinds whose records belong to no one member, such as a decisions directory at the root. A member names its own in its records. chant workspace ls lists them, and chant workspace records and graph --intent read every declared kind when --kind is not given. Added in schema 1 by chant 0.86.0, so a declaration that uses it sets minReader to 0.86.0 or newer.",items:{$ref:"#/$defs/recordKind"}},hosts:{type:"array",description:"The hosts boxes run on (#2727). A host is one machine reached under one hostname: boxes on it share its ports, its state root and, in a browser, its cookie jar, so chant workspace check compares the boxes on one host and never boxes on different hosts. A member's box block names its host. Added in schema 1 by chant 0.91.0, so a declaration that uses it sets minReader to 0.91.0 or newer.",items:{$ref:"#/$defs/host"}},diagrams:{type:"array",description:"The workspace's own diagram artifacts (#2764): the diagrams that belong to no one member, such as a diagrams directory at the root. A member names its own in its diagrams. chant workspace ls lists every declared diagram, and chant workspace check reports one whose render is stale for its source when the entry records a sourceHash. Added in schema 1 by chant 0.91.0, so a declaration that uses it sets minReader to 0.91.0 or newer.",items:{$ref:"#/$defs/diagram"}},checks:{type:"object",description:"Severity for the declaration checks that allow it, keyed by WSP id (#2535, ws-028): error, warning, info or off. chant workspace check refuses an id it does not know, and one whose severity is fixed.",propertyNames:{pattern:"^WSP[0-9]{3}$"},additionalProperties:{$ref:"#/$defs/severity"}},changes:{type:"object",additionalProperties:!1,description:"The forward coverage check, chant workspace check --changes <base>..<head> (#2773): each path a diff changes is mapped to the current records whose constrains cover it. severity says what a finding does: off reports none, warn (the default) reports them and passes, fail reports them and fails. ignore lists globs over files whose changes need no record, such as lockfiles and generated output. Added in schema 1 by chant 0.92.0, so a declaration that uses it sets minReader to 0.92.0 or newer.",properties:{severity:{enum:["off","warn","fail"],description:"What a change-uncovered or change-out-of-scope finding does. warn when absent."},ignore:{type:"array",description:"Globs over file paths from the workspace root: * and ? within one segment, ** across segments. A changed path one matches is listed as ignored and never reported.",items:{$ref:"#/$defs/fileGlob"}}}},writeScope:{type:"object",propertyNames:{$ref:"#/$defs/className"},additionalProperties:{$ref:"#/$defs/classScope",description:"A domain class a pinned package supplies at its ./workspace-principals subpath (#3080, ws-079): principals holding the role the class names in the trust policy at base, and none of the agent, runner and service roles. A key no pinned package supplies fails chant workspace check with WSP003, and a writer judged human is refused with write-scope-class-unknown, since it may be in that class. Added in schema 1 by chant 0.102.0, so a declaration that uses one sets minReader to 0.102.0 or newer."},description:"Who may write what (#2524 D5, #2548, ws-067): for each principal class, the members whose files it may write and the record kinds it may write, with which verbs. A class is human, agent, runner or service, or a domain class a pinned package supplies (#3080). A class with no entry is not restricted. An agent is always bound to its session's member (agents); its entry can only narrow the record kinds and verbs. chant workspace records new, amend, review and close and the MCP record tools refuse a write outside the writer's scope with write-scope-member or write-scope-kind, and chant workspace check --changes reports each commit that writes outside its author's scope, read from the declaration and the trust policy at the range's base, and a write to a path the class's protected list covers with write-scope-protected (#3146). Added in schema 1 by chant 0.101.0, so a declaration that uses it sets minReader to 0.101.0 or newer.",properties:{human:{$ref:"#/$defs/classScope",description:"Principals holding none of the agent, runner and service roles, and none of the roles a domain class names, in the trust policy at base."},agent:{$ref:"#/$defs/agentScope",description:"An agent session (agents), or a principal holding the agent role in the trust policy at base."},runner:{$ref:"#/$defs/classScope",description:"Principals holding the runner role in the trust policy at base, such as a CI job's signing identity."},service:{$ref:"#/$defs/classScope",description:"Principals holding the service role in the trust policy at base."}}},agents:{type:"array",description:"The agent sessions the workspace declares (#2524 D20, #2548, ws-067, ws-101). Each is bound to the members it names, one with member or several with members: it writes the files of any of them and the records of kinds any of them or the workspace declares, as writeScope.agent allows. A session resumes from chant workspace agent <name> --json, which prints its member, its scope and the spec, read from the repository alone. A write names its session with the CHANT_AGENT environment variable, or a commit with a Chant-Agent trailer. Added in schema 1 by chant 0.101.0, so a declaration that uses it sets minReader to 0.101.0 or newer.",items:{$ref:"#/$defs/agent"}},identity:{type:"object",additionalProperties:!1,description:"Who a person-attributed record or gate approval may name, and which gates need a signed approval (#3163, ws-080). Read from the declaration at base, like writeScope, so a change can't loosen its own rule. A person is named by a forge identity (github:<login>, gitlab:<login>, or <forge>@<host>:<login> for forgejo, gitea or a self-hosted github or gitlab) that the surface which signed them in maps their session to, or by a principal .chant/allowed_signers lists at base. chant never authenticates a person: a forge identity is recorded as the surface gives it, and only a seal verified against the signers at base attests it. Added in schema 1 by chant 0.102.0, so a declaration that uses it sets minReader to 0.102.0 or newer.",properties:{attribution:{enum:["any","identified"],description:"any (the default): a record's by, decided_by, reviewer or answerer and a gate approval's actor may be any name, such as a roster name. identified: each must be a forge identity, a principal the signers file at base lists, or a principal holding the agent, runner or service role at base or listed by a declared agent session; chant workspace records new and review, points answer and chant approve refuse any other name with principal-unidentified."},gates:{type:"object",description:"Gates, by name, that pass only on a signed approval: chant approve --sign with a key the signers file at base lists for the approver. The rule applies to a gate of that name in every member, Op and component. An unsigned approval, or one whose signer is not in class, is recorded nowhere and never counts toward the gate.",propertyNames:{type:"string",minLength:1},additionalProperties:{type:"object",additionalProperties:!1,properties:{class:{$ref:"#/$defs/className",description:"The principal class the signer must be in, read from the role grants at base (#3080, ws-079): human, runner, service, or a domain class a pinned package supplies. A class no pinned package supplies lets no approval through (fail closed). Absent: any signer the signers file lists."}}}}}},ci:{type:"object",additionalProperties:!1,patternProperties:{"^x-":!0},description:"What the workspace's CI decides about its commits (#3573, ws-103). Added in schema 1 by chant 0.108.0, so a declaration that uses it sets minReader to 0.108.0 or newer.",properties:{green:{$ref:"#/$defs/ciGreen"},workflow:{$ref:"#/$defs/ciWorkflow"},reportUrl:{type:"string",minLength:1,description:"Where the pull-request jobs copy their reports and events, and where chant ci run keeps the run index, <reportUrl>/runs/index.json (#4160): an s3://<bucket>/<prefix> or file://<directory> URL, as --report-url takes. chant build --pr-loop, chant ci run, chant ci serve and chant ci runs use it when --report-url is not given, and the flag wins. Readers find it in chant workspace ls --json as ci.reportUrl. Added in schema 1 by chant 0.124.32, so a declaration that uses it sets minReader to 0.124.32 or newer."}}},retention:{type:"object",additionalProperties:!1,patternProperties:{"^x-":!0},description:"How long chant lifecycle gc keeps each kind of stored record (#4036). A kind or field left out keeps its default: changeSets 14 days; releases 14 days and the newest 10 of each member; runEvents 14 days and the newest 100. Whatever the policy, gc never prunes a release an environment runs, what a pending gate binds, or a change set a gate names with a kept release. Read from the declaration at base. Added in schema 1 by chant 0.124.29, so a declaration that uses it sets minReader to 0.124.29 or newer.",properties:{changeSets:{type:"object",additionalProperties:!1,description:"Stored change sets, _change-sets/<digest>.json on chant/lifecycle.",properties:{days:{$ref:"#/$defs/retentionDays"}}},releases:{type:"object",additionalProperties:!1,description:"Releases, _releases/<digest>.json on chant/lifecycle, with the template bytes only they name. A release stays promotable for days after its newest cut, and the newest keep releases of each member stay promotable at any age, unless their commit is revoked.",properties:{days:{$ref:"#/$defs/retentionDays"},keep:{$ref:"#/$defs/retentionKeep"}}},runEvents:{type:"object",additionalProperties:!1,description:"Run event files, <git-common-dir>/chant/run-events/<run>.jsonl on each host. A file is kept for days after its last write, and the newest keep files at any age.",properties:{days:{$ref:"#/$defs/retentionDays"},keep:{$ref:"#/$defs/retentionKeep"}}}}},metrics:{type:"object",additionalProperties:!1,patternProperties:{"^x-":!0},description:"How chant workspace metrics counts the DORA metrics (#4039). Added in schema 1 by chant 0.124.29, so a declaration that uses it sets minReader to 0.124.29 or newer.",properties:{failureWindowDays:{type:"integer",minimum:1,maximum:365,description:"A deploy counts as failed when, within this many days after it, the commit it deployed is revoked or the environment is rolled back from it. The default is 7."}}},security:{type:"array",uniqueItems:!0,description:"The security groups the workspace opts into (#4168), for every member; a member's own security adds to them. With none, a security feature the workspace has not turned on never refuses, warns or hides anything. verified-releases: release publish and promote --release take only a verified release. supply-chain: a publish without OIDC provenance warns, and a target with no SBOM source is refused. who-ran-it: ci tick needs a runner key. review-rules: pr-apply requires a forge review. isolated-runners: an apply job requires a runner-start statement. workspace check reports what a declared group lacks (WSP161 to WSP165). Added in schema 1 by chant 0.124.33, so a declaration that uses it sets minReader to 0.124.33 or newer.",items:{enum:["verified-releases","supply-chain","who-ran-it","review-rules","isolated-runners"]}}},patternProperties:{"^x-":!0},additionalProperties:!1,$defs:{retentionDays:{type:"integer",minimum:0,maximum:36500,description:"Days a record is kept past its last write or use. 0 lets every record go that no never-prune rule keeps."},retentionKeep:{type:"integer",minimum:0,maximum:1e5,description:"How many of the newest are kept at any age."},name:{type:"string",pattern:"^[a-z0-9][a-z0-9-]{0,39}$",description:"Lowercase letters, digits and hyphens, starting with a letter or digit, at most 40 characters. _workspace and _members are reserved; the pattern already rules them out."},kindName:{type:"string",pattern:"^[a-z][a-z0-9-]{0,39}$"},className:{type:"string",pattern:"^(?!x-)[a-z][a-z0-9-]{0,39}$",description:"A principal class: human, agent, runner, service, or a domain class a pinned package supplies (#3080)."},version:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?$"},dir:{type:"string",description:'A directory relative to the workspace root, with / separators: "." for the root itself, otherwise no leading /, no . or .. segments and no trailing /.',pattern:"^(\\.|(?!\\.\\.?(/|$))[^/\\\\]+(/(?!\\.\\.?(/|$))[^/\\\\]+)*)$"},glob:{type:"string",description:"A glob over directories, relative to the workspace root: * and ? within one segment, ** across segments, [...] classes. No leading /, no . or .. segments.",pattern:"^(?!\\.\\.?(/|$))[^/\\\\]+(/(?!\\.\\.?(/|$))[^/\\\\]+)*$"},severity:{enum:["error","warning","info","off"]},suppress:{type:"array",description:"Declaration checks suppressed for this entry (#2535). Each names a WSP id and says why. A suppressed finding is still reported, as suppressed, and never fails check.",items:{type:"object",required:["check","because"],properties:{check:{type:"string",pattern:"^WSP[0-9]{3}$"},because:{type:"string",minLength:1}},patternProperties:{"^x-":!0},additionalProperties:!1}},outputName:{type:"string",minLength:1,maxLength:255,pattern:"^[^\\u0000-\\u001f]+$",description:"An output's name, compared exactly."},link:{type:"object",description:"A member link: this member reads output of member (#2539), or sends its telemetry to a pipeline of its collector (#2558).",required:["member","output"],properties:{member:{$ref:"#/$defs/name",description:"The producer: another member of this workspace."},output:{$ref:"#/$defs/outputName",description:"The producer's output, matched exactly. It must be one the producer's kind exposes. For a telemetry link, the id of a pipeline or an exporter in the producer's collector."},kind:{$ref:"#/$defs/kindName",description:"The link kind. output, the default: the consumer reads the named output. telemetry (#2558): the consumer sends its telemetry to the named pipeline or exporter of the producer's collector, and chant workspace graph checks that it exists and, when protocol is given, that it speaks it. A declaration that uses telemetry sets minReader to 0.101.0 or newer."},protocol:{enum:["grpc","http/protobuf","http/json"],description:"For a telemetry link, the OTLP protocol the consumer sends, as OTEL_EXPORTER_OTLP_PROTOCOL names it. Refused on any other kind. Added in schema 1 by chant 0.101.0."}},patternProperties:{"^x-":!0},additionalProperties:!1},entry:{description:"A member, or an example group when kind is examples (ws-051).",type:"object",required:["kind"],properties:{kind:{$ref:"#/$defs/kindName"}},if:{type:"object",properties:{kind:{const:"examples"}},required:["kind"]},then:{$ref:"#/$defs/group"},else:{$ref:"#/$defs/member"}},member:{type:"object",description:"A member (#2524 D2). Its directory leaves the root project, and it gets its own build, lint and ledger.",required:["name","dir","kind"],properties:{name:{$ref:"#/$defs/name",description:"Frozen once the member deploys; a rename is an alias record."},dir:{$ref:"#/$defs/dir"},kind:{$ref:"#/$defs/kindName",description:"How to read the member: chant, workspace, other, or a kind a pinned plugin supplies (#2535)."},roles:{type:"array",description:"Roles the member plays. A role may point at a path inside the member.",items:{oneOf:[{$ref:"#/$defs/kindName"},{type:"object",required:["name"],properties:{name:{$ref:"#/$defs/kindName"},path:{$ref:"#/$defs/dir",description:"Relative to the member's directory."}},patternProperties:{"^x-":!0},additionalProperties:!1}]}},generated:{type:"array",description:"Files in the member's directory that a command writes (#2524 D14, #2541). chant workspace check fails when one differs from what its generator writes, unless the entry is marked handWritten with a reason. The lineage lock classes the same files as generated. skills/*/SKILL.md, which chant update writes, is listed implicitly for a chant member.",items:{$ref:"#/$defs/generatedFile"}},outputs:{type:"array",uniqueItems:!0,description:"The outputs this member exposes as link targets (#2539), for a member whose kind takes them from the entry: other, or a kind a pinned package supplies. A chant member's outputs are read from its source, and a nested workspace exposes none.",items:{$ref:"#/$defs/outputName"}},fields:{$ref:"#/$defs/memberFields"},links:{type:"array",description:"Member links (#2524 D6, #2539): the outputs of other members this member reads. A link is stated once, here on the consumer, and matched exactly against the producer's outputs. chant workspace check resolves it in source.",items:{$ref:"#/$defs/link"}},records:{type:"array",description:"The record kinds this member holds, each a kind file relative to the member's directory (#2680). chant workspace ls lists them, and chant workspace records and graph --intent read every declared kind when --kind is not given. Added in schema 1 by chant 0.86.0, so a declaration that uses it sets minReader to 0.86.0 or newer.",items:{$ref:"#/$defs/recordKind"}},diagrams:{type:"array",description:"The diagram artifacts this member holds (#2764). chant workspace ls lists every declared diagram, and chant workspace check reports one whose render is stale for its source when the entry records a sourceHash. Added in schema 1 by chant 0.91.0, so a declaration that uses it sets minReader to 0.91.0 or newer.",items:{$ref:"#/$defs/diagram"}},box:{$ref:"#/$defs/box"},upstream:{type:"string",minLength:1,description:"Where an embedded member's files come from. Versions live in the lock."},ci:{type:"object",additionalProperties:!1,patternProperties:{"^x-":!0},description:"This member's own CI settings (#4168 step 6). Added in schema 1 by chant 0.124.34, so a declaration that uses it sets minReader to 0.124.34 or newer.",properties:{workflow:{$ref:"#/$defs/ciWorkflow"}}},travel:{type:"boolean",description:"Whether the member goes with an export (#2524 D10, #2552). chant workspace export writes only members that set travel to true into the export member, and refuses to name one that does not. Added in schema 1 by chant 0.101.0, so a declaration that uses it sets minReader to 0.101.0 or newer."},security:{type:"array",uniqueItems:!0,description:"The security groups this member opts into, added to the declaration's top-level security (#4168). A release, publish or pull-request job of this member runs under both lists. Added in schema 1 by chant 0.124.33, so a declaration that uses it sets minReader to 0.124.33 or newer.",items:{enum:["verified-releases","supply-chain","who-ran-it","review-rules","isolated-runners"]}},because:{type:"string",minLength:1,description:"Why the member is there. Required for kind other."},suppress:{$ref:"#/$defs/suppress"}},patternProperties:{"^x-":!0},additionalProperties:!1,if:{type:"object",properties:{kind:{const:"other"}},required:["kind"]},then:{type:"object",properties:{because:{type:"string"}},required:["because"]}},memberFields:{type:"object",description:"Values for the fields the member's kind declares (#3151), such as an app member's scripts, env and health. Each is a string, integer or boolean, or an object of those for a field the kind declares as an object. chant workspace check fails when the kind declares no such field or a value is of the wrong type (WSP005), and chant workspace status --json prints every field the kind declares with its defaults filled in. Added in schema 1 by chant 0.103.0, so a declaration that uses it sets minReader to 0.103.0 or newer.",propertyNames:{pattern:"^[a-z][A-Za-z0-9]{0,39}$"},additionalProperties:{oneOf:[{type:"string"},{type:"integer"},{type:"boolean"},{type:"object",propertyNames:{pattern:"^[a-z][A-Za-z0-9]{0,39}$"},additionalProperties:{oneOf:[{type:"string"},{type:"integer"},{type:"boolean"}]}}]}},group:{type:"object",description:"An example group (ws-051): every directory the glob matches that holds a chant project is built and linted. A group has no ledger, releases or links, and its matches are never members. A match may sit inside a member's directory; that member leaves it to the group.",required:["name","kind","glob"],properties:{name:{$ref:"#/$defs/name"},kind:{const:"examples"},glob:{oneOf:[{$ref:"#/$defs/glob"},{type:"array",minItems:1,uniqueItems:!0,items:{$ref:"#/$defs/glob"}}]},suppress:{$ref:"#/$defs/suppress"}},patternProperties:{"^x-":!0},additionalProperties:!1},path:{type:"string",description:"A file or directory path with / separators: no leading /, no . or .. segments and no trailing /.",pattern:"^(?!\\.\\.?(/|$))[^/\\\\]+(/(?!\\.\\.?(/|$))[^/\\\\]+)*$"},box:{type:"object",description:"The member is a box, or holds a box's declarations (#2726). A box holds no credential: each capability it needs outside itself is reached through a broker, a runtime such as a lobby or a door, which holds the credential and enforces the scope. chant workspace check fails when a file in the member's directory carries a literal secret (WSP121) and when a capability names no broker (WSP122). chant workspace status --json lists the capabilities, so a broker can read the scopes. Its host, slot, ports, state and cookies state the box's isolation (#2727): chant derives each value from the box's identity, its host, the member's name and its slot, and prints them in chant workspace status --json, so a runtime reads them instead of choosing its own. chant workspace check fails when two boxes on a host resolve to the same value (WSP123) and when a box hard-codes a machine path (WSP124). A member that builds the fountain lexicon's Box declares the callback token fountain gives its sandbox as the capability fountain-callback, brokered by fountain, with scope owner, or chant workspace check fails (WSP125, #2780). Its intent names the decision record that says what the box is for (#2850): chant workspace status --json reports the record's state and answer, and chant workspace check fails when no decision record has the id (WSP126) and warns when the record constrains no member or path of this workspace (WSP127, #2857). Its services list what the box runs under its supervisor (#2880), which the fly lexicon observes, restarts and applies through sprite-env, and which chant workspace status --json prints. Its factory declares what the box builds, how a build is checked, which member declares the builder agents and where a finished build is published (#3146, ws-077), its listing what the box shows of itself (#3146), and its replicate where the box's work in progress is pushed so a lost box loses none of it (#3172, ws-085). Added in schema 1 by chant 0.91.0, so a declaration that uses it sets minReader to 0.91.0 or newer.",properties:{intent:{type:"string",minLength:1,description:"The id of the decision record that says what the box is for (#2850), a record of a declared kind named decision. A new box starts as a question: the record is proposed with a null choice until the person who answers it decides it. The record constrains a member or path of this workspace, with member:<a member's name> or a path: entry at, above or inside a member's directory. It need not be this member: the intent can constrain the app the box runs when that app is another member (#2857). When it constrains this member, chant workspace graph --intent shows it for the box's files. Added by chant 0.94.0, so a declaration that uses it sets minReader to 0.94.0 or newer."},services:{type:"array",description:"The services the box runs under its supervisor, sprite-env on a sprite (#2880). Each name is given once, every needs entry names a service of this list, the needs form no cycle, and at most one service sets httpPort; a declaration that breaks one of these can't be read (declaration-invalid). The fly lexicon's spriteServicesObserve and spriteServiceRestart read the list with box: true, and spriteApplyServices with box: true creates and replaces the services through sprite-env. None when omitted. Added by chant 0.95.0, so a declaration that uses it sets minReader to 0.95.0 or newer.",items:{$ref:"#/$defs/boxService"}},factory:{$ref:"#/$defs/boxFactory"},listing:{$ref:"#/$defs/boxListing"},publisher:{type:"string",minLength:1,pattern:"\\S",description:"The command that publishes the box's work (#3165, ws-088): it applies a built work item to the box's checkout and, when factory.publish names a target, pushes it and opens the pull request, and it sends the records a person kept uncommitted. It is run from the workspace root by chant workspace box publish, split into words as a shell splits plain words (quotes group, a backslash escapes) but never given to a shell, with a JSON request on stdin; box-publish.schema.json says what it reads and prints. An orchestrator such as studio supplies it. chant workspace status --json prints it under the member's box, so a surface offers a publish only when a box names one. Added in schema 1 by chant 0.103.0, so a declaration that uses it sets minReader to 0.103.0 or newer."},replicate:{$ref:"#/$defs/boxReplicate"},ship:{$ref:"#/$defs/boxShip"},capabilities:{type:"array",description:"Each capability the box reaches outside itself, named once. None when omitted.",items:{$ref:"#/$defs/capability"}},host:{$ref:"#/$defs/name",description:"The host the box runs on, one of the top-level hosts (#2727). The box's name is the member's name."},slot:{type:"integer",minimum:0,description:"The box's number on its host (#2727). Its ports come from the slot's block of the host's range."},ports:{type:"object",description:"The ports the box listens on, each a name and its offset in the box's block (#2727). The port is the block's first port plus the offset.",propertyNames:{$ref:"#/$defs/kindName"},additionalProperties:{type:"integer",minimum:0,maximum:65534}},state:{type:"object",description:"State the box keeps outside its checkout, such as hud's identity and database, each a name and a path relative to the box's state directory (#2727). The name is usually the environment variable the runtime sets, such as HUD_IDENTITY_PATH. A path that is absolute, starts with ~ or an environment reference, or has a .. segment is a WSP124 finding.",propertyNames:{type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_-]{0,63}$"},additionalProperties:{type:"string",minLength:1}},cookies:{type:"array",description:"Session cookie names the box's runtimes set, such as hud_session (#2727). A browser scopes a cookie to a host, not a port, so each resolves to <cookie>_<member name>.",uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"}}},dependentRequired:{host:["slot"],slot:["host"],ports:["host"],state:["host"],cookies:["host"]},patternProperties:{"^x-":!0},additionalProperties:!1},boxFactory:{type:"object",description:"What the box builds and how (#3146, ws-077), replacing studio's x-factory. Opt-in: a box block without it declares no factory, and nothing here is required of a workspace that doesn't build with agents (#3174). At most one box block in a declaration declares a factory. builds and builders name declared members, or the declaration can't be read (declaration-invalid). chant workspace status --json and chant workspace graph --json print it under the member's box. The factory need not build an app: builds may name any member kind, such as chant or terraform, and the check may be a plan, a lint or a conformance run. Added in schema 1 by chant 0.102.0, so a declaration that uses it sets minReader to 0.102.0 or newer.",required:["builds"],properties:{builds:{type:"array",minItems:1,uniqueItems:!0,description:"The members the factory builds, each a declared member of any kind. A work item a person asks for here constrains member:<the first>.",items:{$ref:"#/$defs/name"}},check:{description:"The command whose exit code is a build's verdict, run from the workspace root after the work item's own checks: a command, or { run, kind } saying what it is. kind is test when omitted.",oneOf:[{type:"string",minLength:1},{type:"object",required:["run"],properties:{run:{type:"string",minLength:1,description:"The command, run from the workspace root."},kind:{enum:["test","build","lint","plan","conformance"],description:"What the command is: an app's tests, a build, a lint, a lifecycle plan or a conformance run. test when omitted."}},patternProperties:{"^x-":!0},additionalProperties:!1}]},checks:{$ref:"#/$defs/path",description:"The directory, from the workspace root, where a work item's builder writes the check for its item. When omitted the orchestrator chooses, such as <the first member of builds>/checks."},builders:{$ref:"#/$defs/name",description:"The member that declares the builder agents, such as the one whose agents/ holds them. tiers says which of them builds at which tier (#3152)."},tiers:{type:"array",minItems:1,description:"Which builder agent builds at which tier (#3152, ws-094), replacing studio's studio/role and studio/tier Agent metadata. Each entry names a tier, in the vocabulary of the work kind's work.tier.tiers (#3147), and an agent the builders member declares, by its name. An entry with kinds builds only members of those kinds, so an infra builder and an app builder can share a tier; an entry without kinds builds the tier for every other kind. A tier has at most one entry without kinds and at most one per kind, tiers needs builders, and a session names a declared agent session, or the declaration can't be read (declaration-invalid). chant workspace status --json prints builderFor, the agent for each built member and tier. Added in schema 1 by chant 0.103.0, so a declaration that uses it sets minReader to 0.103.0 or newer.",items:{type:"object",required:["tier","agent"],properties:{tier:{$ref:"#/$defs/kindName",description:"The tier, such as small, medium or large: a word of the work kind's work.tier.tiers, which a work item's tier or the slice-tier decision point answers."},agent:{type:"string",minLength:1,pattern:"^[^\\u0000-\\u001f]+$",description:"The builder agent's name, as the builders member declares it (such as an Agent of the fountain lexicon in its agents/)."},kinds:{type:"array",minItems:1,uniqueItems:!0,items:{$ref:"#/$defs/kindName"},description:"The member kinds this agent builds at the tier, such as app or terraform. Without it, every kind no other entry of the tier names."},session:{$ref:"#/$defs/name",description:"The declared agent session (agents) the builder writes as, so its write scope is that session's. Optional: without it the orchestrator chooses."}},patternProperties:{"^x-":!0},additionalProperties:!1}},publish:{type:"object",description:"Where a finished build is published: its branch is pushed and a pull request opened against repo's base. The repo is the record, so an orchestrator reads this instead of being told the target in its environment.",required:["repo"],properties:{forge:{enum:["github"],description:"The forge repo is on. github when omitted."},repo:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}$",description:"The repository the pull request is opened on, as owner/name."},base:{type:"string",minLength:1,description:"The branch the pull request targets. The repository's default branch when omitted."},branchPrefix:{type:"string",minLength:1,pattern:"^[A-Za-z0-9._/-]+$",description:"What the published branch's name starts with; the work item's id follows, as in box/ and then box/work-012. chant/work/ when omitted, the work lease's own branch."},head:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}$",description:"The repository the branch is pushed to when it isn't repo, as owner/name: a fork, so the pull request comes from <head owner>:<branch>. A runtime that publishes for one contributor's fork supplies that per contributor instead (arugula-salad/studio#242); this names a fork the whole workspace publishes from."}},patternProperties:{"^x-":!0},additionalProperties:!1}},patternProperties:{"^x-":!0},additionalProperties:!1},boxListing:{type:"object",description:"What the box shows of itself on a home site that lists boxes (#3146, #3154): whether it is listed, its title and one line, and a cover image kept as a file in the repo. A box's listing is configuration, so changing it is a reviewed change (ws-074). chant workspace status --json and chant workspace graph --json print it under the member's box, with the cover's sha256. Added in schema 1 by chant 0.102.0, so a declaration that uses it sets minReader to 0.102.0 or newer.",properties:{published:{type:"boolean",description:"Whether the box is listed. true when omitted: a box is listed unless its owner takes it out."},title:{type:"string",maxLength:60,pattern:"^[^\\u0000-\\u001f\\u007f-\\u009f]*$",description:"The box's title, one line of at most 60 characters. Empty when omitted, and a reader then shows a name of its own."},line:{type:"string",maxLength:140,pattern:"^[^\\u0000-\\u001f\\u007f-\\u009f]*$",description:"One line saying what the box is, at most 140 characters. Empty when omitted."},cover:{$ref:"#/$defs/path",description:"A PNG, JPEG or WebP picture of the box, as a file from the workspace root. None when omitted."}},patternProperties:{"^x-":!0},additionalProperties:!1},boxReplicate:{type:"object",description:"Where the box's work in progress is replicated, so a box that is lost, reclaimed or corrupted before anyone commits loses nothing (#3172, ws-085). Work in progress is the work branches (chant/work/...), the kept attempts (refs/chant/kept/..., #3147), the snapshots chant workspace wip save takes of each branch's working tree, uncommitted records included (refs/chant/wip/<branch>), and the ledger branch, chant/lifecycle. chant pushes them to remote under their own names and never forces a push. Opt-in: a box block without it replicates nothing. At most one box block in a declaration declares one, or the declaration can't be read (declaration-invalid). chant workspace status --json prints it under the member's box, with every default filled in, and reports in replication how far each ref is from the remote. Added in schema 1 by chant 0.103.0, so a declaration that uses it sets minReader to 0.103.0 or newer.",properties:{remote:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",description:"The git remote to push to, by name: the repository's own remote, such as origin, or a mirror the host adds to the box's checkout with its credential, since a box holds none (#2726). origin when omitted."},refs:{type:"array",minItems:1,uniqueItems:!0,description:"What is replicated: work (the branches under chant/work/), kept (the kept attempts under refs/chant/kept/), wip (the snapshots under refs/chant/wip/) and ledger (the chant/lifecycle branch). All four when omitted.",items:{enum:["work","kept","wip","ledger"]}},on:{type:"array",uniqueItems:!0,description:"When chant pushes on its own: save, after each chant workspace wip save, and release, after a work lease is released (chant workspace work release, or a run of an Op under a work lease ending, which is when a kept attempt is written). Both when omitted; an empty list leaves every push to chant workspace wip push. A record write never pushes, because chant's record writes never run git (ws-074).",items:{enum:["save","release"]}},every:{type:"string",pattern:"^[1-9][0-9]*(s|m|h)$",description:"How often the host runs chant workspace wip push on a schedule of its own, such as 10m, beside the pushes on save and release. chant runs no scheduler; it only states the interval. None when omitted."}},patternProperties:{"^x-":!0},additionalProperties:!1},boxShip:{type:"object",description:"How the box ships its staged work to its own site (ws-100): the people working on a box see the working tree at once, everyone else sees the last release, and a person ships. op is the Op in the box member that does it: its own steps commit the staged tree as one commit by the person shipping (named to it in CHANT_SHIP_BY) with a Chant-Record trailer for each work item it lands, then release that commit to the box's site, stopping at gate, and record the release in env's release ledger. chant runs none of it; a surface runs chant run <op> in the member's directory and approves the gate as for any Op. chant workspace status --json prints it under the member's box with the commit the site serves (the latest release in env's ledger) and what is waiting to ship (the files changed between that commit and the working tree, bookkeeping left out). Added in schema 1 by chant 0.104.0, so a declaration that uses it sets minReader to 0.104.0 or newer.",required:["op"],properties:{op:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",description:"The name of the Op in the box member that ships, as chant run takes it."},gate:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",description:"The gate the Op stops at for a person's approval. ship when omitted."},env:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",description:"The environment whose release ledger, under the box member, the Op records each release in. box when omitted."},bookkeeping:{type:"array",uniqueItems:!0,description:"Path prefixes from the workspace root whose changes are bookkeeping, such as the record directories, and never count as waiting to ship. None when omitted.",items:{type:"string",minLength:1,pattern:"^(?!/)(?!.*(^|/)\\.\\.(/|$))[^\\n]+$"}}},patternProperties:{"^x-":!0},additionalProperties:!1},boxService:{type:"object",description:"A service a box runs under its supervisor (#2880).",required:["name","cmd"],properties:{name:{$ref:"#/$defs/kindName",description:"The service's name in the supervisor. Unique within the box."},cmd:{type:"string",minLength:1,description:"The command the supervisor runs (sprite-env services create --cmd). ${HOME} and other ${VAR} references are expanded from the environment of the process that applies the list, so the declaration holds no machine path."},needs:{type:"array",uniqueItems:!0,description:"Names of services of the same box that start before this one (sprite-env services create --needs).",items:{$ref:"#/$defs/kindName"}},httpPort:{$ref:"#/$defs/port",description:"The port the supervisor routes the sprite's URL to (sprite-env services create --http-port). At most one service of a box sets it."},duration:{type:"string",pattern:"^[0-9]+(\\.[0-9]+)?(ms|s|m)$",description:"How long the service must stay up after it is created or started, such as 3s (sprite-env services create --duration)."},health:{type:"string",pattern:"^https?://",description:"A URL that answers 200 while the service works. spriteServicesObserve probes it, and spriteServiceRestart waits for it after a restart. Without it, the supervisor's state decides."},optional:{type:"boolean",description:"True for a service something else creates by name, such as a site a release Op makes: spriteApplyServices creates it only when its only names it, and spriteServicesObserve skips it while the supervisor has no such service."}},patternProperties:{"^x-":!0},additionalProperties:!1},capability:{type:"object",description:"A capability a box needs and does not hold the credential for, such as inference, fountain or a third-party API (#2726).",required:["name"],properties:{name:{$ref:"#/$defs/kindName",description:"The capability, such as inference or fountain. Unique within the box."},broker:{type:"string",minLength:1,description:"What brokers the capability: the runtime that holds the credential and swaps the box's own token for it, such as lobby or door. It may name a member of this workspace, or a runtime outside it. Without it the capability is unbrokered, and chant workspace check fails with WSP122."},scope:{type:"array",uniqueItems:!0,description:"What of the box's own the broker lets it reach, which the broker enforces. For Fountain: agent (start conversations with its own agent), vault (attach its own vault), conversations and sandboxes (its own). The words are the broker's; chant records them.",items:{type:"string",minLength:1,pattern:"^[^\\u0000-\\u001f]+$"}}},patternProperties:{"^x-":!0},additionalProperties:!1},recordKind:{type:"object",description:"A record kind the workspace declares (#2680): a kind file that exports recordKind. chant workspace check fails (WSP115) when the file is missing or does not load as a record kind.",required:["kind"],properties:{kind:{$ref:"#/$defs/path",description:"The kind file, relative to the member's directory, or to the workspace root for the workspace's own records. A path is listed once across the declaration."},name:{$ref:"#/$defs/kindName",description:"The name readers show for the kind. Without it, the kind file's own recordKind.name. Unique across the declaration."}},patternProperties:{"^x-":!0},additionalProperties:!1},diagram:{type:"object",description:"A diagram artifact the workspace declares (#2764): a rendered image with a source, pinned to the renderer that made it. A mermaid or excalidraw diagram may name no render: a reader draws it from its source. chant never runs the renderer.",required:["name","title","renderer"],if:{type:"object",properties:{renderer:{type:"object",properties:{tool:{enum:["mermaid","excalidraw"]}},required:["tool"]}},required:["renderer"]},then:{type:"object",properties:{source:{$ref:"#/$defs/path"}},required:["source"]},else:{type:"object",properties:{render:{$ref:"#/$defs/path"}},required:["render"]},properties:{name:{$ref:"#/$defs/name",description:"Unique across the declaration."},title:{type:"string",minLength:1,description:"Shown above the diagram."},source:{oneOf:[{$ref:"#/$defs/path"},{type:"null"}],description:"The source file, from the workspace root, with / separators. Null for an SVG with no source. Default null."},render:{oneOf:[{$ref:"#/$defs/path"},{type:"null"}],description:"The rendered image, from the workspace root, with / separators. Required for d2 and graphviz. A mermaid or excalidraw diagram needs a source instead and may leave render out or null, from chant 0.96.0: a reader such as hud draws it from the source (an excalidraw diagram may still commit an exported SVG for docs)."},renderer:{$ref:"#/$defs/diagramRenderer"},sourceHash:{type:["string","null"],pattern:"^[0-9a-f]{64}$",description:"sha256 hex of the source's bytes when render was last produced from it, or for a mermaid or excalidraw diagram without a render, when the source was last pinned. chant workspace check compares this against the source in the tree read and reports drift (WSP133) on a mismatch; without it, or without a source, the render is never checked for drift. Default null."}},patternProperties:{"^x-":!0},additionalProperties:!1},diagramRenderer:{type:"object",description:"The renderer a diagram's render was made with. chant records the pin; it never installs or runs the renderer (ws-052).",required:["tool","version"],properties:{tool:{enum:["d2","mermaid","graphviz","excalidraw"]},version:{$ref:"#/$defs/version",description:"The exact release the render was made with, such as 0.9.0. For mermaid or excalidraw, the release of the library a reader draws the source with, such as 11.4.1."},args:{type:"array",description:'Passed before the input and output paths, in order, such as ["--layout=elk", "--theme=0", "--pad=40", "--omit-version"]. Empty when absent.',items:{type:"string"}}},patternProperties:{"^x-":!0},additionalProperties:!1},generatedFile:{type:"object",description:"One generated file of a member (#2524 D14, #2541).",required:["path","generator"],properties:{path:{$ref:"#/$defs/path",description:"The file, relative to the member's directory."},generator:{type:"string",minLength:1,description:"The command line that writes the file, run in the member's directory with the member's own node_modules/.bin first on PATH, such as chant build ci --lexicon github -o ci.yml. When it passes -o or --output with this file's path, chant workspace check --generated points that flag at a temporary file. Otherwise the generator writes in place and check restores the tree afterwards."},sources:{type:"array",description:"The files or directories the generator reads, relative to the workspace root, since a generator often reads other members.",items:{$ref:"#/$defs/path"}},handWritten:{type:"object",description:"The file is kept by hand instead of regenerated. chant workspace check reports it with the reason and never runs its generator, and the lock classes it owned.",required:["because"],properties:{because:{type:"string",minLength:1}},patternProperties:{"^x-":!0},additionalProperties:!1}},patternProperties:{"^x-":!0},additionalProperties:!1},pin:{description:"An npm package at an exact version, or a local plugin by path. integrity is a Subresource Integrity digest.",oneOf:[{type:"object",required:["package","version"],properties:{package:{type:"string",pattern:"^(@[a-z0-9-~][a-z0-9-._~]*/)?[a-z0-9-~][a-z0-9-._~]*$"},version:{$ref:"#/$defs/version"},integrity:{type:"string",pattern:"^sha(256|384|512)-[A-Za-z0-9+/]+={0,2}$"}},patternProperties:{"^x-":!0},additionalProperties:!1},{type:"object",required:["path"],properties:{path:{$ref:"#/$defs/dir"},integrity:{type:"string",pattern:"^sha(256|384|512)-[A-Za-z0-9+/]+={0,2}$"}},patternProperties:{"^x-":!0},additionalProperties:!1}]},host:{type:"object",description:"A host boxes run on (#2727).",required:["name","ports"],properties:{name:{$ref:"#/$defs/name",description:"The host's name, unique among hosts. A box block names it in host."},ports:{type:"object",description:"The TCP ports boxes on this host take theirs from. Slot n owns the block from + n * perBox to from + (n + 1) * perBox - 1, which must end at or before to.",required:["from","to","perBox"],properties:{from:{$ref:"#/$defs/port",description:"The first port of the range."},to:{$ref:"#/$defs/port",description:"The last port of the range, inclusive."},perBox:{type:"integer",minimum:1,maximum:65535,description:"How many ports each box's block holds. A box's port offsets are below it."}},additionalProperties:!1},stateRoot:{type:"string",minLength:1,description:"Where boxes on this host keep state, as an environment reference such as ${XDG_STATE_HOME}/chant/boxes, which the runtime expands on the machine. A box's state directory is <stateRoot>/<member name>. A literal machine path, such as /Users/... or anything under $HOME, is a WSP124 finding. Default ${XDG_STATE_HOME}/chant/boxes."}},patternProperties:{"^x-":!0},additionalProperties:!1},port:{type:"integer",minimum:1,maximum:65535},fileGlob:{type:"string",description:"A glob over file paths, relative to the workspace root: * and ? within one segment, ** across segments, [...] classes and {a,b} alternatives. No leading /, no . or .. segments.",pattern:"^(?!\\.\\.?(/|$))[^/\\\\]+(/(?!\\.\\.?(/|$))[^/\\\\]+)*$"},recordScope:{type:"object",description:"Record kind names, as the kind file's recordKind.name or the name the declaration gives it, each with the verbs the class may write it with: new, amend, review and close (a review session). A kind left out may not be written at all. A record file a commit deletes is never in scope.",propertyNames:{$ref:"#/$defs/kindName"},additionalProperties:{type:"array",uniqueItems:!0,items:{enum:["new","amend","review","close"]}}},protectedPath:{description:"A protected path: a glob from the workspace root, or { path, except } for a JSON file whose listed top-level keys, or the values JSON Pointers name, may still change.",oneOf:[{$ref:"#/$defs/fileGlob"},{type:"object",required:["path"],properties:{path:{$ref:"#/$defs/fileGlob"},except:{type:"array",minItems:1,uniqueItems:!0,description:"What a write may change in the JSON file: a top-level key, or, for an entry starting with /, the values a JSON Pointer matches, where a * token matches every key or array index at its level, such as /members/*/box/listing for every box's listing (#3308). A change anywhere else in the file, or to a file that doesn't parse as a JSON object before and after, is still outside the scope.",items:{type:"string",minLength:1}}},patternProperties:{"^x-":!0},additionalProperties:!1}]},classScope:{type:"object",description:"A principal class's write scope.",properties:{members:{description:"The members whose files the class may write, by name, or * for every path. Without it, every path. A path in no member is in scope only under *.",oneOf:[{const:"*"},{type:"array",uniqueItems:!0,items:{$ref:"#/$defs/name"}}]},protected:{type:"array",description:"Paths the class may not write, even inside a member it may (#3146, ws-077): each a glob from the workspace root, or { path, except } for a JSON file the class may change only in the top-level keys except names. An entry protects the files it matches and everything under a directory it matches. A record file is judged by records, not here. Added in schema 1 by chant 0.102.0, so a declaration that uses it sets minReader to 0.102.0 or newer.",items:{$ref:"#/$defs/protectedPath"}},records:{$ref:"#/$defs/recordScope",description:"The record kinds the class may write, and how. Without it, every kind in reach, with every verb. A kind a member declares is in reach when that member is; the workspace's own kinds always are."}},patternProperties:{"^x-":!0},additionalProperties:!1},agentScope:{type:"object",description:"The agent class's write scope. Its members are always the members its session is bound to, so only the record kinds and the protected paths can be set.",properties:{protected:{type:"array",description:"Paths the class may not write, even inside a member it may (#3146, ws-077): each a glob from the workspace root, or { path, except } for a JSON file the class may change only in the top-level keys except names. An entry protects the files it matches and everything under a directory it matches. A record file is judged by records, not here. Added in schema 1 by chant 0.102.0, so a declaration that uses it sets minReader to 0.102.0 or newer.",items:{$ref:"#/$defs/protectedPath"}},records:{$ref:"#/$defs/recordScope",description:"The record kinds an agent may write, and how. Without it, every kind in reach of its member, with every verb."}},patternProperties:{"^x-":!0},additionalProperties:!1},agent:{type:"object",description:"An agent session (#2548). It names its members with exactly one of member and members (ws-101).",required:["name"],oneOf:[{properties:{member:!0},required:["member"]},{properties:{members:!0},required:["members"]}],properties:{name:{$ref:"#/$defs/name",description:"The session's name, unique among agents: what CHANT_AGENT and a Chant-Agent trailer give."},member:{$ref:"#/$defs/name",description:"The one member the session is bound to. It must be a declared member, not an example group. A session bound to several names them with members instead."},members:{type:"array",minItems:1,uniqueItems:!0,items:{$ref:"#/$defs/name"},description:"The members the session is bound to, when it writes in more than one, such as a factory that builds an app and writes its evidence records in a design member (ws-101, arugula-salad/studio#402). Each must be a declared member, not an example group. The session may write the files of any of them and the records of kinds any of them or the workspace declares, and the write scope is judged against all of them together. Added in schema 1 by chant 0.105.0, so a declaration that uses it sets minReader to 0.105.0 or newer."},principals:{type:"array",uniqueItems:!0,items:{type:"string",minLength:1},description:"Principals that write only as this session: a commit attested by one, or a write whose by names one, is judged as the session. A principal is listed by one session at most."}},patternProperties:{"^x-":!0},additionalProperties:!1},ciGreen:{type:"object",description:"Which commits passed CI (#3573, ws-103). chant ci tick tags each first-parent commit of branch, within window, whose required phases all passed with ci/green/<sha>, and a green commit that later fails a required phase with ci/revoked/<sha>. Both are annotated tags made once and never moved or deleted by chant. chant ci last-green prints the newest commit with a green tag and no revoked tag.",required:["branch","phases","require"],properties:{branch:{type:"string",minLength:1,pattern:"^[^\\s~^:?*\\[\\\\]+$",description:"The branch whose commits are tagged, such as main. Only its first-parent commits count."},window:{type:"string",pattern:"^[1-9][0-9]*(m|h|d)$",description:"How far back a tick looks, by committer time, such as 24h, 90m or 7d. 24h when absent."},phases:{type:"object",minProperties:1,description:"The phases, by name. Each is a list of check-run name patterns, or { runs, skipped }. A pattern matches a check run's whole name, with * standing for any run of characters. A phase passes when every check run its patterns match finished with success, judged by each run's latest attempt.",propertyNames:{$ref:"#/$defs/ciPhaseName"},additionalProperties:{$ref:"#/$defs/ciPhase"}},require:{type:"array",minItems:1,uniqueItems:!0,description:"The phases a commit must pass to be tagged green, by name. Each must be a declared phase.",items:{$ref:"#/$defs/ciPhaseName"}},preMerge:{type:"array",uniqueItems:!0,description:"The phases that must pass before the branch moves (#4168 4.4), by name: the quick checks a pull request's checks, a merge queue, chant ci serve landing a branch, or chant ci run --local give before a change lands. Each must be a declared phase. The trunk-curated workflow needs at least one. Added in schema 1 by chant 0.124.34, so a declaration that uses it sets minReader to 0.124.34 or newer.",items:{$ref:"#/$defs/ciPhaseName"}},signedSince:{type:"string",pattern:"^[0-9a-f]{40}([0-9a-f]{24})?$",description:"Added by #4031, read by chant 0.124.28 and newer. The full sha of the first commit on branch whose ci/green and ci/revoked tags must carry a DSSE statement in their annotation, signed by a key .chant/trust.json at base lists under runners for a principal holding the runner role. A tag on a strict first-parent ancestor of this commit counts unsigned, so existing tags keep working; a tag on any other commit, this one included, needs a statement. Position in history decides, never a date, which whoever makes a commit or a tag sets. A reader refuses a sha that names no commit in its clone with declaration-invalid. Absent, no tag needs a statement. Since chant 0.124.32 (#4156) it covers Op run records the same way, when ci.green.source is runs: an unsigned run counts on a strict first-parent ancestor of this commit and needs a statement on any other, ci serve refuses to start without a runner key trusted at the target's head, and ci run and chant run warn about a run they leave unsigned. Absent, an unsigned run counts and nothing asks for a key."},source:{enum:["checks","runs"],description:"Added by #4044, read by chant 0.124.28 and newer, so a declaration that sets it sets minReader to 0.124.28 or newer. Where chant ci tick reads each phase's results. checks (the default): the forge's check runs, whose names the phases' patterns match. runs: chant's own Op runs, read from the run ledger on chant/lifecycle, for a project whose pipelines run as chant Ops, such as one on GitLab or Forgejo. A phase's patterns then match Op names, a run counts for the commit its record names as gitSha, and the latest run of each Op decides. A run counts only when its record carries a statement signed by a key .chant/trust.json at base lists under runners for a principal holding the runner role; the tick ignores and reports any other. A tick from runs signs every tag it makes, so it needs a runner key."}},patternProperties:{"^x-":!0},additionalProperties:!1},ciWorkflow:{enum:["trunk-curated","trunk-curated+apply-on-merge"],description:"A prescribed delivery workflow (#4168). trunk-curated: a merge records the plan and deploys nothing; releases are cut from green commits and promoted through each member's environments, gated in the last. trunk-curated+apply-on-merge: the same, with the apply on merge turned back on. chant workspace check reports what a member under one still lacks (WSP151), and chant ci init writes it. At the top level for every member, or on a member, which wins. Added in schema 1 by chant 0.124.34, so a declaration that uses it sets minReader to 0.124.34 or newer."},ciPhaseName:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$"},ciPhase:{oneOf:[{$ref:"#/$defs/ciRunPatterns"},{type:"object",required:["runs"],properties:{runs:{$ref:"#/$defs/ciRunPatterns"},skipped:{enum:["pass","fail"],description:"What a check run that finished as skipped counts as. fail (the default): it never passes. pass: it passes, for a job a path filter runs only on some commits."},build:{enum:["every","newest"],description:"Added by #4169, read by chant 0.124.33 and newer. Which first-parent commits of the branch the phase runs on. every (the default): each one. newest: only the newest commit when a runner frees. Under either, a run that was cancelled leaves the commit unbuilt rather than red. Under newest, a commit a newer run superseded is unbuilt too, and a red commit starts a bisect over the unbuilt commits back to the last one the phase passed on. chant ci workflow writes the triggers and concurrency of the workflows holding a phase that sets build, and leaves them alone for a phase that does not."}},patternProperties:{"^x-":!0},additionalProperties:!1}]},ciRunPatterns:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1,description:"A check run's name, such as lint, or a pattern with *, such as e2e (*)."}}}}});var q_={};_e(q_,{gitTop:()=>vs,gitTree:()=>cd,joinPath:()=>qe,resolveCommit:()=>H_,skippedDir:()=>Bi,workingTree:()=>Rn});import{execFileSync as WV}from"node:child_process";import{readdirSync as nue,readFileSync as FV,statSync as GV}from"node:fs";import{join as km}from"node:path";function qe(...e){return e.filter(t=>t!==""&&t!==".").join("/")}function Rn(e){return{label:"",stat(t){try{let n=GV(km(e,t));return n.isDirectory()?"dir":n.isFile()?"file":void 0}catch{return}},list(t){let n;try{n=nue(km(e,t),{withFileTypes:!0})}catch{return}let i=[];for(let r of n){let o=r.isDirectory()?"dir":r.isFile()?"file":void 0;if(!o&&r.isSymbolicLink())try{let s=GV(km(e,t,r.name));o=s.isDirectory()?"dir":s.isFile()?"file":void 0}catch{}o&&i.push({name:r.name,type:o})}return i},read(t){return FV(km(e,t),"utf-8")},bytes(t){return FV(km(e,t))}}}function xv(e,t){return WV("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],maxBuffer:512*1024*1024})}function vs(e){try{return xv(e,["rev-parse","--show-toplevel"]).trim()}catch{return}}function H_(e,t){if(!t.startsWith("-"))try{return xv(e,["rev-parse","--verify","--quiet",`${t}^{commit}`]).trim()}catch{return}}function cd(e,t,n=""){let i=new Map([["","dir"]]),r=new Map([["",[]]]),o=xv(e,["ls-tree","-r","-t","-z","--full-tree",t]);for(let s of o.split("\0")){if(!s)continue;let a=s.indexOf(" "),c=s.slice(0,a).split(" ")[1],l=s.slice(a+1),u;if(n==="")u=l;else if(l.startsWith(`${n}/`))u=l.slice(n.length+1);else continue;let d=c==="tree"?"dir":c==="blob"?"file":void 0;if(!d)continue;i.set(u,d);let p=u.lastIndexOf("/"),f=p<0?"":u.slice(0,p);r.has(f)||r.set(f,[]),r.get(f).push({name:u.slice(p+1),type:d}),d==="dir"&&!r.has(u)&&r.set(u,[])}return{label:` at ${t.slice(0,8)}`,stat:s=>i.get(s),list:s=>i.get(s)==="dir"?[...r.get(s)??[]]:void 0,read(s){if(i.get(s)!=="file")throw new Error(`${s} is not a file${` at ${t.slice(0,8)}`}`);return xv(e,["cat-file","blob",`${t}:${qe(n,s)}`])},bytes(s){if(i.get(s)!=="file")throw new Error(`${s} is not a file${` at ${t.slice(0,8)}`}`);return WV("git",["cat-file","blob",`${t}:${qe(n,s)}`],{cwd:e,stdio:["ignore","pipe","pipe"],maxBuffer:512*1024*1024})}}}function Bi(e){return e==="node_modules"||e.startsWith(".")}var on=v(()=>{"use strict"});function zV(e,t){let i=t.split("/").map(a=>a==="**"?"**":rue(a)?a:(0,BV.default)(a,{dot:!1})),r=new Set,o=a=>(e.list(a)??[]).filter(c=>c.type==="dir"&&!Bi(c.name)).map(c=>c.name),s=(a,c)=>{if(c===i.length){a!==""&&r.add(a);return}let l=i[c];if(l==="**"){s(a,c+1);for(let u of o(a))s(qe(a,u),c);return}if(typeof l=="string"){let u=qe(a,l);e.stat(u)==="dir"&&s(u,c+1);return}for(let u of o(a))l(u)&&s(qe(a,u),c+1)};return s("",0),[...r].sort()}var BV,rue,UV=v(()=>{"use strict";BV=Ye(vm(),1);on();rue=e=>!/[*?[\]{}()!+@]/.test(e)});var K_,VV=v(()=>{K_={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://intentius.io/chant/schemas/workspace/kinds/v1/workspace-kinds.schema.json",title:"workspace-kinds.json",description:"Member kinds a plugin supplies (#2524 D3, #2535, ws-031). A package publishes this file as data at its ./workspace-kinds subpath. chant reads it with the file system and never imports the package, so reading kinds never loads a lexicon.",type:"object",required:["schema","kinds"],properties:{$schema:{type:"string",description:"An editor hint. chant ignores it."},$comment:{type:"string",description:"A note for people. chant ignores it."},schema:{const:1,description:"The kinds format version."},kinds:{type:"array",minItems:1,items:{$ref:"#/$defs/kind"}}},patternProperties:{"^x-":!0},additionalProperties:!1,$defs:{kind:{type:"object",required:["name","description","precedence","probe"],properties:{name:{type:"string",pattern:"^[a-z][a-z0-9-]{0,39}$",description:"The kind's name, as a member's kind field names it. chant, workspace, other and examples are built in and can't be supplied."},description:{type:"string",minLength:1,description:"One line saying what the member's directory holds, for listings and error messages."},precedence:{type:"integer",minimum:1,maximum:999,description:"When the probes of several kinds claim one directory, the highest precedence decides. Two claiming kinds with the same highest precedence are a tie, and a tie fails. The built-in chant kind has 500 and workspace has 1000."},probe:{$ref:"#/$defs/probe"},outputs:{type:"array",uniqueItems:!0,description:"The outputs every member of this kind exposes as link targets (#2524 D6, #2539). A member entry of the kind may list more in its own outputs field. Without this field the kind exposes only what each entry lists.",items:{type:"string",minLength:1,maxLength:255,pattern:"^[^\\u0000-\\u001f]+$"}},graph:{$ref:"#/$defs/graph"},fields:{$ref:"#/$defs/fields"},reader:{type:"string",pattern:"^[a-z][a-z0-9-]{0,39}$",description:"A link reader chant ships, by name, that derives a member's links from the member's own files (#3932): dbt-project reads a dbt project's sources. The reader is chant's code and runs offline, parsing files as data; the package supplies only the name. A name this chant doesn't have keeps the kind without a reader, and the load reports it. A chant older than this field fails a kinds file that uses it."}},patternProperties:{"^x-":!0},additionalProperties:!1},probe:{type:"object",description:"What the probe checks in a member's directory. It runs no code. It passes when any of its clauses does, and it needs at least one.",minProperties:1,properties:{anyFile:{type:"array",minItems:1,uniqueItems:!0,description:"The directory passes when a file matching one of these names sits directly in it. A * in a name matches any run of characters, so *.tf matches every Terraform file.",items:{$ref:"#/$defs/fileName"}},anyBlock:{type:"object",description:"The directory passes when a file directly in it, whose name matches one of in, has a line opening an unlabelled block named in blocks: leading space, the name, optional space, then {. No file is parsed.",required:["in","blocks"],properties:{in:{type:"array",minItems:1,uniqueItems:!0,items:{$ref:"#/$defs/fileName"}},blocks:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_-]{0,63}$"}}},additionalProperties:!1},anyJsonKey:{type:"object",description:"The directory passes when a file directly in it, whose name matches one of in, parses as JSON and has a value at one of pointers, each a JSON Pointer such as /scripts/start (#3151). A file that is not JSON is no evidence either way. Added by chant 0.103.0.",required:["in","pointers"],properties:{in:{type:"array",minItems:1,uniqueItems:!0,items:{$ref:"#/$defs/fileName"}},pointers:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",pattern:"^(/[^/]+)+$"}}},additionalProperties:!1}},additionalProperties:!1},fileName:{type:"string",description:"A file name, with no directory part. A * matches any run of characters.",pattern:"^(?!\\.\\.?$)[^/\\\\]+$"},graph:{type:"object",description:"How chant workspace graph reads a member of this kind (#2874). chant writes a reader project of its own outside the workspace, with a chant.config.json that declares lexicon and puts config under that lexicon's key, and runs the member's chant graph there. In every string key and value of config, {member} becomes the member's name, {dir} its absolute directory and {workspace} the absolute workspace root. Without this field a member of the kind is listed with kind-not-run.",required:["lexicon","config"],properties:{lexicon:{type:"string",pattern:"^[a-z][a-z0-9-]{0,39}$",description:"The lexicon that reads the member, by name. The package that supplies the kind must be @intentius/chant-lexicon-<lexicon>, so the lexicon chant loads is the one the declaration pins."},config:{type:"object",description:"The lexicon's config namespace for the reader project, such as terraform's roots. Placeholders are substituted; nothing else is interpreted."}},patternProperties:{"^x-":!0},additionalProperties:!1},fields:{type:"object",description:"The fields a member entry of this kind may set under its own fields block, each with a type and, optionally, a default (#3151). chant workspace check fails a member whose fields name one the kind doesn't declare or give a value of the wrong type (WSP005), and chant workspace status --json prints every declared field with the defaults filled in. Added by chant 0.103.0; an older chant can't read a kinds file that uses it.",minProperties:1,propertyNames:{$ref:"#/$defs/fieldName"},additionalProperties:{oneOf:[{$ref:"#/$defs/scalarField"},{$ref:"#/$defs/objectField"}]}},fieldName:{type:"string",pattern:"^[a-z][A-Za-z0-9]{0,39}$"},scalarField:{type:"object",required:["type","description"],properties:{type:{enum:["string","integer","boolean"]},description:{type:"string",minLength:1},default:{oneOf:[{type:"string"},{type:"integer"},{type:"boolean"}],description:"The value a member that doesn't set the field gets. Its type is the field's. Without it the field reads as null when unset."},pattern:{type:"string",minLength:1,description:"For a string field: a regular expression the value must match."}},additionalProperties:!1},objectField:{type:"object",required:["type","description","properties"],properties:{type:{const:"object"},description:{type:"string",minLength:1},properties:{type:"object",minProperties:1,propertyNames:{$ref:"#/$defs/fieldName"},additionalProperties:{$ref:"#/$defs/scalarField"},description:"The object's own fields, each a string, integer or boolean field. A member sets any of them; the rest take their defaults."}},additionalProperties:!1}}}});function HV(e){return e===$v||e.endsWith(`/${$v}`)}var $v,oBe,J_=v(()=>{"use strict";$v=".chant/work",oBe=`/${$v}/`});import{createHash as Z_}from"node:crypto";import{lstatSync as oue,readdirSync as sue,readFileSync as qV}from"node:fs";import{join as KV}from"node:path";function cue(e){let t=aue.exec(e);return t?{algorithm:t[1],digest:t[2]}:void 0}function JV(e,t,n){for(let i of sue(e,{withFileTypes:!0})){let r=t===""?i.name:`${t}/${i.name}`;if(i.isSymbolicLink())throw new ld(`${r} is a symbolic link, which a pinned plugin may not contain`);i.isDirectory()?!lue.has(i.name)&&!HV(r)&&JV(KV(e,i.name),r,n):i.isFile()&&n.push(r)}}function uue(e){let t=[];return JV(e,"",t),t.sort((n,i)=>n<i?-1:n>i?1:0)}function due(e,t="sha256"){let n;try{n=oue(e)}catch{throw new ld("it does not exist")}if(n.isSymbolicLink())throw new ld("it is a symbolic link, which a pinned plugin may not be");if(n.isFile())return{integrity:`${t}-${Z_(t).update(qV(e)).digest("base64")}`,files:1};let i=uue(e),r=i.map(o=>`${Z_(t).update(qV(KV(e,...o.split("/")))).digest("hex")} ${o}
55
55
  `).join("");return{integrity:`${t}-${Z_(t).update(r,"utf8").digest("base64")}`,files:i.length}}function ZV(e,t,n){let i=cue(t);if(!i)return{ok:!1,message:`${n}: integrity ${JSON.stringify(t)} is not sha256-, sha384- or sha512- and a base64 digest`};let r;try{r=due(e,i.algorithm).integrity}catch(o){if(!(o instanceof ld))throw o;return{ok:!1,message:`${n}: can't check its integrity, ${o.message}`}}return r===t?{ok:!0}:{ok:!1,message:`${n}: integrity mismatch, so nothing is read from it. The pin says ${t} and the plugin hashes to ${r}. If the change is intended, run \`chant workspace pin ${n}\` and put the value it prints in the pin; otherwise restore the plugin`}}var aue,lue,ld,YV=v(()=>{"use strict";J_();aue=/^(sha(?:256|384|512))-([A-Za-z0-9+/]+={0,2})$/;lue=new Set(["node_modules",".git"]),ld=class extends Error{}});import{createHash as pue,createPublicKey as Y_,verify as X_}from"node:crypto";function Rm(e){let t=e.carriedFrom;if(t===void 0)return e;let{carriedFrom:n,checkpointDigest:i,...r}=e;return{...r,op:t.op,gate:t.gate,timestamp:t.timestamp,...t.checkpointDigest!==void 0?{checkpointDigest:t.checkpointDigest}:{}}}function Sm(e){return(e.carriedFrom!==void 0?e.carriedFrom.checkpointDigest:e.checkpointDigest)!==void 0?2:1}function Ao(e){let t=Rm(e),n=t.relayedBy!==void 0?`
56
56
  relayed-by ${t.relayedBy}`:"",i=Sm(t)===2?`
57
57
  checkpoint ${t.checkpointDigest}`:"";return Buffer.from(`${t.op}
@@ -71,7 +71,7 @@ ${e.timestamp}`,"utf-8")}function yue(e,t,n){let i=`the approval of gate ${n.gat
71
71
  depsCount: ${t},
72
72
  deps: ${n}}`};var rge={keyword:"dependencies",type:"object",schemaType:"object",error:To.error,code(e){let[t,n]=ige(e);Xq(e,t),Qq(e,n)}};function ige({schema:e}){let t={},n={};for(let i in e){if(i==="__proto__")continue;let r=Array.isArray(e[i])?t:n;r[i]=e[i]}return[t,n]}function Xq(e,t=e.schema){let{gen:n,data:i,it:r}=e;if(Object.keys(t).length===0)return;let o=n.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let c=(0,rg.propertyInData)(n,i,s,r.opts.ownProperties);e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),r.allErrors?n.if(c,()=>{for(let l of a)(0,rg.checkReportMissingProp)(e,l)}):(n.if((0,AT._)`${c} && (${(0,rg.checkMissingProp)(e,a,o)})`),(0,rg.reportMissingProp)(e,o),n.else())}}To.validatePropertyDeps=Xq;function Qq(e,t=e.schema){let{gen:n,data:i,keyword:r,it:o}=e,s=n.name("valid");for(let a in t)(0,nge.alwaysValidSchema)(o,t[a])||(n.if((0,rg.propertyInData)(n,i,a,o.opts.ownProperties),()=>{let c=e.subschema({keyword:r,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>n.var(s,!0)),e.ok(s))}To.validateSchemaDeps=Qq;To.default=rge});var tK=ae(PT=>{"use strict";Object.defineProperty(PT,"__esModule",{value:!0});var eK=tt(),oge=ft(),sge={message:"property name must be valid",params:({params:e})=>(0,eK._)`{propertyName: ${e.propertyName}}`},age={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:sge,code(e){let{gen:t,schema:n,data:i,it:r}=e;if((0,oge.alwaysValidSchema)(r,n))return;let o=t.name("valid");t.forIn("key",i,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),t.if((0,eK.not)(o),()=>{e.error(!0),r.allErrors||t.break()})}),e.ok(o)}};PT.default=age});var _T=ae(CT=>{"use strict";Object.defineProperty(CT,"__esModule",{value:!0});var rk=mi(),Hi=tt(),cge=fi(),ik=ft(),lge={message:"must NOT have additional properties",params:({params:e})=>(0,Hi._)`{additionalProperty: ${e.additionalProperty}}`},uge={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:lge,code(e){let{gen:t,schema:n,parentSchema:i,data:r,errsCount:o,it:s}=e;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,ik.alwaysValidSchema)(s,n))return;let l=(0,rk.allSchemaProperties)(i.properties),u=(0,rk.allSchemaProperties)(i.patternProperties);d(),e.ok((0,Hi._)`${o} === ${cge.default.errors}`);function d(){t.forIn("key",r,w=>{!l.length&&!u.length?g(w):t.if(p(w),()=>g(w))})}function p(w){let b;if(l.length>8){let k=(0,ik.schemaRefOrVal)(s,i.properties,"properties");b=(0,rk.isOwnProperty)(t,k,w)}else l.length?b=(0,Hi.or)(...l.map(k=>(0,Hi._)`${w} === ${k}`)):b=Hi.nil;return u.length&&(b=(0,Hi.or)(b,...u.map(k=>(0,Hi._)`${(0,rk.usePattern)(e,k)}.test(${w})`))),(0,Hi.not)(b)}function f(w){t.code((0,Hi._)`delete ${r}[${w}]`)}function g(w){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){f(w);return}if(n===!1){e.setParams({additionalProperty:w}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,ik.alwaysValidSchema)(s,n)){let b=t.name("valid");c.removeAdditional==="failing"?(h(w,b,!1),t.if((0,Hi.not)(b),()=>{e.reset(),f(w)})):(h(w,b),a||t.if((0,Hi.not)(b),()=>t.break()))}}function h(w,b,k){let $={keyword:"additionalProperties",dataProp:w,dataPropType:ik.Type.Str};k===!1&&Object.assign($,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema($,b)}}};CT.default=uge});var iK=ae(IT=>{"use strict";Object.defineProperty(IT,"__esModule",{value:!0});var dge=vd(),nK=mi(),TT=ft(),rK=_T(),pge={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:n,parentSchema:i,data:r,it:o}=e;o.opts.removeAdditional==="all"&&i.additionalProperties===void 0&&rK.default.code(new dge.KeywordCxt(o,rK.default,"additionalProperties"));let s=(0,nK.allSchemaProperties)(n);for(let d of s)o.definedProperties.add(d);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=TT.mergeEvaluated.props(t,(0,TT.toHash)(s),o.props));let a=s.filter(d=>!(0,TT.alwaysValidSchema)(o,n[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a)l(d)?u(d):(t.if((0,nK.propertyInData)(t,r,d,o.opts.ownProperties)),u(d),o.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(d),e.ok(c);function l(d){return o.opts.useDefaults&&!o.compositeRule&&n[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};IT.default=pge});var cK=ae(DT=>{"use strict";Object.defineProperty(DT,"__esModule",{value:!0});var oK=mi(),ok=tt(),sK=ft(),aK=ft(),fge={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:n,data:i,parentSchema:r,it:o}=e,{opts:s}=o,a=(0,oK.allSchemaProperties)(n),c=a.filter(h=>(0,sK.alwaysValidSchema)(o,n[h]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let l=s.strictSchema&&!s.allowMatchingProperties&&r.properties,u=t.name("valid");o.props!==!0&&!(o.props instanceof ok.Name)&&(o.props=(0,aK.evaluatedPropsToName)(t,o.props));let{props:d}=o;p();function p(){for(let h of a)l&&f(h),o.allErrors?g(h):(t.var(u,!0),g(h),t.if(u))}function f(h){for(let w in l)new RegExp(h).test(w)&&(0,sK.checkStrictMode)(o,`property ${w} matches pattern ${h} (use allowMatchingProperties)`)}function g(h){t.forIn("key",i,w=>{t.if((0,ok._)`${(0,oK.usePattern)(e,h)}.test(${w})`,()=>{let b=c.includes(h);b||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:w,dataPropType:aK.Type.Str},u),o.opts.unevaluated&&d!==!0?t.assign((0,ok._)`${d}[${w}]`,!0):!b&&!o.allErrors&&t.if((0,ok.not)(u),()=>t.break())})})}}};DT.default=fge});var lK=ae(jT=>{"use strict";Object.defineProperty(jT,"__esModule",{value:!0});var mge=ft(),gge={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:n,it:i}=e;if((0,mge.alwaysValidSchema)(i,n)){e.fail();return}let r=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},r),e.failResult(r,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};jT.default=gge});var uK=ae(NT=>{"use strict";Object.defineProperty(NT,"__esModule",{value:!0});var hge=mi(),yge={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:hge.validateUnion,error:{message:"must match a schema in anyOf"}};NT.default=yge});var dK=ae(LT=>{"use strict";Object.defineProperty(LT,"__esModule",{value:!0});var sk=tt(),wge=ft(),bge={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,sk._)`{passingSchemas: ${e.passing}}`},vge={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:bge,code(e){let{gen:t,schema:n,parentSchema:i,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(r.opts.discriminator&&i.discriminator)return;let o=n,s=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(s,()=>e.reset(),()=>e.error(!0));function l(){o.forEach((u,d)=>{let p;(0,wge.alwaysValidSchema)(r,u)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&t.if((0,sk._)`${c} && ${s}`).assign(s,!1).assign(a,(0,sk._)`[${a}, ${d}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,d),p&&e.mergeEvaluated(p,sk.Name)})})}}};LT.default=vge});var pK=ae(MT=>{"use strict";Object.defineProperty(MT,"__esModule",{value:!0});var kge=ft(),xge={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:n,it:i}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");let r=t.name("valid");n.forEach((o,s)=>{if((0,kge.alwaysValidSchema)(i,o))return;let a=e.subschema({keyword:"allOf",schemaProp:s},r);e.ok(r),e.mergeEvaluated(a)})}};MT.default=xge});var gK=ae(FT=>{"use strict";Object.defineProperty(FT,"__esModule",{value:!0});var ak=tt(),mK=ft(),$ge={message:({params:e})=>(0,ak.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,ak._)`{failingKeyword: ${e.ifClause}}`},Rge={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:$ge,code(e){let{gen:t,parentSchema:n,it:i}=e;n.then===void 0&&n.else===void 0&&(0,mK.checkStrictMode)(i,'"if" without "then" and "else" is ignored');let r=fK(i,"then"),o=fK(i,"else");if(!r&&!o)return;let s=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),r&&o){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(a,l("then",u),l("else",u))}else r?t.if(a,l("then")):t.if((0,ak.not)(a),l("else"));e.pass(s,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(u)}function l(u,d){return()=>{let p=e.subschema({keyword:u},a);t.assign(s,a),e.mergeValidEvaluated(p,s),d?t.assign(d,(0,ak._)`${u}`):e.setParams({ifClause:u})}}}};function fK(e,t){let n=e.schema[t];return n!==void 0&&!(0,mK.alwaysValidSchema)(e,n)}FT.default=Rge});var hK=ae(GT=>{"use strict";Object.defineProperty(GT,"__esModule",{value:!0});var Sge=ft(),Ege={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,Sge.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};GT.default=Ege});var BT=ae(WT=>{"use strict";Object.defineProperty(WT,"__esModule",{value:!0});var Oge=$T(),Age=Kq(),Pge=RT(),Cge=Zq(),_ge=Yq(),Tge=nk(),Ige=tK(),Dge=_T(),jge=iK(),Nge=cK(),Lge=lK(),Mge=uK(),Fge=dK(),Gge=pK(),Wge=gK(),Bge=hK();function zge(e=!1){let t=[Lge.default,Mge.default,Fge.default,Gge.default,Wge.default,Bge.default,Ige.default,Dge.default,Tge.default,jge.default,Nge.default];return e?t.push(Age.default,Cge.default):t.push(Oge.default,Pge.default),t.push(_ge.default),t}WT.default=zge});var UT=ae(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});ig.dynamicAnchor=void 0;var zT=tt(),Uge=fi(),yK=Um(),Vge=Zv(),Hge={keyword:"$dynamicAnchor",schemaType:"string",code:e=>wK(e,e.schema)};function wK(e,t){let{gen:n,it:i}=e;i.schemaEnv.root.dynamicAnchors[t]=!0;let r=(0,zT._)`${Uge.default.dynamicAnchors}${(0,zT.getProperty)(t)}`,o=i.errSchemaPath==="#"?i.validateName:qge(e);n.if((0,zT._)`!${r}`,()=>n.assign(r,o))}ig.dynamicAnchor=wK;function qge(e){let{schemaEnv:t,schema:n,self:i}=e.it,{root:r,baseId:o,localRefs:s,meta:a}=t.root,{schemaId:c}=i.opts,l=new yK.SchemaEnv({schema:n,schemaId:c,root:r,baseId:o,localRefs:s,meta:a});return yK.compileSchema.call(i,l),(0,Vge.getValidate)(e,l)}ig.default=Hge});var VT=ae(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});og.dynamicRef=void 0;var bK=tt(),Kge=fi(),vK=Zv(),Jge={keyword:"$dynamicRef",schemaType:"string",code:e=>kK(e,e.schema)};function kK(e,t){let{gen:n,keyword:i,it:r}=e;if(t[0]!=="#")throw new Error(`"${i}" only supports hash fragment reference`);let o=t.slice(1);if(r.allErrors)s();else{let c=n.let("valid",!1);s(c),e.ok(c)}function s(c){if(r.schemaEnv.root.dynamicAnchors[o]){let l=n.let("_v",(0,bK._)`${Kge.default.dynamicAnchors}${(0,bK.getProperty)(o)}`);n.if(l,a(l,c),a(r.validateName,c))}else a(r.validateName,c)()}function a(c,l){return l?()=>n.block(()=>{(0,vK.callRef)(e,c),n.let(l,!0)}):()=>(0,vK.callRef)(e,c)}}og.dynamicRef=kK;og.default=Jge});var xK=ae(HT=>{"use strict";Object.defineProperty(HT,"__esModule",{value:!0});var Zge=UT(),Yge=ft(),Xge={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,Zge.dynamicAnchor)(e,""):(0,Yge.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};HT.default=Xge});var $K=ae(qT=>{"use strict";Object.defineProperty(qT,"__esModule",{value:!0});var Qge=VT(),ehe={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,Qge.dynamicRef)(e,e.schema)};qT.default=ehe});var RK=ae(KT=>{"use strict";Object.defineProperty(KT,"__esModule",{value:!0});var the=UT(),nhe=VT(),rhe=xK(),ihe=$K(),ohe=[the.default,nhe.default,rhe.default,ihe.default];KT.default=ohe});var EK=ae(JT=>{"use strict";Object.defineProperty(JT,"__esModule",{value:!0});var SK=nk(),she={keyword:"dependentRequired",type:"object",schemaType:"object",error:SK.error,code:e=>(0,SK.validatePropertyDeps)(e)};JT.default=she});var OK=ae(ZT=>{"use strict";Object.defineProperty(ZT,"__esModule",{value:!0});var ahe=nk(),che={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,ahe.validateSchemaDeps)(e)};ZT.default=che});var AK=ae(YT=>{"use strict";Object.defineProperty(YT,"__esModule",{value:!0});var lhe=ft(),uhe={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:n}){t.contains===void 0&&(0,lhe.checkStrictMode)(n,`"${e}" without "contains" is ignored`)}};YT.default=uhe});var PK=ae(XT=>{"use strict";Object.defineProperty(XT,"__esModule",{value:!0});var dhe=EK(),phe=OK(),fhe=AK(),mhe=[dhe.default,phe.default,fhe.default];XT.default=mhe});var _K=ae(QT=>{"use strict";Object.defineProperty(QT,"__esModule",{value:!0});var Oa=tt(),CK=ft(),ghe=fi(),hhe={message:"must NOT have unevaluated properties",params:({params:e})=>(0,Oa._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},yhe={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:hhe,code(e){let{gen:t,schema:n,data:i,errsCount:r,it:o}=e;if(!r)throw new Error("ajv implementation error");let{allErrors:s,props:a}=o;a instanceof Oa.Name?t.if((0,Oa._)`${a} !== true`,()=>t.forIn("key",i,d=>t.if(l(a,d),()=>c(d)))):a!==!0&&t.forIn("key",i,d=>a===void 0?c(d):t.if(u(a,d),()=>c(d))),o.props=!0,e.ok((0,Oa._)`${r} === ${ghe.default.errors}`);function c(d){if(n===!1){e.setParams({unevaluatedProperty:d}),e.error(),s||t.break();return}if(!(0,CK.alwaysValidSchema)(o,n)){let p=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:CK.Type.Str},p),s||t.if((0,Oa.not)(p),()=>t.break())}}function l(d,p){return(0,Oa._)`!${d} || !${d}[${p}]`}function u(d,p){let f=[];for(let g in d)d[g]===!0&&f.push((0,Oa._)`${p} !== ${g}`);return(0,Oa.and)(...f)}}};QT.default=yhe});var IK=ae(eI=>{"use strict";Object.defineProperty(eI,"__esModule",{value:!0});var pl=tt(),TK=ft(),whe={message:({params:{len:e}})=>(0,pl.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,pl._)`{limit: ${e}}`},bhe={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:whe,code(e){let{gen:t,schema:n,data:i,it:r}=e,o=r.items||0;if(o===!0)return;let s=t.const("len",(0,pl._)`${i}.length`);if(n===!1)e.setParams({len:o}),e.fail((0,pl._)`${s} > ${o}`);else if(typeof n=="object"&&!(0,TK.alwaysValidSchema)(r,n)){let c=t.var("valid",(0,pl._)`${s} <= ${o}`);t.if((0,pl.not)(c),()=>a(c,o)),e.ok(c)}r.items=!0;function a(c,l){t.forRange("i",l,s,u=>{e.subschema({keyword:"unevaluatedItems",dataProp:u,dataPropType:TK.Type.Num},c),r.allErrors||t.if((0,pl.not)(c),()=>t.break())})}}};eI.default=bhe});var DK=ae(tI=>{"use strict";Object.defineProperty(tI,"__esModule",{value:!0});var vhe=_K(),khe=IK(),xhe=[vhe.default,khe.default];tI.default=xhe});var jK=ae(nI=>{"use strict";Object.defineProperty(nI,"__esModule",{value:!0});var ln=tt(),$he={message:({schemaCode:e})=>(0,ln.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ln._)`{format: ${e}}`},Rhe={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:$he,code(e,t){let{gen:n,data:i,$data:r,schema:o,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;r?p():f();function p(){let g=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=n.const("fDef",(0,ln._)`${g}[${s}]`),w=n.let("fType"),b=n.let("format");n.if((0,ln._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(w,(0,ln._)`${h}.type || "string"`).assign(b,(0,ln._)`${h}.validate`),()=>n.assign(w,(0,ln._)`"string"`).assign(b,h)),e.fail$data((0,ln.or)(k(),$()));function k(){return c.strictSchema===!1?ln.nil:(0,ln._)`${s} && !${b}`}function $(){let x=u.$async?(0,ln._)`(${h}.async ? await ${b}(${i}) : ${b}(${i}))`:(0,ln._)`${b}(${i})`,R=(0,ln._)`(typeof ${b} == "function" ? ${x} : ${b}.test(${i}))`;return(0,ln._)`${b} && ${b} !== true && ${w} === ${t} && !${R}`}}function f(){let g=d.formats[o];if(!g){k();return}if(g===!0)return;let[h,w,b]=$(g);h===t&&e.pass(x());function k(){if(c.strictSchema===!1){d.logger.warn(R());return}throw new Error(R());function R(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function $(R){let P=R instanceof RegExp?(0,ln.regexpCode)(R):c.code.formats?(0,ln._)`${c.code.formats}${(0,ln.getProperty)(o)}`:void 0,I=n.scopeValue("formats",{key:o,ref:R,code:P});return typeof R=="object"&&!(R instanceof RegExp)?[R.type||"string",R.validate,(0,ln._)`${I}.validate`]:["string",R,I]}function x(){if(typeof g=="object"&&!(g instanceof RegExp)&&g.async){if(!u.$async)throw new Error("async format in sync schema");return(0,ln._)`await ${b}(${i})`}return typeof w=="function"?(0,ln._)`${b}(${i})`:(0,ln._)`${b}.test(${i})`}}}};nI.default=Rhe});var iI=ae(rI=>{"use strict";Object.defineProperty(rI,"__esModule",{value:!0});var She=jK(),Ehe=[She.default];rI.default=Ehe});var oI=ae(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});Od.contentVocabulary=Od.metadataVocabulary=void 0;Od.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Od.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var LK=ae(sI=>{"use strict";Object.defineProperty(sI,"__esModule",{value:!0});var Ohe=oT(),Ahe=kT(),Phe=BT(),Che=RK(),_he=PK(),The=DK(),Ihe=iI(),NK=oI(),Dhe=[Che.default,Ohe.default,Ahe.default,(0,Phe.default)(!0),Ihe.default,NK.metadataVocabulary,NK.contentVocabulary,_he.default,The.default];sI.default=Dhe});var FK=ae(ck=>{"use strict";Object.defineProperty(ck,"__esModule",{value:!0});ck.DiscrError=void 0;var MK;(function(e){e.Tag="tag",e.Mapping="mapping"})(MK||(ck.DiscrError=MK={}))});var lI=ae(cI=>{"use strict";Object.defineProperty(cI,"__esModule",{value:!0});var Ad=tt(),aI=FK(),GK=Um(),jhe=kd(),Nhe=ft(),Lhe={message:({params:{discrError:e,tagName:t}})=>e===aI.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Ad._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},Mhe={keyword:"discriminator",type:"object",schemaType:"object",error:Lhe,code(e){let{gen:t,data:n,schema:i,parentSchema:r,it:o}=e,{oneOf:s}=r;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=i.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(i.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",(0,Ad._)`${n}${(0,Ad.getProperty)(a)}`);t.if((0,Ad._)`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:aI.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function u(){let f=p();t.if(!1);for(let g in f)t.elseIf((0,Ad._)`${l} === ${g}`),t.assign(c,d(f[g]));t.else(),e.error(!1,{discrError:aI.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function d(f){let g=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:f},g);return e.mergeEvaluated(h,Ad.Name),g}function p(){var f;let g={},h=b(r),w=!0;for(let x=0;x<s.length;x++){let R=s[x];if(R?.$ref&&!(0,Nhe.schemaHasRulesButRef)(R,o.self.RULES)){let I=R.$ref;if(R=GK.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,I),R instanceof GK.SchemaEnv&&(R=R.schema),R===void 0)throw new jhe.default(o.opts.uriResolver,o.baseId,I)}let P=(f=R?.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);w=w&&(h||b(R)),k(P,x)}if(!w)throw new Error(`discriminator: "${a}" must be required`);return g;function b({required:x}){return Array.isArray(x)&&x.includes(a)}function k(x,R){if(x.const)$(x.const,R);else if(x.enum)for(let P of x.enum)$(P,R);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function $(x,R){if(typeof x!="string"||x in g)throw new Error(`discriminator: "${a}" values must be unique strings`);g[x]=R}}}};cI.default=Mhe});var WK=ae((Uze,Fhe)=>{Fhe.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var BK=ae((Vze,Ghe)=>{Ghe.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var zK=ae((Hze,Whe)=>{Whe.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var UK=ae((qze,Bhe)=>{Bhe.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var VK=ae((Kze,zhe)=>{zhe.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var HK=ae((Jze,Uhe)=>{Uhe.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var qK=ae((Zze,Vhe)=>{Vhe.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var KK=ae((Yze,Hhe)=>{Hhe.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var JK=ae(uI=>{"use strict";Object.defineProperty(uI,"__esModule",{value:!0});var qhe=WK(),Khe=BK(),Jhe=zK(),Zhe=UK(),Yhe=VK(),Xhe=HK(),Qhe=qK(),eye=KK(),tye=["/properties"];function nye(e){return[qhe,Khe,Jhe,Zhe,Yhe,t(this,Xhe),Qhe,t(this,eye)].forEach(n=>this.addMetaSchema(n,void 0,!1)),this;function t(n,i){return e?n.$dataMetaSchema(i,tye):i}}uI.default=nye});var ZK=ae((Yt,pI)=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.MissingRefError=Yt.ValidationError=Yt.CodeGen=Yt.Name=Yt.nil=Yt.stringify=Yt.str=Yt._=Yt.KeywordCxt=Yt.Ajv2020=void 0;var rye=nT(),iye=LK(),oye=lI(),sye=JK(),dI="https://json-schema.org/draft/2020-12/schema",Pd=class extends rye.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),iye.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(oye.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:n}=this.opts;n&&(sye.default.call(this,t),this.refs["http://json-schema.org/schema"]=dI)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(dI)?dI:void 0)}};Yt.Ajv2020=Pd;pI.exports=Yt=Pd;pI.exports.Ajv2020=Pd;Object.defineProperty(Yt,"__esModule",{value:!0});Yt.default=Pd;var aye=vd();Object.defineProperty(Yt,"KeywordCxt",{enumerable:!0,get:function(){return aye.KeywordCxt}});var Cd=tt();Object.defineProperty(Yt,"_",{enumerable:!0,get:function(){return Cd._}});Object.defineProperty(Yt,"str",{enumerable:!0,get:function(){return Cd.str}});Object.defineProperty(Yt,"stringify",{enumerable:!0,get:function(){return Cd.stringify}});Object.defineProperty(Yt,"nil",{enumerable:!0,get:function(){return Cd.nil}});Object.defineProperty(Yt,"Name",{enumerable:!0,get:function(){return Cd.Name}});Object.defineProperty(Yt,"CodeGen",{enumerable:!0,get:function(){return Cd.CodeGen}});var cye=zm();Object.defineProperty(Yt,"ValidationError",{enumerable:!0,get:function(){return cye.default}});var lye=kd();Object.defineProperty(Yt,"MissingRefError",{enumerable:!0,get:function(){return lye.default}})});function Aa(){let e=ZK();return e.default??e}var sg=v(()=>{"use strict"});import{readFileSync as gI}from"node:fs";import{isAbsolute as uye,join as hI,relative as dye,resolve as pye}from"node:path";function XK(e=[]){let t=new Map;for(let n of[...YK,...e]){if(t.has(n.name))throw new Error(`kind ${n.name} is registered twice`);t.set(n.name,n)}return{get:n=>t.get(n),names:()=>[...t.values()].filter(n=>n.shape==="member").map(n=>n.name).sort(),all:()=>[...t.values()]}}function QK(){return XK()}function e4(e,t,n){if("directory"in e.probe)return!0;if("chantProject"in e.probe)return wI(t,n);let{anyFile:i,anyBlock:r,anyJsonKey:o}=e.probe;if(i&&mI(t,n,i).length>0)return!0;if(o)for(let s of mI(t,n,o.in))try{let a=JSON.parse(t.read(s));if(o.pointers.some(c=>gye(a,c)!==void 0))return!0}catch{}if(r){let s=new RegExp(`^\\s*(?:${r.blocks.map(t4).join("|")})\\s*\\{`,"m");for(let a of mI(t,n,r.in))try{if(s.test(t.read(a)))return!0}catch{}}return!1}function mI(e,t,n){let i=[],r=n.filter(o=>o.includes("*"));for(let o of n)!o.includes("*")&&e.stat(qe(t,o))==="file"&&i.push(qe(t,o));if(r.length>0){let o=r.map(s=>new RegExp(`^${s.split("*").map(t4).join("[^/]*")}$`));for(let s of e.list(t)??[])s.type==="file"&&o.some(a=>a.test(s.name))&&i.push(qe(t,s.name))}return i.sort()}function gye(e,t){let n=e;for(let i of t.split("/").slice(1)){let r=i.replace(/~1/g,"/").replace(/~0/g,"~");if(n===null||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function t4(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wI(e,t){let n=qe(t,"package.json");if(e.stat(n)==="file")try{let r=JSON.parse(e.read(n));for(let o of["dependencies","devDependencies","peerDependencies"]){let s=r[o];if(s&&typeof s=="object"&&Object.keys(s).some(wye))return!0}}catch{}let i=(r,o)=>{let s=e.list(r)??[];return s.some(a=>a.type==="file"&&hye.includes(a.name))?!0:o===yye?!1:s.some(a=>a.type==="dir"&&!Bi(a.name)&&i(qe(r,a.name),o+1))};return i(t,0)}function wye(e){return e==="@intentius/chant"||e.startsWith("@intentius/chant-lexicon-")}function bye(){if(lk)return lk;let e=Aa();return lk=new e({allErrors:!0,strict:!0}).compile(K_),lk}function vye(e,t){let n;try{n=JSON.parse(e)}catch(a){return{kinds:[],problems:[`${t}: the kinds file is not JSON (${a.message})`]}}let i=bye();if(!i(n)){let a=(i.errors??[]).map(c=>`${t}: ${c.instancePath||"the kinds file"} ${c.message??"is invalid"}`);return{kinds:[],problems:[...new Set(a)]}}let r=[],o=[],s=new Set;for(let a of n.kinds){if(mye.includes(a.name)){r.push(`${t}: kind ${a.name} is built in and can't be supplied by a package`);continue}if(s.has(a.name)){r.push(`${t}: kind ${a.name} is listed twice`);continue}s.add(a.name),o.push({name:a.name,description:a.description,probe:{...a.probe.anyFile?{anyFile:[...a.probe.anyFile]}:{},...a.probe.anyBlock?{anyBlock:{in:[...a.probe.anyBlock.in],blocks:[...a.probe.anyBlock.blocks]}}:{},...a.probe.anyJsonKey?{anyJsonKey:{in:[...a.probe.anyJsonKey.in],pointers:[...a.probe.anyJsonKey.pointers]}}:{}},precedence:a.precedence,shape:"member",outputs:{from:"declared",names:[...a.outputs??[]]},source:t,...a.graph?{graph:{lexicon:a.graph.lexicon,config:structuredClone(a.graph.config)}}:{},...a.fields?{fields:structuredClone(a.fields)}:{},...a.reader&&fI.includes(a.reader)?{reader:a.reader}:{}}),a.reader&&!fI.includes(a.reader)&&r.push(`${t}: kind ${a.name} names link reader ${a.reader}, which this chant does not have (it has ${fI.join(", ")}); the kind is kept, and its members' links are only those their entries state`);for(let c of $ye(a.fields??{}))r.push(`${t}: kind ${a.name} ${c}`)}return{kinds:o,problems:r}}function kye(e,t=yI){return r0(e,t)}function xye(e,t){let n=hI(e,"package.json"),i;try{i=JSON.parse(gI(n,"utf-8"))}catch{return{kinds:[],problems:[`${t??e}: no readable package.json in ${e}`],file:void 0}}let r=t??(typeof i.name=="string"?i.name:e),o=kye(i);if(o===void 0)return{kinds:[],problems:[],file:void 0};if(typeof o!="string")return{kinds:[],problems:[`${r}: ${o.problem}`],file:void 0};let s=pye(e,o),a=dye(e,s);if(a.startsWith("..")||uye(a))return{kinds:[],problems:[`${r}: exports["${yI}"] points outside the package`],file:void 0};let c;try{c=gI(s,"utf-8")}catch{return{kinds:[],problems:[`${r}: exports["${yI}"] names ${o}, which does not exist`],file:s}}let l=vye(c,r),u=typeof i.name=="string"?i.name:void 0;for(let d of l.kinds)d.packageDir=e,d.graph&&u!==uk(d.graph.lexicon)&&(l.problems.push(`${r}: kind ${d.name} reads its members with lexicon ${d.graph.lexicon}, which is ${uk(d.graph.lexicon)}, and this package is ${u??"unnamed"}; the kind is kept, and workspace graph lists its members with kind-not-run`),delete d.graph);return{...l,file:s}}function uk(e){return`@intentius/chant-lexicon-${e}`}function n4(e,t){let n=r=>r.replace(/\{(member|dir|workspace)\}/g,(o,s)=>t[s]),i=r=>typeof r=="string"?n(r):Array.isArray(r)?r.map(i):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([o,s])=>[n(o),i(s)])):r;return i(e)}function bI(e,t){if(e.package){let n=ba(e.package,t);if(!n)return{problem:`pinned package ${e.package} is not installed; install it to read the kinds it supplies`};let i;try{i=JSON.parse(gI(hI(n,"package.json"),"utf-8")).version}catch{i=void 0}return e.version&&i!==e.version?{problem:`${e.package} is pinned at ${e.version}, and ${String(i??"an unknown version")} is installed`}:{dir:n,source:e.package}}if(e.path){let n=hI(t,...e.path.split("/"));if(e.integrity){let i=ZV(n,e.integrity,e.path);if(!i.ok)return{problem:i.message}}return{dir:n,source:e.path}}return null}function Pa(e,t){let n=[],i=[],r=new Map,o=new Set;return e.forEach((s,a)=>{let c=bI(s,t);if(c===null)return;if("problem"in c){n.push({pin:a,message:c.problem});return}let{dir:l,source:u}=c,d=xye(l,u);for(let p of d.problems)n.push({pin:a,message:p});for(let p of d.kinds){let f=r.get(p.name);if(f){o.add(p.name),n.push({pin:a,message:`kind ${p.name} is supplied by both ${f} and ${u}; a kind name has one source`});continue}r.set(p.name,u),i.push(p)}}),{registry:XK(i.filter(s=>!o.has(s.name))),problems:n}}function r4(e,t){if(!(e.type==="integer"?typeof t=="number"&&Number.isInteger(t):typeof t===e.type))return`is ${JSON.stringify(t)}, and the field is ${e.type==="integer"?"an integer":`a ${e.type}`}`;if(e.pattern!==void 0&&typeof t=="string"){let i;try{i=new RegExp(e.pattern,"u")}catch{return}if(!i.test(t))return`is ${JSON.stringify(t)}, which does not match ${e.pattern}`}}function $ye(e){let t=[],n=(i,r)=>{if(r.pattern!==void 0)try{new RegExp(r.pattern,"u")}catch{t.push(`declares field ${i} with pattern ${r.pattern}, which is not a regular expression`);return}if(r.default===void 0)return;let o=r4(r,r.default);o&&t.push(`declares field ${i} whose default ${o}`)};for(let[i,r]of Object.entries(e))if(r.type==="object")for(let[o,s]of Object.entries(r.properties))n(`${i}.${o}`,s);else n(i,r);return t}function vI(e,t){if(e===void 0)return{fields:null,problems:[]};let n=e.fields,i=[];if(n===void 0)return t!==null&&i.push({path:"",message:`kind ${e.name} declares no fields, and the entry sets ${Object.keys(t).join(", ")||"an empty fields block"}`}),{fields:null,problems:i};let r=t??{};for(let a of Object.keys(r))a in n||i.push({path:a,message:`kind ${e.name} declares no field ${a}; its fields are ${Object.keys(n).join(", ")}`});let o=(a,c,l)=>{if(l!==void 0){let u=r4(c,l);if(!u)return l;i.push({path:a,message:`field ${a.replace("/",".")} ${u}`})}return c.default??null},s={};for(let[a,c]of Object.entries(n)){if(c.type!=="object"){s[a]=o(a,c,r[a]);continue}let l=r[a],u={};l!==void 0&&(l!==null&&typeof l=="object"&&!Array.isArray(l)?u=l:i.push({path:a,message:`field ${a} is ${JSON.stringify(l)}, and the field is an object`}));for(let d of Object.keys(u))d in c.properties||i.push({path:`${a}/${d}`,message:`kind ${e.name} declares no field ${a}.${d}; ${a} has ${Object.keys(c.properties).join(", ")}`});s[a]=Object.fromEntries(Object.entries(c.properties).map(([d,p])=>[d,o(`${a}/${d}`,p,u[d])]))}return{fields:s,problems:i}}var aUe,yI,fI,dk,fye,YK,mye,hye,yye,lk,qi=v(()=>{"use strict";VV();on();YV();pd();sg();aUe=K_.$id,yI="./workspace-kinds",fI=["dbt-project"],dk="examples",fye="design",YK=[{name:"chant",description:"a chant project, with a chant.config.ts or chant.config.json in its directory",probe:{anyFile:["chant.config.ts","chant.config.json"]},precedence:500,shape:"member",outputs:{from:"chant-source"},source:"builtin"},{name:"workspace",description:"a nested workspace, with its own chant.workspace.json; the outer one reads it through its own chant workspace graph and never writes inside it",probe:{anyFile:["chant.workspace.json","chant.workspace.jsonc"]},precedence:1e3,shape:"member",outputs:{from:"none"},source:"builtin"},{name:"other",description:"a directory chant does not read; the entry says why in `because`",probe:{directory:!0},precedence:0,shape:"member",outputs:{from:"declared",names:[]},source:"builtin"},{name:fye,description:"a data member holding the design artifacts the workspace owns; chant reads its files for record pins and builds nothing",probe:{directory:!0},precedence:0,shape:"member",outputs:{from:"declared",names:[]},source:"builtin"},{name:dk,description:"an example group: every directory its glob matches that holds a chant project is built and linted",probe:{chantProject:!0},precedence:0,shape:"group",outputs:{from:"none"},source:"builtin"}],mye=YK.map(e=>e.name);hye=["chant.config.ts","chant.config.json"],yye=4});function _d(e){return String(e).replace(/~/g,"~0").replace(/\//g,"~1")}function Ca(e,t){let n=[0];for(let w=0;w<e.length;w++)e.charCodeAt(w)===10&&n.push(w+1);let i=w=>{let b=0,k=n.length-1;for(;b<k;){let $=b+k+1>>1;n[$]<=w?b=$:k=$-1}return{line:b+1,column:w-n[b]+1}},r=new Map,o=new Map,s=new Map,a=e.charCodeAt(0)===65279?1:0,c=(w,b=a)=>{throw new pk(w,b)},l=w=>w>=e.length?"the end of the file":`${JSON.stringify(e[w])}`;function u(){for(;;){let w=e[a];if(w===" "||w===" "||w===`
73
73
  `||w==="\r")a++;else if(w==="/"&&(e[a+1]==="/"||e[a+1]==="*"))if(t.jsonc||c("comments are only allowed in chant.workspace.jsonc"),e[a+1]==="/")for(;a<e.length&&e[a]!==`
74
- `;)a++;else{let b=e.indexOf("*/",a+2);b<0&&c("unterminated /* comment"),a=b+2}else return}}function d(){let w=a;for(a++;;){a>=e.length&&c("unterminated string",w);let b=e.charCodeAt(a);if(b===34)break;b<32&&c("control character in a string; escape it",a),a+=b===92?2:1}a++;try{return JSON.parse(e.slice(w,a))}catch{return c("invalid escape in a string",w)}}function p(w){u(),r.set(w,a);let b=f(w);return o.set(w,a),b}function f(w){let b=e[a];if(b==="{")return g(w);if(b==="[")return h(w);if(b==='"')return d();for(let[$,x]of[["true",!0],["false",!1],["null",null]])if(e.startsWith($,a))return a+=$.length,x;let k=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(e.slice(a,a+64));return k?(a+=k[0].length,Number(k[0])):c(`expected a value, found ${l(a)}`)}function g(w){let b={},k=new Set;if(a++,u(),e[a]==="}")return a++,b;for(;;){u(),e[a]!=='"'&&c(`expected a quoted key, found ${l(a)}`);let $=a,x=d();k.has(x)&&c(`duplicate key ${JSON.stringify(x)}`,$),k.add(x);let R=`${w}/${_d(x)}`;if(s.set(R,$),u(),e[a]!==":"&&c(`expected ":" after key ${JSON.stringify(x)}, found ${l(a)}`),a++,Object.defineProperty(b,x,{value:p(R),enumerable:!0,writable:!0,configurable:!0}),u(),e[a]===","){if(a++,u(),e[a]==="}")return t.jsonc||c("trailing comma; only chant.workspace.jsonc allows one"),a++,b;continue}if(e[a]==="}")return a++,b;c(`expected "," or "}", found ${l(a)}`)}}function h(w){let b=[];if(a++,u(),e[a]==="]")return a++,b;for(;;){if(b.push(p(`${w}/${b.length}`)),u(),e[a]===","){if(a++,u(),e[a]==="]")return t.jsonc||c("trailing comma; only chant.workspace.jsonc allows one"),a++,b;continue}if(e[a]==="]")return a++,b;c(`expected "," or "]", found ${l(a)}`)}}try{u(),a>=e.length&&c("the file is empty");let w=p("");return u(),a<e.length&&c(`unexpected ${l(a)} after the value`),{ok:!0,value:w,locate(b,k){if(k&&s.has(b))return i(s.get(b));for(let $=b;;$=$.slice(0,$.lastIndexOf("/"))){let x=r.get($);if(x!==void 0)return i(x);if($==="")return i(0)}},span(b){let k=r.get(b),$=o.get(b);if(!(k===void 0||$===void 0))return{key:s.get(b)??null,start:k,end:$}}}}catch(w){if(!(w instanceof pk))throw w;return{ok:!1,message:w.message,location:i(w.offset)}}}var pk,Td=v(()=>{"use strict";pk=class extends Error{constructor(n,i){super(n);this.offset=i}}});function i4(){return"0.124.33"}var o4=v(()=>{"use strict"});var EI={};_e(EI,{CHANT_PACKAGE:()=>Dd,DECLARATION_FILES:()=>Id,DECLARATION_SCHEMA_ID:()=>Rye,DECLARATION_SCHEMA_VERSION:()=>Sye,DEFAULT_CI_WINDOW:()=>u4,DEFAULT_PUBLISH_BRANCH_PREFIX:()=>m4,DEFAULT_REPLICATE_REMOTE:()=>f4,DEFAULT_SHIP_ENV:()=>p4,DEFAULT_SHIP_GATE:()=>d4,DEFAULT_STATE_ROOT:()=>g4,DIAGRAM_TOOLS:()=>Pye,FACTORY_CHECK_KINDS:()=>Cye,NAME_PATTERN:()=>Eye,PRINCIPAL_CLASSES:()=>Oye,REPLICATE_REF_CLASSES:()=>kI,REPLICATE_TRIGGERS:()=>xI,RESERVED_NAMES:()=>l4,WORKSPACE_ERROR_CODES:()=>yi,WRITE_VERBS:()=>Aye,WorkspaceReadError:()=>xe,boxServicesProblem:()=>v4,compareVersions:()=>h4,declaredDiagrams:()=>RI,declaredRecordKinds:()=>yr,extensionsAt:()=>ag,findDeclarationDir:()=>SI,isInside:()=>Nr,ownerOf:()=>k4,parseDeclaration:()=>w4,pinnedChant:()=>mk,readDeclaration:()=>_t,readerVersion:()=>en,resolveGroups:()=>_a,rootExclusions:()=>gk});function en(){return s4??=i4(),s4}function h4(e,t){let n=$I.exec(e),i=$I.exec(t);if(!n||!i)throw new Error(`not a version: ${n?t:e}`);for(let r=1;r<=3;r++){let o=Number(n[r])-Number(i[r]);if(o!==0)return o}return n[4]===i[4]?0:n[4]===void 0?1:i[4]===void 0||n[4]<i[4]?-1:1}function _ye(){if(fk)return fk;let e=Aa();return fk=new e({allErrors:!0,strict:!0}).compile(V_),fk}function Tye(e,t){let n=/#\/\$defs\/([A-Za-z]+)\//.exec(e.schemaPath)?.[1];if(e.keyword==="pattern"){let i=JSON.stringify(t);return n==="name"&&typeof t=="string"&&l4.includes(t)?`${i} is reserved; pick another name`:n==="name"?`${i} is not a valid name: use lowercase letters, digits and hyphens, starting with a letter or digit, at most 40 characters`:n==="kindName"?`${i} is not a valid kind or role name`:n==="dir"?`${i} is not a directory inside the workspace: use a relative path with / separators, and no . or .. segments`:n==="path"?`${i} is not a path inside the member or workspace: use a relative path with / separators, and no . or .. segments`:n==="glob"?`${i} is not a glob inside the workspace: use a relative pattern with / separators, and no . or .. segments`:n==="version"?`${i} is not a version such as 1.2.3`:`${i} is not allowed here`}if(e.keyword==="additionalProperties")return`unknown field ${JSON.stringify(e.params.additionalProperty)}; only fields named x-... may be added`;if(e.keyword==="required"){let i=String(e.params.missingProperty);return i==="because"&&e.instancePath.endsWith("/handWritten")?'a hand-written generated file needs "because", saying why it is kept by hand':i==="because"?'a member of kind other needs "because", saying why it is there':`missing required field ${JSON.stringify(i)}`}return e.keyword==="const"&&e.instancePath==="/schema"?"schema must be 1, the only declaration format this chant reads":e.message??"is invalid"}function y4(e,t){let n=e;for(let i of t.split("/").slice(1)){let r=i.replace(/~1/g,"/").replace(/~0/g,"~");if(n===null||typeof n!="object")return;n=n[r]}return n}function mk(e){if(!Array.isArray(e.pins))return;let t=e.pins.findIndex(n=>n!==null&&typeof n=="object"&&n.package===Dd&&typeof n.version=="string");return t<0?void 0:{version:e.pins[t].version,index:t}}function w4(e,t,n=en(),i={}){let r=Ca(e,{jsonc:t.endsWith(".jsonc")});if(!r.ok)throw new xe("declaration-unparseable",r.message,{file:t,...r.location});let o=(L,M=!1)=>({file:t,...r.locate(L,M)}),s=r.value;if(s===null||typeof s!="object"||Array.isArray(s))throw new xe("declaration-invalid","the declaration must be a JSON object",o(""));let a=s,c=i.rootChant?mk(a):void 0;if(c&&c.version!==n)throw new xe("root-chant-required",`this declaration pins ${Dd} ${c.version}, and this is chant ${n}; the root's chant reads it, so install ${Dd}@${c.version} at the workspace root`,o(`/pins/${c.index}/version`));if(typeof a.minReader=="string"&&$I.test(a.minReader)&&h4(n,a.minReader)<0)throw new xe("reader-too-old",`this declaration needs chant ${a.minReader} or newer to read it, and this is chant ${n}`,o("/minReader"));let l=_ye();if(!l(s)){let L=(l.errors??[]).filter(re=>!Iye.has(re.keyword));L.sort((re,be)=>be.instancePath.split("/").length-re.instancePath.split("/").length);let M=L[0]??l.errors[0],_=M.keyword==="additionalProperties",T=_?`${M.instancePath}/${_d(String(M.params.additionalProperty))}`:M.instancePath,W=M.instancePath===""?"":` (at ${M.instancePath})`,ve=L.length>1?`; ${L.length-1} more problem${L.length>2?"s":""} after this one`:"";throw new xe("declaration-invalid",`${Tye(M,y4(s,M.instancePath))}${W}${ve}`,o(T,_))}let u=a.members.map((L,M)=>{let _=`/members/${M}`,T=(L.suppress??[]).map(ne=>({check:ne.check,because:ne.because}));if(L.kind===dk){let ne=L.glob;return{type:"group",name:L.name,kind:dk,globs:typeof ne=="string"?[ne]:[...ne],suppress:T,pointer:_,globLocation:r.locate(`${_}/glob`)}}let W=(L.roles??[]).map(ne=>typeof ne=="string"?{name:ne,path:null}:{name:ne.name,path:ne.path??null}),ve=(L.generated??[]).map((ne,ye)=>({path:ne.path,generator:ne.generator,sources:[...ne.sources??[]],handWritten:ne.handWritten?{because:ne.handWritten.because}:null,pointer:`${_}/generated/${ye}`})),re=(L.links??[]).map((ne,ye)=>({member:ne.member,output:ne.output,kind:ne.kind??null,protocol:ne.protocol??null,pointer:`${_}/links/${ye}`})),be=a4(L.records,L.dir,L.name,`${_}/records`),Be=c4(L.diagrams,L.name,`${_}/diagrams`),dt=Wye(L.box,`${_}/box`);return{type:"member",name:L.name,dir:L.dir,kind:L.kind,roles:W,generated:ve,outputs:L.outputs===void 0?null:[...L.outputs],fields:L.fields===void 0?null:structuredClone(L.fields),links:re,records:be,diagrams:Be,box:dt,upstream:L.upstream??null,because:L.because??null,travel:L.travel===!0,security:[...L.security??[]],suppress:T,pointer:_}}),d=new Map;for(let L of u){let M=d.get(L.name);if(M)throw new xe("declaration-invalid",`the name ${JSON.stringify(L.name)} is already used by the entry at ${M.pointer}`,o(`${L.pointer}/name`));d.set(L.name,L)}let p=u.filter(L=>L.type==="member"),f=new Map;for(let L of p){let M=f.get(L.dir);if(M)throw new xe("placement-invalid",`member ${L.name} has the same directory as member ${M.name} (${L.dir})`,o(`${L.pointer}/dir`));f.set(L.dir,L)}for(let L of p){let M=p.find(_=>_!==L&&_.dir!=="."&&Nr(L.dir,_.dir));if(M)throw new xe("placement-invalid",`member ${L.name} (${L.dir}) sits inside member ${M.name} (${M.dir}); only the root member "." may contain other members`,o(`${L.pointer}/dir`))}for(let L of p){let M=new Map;for(let _ of L.generated){let T=M.get(_.path);if(T)throw new xe("declaration-invalid",`member ${L.name} lists the generated file ${_.path} twice; the first is at ${T.pointer}`,o(`${_.pointer}/path`));M.set(_.path,_);let W=L.dir==="."?_.path:`${L.dir}/${_.path}`,ve=p.find(re=>re!==L&&re.dir!=="."&&Nr(re.dir,L.dir)&&Nr(W,re.dir));if(ve)throw new xe("placement-invalid",`member ${L.name} lists the generated file ${_.path}, which sits inside member ${ve.name} (${ve.dir}); list it there`,o(`${_.pointer}/path`))}}let g=a4(a.records,".",null,"/records"),h=new Map,w=new Map;for(let L of[...g,...p.flatMap(M=>M.records)]){let M=h.get(L.path);if(M)throw new xe("declaration-invalid",`the record kind ${L.path} is already declared at ${M.pointer}`,o(`${L.pointer}/kind`));if(h.set(L.path,L),L.name===null)continue;let _=w.get(L.name);if(_)throw new xe("declaration-invalid",`the record kind name ${JSON.stringify(L.name)} is already given at ${_.pointer}`,o(`${L.pointer}/name`));w.set(L.name,L)}for(let L of p){let M=new Map;for(let T of L.box?.capabilities??[]){let W=M.get(T.name);if(W)throw new xe("declaration-invalid",`member ${L.name}'s box lists the capability ${T.name} twice; the first is at ${W.pointer}`,o(`${T.pointer}/name`));M.set(T.name,T)}let _=L.box?v4(L.name,L.box.services):null;if(_)throw new xe("declaration-invalid",_.message,o(_.pointer))}let b=Bye(p);if(b)throw new xe("declaration-invalid",b.message,o(b.pointer));let k=p.filter(L=>L.box?.replicate);if(k.length>1)throw new xe("declaration-invalid",`members ${k[0].name} and ${k[1].name} both declare replicate in their box block; a checkout's work in progress goes to one remote, so a workspace has one replicate policy`,o(k[1].box.replicate.pointer));let $=c4(a.diagrams,null,"/diagrams"),x=new Map;for(let L of[...$,...p.flatMap(M=>M.diagrams)]){let M=x.get(L.name);if(M)throw new xe("declaration-invalid",`the diagram name ${JSON.stringify(L.name)} is already used by the diagram at ${M.pointer}`,o(`${L.pointer}/name`));x.set(L.name,L)}let R=Vye(a,p,o),P=Dye(a.writeScope,p,o),I=Fye(a.agents,p,o),A=zye(p,I);if(A)throw new xe("declaration-invalid",A.message,o(A.pointer));let B=Mye(a.ci,o),C=(a.pins??[]).map(L=>({package:L.package??null,version:L.version??null,path:L.path??null,integrity:L.integrity??null})),q={name:a.name,schema:a.schema,minReader:a.minReader??null,entries:u,members:p,groups:u.filter(L=>L.type==="group"),pins:C,checks:{...a.checks??{}},quorum:typeof a.quorum=="number"?a.quorum:null,records:g,diagrams:$,hosts:R,changes:Gye(a.changes),writeScope:P,agents:I,identity:jye(a.identity),ci:B,retention:Lye(a.retention),metrics:Nye(a.metrics),security:[...a.security??[]],file:t};return b4.set(q,s),q}function ag(e,t){let n=y4(b4.get(e),t);return n===null||typeof n!="object"||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(([i])=>i.startsWith("x-")))}function Dye(e,t,n){if(e===void 0)return null;let i=e,r={};for(let[o,s]of Object.entries(i)){let a=`/writeScope/${o}`,c=s.members===void 0||s.members==="*"?null:[...s.members];for(let[d,p]of(c??[]).entries())if(!t.some(f=>f.name===p))throw new xe("declaration-invalid",`writeScope.${o} names the member ${JSON.stringify(p)}, which the declaration does not declare; declared members: ${t.map(f=>f.name).join(", ")||"none"}`,n(`${a}/members/${d}`));let l=s.records===void 0?null:Object.fromEntries(Object.entries(s.records).map(([d,p])=>[d,[...p]])),u=(s.protected??[]).map(d=>typeof d=="string"?{path:d,except:[]}:{path:d.path,except:[...d.except??[]]});r[o]={members:c,records:l,protected:u,pointer:a}}return r}function jye(e){if(e===void 0)return null;let t=e,n={};for(let[i,r]of Object.entries(t.gates??{}))n[i]={gate:i,class:r.class??null,pointer:`/identity/gates/${i.replace(/~/g,"~0").replace(/\//g,"~1")}`};return{attribution:t.attribution??"any",gates:n}}function Nye(e){if(!e||typeof e!="object")return null;let t=e.failureWindowDays;return typeof t=="number"?{failureWindowDays:t}:{}}function Lye(e){if(!e||typeof e!="object")return null;let t={};for(let n of jV){let i=e[n];i&&(t[n]={...typeof i.days=="number"?{days:i.days}:{},...typeof i.keep=="number"?{keep:i.keep}:{}})}return t}function Mye(e,t){if(e===void 0)return null;let n=e,i=null;if(n.reportUrl!==void 0){let s=NV(n.reportUrl,"ci.reportUrl");if("error"in s)throw new xe("declaration-invalid",s.error,t("/ci/reportUrl"));i=s.url}if(n.green===void 0)return{green:null,reportUrl:i};let r=n.green,o=Object.entries(r.phases).map(([s,a])=>({name:s,runs:[...Array.isArray(a)?a:a.runs],skipped:Array.isArray(a)?"fail":a.skipped??"fail",...!Array.isArray(a)&&a.build!==void 0?{build:a.build}:{},pointer:`/ci/green/phases/${_d(s)}`}));for(let[s,a]of r.require.entries())if(!o.some(c=>c.name===a))throw new xe("declaration-invalid",`ci.green.require names the phase ${JSON.stringify(a)}, which ci.green.phases does not declare; declared phases: ${o.map(c=>c.name).join(", ")}`,t(`/ci/green/require/${s}`));return{green:{branch:r.branch,window:r.window??u4,phases:o,require:[...r.require],signedSince:r.signedSince??null,source:r.source??"checks",pointer:"/ci/green"},reportUrl:i}}function Fye(e,t,n){let i=(e??[]).map((s,a)=>{let c=s.members!==void 0?[...s.members]:[s.member];return{name:s.name,members:c,member:c[0],principals:[...s.principals??[]],pointer:`/agents/${a}`,listed:s.members!==void 0}}),r=new Map,o=new Map;for(let{listed:s,...a}of i){let c=r.get(a.name);if(c)throw new xe("declaration-invalid",`the agent name ${JSON.stringify(a.name)} is already used by the agent at ${c.pointer}`,n(`${a.pointer}/name`));r.set(a.name,a);for(let[l,u]of a.members.entries())if(!t.some(d=>d.name===u))throw new xe("declaration-invalid",`agent ${a.name} is bound to ${JSON.stringify(u)}, which is not a declared member; an agent session is bound to members, not an example group`,n(s?`${a.pointer}/members/${l}`:`${a.pointer}/member`));for(let[l,u]of a.principals.entries()){let d=o.get(u);if(d)throw new xe("declaration-invalid",`the principal ${JSON.stringify(u)} is already listed by agent ${d.name}`,n(`${a.pointer}/principals/${l}`));o.set(u,a)}}return[...r.values()]}function Gye(e){return e===void 0?null:{severity:e.severity??"warn",ignore:[...e.ignore??[]]}}function a4(e,t,n,i){return(e??[]).map((r,o)=>({kind:r.kind,path:t==="."?r.kind:`${t}/${r.kind}`,name:r.name??null,member:n,pointer:`${i}/${o}`}))}function c4(e,t,n){return(e??[]).map((i,r)=>({name:i.name,title:i.title,source:i.source??null,render:i.render??null,renderer:{tool:i.renderer.tool,version:i.renderer.version,args:[...i.renderer.args??[]]},sourceHash:i.sourceHash??null,member:t,pointer:`${n}/${r}`}))}function Wye(e,t){if(e===void 0)return null;let n=e,i=n.factory,r=n.listing,o=n.replicate;return{capabilities:(n.capabilities??[]).map((s,a)=>({name:s.name,broker:s.broker??null,scope:[...s.scope??[]],pointer:`${t}/capabilities/${a}`})),isolation:n.host===void 0?null:{host:n.host,slot:n.slot,ports:{...n.ports??{}},state:{...n.state??{}},cookies:[...n.cookies??[]]},intent:n.intent??null,services:(n.services??[]).map((s,a)=>({name:s.name,cmd:s.cmd,needs:[...s.needs??[]],httpPort:s.httpPort??null,duration:s.duration??null,health:s.health??null,optional:s.optional??!1,pointer:`${t}/services/${a}`})),factory:i===void 0?null:{builds:[...i.builds],check:i.check===void 0?null:typeof i.check=="string"?{run:i.check,kind:"test"}:{run:i.check.run,kind:i.check.kind??"test"},checks:i.checks??null,builders:i.builders??null,tiers:(i.tiers??[]).map(s=>({tier:s.tier,agent:s.agent,kinds:s.kinds===void 0?null:[...s.kinds],session:s.session??null})),publish:i.publish===void 0?null:{forge:i.publish.forge??"github",repo:i.publish.repo,base:i.publish.base??null,branchPrefix:i.publish.branchPrefix??m4,head:i.publish.head??null},pointer:`${t}/factory`},listing:r===void 0?null:{published:r.published??!0,title:r.title??"",line:r.line??"",cover:r.cover??null},publisher:n.publisher??null,ship:n.ship===void 0?null:{op:n.ship.op,gate:n.ship.gate??d4,env:n.ship.env??p4,bookkeeping:(n.ship.bookkeeping??[]).map(s=>s.replace(/^\.\//,"").replace(/\/+$/,"")),pointer:`${t}/ship`},replicate:o===void 0?null:{remote:o.remote??f4,refs:kI.filter(s=>(o.refs??kI).includes(s)),on:xI.filter(s=>(o.on??xI).includes(s)),every:o.every??null,pointer:`${t}/replicate`},pointer:t}}function Bye(e){let t=e.filter(s=>s.box?.factory);if(t.length>1)return{message:`members ${t[0].name} and ${t[1].name} both declare a factory in their box block; a workspace has one factory, so an orchestrator reads one`,pointer:t[1].box.factory.pointer};let n=t[0]?.box?.factory;if(!n)return null;let i=()=>e.map(s=>s.name).join(", "),r=n.builds.findIndex(s=>!e.some(a=>a.name===s));if(r>=0)return{message:`the factory builds ${JSON.stringify(n.builds[r])}, which is not a declared member; declared members: ${i()}`,pointer:`${n.pointer}/builds/${r}`};if(n.builders!==null&&!e.some(s=>s.name===n.builders))return{message:`the factory's builders names ${JSON.stringify(n.builders)}, which is not a declared member; declared members: ${i()}`,pointer:`${n.pointer}/builders`};if(n.tiers.length>0&&n.builders===null)return{message:"the factory declares tiers and no builders; tiers name agents the builders member declares, so name it",pointer:`${n.pointer}/tiers`};let o=new Map;for(let[s,a]of n.tiers.entries())for(let c of a.kinds??[null]){let l=`${a.tier}\0${c??""}`,u=o.get(l);if(u!==void 0){let d=c===null?"with no kinds":`for kind ${c}`;return{message:`tiers/${u} and tiers/${s} both name a builder at tier ${a.tier} ${d}; a tier has one builder per kind, so one entry answers it`,pointer:`${n.pointer}/tiers/${s}`}}o.set(l,s)}return null}function zye(e,t){let n=e.find(i=>i.box?.factory)?.box?.factory;if(!n)return null;for(let[i,r]of n.tiers.entries())if(r.session!==null&&!t.some(o=>o.name===r.session)){let o=t.map(s=>s.name).join(", ")||"none";return{message:`tiers/${i} names the session ${JSON.stringify(r.session)}, which is not a declared agent session; declared sessions: ${o}`,pointer:`${n.pointer}/tiers/${i}/session`}}return null}function v4(e,t){let n=new Map;for(let o of t){let s=n.get(o.name);if(s)return{message:`member ${e}'s box declares the service ${o.name} twice; the first is at ${s.pointer}`,pointer:`${o.pointer}/name`};n.set(o.name,o)}let i;for(let o of t)if(o.httpPort!==null){if(i)return{message:`member ${e}'s box gives both ${i.name} (port ${i.httpPort}) and ${o.name} (port ${o.httpPort}) an httpPort, and the supervisor routes the sprite's URL to one service`,pointer:`${o.pointer}/httpPort`};i=o}for(let o of t){let s=o.needs.findIndex(a=>!n.has(a));if(s>=0){let a=t.map(c=>c.name).join(", ");return{message:`member ${e}'s box service ${o.name} needs ${JSON.stringify(o.needs[s])}, which the block does not declare; declared services: ${a}`,pointer:`${o.pointer}/needs/${s}`}}}let r=Uye(t);if(r){let o=n.get(r[0]);return{message:`member ${e}'s box services need each other in a cycle: ${r.join(" -> ")}`,pointer:`${o.pointer}/needs`}}return null}function Uye(e){let t=new Map(e.map(r=>[r.name,r])),n=new Map,i=(r,o)=>{let s=n.get(r);if(s==="done")return null;if(s==="visiting")return[...o.slice(o.indexOf(r)),r];n.set(r,"visiting");for(let a of t.get(r)?.needs??[]){let c=i(a,[...o,r]);if(c)return c}return n.set(r,"done"),null};for(let r of e){let o=i(r.name,[]);if(o)return o}return null}function Vye(e,t,n){let i=(e.hosts??[]).map((s,a)=>({name:s.name,ports:{...s.ports},stateRoot:s.stateRoot??null,pointer:`/hosts/${a}`})),r=(s,a)=>new xe("declaration-invalid",s,n(a)),o=new Map;for(let s of i){let a=o.get(s.name);if(a)throw r(`the host name ${JSON.stringify(s.name)} is already used by the host at ${a.pointer}`,`${s.pointer}/name`);if(o.set(s.name,s),s.ports.from>s.ports.to)throw r(`host ${s.name}'s port range starts at ${s.ports.from}, after its end ${s.ports.to}`,`${s.pointer}/ports`)}for(let s of t){let a=s.box?.isolation;if(!a)continue;let c=s.box.pointer,l=o.get(a.host);if(!l){let g=i.map(h=>h.name).join(", ")||"none are declared";throw r(`member ${s.name}'s box names the host ${JSON.stringify(a.host)}, which hosts does not declare; declared hosts: ${g}`,`${c}/host`)}let{from:u,to:d,perBox:p}=l.ports,f=u+(a.slot+1)*p-1;if(f>d){let g=Math.floor((d-u+1)/p);throw r(`member ${s.name}'s box has slot ${a.slot} on host ${l.name}, which needs ports ${u+a.slot*p} to ${f}, past the end of the host's range (${d}); the range holds ${g} slot${g===1?"":"s"}`,`${c}/slot`)}for(let[g,h]of Object.entries(a.ports))if(h>=p)throw r(`member ${s.name}'s box gives port ${g} offset ${h}, and host ${l.name} gives each box ${p} port${p===1?"":"s"} (offsets 0 to ${p-1})`,`${c}/ports/${_d(g)}`)}return i}function yr(e){return[...e.records,...e.members.flatMap(t=>t.records)]}function RI(e){return[...e.diagrams,...e.members.flatMap(t=>t.diagrams)]}function Nr(e,t){return t==="."?!0:e===t||e.startsWith(`${t}/`)}function _t(e,t="",n={}){let i=Id.map(r=>qe(t,r)).filter(r=>e.stat(r)==="file");if(i.length===0)throw new xe("declaration-missing",`no ${Id.join(" or ")} in ${t||"the workspace root"}${e.label}`);if(i.length>1)throw new xe("declaration-ambiguous",`both ${i.join(" and ")} exist${e.label}; keep one of them`,{file:i[1],line:1,column:1});return w4(e.read(i[0]),i[0],en(),n)}function SI(e,t){for(let n=t;;n=n.includes("/")?n.slice(0,n.lastIndexOf("/")):""){if(Id.some(i=>e.stat(qe(n,i))==="file"))return n;if(n==="")return}}function _a(e,t){let n=o=>({file:e.file,...o.globLocation}),i=new Map,r=[];for(let o of e.groups){let s=[...new Set(o.globs.flatMap(l=>zV(t,l)))].sort(),a=[],c=[];for(let l of s){if(!wI(t,l)){c.push(l);continue}let u=p=>new xe("placement-invalid",`group ${o.name} matches ${l}, ${p}`,n(o));for(let p of e.members)if(p.dir!=="."){if(p.dir===l)throw u(`which is member ${p.name}'s directory; a match is never a member`);if(Nr(p.dir,l))throw u(`which contains member ${p.name} (${p.dir})`);if(p.kind==="workspace"&&Nr(l,p.dir))throw u(`which sits inside the nested workspace ${p.name}; that workspace declares its own examples`)}let d=i.get(l);if(d)throw u(`which group ${d.name} also matches`);i.set(l,o),a.push(l)}r.push({group:o,matches:a,skipped:c})}return r}function k4(e,t,n){for(let r of t){let o=r.matches.find(s=>Nr(n,s));if(o)return{group:r.group,match:o}}let i;for(let r of e.members)Nr(n,r.dir)&&(!i||i.dir==="."||r.dir!=="."&&r.dir.length>i.dir.length)&&(i=r);return i?{member:i}:void 0}function gk(e,t){let n=[];for(let i of e.members)i.dir!=="."&&n.push({dir:i.dir,owner:i.name});for(let i of t)for(let r of i.matches)e.members.some(o=>o.dir!=="."&&Nr(r,o.dir))||n.push({dir:r,owner:i.group.name});return n.sort((i,r)=>i.dir<r.dir?-1:i.dir>r.dir?1:0)}var Rye,Id,Sye,l4,Eye,yi,xe,Oye,Aye,u4,Pye,d4,p4,kI,xI,f4,Cye,m4,g4,Dd,s4,$I,fk,Iye,b4,Tt=v(()=>{"use strict";U_();LV();MV();UV();qi();Td();on();sg();o4();Rye=V_.$id,Id=["chant.workspace.json","chant.workspace.jsonc"],Sye=1,l4=["_workspace","_members"],Eye=/^[a-z0-9][a-z0-9-]{0,39}$/,yi=["declaration-missing","declaration-ambiguous","declaration-unparseable","declaration-invalid","placement-invalid","reader-too-old","root-chant-required","not-a-git-repository","revision-unknown"],xe=class extends Error{constructor(n,i,r){super(i);this.code=n;this.location=r;this.name="WorkspaceReadError"}describe(){let n=this.location;return n?`${n.file}:${n.line}:${n.column}: ${this.message}`:this.message}},Oye=["human","agent","runner","service"],Aye=["new","amend","review","close"],u4="24h",Pye=["d2","mermaid","graphviz","excalidraw"],d4="ship",p4="box",kI=["work","kept","wip","ledger"],xI=["save","release"],f4="origin",Cye=["test","build","lint","plan","conformance"],m4="chant/work/",g4="${XDG_STATE_HOME}/chant/boxes",Dd="@intentius/chant";$I=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?$/;Iye=new Set(["if","then","else","oneOf","anyOf"]);b4=new WeakMap});var R4={};_e(R4,{MEMBERS_DIR:()=>wk,MEMBER_LEDGER_FLOOR:()=>Xye,MemberLedgerError:()=>yk,clearMemberLedgerCache:()=>Qye,memberLedgerPrefix:()=>bk,resolveMemberLedger:()=>Xr});import{existsSync as Hye}from"node:fs";import{dirname as qye,join as Kye,relative as Jye,resolve as Zye,sep as Yye}from"node:path";function bk(e){return e.map(t=>`${wk}/${t}/`).join("")}function Xr(e){let t=Zye(e),n=hk.get(t);return n||(n=twe(t),hk.set(t,n),n.catch(()=>hk.delete(t))),n}function Qye(){hk.clear()}function ewe(e,t){let n=Jye(e,t);return n===""?"":n.split(Yye).join("/")}async function twe(e){let t=tr(e);return t?$4(t.dir,e):x4}async function $4(e,t){let{readDeclaration:n,resolveGroups:i,ownerOf:r,WorkspaceReadError:o}=await Promise.resolve().then(()=>(Tt(),EI)),{workingTree:s}=await Promise.resolve().then(()=>(on(),q_)),a;try{let d=s(e),p=n(d),f=r(p,i(p,d),ewe(e,t));a=f&&"member"in f&&f.member.dir!=="."?[f.member.name]:[]}catch(d){throw d instanceof o?new yk(`cannot place this project's lifecycle ledger: ${d.describe()}. A project inside a workspace writes under ${wk}/<member>/ on chant/lifecycle, and chant does not guess the member. Fix the declaration and retry.`):d}let c=x4,l=qye(e);if(l!==e&&!Hye(Kye(e,".git"))){let d=tr(l);d&&(c=await $4(d.dir,e))}let u=[...c.members,...a];return{members:u,prefix:bk(u)}}var wk,Xye,x4,yk,hk,Io=v(()=>{"use strict";Mi();wk="_members",Xye="0.81.0",x4={members:[],prefix:""};yk=class extends Error{constructor(t){super(t),this.name="MemberLedgerError"}},hk=new Map});function cg(e){return e===jd}var jd,lg=v(()=>{"use strict";jd="recorded locally (no remote for chant/lifecycle)"});function Ki(e=process.env){let t=e[vk]?.trim().toLowerCase();return t!==void 0&&t!==""&&t!=="0"&&t!=="false"}function ug(e){return OI.get(e)?.tip}function S4(e,t,n,i){let r=OI.get(e)??{tip:null,writes:[]};r.tip=t;for(let o of n)r.writes.push({path:o,message:i});OI.set(e,r)}function kk(e,t){if(Ki())throw new AI(e,t)}var vk,PI,OI,AI,Nd=v(()=>{"use strict";vk="CHANT_NO_RECORD";PI="not recorded (--no-record): chant/lifecycle was not written or pushed",OI=new Map;AI=class extends Error{constructor(n,i){super(`gate "${i}" of "${n}" cannot be passed under --no-record: a gate is decided and approved on chant/lifecycle, which this run does not write. Run without --no-record (and without CHANT_NO_RECORD) to stop at the gate for approval.`);this.op=n;this.gate=i;this.name="GateNotRecordableError"}}});var MI={};_e(MI,{LifecycleLedgerUnreadableError:()=>pg,RefCASConflictError:()=>Ot,StaleLifecycleBranchError:()=>dg,StaleLockError:()=>fl,appendLedgerLine:()=>D4,appendReleaseRecordLine:()=>TI,deleteRefCAS:()=>Fd,describeLifecyclePush:()=>jI,fetchLifecycle:()=>uwe,fetchLifecycleStatus:()=>Yi,fetchRef:()=>mwe,fetchRefInto:()=>F4,fetchRefIntoStatus:()=>Rk,getHeadCommit:()=>Sk,getRemoteLifecycleBranchSha:()=>j4,gitLedgerReadPort:()=>hwe,ledgerDir:()=>qn,ledgerRevision:()=>Gd,listFilesInDir:()=>Zi,listLedgerEnvironments:()=>DI,listLedgerTrees:()=>fg,listSnapshots:()=>lwe,pushLifecycle:()=>Ld,pushLifecycleReport:()=>Ia,pushLifecycleStatus:()=>Ta,pushRef:()=>fwe,pushRefStatus:()=>mg,readBlobBySha:()=>hn,readBlobFromPath:()=>At,readEnvironmentSnapshots:()=>cwe,readPathSha:()=>gn,readRefSha:()=>Da,readReleaseLedgerLines:()=>II,readSnapshot:()=>I4,readSnapshotAt:()=>awe,requireLifecycleLedger:()=>Lr,snapshotStorageKey:()=>_4,updateRefCAS:()=>Md,writeBlob:()=>NI,writeBlobToPath:()=>mn,writeLedgerFiles:()=>Ji,writeSnapshot:()=>T4});async function qn(e,t){return`${await nwe(t)}${e}`}async function nwe(e){return e?.ledgerPrefix!==void 0?e.ledgerPrefix:e?.member!==void 0?bk((typeof e.member=="string"?[e.member]:[...e.member]).filter(t=>t!==".")):(await Xr(e?.cwd??process.cwd())).prefix}async function owe(e){let t=bt();if((await t.spawn(["git","var","GIT_COMMITTER_IDENT"],{cwd:e,env:wi})).exitCode===0)return[];let i=[];for(let[r,o,s]of[["user.name","CHANT_LIFECYCLE_COMMITTER_NAME",rwe],["user.email","CHANT_LIFECYCLE_COMMITTER_EMAIL",iwe]]){let a=await t.spawn(["git","config","--get",r],{cwd:e,env:wi});a.exitCode===0&&a.stdout.trim()!==""||i.push("-c",`${r}=${process.env[o]?.trim()||s}`)}return i}function CI(e,t,n){return new Error(`cannot write ${t} on the ${Nt} branch: ${e} failed: ${(n??"").trim()}`)}async function mn(e,t,n,i,r){let o=await qn(e,r);return Ji([{path:`${o}/${t}`,content:n,...r?.expectPriorPathSha!==void 0?{expectPriorSha:r.expectPriorPathSha}:{}}],i,r)}async function Ji(e,t,n){let i=bt(),r=n?.cwd;if(e.length===0)throw new Error("writeLedgerFiles needs at least one file");let o=e[0].path;for(let u of e){let d=u.path.split("/");if(d.length<2||d.some(p=>p===""))throw new Error(`cannot write ${u.path} on the ${Nt} branch: a ledger path is <dir>/<file>`)}let s=[];for(let u of e){if(swe(u)){s.push({path:u.path,sha:null});continue}let d=await i.spawn(["git","hash-object","-w","--stdin"],{cwd:r,stdin:u.content});if(d.exitCode!==0)throw CI("git hash-object",u.path,d.stderr);s.push({path:u.path,sha:d.stdout.trim()})}let a=await owe(r);await ml(r)===null&&await Lr({...r?{cwd:r}:{}});let c=new Map(e.map(u=>[u.path,u.expectPriorSha])),l;for(let u=1;u<=C4;u++){let d=await ml(r);if(n?.expectTip!==void 0&&d!==n.expectTip)throw new Ot(`refs/heads/${Nt}`,n.expectTip,`the branch moved to ${d??"(none)"} since it was read`);let p=new Map,f=async x=>{let R=p.get(x);return R||(R=d?await gwe(d,x,r):new Map,p.set(x,R)),R};for(let x of s){let{dir:R,name:P}=O4(x.path),I=(await f(R)).get(P),A=I?.type==="blob"?I.sha:null,B=c.get(x.path);if(B!==void 0&&A!==B)throw l??new Ot(`refs/heads/${Nt}`,B,"target path changed concurrently");c.set(x.path,A)}for(let x of s){let{dir:R,name:P}=O4(x.path);x.sha===null?(await f(R)).delete(P):(await f(R)).set(P,{mode:"100644",type:"blob",sha:x.sha});for(let I=R;I!=="";I=$k(I))await f($k(I))}let g=[...p.keys()].sort((x,R)=>P4(R)-P4(x)||(x<R?-1:1)),h="";for(let x of g){if(x!==""&&p.get(x).size===0){p.get($k(x)).delete(A4(x));continue}let R=[...p.get(x)].map(([A,B])=>`${B.mode} ${B.type} ${B.sha} ${A}`).join(`
74
+ `;)a++;else{let b=e.indexOf("*/",a+2);b<0&&c("unterminated /* comment"),a=b+2}else return}}function d(){let w=a;for(a++;;){a>=e.length&&c("unterminated string",w);let b=e.charCodeAt(a);if(b===34)break;b<32&&c("control character in a string; escape it",a),a+=b===92?2:1}a++;try{return JSON.parse(e.slice(w,a))}catch{return c("invalid escape in a string",w)}}function p(w){u(),r.set(w,a);let b=f(w);return o.set(w,a),b}function f(w){let b=e[a];if(b==="{")return g(w);if(b==="[")return h(w);if(b==='"')return d();for(let[$,x]of[["true",!0],["false",!1],["null",null]])if(e.startsWith($,a))return a+=$.length,x;let k=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(e.slice(a,a+64));return k?(a+=k[0].length,Number(k[0])):c(`expected a value, found ${l(a)}`)}function g(w){let b={},k=new Set;if(a++,u(),e[a]==="}")return a++,b;for(;;){u(),e[a]!=='"'&&c(`expected a quoted key, found ${l(a)}`);let $=a,x=d();k.has(x)&&c(`duplicate key ${JSON.stringify(x)}`,$),k.add(x);let R=`${w}/${_d(x)}`;if(s.set(R,$),u(),e[a]!==":"&&c(`expected ":" after key ${JSON.stringify(x)}, found ${l(a)}`),a++,Object.defineProperty(b,x,{value:p(R),enumerable:!0,writable:!0,configurable:!0}),u(),e[a]===","){if(a++,u(),e[a]==="}")return t.jsonc||c("trailing comma; only chant.workspace.jsonc allows one"),a++,b;continue}if(e[a]==="}")return a++,b;c(`expected "," or "}", found ${l(a)}`)}}function h(w){let b=[];if(a++,u(),e[a]==="]")return a++,b;for(;;){if(b.push(p(`${w}/${b.length}`)),u(),e[a]===","){if(a++,u(),e[a]==="]")return t.jsonc||c("trailing comma; only chant.workspace.jsonc allows one"),a++,b;continue}if(e[a]==="]")return a++,b;c(`expected "," or "]", found ${l(a)}`)}}try{u(),a>=e.length&&c("the file is empty");let w=p("");return u(),a<e.length&&c(`unexpected ${l(a)} after the value`),{ok:!0,value:w,locate(b,k){if(k&&s.has(b))return i(s.get(b));for(let $=b;;$=$.slice(0,$.lastIndexOf("/"))){let x=r.get($);if(x!==void 0)return i(x);if($==="")return i(0)}},span(b){let k=r.get(b),$=o.get(b);if(!(k===void 0||$===void 0))return{key:s.get(b)??null,start:k,end:$}}}}catch(w){if(!(w instanceof pk))throw w;return{ok:!1,message:w.message,location:i(w.offset)}}}var pk,Td=v(()=>{"use strict";pk=class extends Error{constructor(n,i){super(n);this.offset=i}}});function i4(){return"0.124.34"}var o4=v(()=>{"use strict"});var EI={};_e(EI,{CHANT_PACKAGE:()=>Dd,DECLARATION_FILES:()=>Id,DECLARATION_SCHEMA_ID:()=>Rye,DECLARATION_SCHEMA_VERSION:()=>Sye,DEFAULT_CI_WINDOW:()=>u4,DEFAULT_PUBLISH_BRANCH_PREFIX:()=>m4,DEFAULT_REPLICATE_REMOTE:()=>f4,DEFAULT_SHIP_ENV:()=>p4,DEFAULT_SHIP_GATE:()=>d4,DEFAULT_STATE_ROOT:()=>g4,DIAGRAM_TOOLS:()=>Pye,FACTORY_CHECK_KINDS:()=>Cye,NAME_PATTERN:()=>Eye,PRINCIPAL_CLASSES:()=>Oye,REPLICATE_REF_CLASSES:()=>kI,REPLICATE_TRIGGERS:()=>xI,RESERVED_NAMES:()=>l4,WORKSPACE_ERROR_CODES:()=>yi,WRITE_VERBS:()=>Aye,WorkspaceReadError:()=>ve,boxServicesProblem:()=>v4,compareVersions:()=>h4,declaredDiagrams:()=>RI,declaredRecordKinds:()=>yr,extensionsAt:()=>ag,findDeclarationDir:()=>SI,isInside:()=>Nr,ownerOf:()=>k4,parseDeclaration:()=>w4,pinnedChant:()=>mk,readDeclaration:()=>_t,readerVersion:()=>en,resolveGroups:()=>_a,rootExclusions:()=>gk});function en(){return s4??=i4(),s4}function h4(e,t){let n=$I.exec(e),i=$I.exec(t);if(!n||!i)throw new Error(`not a version: ${n?t:e}`);for(let r=1;r<=3;r++){let o=Number(n[r])-Number(i[r]);if(o!==0)return o}return n[4]===i[4]?0:n[4]===void 0?1:i[4]===void 0||n[4]<i[4]?-1:1}function _ye(){if(fk)return fk;let e=Aa();return fk=new e({allErrors:!0,strict:!0}).compile(V_),fk}function Tye(e,t){let n=/#\/\$defs\/([A-Za-z]+)\//.exec(e.schemaPath)?.[1];if(e.keyword==="pattern"){let i=JSON.stringify(t);return n==="name"&&typeof t=="string"&&l4.includes(t)?`${i} is reserved; pick another name`:n==="name"?`${i} is not a valid name: use lowercase letters, digits and hyphens, starting with a letter or digit, at most 40 characters`:n==="kindName"?`${i} is not a valid kind or role name`:n==="dir"?`${i} is not a directory inside the workspace: use a relative path with / separators, and no . or .. segments`:n==="path"?`${i} is not a path inside the member or workspace: use a relative path with / separators, and no . or .. segments`:n==="glob"?`${i} is not a glob inside the workspace: use a relative pattern with / separators, and no . or .. segments`:n==="version"?`${i} is not a version such as 1.2.3`:`${i} is not allowed here`}if(e.keyword==="additionalProperties")return`unknown field ${JSON.stringify(e.params.additionalProperty)}; only fields named x-... may be added`;if(e.keyword==="required"){let i=String(e.params.missingProperty);return i==="because"&&e.instancePath.endsWith("/handWritten")?'a hand-written generated file needs "because", saying why it is kept by hand':i==="because"?'a member of kind other needs "because", saying why it is there':`missing required field ${JSON.stringify(i)}`}return e.keyword==="const"&&e.instancePath==="/schema"?"schema must be 1, the only declaration format this chant reads":e.message??"is invalid"}function y4(e,t){let n=e;for(let i of t.split("/").slice(1)){let r=i.replace(/~1/g,"/").replace(/~0/g,"~");if(n===null||typeof n!="object")return;n=n[r]}return n}function mk(e){if(!Array.isArray(e.pins))return;let t=e.pins.findIndex(n=>n!==null&&typeof n=="object"&&n.package===Dd&&typeof n.version=="string");return t<0?void 0:{version:e.pins[t].version,index:t}}function w4(e,t,n=en(),i={}){let r=Ca(e,{jsonc:t.endsWith(".jsonc")});if(!r.ok)throw new ve("declaration-unparseable",r.message,{file:t,...r.location});let o=(L,M=!1)=>({file:t,...r.locate(L,M)}),s=r.value;if(s===null||typeof s!="object"||Array.isArray(s))throw new ve("declaration-invalid","the declaration must be a JSON object",o(""));let a=s,c=i.rootChant?mk(a):void 0;if(c&&c.version!==n)throw new ve("root-chant-required",`this declaration pins ${Dd} ${c.version}, and this is chant ${n}; the root's chant reads it, so install ${Dd}@${c.version} at the workspace root`,o(`/pins/${c.index}/version`));if(typeof a.minReader=="string"&&$I.test(a.minReader)&&h4(n,a.minReader)<0)throw new ve("reader-too-old",`this declaration needs chant ${a.minReader} or newer to read it, and this is chant ${n}`,o("/minReader"));let l=_ye();if(!l(s)){let L=(l.errors??[]).filter(re=>!Iye.has(re.keyword));L.sort((re,be)=>be.instancePath.split("/").length-re.instancePath.split("/").length);let M=L[0]??l.errors[0],_=M.keyword==="additionalProperties",T=_?`${M.instancePath}/${_d(String(M.params.additionalProperty))}`:M.instancePath,W=M.instancePath===""?"":` (at ${M.instancePath})`,ke=L.length>1?`; ${L.length-1} more problem${L.length>2?"s":""} after this one`:"";throw new ve("declaration-invalid",`${Tye(M,y4(s,M.instancePath))}${W}${ke}`,o(T,_))}let u=a.members.map((L,M)=>{let _=`/members/${M}`,T=(L.suppress??[]).map(ne=>({check:ne.check,because:ne.because}));if(L.kind===dk){let ne=L.glob;return{type:"group",name:L.name,kind:dk,globs:typeof ne=="string"?[ne]:[...ne],suppress:T,pointer:_,globLocation:r.locate(`${_}/glob`)}}let W=(L.roles??[]).map(ne=>typeof ne=="string"?{name:ne,path:null}:{name:ne.name,path:ne.path??null}),ke=(L.generated??[]).map((ne,ye)=>({path:ne.path,generator:ne.generator,sources:[...ne.sources??[]],handWritten:ne.handWritten?{because:ne.handWritten.because}:null,pointer:`${_}/generated/${ye}`})),re=(L.links??[]).map((ne,ye)=>({member:ne.member,output:ne.output,kind:ne.kind??null,protocol:ne.protocol??null,pointer:`${_}/links/${ye}`})),be=a4(L.records,L.dir,L.name,`${_}/records`),Be=c4(L.diagrams,L.name,`${_}/diagrams`),dt=Wye(L.box,`${_}/box`);return{type:"member",name:L.name,dir:L.dir,kind:L.kind,roles:W,generated:ke,outputs:L.outputs===void 0?null:[...L.outputs],fields:L.fields===void 0?null:structuredClone(L.fields),links:re,records:be,diagrams:Be,box:dt,upstream:L.upstream??null,because:L.because??null,travel:L.travel===!0,security:[...L.security??[]],ciWorkflow:L.ci?.workflow??null,suppress:T,pointer:_}}),d=new Map;for(let L of u){let M=d.get(L.name);if(M)throw new ve("declaration-invalid",`the name ${JSON.stringify(L.name)} is already used by the entry at ${M.pointer}`,o(`${L.pointer}/name`));d.set(L.name,L)}let p=u.filter(L=>L.type==="member"),f=new Map;for(let L of p){let M=f.get(L.dir);if(M)throw new ve("placement-invalid",`member ${L.name} has the same directory as member ${M.name} (${L.dir})`,o(`${L.pointer}/dir`));f.set(L.dir,L)}for(let L of p){let M=p.find(_=>_!==L&&_.dir!=="."&&Nr(L.dir,_.dir));if(M)throw new ve("placement-invalid",`member ${L.name} (${L.dir}) sits inside member ${M.name} (${M.dir}); only the root member "." may contain other members`,o(`${L.pointer}/dir`))}for(let L of p){let M=new Map;for(let _ of L.generated){let T=M.get(_.path);if(T)throw new ve("declaration-invalid",`member ${L.name} lists the generated file ${_.path} twice; the first is at ${T.pointer}`,o(`${_.pointer}/path`));M.set(_.path,_);let W=L.dir==="."?_.path:`${L.dir}/${_.path}`,ke=p.find(re=>re!==L&&re.dir!=="."&&Nr(re.dir,L.dir)&&Nr(W,re.dir));if(ke)throw new ve("placement-invalid",`member ${L.name} lists the generated file ${_.path}, which sits inside member ${ke.name} (${ke.dir}); list it there`,o(`${_.pointer}/path`))}}let g=a4(a.records,".",null,"/records"),h=new Map,w=new Map;for(let L of[...g,...p.flatMap(M=>M.records)]){let M=h.get(L.path);if(M)throw new ve("declaration-invalid",`the record kind ${L.path} is already declared at ${M.pointer}`,o(`${L.pointer}/kind`));if(h.set(L.path,L),L.name===null)continue;let _=w.get(L.name);if(_)throw new ve("declaration-invalid",`the record kind name ${JSON.stringify(L.name)} is already given at ${_.pointer}`,o(`${L.pointer}/name`));w.set(L.name,L)}for(let L of p){let M=new Map;for(let T of L.box?.capabilities??[]){let W=M.get(T.name);if(W)throw new ve("declaration-invalid",`member ${L.name}'s box lists the capability ${T.name} twice; the first is at ${W.pointer}`,o(`${T.pointer}/name`));M.set(T.name,T)}let _=L.box?v4(L.name,L.box.services):null;if(_)throw new ve("declaration-invalid",_.message,o(_.pointer))}let b=Bye(p);if(b)throw new ve("declaration-invalid",b.message,o(b.pointer));let k=p.filter(L=>L.box?.replicate);if(k.length>1)throw new ve("declaration-invalid",`members ${k[0].name} and ${k[1].name} both declare replicate in their box block; a checkout's work in progress goes to one remote, so a workspace has one replicate policy`,o(k[1].box.replicate.pointer));let $=c4(a.diagrams,null,"/diagrams"),x=new Map;for(let L of[...$,...p.flatMap(M=>M.diagrams)]){let M=x.get(L.name);if(M)throw new ve("declaration-invalid",`the diagram name ${JSON.stringify(L.name)} is already used by the diagram at ${M.pointer}`,o(`${L.pointer}/name`));x.set(L.name,L)}let R=Vye(a,p,o),P=Dye(a.writeScope,p,o),I=Fye(a.agents,p,o),A=zye(p,I);if(A)throw new ve("declaration-invalid",A.message,o(A.pointer));let B=Mye(a.ci,o),C=(a.pins??[]).map(L=>({package:L.package??null,version:L.version??null,path:L.path??null,integrity:L.integrity??null})),q={name:a.name,schema:a.schema,minReader:a.minReader??null,entries:u,members:p,groups:u.filter(L=>L.type==="group"),pins:C,checks:{...a.checks??{}},quorum:typeof a.quorum=="number"?a.quorum:null,records:g,diagrams:$,hosts:R,changes:Gye(a.changes),writeScope:P,agents:I,identity:jye(a.identity),ci:B,retention:Lye(a.retention),metrics:Nye(a.metrics),security:[...a.security??[]],file:t};return b4.set(q,s),q}function ag(e,t){let n=y4(b4.get(e),t);return n===null||typeof n!="object"||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(([i])=>i.startsWith("x-")))}function Dye(e,t,n){if(e===void 0)return null;let i=e,r={};for(let[o,s]of Object.entries(i)){let a=`/writeScope/${o}`,c=s.members===void 0||s.members==="*"?null:[...s.members];for(let[d,p]of(c??[]).entries())if(!t.some(f=>f.name===p))throw new ve("declaration-invalid",`writeScope.${o} names the member ${JSON.stringify(p)}, which the declaration does not declare; declared members: ${t.map(f=>f.name).join(", ")||"none"}`,n(`${a}/members/${d}`));let l=s.records===void 0?null:Object.fromEntries(Object.entries(s.records).map(([d,p])=>[d,[...p]])),u=(s.protected??[]).map(d=>typeof d=="string"?{path:d,except:[]}:{path:d.path,except:[...d.except??[]]});r[o]={members:c,records:l,protected:u,pointer:a}}return r}function jye(e){if(e===void 0)return null;let t=e,n={};for(let[i,r]of Object.entries(t.gates??{}))n[i]={gate:i,class:r.class??null,pointer:`/identity/gates/${i.replace(/~/g,"~0").replace(/\//g,"~1")}`};return{attribution:t.attribution??"any",gates:n}}function Nye(e){if(!e||typeof e!="object")return null;let t=e.failureWindowDays;return typeof t=="number"?{failureWindowDays:t}:{}}function Lye(e){if(!e||typeof e!="object")return null;let t={};for(let n of jV){let i=e[n];i&&(t[n]={...typeof i.days=="number"?{days:i.days}:{},...typeof i.keep=="number"?{keep:i.keep}:{}})}return t}function Mye(e,t){if(e===void 0)return null;let n=e,i=n.workflow!==void 0?{workflow:n.workflow}:{},r=null;if(n.reportUrl!==void 0){let a=NV(n.reportUrl,"ci.reportUrl");if("error"in a)throw new ve("declaration-invalid",a.error,t("/ci/reportUrl"));r=a.url}if(n.green===void 0)return{green:null,...i,reportUrl:r};let o=n.green,s=Object.entries(o.phases).map(([a,c])=>({name:a,runs:[...Array.isArray(c)?c:c.runs],skipped:Array.isArray(c)?"fail":c.skipped??"fail",...!Array.isArray(c)&&c.build!==void 0?{build:c.build}:{},pointer:`/ci/green/phases/${_d(a)}`}));for(let[a,c]of o.require.entries())if(!s.some(l=>l.name===c))throw new ve("declaration-invalid",`ci.green.require names the phase ${JSON.stringify(c)}, which ci.green.phases does not declare; declared phases: ${s.map(l=>l.name).join(", ")}`,t(`/ci/green/require/${a}`));for(let[a,c]of(o.preMerge??[]).entries())if(!s.some(l=>l.name===c))throw new ve("declaration-invalid",`ci.green.preMerge names the phase ${JSON.stringify(c)}, which ci.green.phases does not declare; declared phases: ${s.map(l=>l.name).join(", ")}`,t(`/ci/green/preMerge/${a}`));return{green:{branch:o.branch,window:o.window??u4,phases:s,require:[...o.require],...o.preMerge!==void 0?{preMerge:[...o.preMerge]}:{},signedSince:o.signedSince??null,source:o.source??"checks",pointer:"/ci/green"},...i,reportUrl:r}}function Fye(e,t,n){let i=(e??[]).map((s,a)=>{let c=s.members!==void 0?[...s.members]:[s.member];return{name:s.name,members:c,member:c[0],principals:[...s.principals??[]],pointer:`/agents/${a}`,listed:s.members!==void 0}}),r=new Map,o=new Map;for(let{listed:s,...a}of i){let c=r.get(a.name);if(c)throw new ve("declaration-invalid",`the agent name ${JSON.stringify(a.name)} is already used by the agent at ${c.pointer}`,n(`${a.pointer}/name`));r.set(a.name,a);for(let[l,u]of a.members.entries())if(!t.some(d=>d.name===u))throw new ve("declaration-invalid",`agent ${a.name} is bound to ${JSON.stringify(u)}, which is not a declared member; an agent session is bound to members, not an example group`,n(s?`${a.pointer}/members/${l}`:`${a.pointer}/member`));for(let[l,u]of a.principals.entries()){let d=o.get(u);if(d)throw new ve("declaration-invalid",`the principal ${JSON.stringify(u)} is already listed by agent ${d.name}`,n(`${a.pointer}/principals/${l}`));o.set(u,a)}}return[...r.values()]}function Gye(e){return e===void 0?null:{severity:e.severity??"warn",ignore:[...e.ignore??[]]}}function a4(e,t,n,i){return(e??[]).map((r,o)=>({kind:r.kind,path:t==="."?r.kind:`${t}/${r.kind}`,name:r.name??null,member:n,pointer:`${i}/${o}`}))}function c4(e,t,n){return(e??[]).map((i,r)=>({name:i.name,title:i.title,source:i.source??null,render:i.render??null,renderer:{tool:i.renderer.tool,version:i.renderer.version,args:[...i.renderer.args??[]]},sourceHash:i.sourceHash??null,member:t,pointer:`${n}/${r}`}))}function Wye(e,t){if(e===void 0)return null;let n=e,i=n.factory,r=n.listing,o=n.replicate;return{capabilities:(n.capabilities??[]).map((s,a)=>({name:s.name,broker:s.broker??null,scope:[...s.scope??[]],pointer:`${t}/capabilities/${a}`})),isolation:n.host===void 0?null:{host:n.host,slot:n.slot,ports:{...n.ports??{}},state:{...n.state??{}},cookies:[...n.cookies??[]]},intent:n.intent??null,services:(n.services??[]).map((s,a)=>({name:s.name,cmd:s.cmd,needs:[...s.needs??[]],httpPort:s.httpPort??null,duration:s.duration??null,health:s.health??null,optional:s.optional??!1,pointer:`${t}/services/${a}`})),factory:i===void 0?null:{builds:[...i.builds],check:i.check===void 0?null:typeof i.check=="string"?{run:i.check,kind:"test"}:{run:i.check.run,kind:i.check.kind??"test"},checks:i.checks??null,builders:i.builders??null,tiers:(i.tiers??[]).map(s=>({tier:s.tier,agent:s.agent,kinds:s.kinds===void 0?null:[...s.kinds],session:s.session??null})),publish:i.publish===void 0?null:{forge:i.publish.forge??"github",repo:i.publish.repo,base:i.publish.base??null,branchPrefix:i.publish.branchPrefix??m4,head:i.publish.head??null},pointer:`${t}/factory`},listing:r===void 0?null:{published:r.published??!0,title:r.title??"",line:r.line??"",cover:r.cover??null},publisher:n.publisher??null,ship:n.ship===void 0?null:{op:n.ship.op,gate:n.ship.gate??d4,env:n.ship.env??p4,bookkeeping:(n.ship.bookkeeping??[]).map(s=>s.replace(/^\.\//,"").replace(/\/+$/,"")),pointer:`${t}/ship`},replicate:o===void 0?null:{remote:o.remote??f4,refs:kI.filter(s=>(o.refs??kI).includes(s)),on:xI.filter(s=>(o.on??xI).includes(s)),every:o.every??null,pointer:`${t}/replicate`},pointer:t}}function Bye(e){let t=e.filter(s=>s.box?.factory);if(t.length>1)return{message:`members ${t[0].name} and ${t[1].name} both declare a factory in their box block; a workspace has one factory, so an orchestrator reads one`,pointer:t[1].box.factory.pointer};let n=t[0]?.box?.factory;if(!n)return null;let i=()=>e.map(s=>s.name).join(", "),r=n.builds.findIndex(s=>!e.some(a=>a.name===s));if(r>=0)return{message:`the factory builds ${JSON.stringify(n.builds[r])}, which is not a declared member; declared members: ${i()}`,pointer:`${n.pointer}/builds/${r}`};if(n.builders!==null&&!e.some(s=>s.name===n.builders))return{message:`the factory's builders names ${JSON.stringify(n.builders)}, which is not a declared member; declared members: ${i()}`,pointer:`${n.pointer}/builders`};if(n.tiers.length>0&&n.builders===null)return{message:"the factory declares tiers and no builders; tiers name agents the builders member declares, so name it",pointer:`${n.pointer}/tiers`};let o=new Map;for(let[s,a]of n.tiers.entries())for(let c of a.kinds??[null]){let l=`${a.tier}\0${c??""}`,u=o.get(l);if(u!==void 0){let d=c===null?"with no kinds":`for kind ${c}`;return{message:`tiers/${u} and tiers/${s} both name a builder at tier ${a.tier} ${d}; a tier has one builder per kind, so one entry answers it`,pointer:`${n.pointer}/tiers/${s}`}}o.set(l,s)}return null}function zye(e,t){let n=e.find(i=>i.box?.factory)?.box?.factory;if(!n)return null;for(let[i,r]of n.tiers.entries())if(r.session!==null&&!t.some(o=>o.name===r.session)){let o=t.map(s=>s.name).join(", ")||"none";return{message:`tiers/${i} names the session ${JSON.stringify(r.session)}, which is not a declared agent session; declared sessions: ${o}`,pointer:`${n.pointer}/tiers/${i}/session`}}return null}function v4(e,t){let n=new Map;for(let o of t){let s=n.get(o.name);if(s)return{message:`member ${e}'s box declares the service ${o.name} twice; the first is at ${s.pointer}`,pointer:`${o.pointer}/name`};n.set(o.name,o)}let i;for(let o of t)if(o.httpPort!==null){if(i)return{message:`member ${e}'s box gives both ${i.name} (port ${i.httpPort}) and ${o.name} (port ${o.httpPort}) an httpPort, and the supervisor routes the sprite's URL to one service`,pointer:`${o.pointer}/httpPort`};i=o}for(let o of t){let s=o.needs.findIndex(a=>!n.has(a));if(s>=0){let a=t.map(c=>c.name).join(", ");return{message:`member ${e}'s box service ${o.name} needs ${JSON.stringify(o.needs[s])}, which the block does not declare; declared services: ${a}`,pointer:`${o.pointer}/needs/${s}`}}}let r=Uye(t);if(r){let o=n.get(r[0]);return{message:`member ${e}'s box services need each other in a cycle: ${r.join(" -> ")}`,pointer:`${o.pointer}/needs`}}return null}function Uye(e){let t=new Map(e.map(r=>[r.name,r])),n=new Map,i=(r,o)=>{let s=n.get(r);if(s==="done")return null;if(s==="visiting")return[...o.slice(o.indexOf(r)),r];n.set(r,"visiting");for(let a of t.get(r)?.needs??[]){let c=i(a,[...o,r]);if(c)return c}return n.set(r,"done"),null};for(let r of e){let o=i(r.name,[]);if(o)return o}return null}function Vye(e,t,n){let i=(e.hosts??[]).map((s,a)=>({name:s.name,ports:{...s.ports},stateRoot:s.stateRoot??null,pointer:`/hosts/${a}`})),r=(s,a)=>new ve("declaration-invalid",s,n(a)),o=new Map;for(let s of i){let a=o.get(s.name);if(a)throw r(`the host name ${JSON.stringify(s.name)} is already used by the host at ${a.pointer}`,`${s.pointer}/name`);if(o.set(s.name,s),s.ports.from>s.ports.to)throw r(`host ${s.name}'s port range starts at ${s.ports.from}, after its end ${s.ports.to}`,`${s.pointer}/ports`)}for(let s of t){let a=s.box?.isolation;if(!a)continue;let c=s.box.pointer,l=o.get(a.host);if(!l){let g=i.map(h=>h.name).join(", ")||"none are declared";throw r(`member ${s.name}'s box names the host ${JSON.stringify(a.host)}, which hosts does not declare; declared hosts: ${g}`,`${c}/host`)}let{from:u,to:d,perBox:p}=l.ports,f=u+(a.slot+1)*p-1;if(f>d){let g=Math.floor((d-u+1)/p);throw r(`member ${s.name}'s box has slot ${a.slot} on host ${l.name}, which needs ports ${u+a.slot*p} to ${f}, past the end of the host's range (${d}); the range holds ${g} slot${g===1?"":"s"}`,`${c}/slot`)}for(let[g,h]of Object.entries(a.ports))if(h>=p)throw r(`member ${s.name}'s box gives port ${g} offset ${h}, and host ${l.name} gives each box ${p} port${p===1?"":"s"} (offsets 0 to ${p-1})`,`${c}/ports/${_d(g)}`)}return i}function yr(e){return[...e.records,...e.members.flatMap(t=>t.records)]}function RI(e){return[...e.diagrams,...e.members.flatMap(t=>t.diagrams)]}function Nr(e,t){return t==="."?!0:e===t||e.startsWith(`${t}/`)}function _t(e,t="",n={}){let i=Id.map(r=>qe(t,r)).filter(r=>e.stat(r)==="file");if(i.length===0)throw new ve("declaration-missing",`no ${Id.join(" or ")} in ${t||"the workspace root"}${e.label}`);if(i.length>1)throw new ve("declaration-ambiguous",`both ${i.join(" and ")} exist${e.label}; keep one of them`,{file:i[1],line:1,column:1});return w4(e.read(i[0]),i[0],en(),n)}function SI(e,t){for(let n=t;;n=n.includes("/")?n.slice(0,n.lastIndexOf("/")):""){if(Id.some(i=>e.stat(qe(n,i))==="file"))return n;if(n==="")return}}function _a(e,t){let n=o=>({file:e.file,...o.globLocation}),i=new Map,r=[];for(let o of e.groups){let s=[...new Set(o.globs.flatMap(l=>zV(t,l)))].sort(),a=[],c=[];for(let l of s){if(!wI(t,l)){c.push(l);continue}let u=p=>new ve("placement-invalid",`group ${o.name} matches ${l}, ${p}`,n(o));for(let p of e.members)if(p.dir!=="."){if(p.dir===l)throw u(`which is member ${p.name}'s directory; a match is never a member`);if(Nr(p.dir,l))throw u(`which contains member ${p.name} (${p.dir})`);if(p.kind==="workspace"&&Nr(l,p.dir))throw u(`which sits inside the nested workspace ${p.name}; that workspace declares its own examples`)}let d=i.get(l);if(d)throw u(`which group ${d.name} also matches`);i.set(l,o),a.push(l)}r.push({group:o,matches:a,skipped:c})}return r}function k4(e,t,n){for(let r of t){let o=r.matches.find(s=>Nr(n,s));if(o)return{group:r.group,match:o}}let i;for(let r of e.members)Nr(n,r.dir)&&(!i||i.dir==="."||r.dir!=="."&&r.dir.length>i.dir.length)&&(i=r);return i?{member:i}:void 0}function gk(e,t){let n=[];for(let i of e.members)i.dir!=="."&&n.push({dir:i.dir,owner:i.name});for(let i of t)for(let r of i.matches)e.members.some(o=>o.dir!=="."&&Nr(r,o.dir))||n.push({dir:r,owner:i.group.name});return n.sort((i,r)=>i.dir<r.dir?-1:i.dir>r.dir?1:0)}var Rye,Id,Sye,l4,Eye,yi,ve,Oye,Aye,u4,Pye,d4,p4,kI,xI,f4,Cye,m4,g4,Dd,s4,$I,fk,Iye,b4,Tt=v(()=>{"use strict";U_();LV();MV();UV();qi();Td();on();sg();o4();Rye=V_.$id,Id=["chant.workspace.json","chant.workspace.jsonc"],Sye=1,l4=["_workspace","_members"],Eye=/^[a-z0-9][a-z0-9-]{0,39}$/,yi=["declaration-missing","declaration-ambiguous","declaration-unparseable","declaration-invalid","placement-invalid","reader-too-old","root-chant-required","not-a-git-repository","revision-unknown"],ve=class extends Error{constructor(n,i,r){super(i);this.code=n;this.location=r;this.name="WorkspaceReadError"}describe(){let n=this.location;return n?`${n.file}:${n.line}:${n.column}: ${this.message}`:this.message}},Oye=["human","agent","runner","service"],Aye=["new","amend","review","close"],u4="24h",Pye=["d2","mermaid","graphviz","excalidraw"],d4="ship",p4="box",kI=["work","kept","wip","ledger"],xI=["save","release"],f4="origin",Cye=["test","build","lint","plan","conformance"],m4="chant/work/",g4="${XDG_STATE_HOME}/chant/boxes",Dd="@intentius/chant";$I=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?$/;Iye=new Set(["if","then","else","oneOf","anyOf"]);b4=new WeakMap});var R4={};_e(R4,{MEMBERS_DIR:()=>wk,MEMBER_LEDGER_FLOOR:()=>Xye,MemberLedgerError:()=>yk,clearMemberLedgerCache:()=>Qye,memberLedgerPrefix:()=>bk,resolveMemberLedger:()=>Xr});import{existsSync as Hye}from"node:fs";import{dirname as qye,join as Kye,relative as Jye,resolve as Zye,sep as Yye}from"node:path";function bk(e){return e.map(t=>`${wk}/${t}/`).join("")}function Xr(e){let t=Zye(e),n=hk.get(t);return n||(n=twe(t),hk.set(t,n),n.catch(()=>hk.delete(t))),n}function Qye(){hk.clear()}function ewe(e,t){let n=Jye(e,t);return n===""?"":n.split(Yye).join("/")}async function twe(e){let t=tr(e);return t?$4(t.dir,e):x4}async function $4(e,t){let{readDeclaration:n,resolveGroups:i,ownerOf:r,WorkspaceReadError:o}=await Promise.resolve().then(()=>(Tt(),EI)),{workingTree:s}=await Promise.resolve().then(()=>(on(),q_)),a;try{let d=s(e),p=n(d),f=r(p,i(p,d),ewe(e,t));a=f&&"member"in f&&f.member.dir!=="."?[f.member.name]:[]}catch(d){throw d instanceof o?new yk(`cannot place this project's lifecycle ledger: ${d.describe()}. A project inside a workspace writes under ${wk}/<member>/ on chant/lifecycle, and chant does not guess the member. Fix the declaration and retry.`):d}let c=x4,l=qye(e);if(l!==e&&!Hye(Kye(e,".git"))){let d=tr(l);d&&(c=await $4(d.dir,e))}let u=[...c.members,...a];return{members:u,prefix:bk(u)}}var wk,Xye,x4,yk,hk,Io=v(()=>{"use strict";Mi();wk="_members",Xye="0.81.0",x4={members:[],prefix:""};yk=class extends Error{constructor(t){super(t),this.name="MemberLedgerError"}},hk=new Map});function cg(e){return e===jd}var jd,lg=v(()=>{"use strict";jd="recorded locally (no remote for chant/lifecycle)"});function Ki(e=process.env){let t=e[vk]?.trim().toLowerCase();return t!==void 0&&t!==""&&t!=="0"&&t!=="false"}function ug(e){return OI.get(e)?.tip}function S4(e,t,n,i){let r=OI.get(e)??{tip:null,writes:[]};r.tip=t;for(let o of n)r.writes.push({path:o,message:i});OI.set(e,r)}function kk(e,t){if(Ki())throw new AI(e,t)}var vk,PI,OI,AI,Nd=v(()=>{"use strict";vk="CHANT_NO_RECORD";PI="not recorded (--no-record): chant/lifecycle was not written or pushed",OI=new Map;AI=class extends Error{constructor(n,i){super(`gate "${i}" of "${n}" cannot be passed under --no-record: a gate is decided and approved on chant/lifecycle, which this run does not write. Run without --no-record (and without CHANT_NO_RECORD) to stop at the gate for approval.`);this.op=n;this.gate=i;this.name="GateNotRecordableError"}}});var MI={};_e(MI,{LifecycleLedgerUnreadableError:()=>pg,RefCASConflictError:()=>Ot,StaleLifecycleBranchError:()=>dg,StaleLockError:()=>fl,appendLedgerLine:()=>D4,appendReleaseRecordLine:()=>TI,deleteRefCAS:()=>Fd,describeLifecyclePush:()=>jI,fetchLifecycle:()=>uwe,fetchLifecycleStatus:()=>Yi,fetchRef:()=>mwe,fetchRefInto:()=>F4,fetchRefIntoStatus:()=>Rk,getHeadCommit:()=>Sk,getRemoteLifecycleBranchSha:()=>j4,gitLedgerReadPort:()=>hwe,ledgerDir:()=>qn,ledgerRevision:()=>Gd,listFilesInDir:()=>Zi,listLedgerEnvironments:()=>DI,listLedgerTrees:()=>fg,listSnapshots:()=>lwe,pushLifecycle:()=>Ld,pushLifecycleReport:()=>Ia,pushLifecycleStatus:()=>Ta,pushRef:()=>fwe,pushRefStatus:()=>mg,readBlobBySha:()=>hn,readBlobFromPath:()=>At,readEnvironmentSnapshots:()=>cwe,readPathSha:()=>gn,readRefSha:()=>Da,readReleaseLedgerLines:()=>II,readSnapshot:()=>I4,readSnapshotAt:()=>awe,requireLifecycleLedger:()=>Lr,snapshotStorageKey:()=>_4,updateRefCAS:()=>Md,writeBlob:()=>NI,writeBlobToPath:()=>mn,writeLedgerFiles:()=>Ji,writeSnapshot:()=>T4});async function qn(e,t){return`${await nwe(t)}${e}`}async function nwe(e){return e?.ledgerPrefix!==void 0?e.ledgerPrefix:e?.member!==void 0?bk((typeof e.member=="string"?[e.member]:[...e.member]).filter(t=>t!==".")):(await Xr(e?.cwd??process.cwd())).prefix}async function owe(e){let t=bt();if((await t.spawn(["git","var","GIT_COMMITTER_IDENT"],{cwd:e,env:wi})).exitCode===0)return[];let i=[];for(let[r,o,s]of[["user.name","CHANT_LIFECYCLE_COMMITTER_NAME",rwe],["user.email","CHANT_LIFECYCLE_COMMITTER_EMAIL",iwe]]){let a=await t.spawn(["git","config","--get",r],{cwd:e,env:wi});a.exitCode===0&&a.stdout.trim()!==""||i.push("-c",`${r}=${process.env[o]?.trim()||s}`)}return i}function CI(e,t,n){return new Error(`cannot write ${t} on the ${Nt} branch: ${e} failed: ${(n??"").trim()}`)}async function mn(e,t,n,i,r){let o=await qn(e,r);return Ji([{path:`${o}/${t}`,content:n,...r?.expectPriorPathSha!==void 0?{expectPriorSha:r.expectPriorPathSha}:{}}],i,r)}async function Ji(e,t,n){let i=bt(),r=n?.cwd;if(e.length===0)throw new Error("writeLedgerFiles needs at least one file");let o=e[0].path;for(let u of e){let d=u.path.split("/");if(d.length<2||d.some(p=>p===""))throw new Error(`cannot write ${u.path} on the ${Nt} branch: a ledger path is <dir>/<file>`)}let s=[];for(let u of e){if(swe(u)){s.push({path:u.path,sha:null});continue}let d=await i.spawn(["git","hash-object","-w","--stdin"],{cwd:r,stdin:u.content});if(d.exitCode!==0)throw CI("git hash-object",u.path,d.stderr);s.push({path:u.path,sha:d.stdout.trim()})}let a=await owe(r);await ml(r)===null&&await Lr({...r?{cwd:r}:{}});let c=new Map(e.map(u=>[u.path,u.expectPriorSha])),l;for(let u=1;u<=C4;u++){let d=await ml(r);if(n?.expectTip!==void 0&&d!==n.expectTip)throw new Ot(`refs/heads/${Nt}`,n.expectTip,`the branch moved to ${d??"(none)"} since it was read`);let p=new Map,f=async x=>{let R=p.get(x);return R||(R=d?await gwe(d,x,r):new Map,p.set(x,R)),R};for(let x of s){let{dir:R,name:P}=O4(x.path),I=(await f(R)).get(P),A=I?.type==="blob"?I.sha:null,B=c.get(x.path);if(B!==void 0&&A!==B)throw l??new Ot(`refs/heads/${Nt}`,B,"target path changed concurrently");c.set(x.path,A)}for(let x of s){let{dir:R,name:P}=O4(x.path);x.sha===null?(await f(R)).delete(P):(await f(R)).set(P,{mode:"100644",type:"blob",sha:x.sha});for(let I=R;I!=="";I=$k(I))await f($k(I))}let g=[...p.keys()].sort((x,R)=>P4(R)-P4(x)||(x<R?-1:1)),h="";for(let x of g){if(x!==""&&p.get(x).size===0){p.get($k(x)).delete(A4(x));continue}let R=[...p.get(x)].map(([A,B])=>`${B.mode} ${B.type} ${B.sha} ${A}`).join(`
75
75
  `),P=await i.spawn(["git","mktree"],{cwd:r,stdin:R===""?"":`${R}
76
76
  `});if(P.exitCode!==0)throw CI(`git mktree (${x===""?"root":x})`,o,P.stderr);let I=P.stdout.trim();x===""?h=I:p.get($k(x)).set(A4(x),{mode:"040000",type:"tree",sha:I})}let w=d,b=w?["-p",w]:[],k=await i.spawn(["git",...a,"commit-tree",...b,"-m",t,h],{cwd:r});if(k.exitCode!==0)throw CI("git commit-tree",o,k.stderr);let $=k.stdout.trim();if(Ki()){let x=await LI(r),R=ug(x)===void 0?await Da(`refs/heads/${Nt}`,{cwd:r}):null,P=ug(x),I=P!==void 0?P:R;if(I===w)return S4(x,$,e.map(A=>A.path),t),$;l=new Ot(`refs/heads/${Nt}`,w,`the run's unrecorded tip is ${I??"(none)"}`);continue}try{return await Md(`refs/heads/${Nt}`,$,w,{cwd:r}),$}catch(x){if(!(x instanceof Ot))throw x;l=x}}throw l}async function At(e,t,n){let i=bt(),r=await qn(e,n),o=await i.spawn(["git","show",`${await Gd(n?.cwd)}:${r}/${t}`],{cwd:n?.cwd});return o.exitCode!==0?null:o.stdout}async function gn(e,t,n){let i=bt(),r=await qn(e,n),o=await i.spawn(["git","rev-parse","--verify",`${await Gd(n?.cwd)}:${r}/${t}`],{cwd:n?.cwd});return o.exitCode!==0?null:o.stdout.trim()||null}function _4(e,t){return t?`${t}__${e}`:e}async function T4(e,t,n,i){return mn(e,`${t}.json`,n,"State snapshot",i)}async function I4(e,t,n){return At(e,`${t}.json`,n)}async function awe(e,t,n,i){let r=bt(),o=await qn(e,i),s=await r.spawn(["git","show",`${n}:${o}/${t}.json`],{cwd:i?.cwd});return s.exitCode!==0?null:s.stdout}async function TI(e,t,n){return D4(e,"releases.jsonl",t,"Release record",n)}async function D4(e,t,n,i,r){let o;for(let s=1;s<=C4;s++)try{let a=await gn(e,t,r),c=a?await hn(a,r):null,l=`${c?`${c.replace(/\n$/,"")}
77
77
  `:""}${n}
@@ -105,18 +105,18 @@ ${e.timestamp}`,"utf-8")}function yue(e,t,n){let i=`the approval of gate ${n.gat
105
105
  `;for(let h=1;h<=o.linesAfter&&!(u+h>=c.length);h++){let w=t(r.buffer,a[u+h],c[u+h],r.position-(a[u]-a[u+h]),f);d+=e.repeat(" ",o.indent)+n((r.line+h+1).toString(),p)+" | "+w.str+`
106
106
  `}return d.replace(/\n$/,"")}return eD=i,eD}function wr(){if(o6)return tD;o6=1;let e=$g(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],n=["scalar","sequence","mapping"];function i(o){let s={};return o!==null&&Object.keys(o).forEach(function(a){o[a].forEach(function(c){s[String(c)]=a})}),s}function r(o,s){if(s=s||{},Object.keys(s).forEach(function(a){if(t.indexOf(a)===-1)throw new e('Unknown option "'+a+'" is met in definition of "'+o+'" YAML type.')}),this.options=s,this.tag=o,this.kind=s.kind||null,this.resolve=s.resolve||function(){return!0},this.construct=s.construct||function(a){return a},this.instanceOf=s.instanceOf||null,this.predicate=s.predicate||null,this.represent=s.represent||null,this.representName=s.representName||null,this.defaultStyle=s.defaultStyle||null,this.multi=s.multi||!1,this.styleAliases=i(s.styleAliases||null),n.indexOf(this.kind)===-1)throw new e('Unknown kind "'+this.kind+'" is specified for "'+o+'" YAML type.')}return tD=r,tD}function O6(){if(s6)return nD;s6=1;let e=$g(),t=wr();function n(o,s){let a=[];return o[s].forEach(function(c){let l=a.length;a.forEach(function(u,d){u.tag===c.tag&&u.kind===c.kind&&u.multi===c.multi&&(l=d)}),a[l]=c}),a}function i(){let o={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(a){a.multi?(o.multi[a.kind].push(a),o.multi.fallback.push(a)):o[a.kind][a.tag]=o.fallback[a.tag]=a}for(let a=0,c=arguments.length;a<c;a+=1)arguments[a].forEach(s);return o}function r(o){return this.extend(o)}return r.prototype.extend=function(s){let a=[],c=[];if(s instanceof t)c.push(s);else if(Array.isArray(s))c=c.concat(s);else if(s&&(Array.isArray(s.implicit)||Array.isArray(s.explicit)))s.implicit&&(a=a.concat(s.implicit)),s.explicit&&(c=c.concat(s.explicit));else throw new e("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");a.forEach(function(u){if(!(u instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(u.loadKind&&u.loadKind!=="scalar")throw new e("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(u.multi)throw new e("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),c.forEach(function(u){if(!(u instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.")});let l=Object.create(r.prototype);return l.implicit=(this.implicit||[]).concat(a),l.explicit=(this.explicit||[]).concat(c),l.compiledImplicit=n(l,"implicit"),l.compiledExplicit=n(l,"explicit"),l.compiledTypeMap=i(l.compiledImplicit,l.compiledExplicit),l},nD=r,nD}function A6(){if(a6)return rD;a6=1;let e=wr();return rD=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),rD}function P6(){if(c6)return iD;c6=1;let e=wr();return iD=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),iD}function C6(){if(l6)return oD;l6=1;let e=wr();return oD=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),oD}function _6(){if(u6)return sD;u6=1;let e=O6();return sD=new e({explicit:[A6(),P6(),C6()]}),sD}function T6(){if(d6)return aD;d6=1;let e=wr();function t(r){if(r===null)return!0;let o=r.length;return o===1&&r==="~"||o===4&&(r==="null"||r==="Null"||r==="NULL")}function n(){return null}function i(r){return r===null}return aD=new e("tag:yaml.org,2002:null",{kind:"scalar",resolve:t,construct:n,predicate:i,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"}),aD}function I6(){if(p6)return cD;p6=1;let e=wr();function t(r){if(r===null)return!1;let o=r.length;return o===4&&(r==="true"||r==="True"||r==="TRUE")||o===5&&(r==="false"||r==="False"||r==="FALSE")}function n(r){return r==="true"||r==="True"||r==="TRUE"}function i(r){return Object.prototype.toString.call(r)==="[object Boolean]"}return cD=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:t,construct:n,predicate:i,represent:{lowercase:function(r){return r?"true":"false"},uppercase:function(r){return r?"TRUE":"FALSE"},camelcase:function(r){return r?"True":"False"}},defaultStyle:"lowercase"}),cD}function D6(){if(f6)return lD;f6=1;let e=xg(),t=wr();function n(l){return l>=48&&l<=57||l>=65&&l<=70||l>=97&&l<=102}function i(l){return l>=48&&l<=55}function r(l){return l>=48&&l<=57}function o(l){if(l===null)return!1;let u=l.length,d=0,p=!1;if(!u)return!1;let f=l[d];if((f==="-"||f==="+")&&(f=l[++d]),f==="0"){if(d+1===u)return!0;if(f=l[++d],f==="b"){for(d++;d<u;d++){if(f=l[d],f!=="0"&&f!=="1")return!1;p=!0}return p&&isFinite(s(l))}if(f==="x"){for(d++;d<u;d++){if(!n(l.charCodeAt(d)))return!1;p=!0}return p&&isFinite(s(l))}if(f==="o"){for(d++;d<u;d++){if(!i(l.charCodeAt(d)))return!1;p=!0}return p&&isFinite(s(l))}}for(;d<u;d++){if(!r(l.charCodeAt(d)))return!1;p=!0}return p?isFinite(s(l)):!1}function s(l){let u=l,d=1,p=u[0];if((p==="-"||p==="+")&&(p==="-"&&(d=-1),u=u.slice(1),p=u[0]),u==="0")return 0;if(p==="0"){if(u[1]==="b")return d*parseInt(u.slice(2),2);if(u[1]==="x")return d*parseInt(u.slice(2),16);if(u[1]==="o")return d*parseInt(u.slice(2),8)}return d*parseInt(u,10)}function a(l){return s(l)}function c(l){return Object.prototype.toString.call(l)==="[object Number]"&&l%1===0&&!e.isNegativeZero(l)}return lD=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:o,construct:a,predicate:c,represent:{binary:function(l){return l>=0?"0b"+l.toString(2):"-0b"+l.toString(2).slice(1)},octal:function(l){return l>=0?"0o"+l.toString(8):"-0o"+l.toString(8).slice(1)},decimal:function(l){return l.toString(10)},hexadecimal:function(l){return l>=0?"0x"+l.toString(16).toUpperCase():"-0x"+l.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),lD}function j6(){if(m6)return uD;m6=1;let e=xg(),t=wr(),n=new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),i=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function r(l){return l===null||!n.test(l)?!1:isFinite(parseFloat(l,10))?!0:i.test(l)}function o(l){let u=l.toLowerCase(),d=u[0]==="-"?-1:1;return"+-".indexOf(u[0])>=0&&(u=u.slice(1)),u===".inf"?d===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:u===".nan"?NaN:d*parseFloat(u,10)}let s=/^[-+]?[0-9]+e/;function a(l,u){if(isNaN(l))switch(u){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===l)switch(u){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===l)switch(u){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(l))return"-0.0";let d=l.toString(10);return s.test(d)?d.replace("e",".e"):d}function c(l){return Object.prototype.toString.call(l)==="[object Number]"&&(l%1!==0||e.isNegativeZero(l))}return uD=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:r,construct:o,predicate:c,represent:a,defaultStyle:"lowercase"}),uD}function N6(){return g6||(g6=1,dD=_6().extend({implicit:[T6(),I6(),D6(),j6()]})),dD}function L6(){return h6||(h6=1,pD=N6()),pD}function M6(){if(y6)return fD;y6=1;let e=wr(),t=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),n=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function i(s){return s===null?!1:t.exec(s)!==null||n.exec(s)!==null}function r(s){let a=0,c=null,l=t.exec(s);if(l===null&&(l=n.exec(s)),l===null)throw new Error("Date resolve error");let u=+l[1],d=+l[2]-1,p=+l[3];if(!l[4])return new Date(Date.UTC(u,d,p));let f=+l[4],g=+l[5],h=+l[6];if(l[7]){for(a=l[7].slice(0,3);a.length<3;)a+="0";a=+a}if(l[9]){let b=+l[10],k=+(l[11]||0);c=(b*60+k)*6e4,l[9]==="-"&&(c=-c)}let w=new Date(Date.UTC(u,d,p,f,g,h,a));return c&&w.setTime(w.getTime()-c),w}function o(s){return s.toISOString()}return fD=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:i,construct:r,instanceOf:Date,represent:o}),fD}function F6(){if(w6)return mD;w6=1;let e=wr();function t(n){return n==="<<"||n===null}return mD=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),mD}function G6(){if(b6)return gD;b6=1;let e=wr(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
107
107
  \r`;function n(s){if(s===null)return!1;let a=0,c=s.length,l=t;for(let u=0;u<c;u++){let d=l.indexOf(s.charAt(u));if(!(d>64)){if(d<0)return!1;a+=6}}return a%8===0}function i(s){let a=s.replace(/[\r\n=]/g,""),c=a.length,l=t,u=0,d=[];for(let f=0;f<c;f++)f%4===0&&f&&(d.push(u>>16&255),d.push(u>>8&255),d.push(u&255)),u=u<<6|l.indexOf(a.charAt(f));let p=c%4*6;return p===0?(d.push(u>>16&255),d.push(u>>8&255),d.push(u&255)):p===18?(d.push(u>>10&255),d.push(u>>2&255)):p===12&&d.push(u>>4&255),new Uint8Array(d)}function r(s){let a="",c=0,l=s.length,u=t;for(let p=0;p<l;p++)p%3===0&&p&&(a+=u[c>>18&63],a+=u[c>>12&63],a+=u[c>>6&63],a+=u[c&63]),c=(c<<8)+s[p];let d=l%3;return d===0?(a+=u[c>>18&63],a+=u[c>>12&63],a+=u[c>>6&63],a+=u[c&63]):d===2?(a+=u[c>>10&63],a+=u[c>>4&63],a+=u[c<<2&63],a+=u[64]):d===1&&(a+=u[c>>2&63],a+=u[c<<4&63],a+=u[64],a+=u[64]),a}function o(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return gD=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:i,predicate:o,represent:r}),gD}function W6(){if(v6)return hD;v6=1;let e=wr(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function i(o){if(o===null)return!0;let s={},a=o;for(let c=0,l=a.length;c<l;c+=1){let u=a[c],d=!1;if(n.call(u)!=="[object Object]")return!1;let p;for(p in u)if(t.call(u,p))if(!d)d=!0;else return!1;if(!d||t.call(s,p))return!1;Object.defineProperty(s,p,{value:!0})}return!0}function r(o){return o!==null?o:[]}return hD=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:i,construct:r}),hD}function B6(){if(k6)return yD;k6=1;let e=wr(),t=Object.prototype.toString;function n(r){if(r===null)return!0;let o=r,s=new Array(o.length);for(let a=0,c=o.length;a<c;a+=1){let l=o[a];if(t.call(l)!=="[object Object]")return!1;let u=Object.keys(l);if(u.length!==1)return!1;s[a]=[u[0],l[u[0]]]}return!0}function i(r){if(r===null)return[];let o=r,s=new Array(o.length);for(let a=0,c=o.length;a<c;a+=1){let l=o[a],u=Object.keys(l);s[a]=[u[0],l[u[0]]]}return s}return yD=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:i}),yD}function z6(){if(x6)return wD;x6=1;let e=wr(),t=Object.prototype.hasOwnProperty;function n(r){if(r===null)return!0;let o=r;for(let s in o)if(t.call(o,s)&&o[s]!==null)return!1;return!0}function i(r){return r!==null?r:{}}return wD=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:i}),wD}function kD(){return $6||($6=1,bD=L6().extend({implicit:[M6(),F6()],explicit:[G6(),W6(),B6(),z6()]})),bD}function Lwe(){if(R6)return Fk;R6=1;let e=xg(),t=$g(),n=Nwe(),i=kD(),r=Object.prototype.hasOwnProperty,o=1,s=2,a=3,c=4,l=1,u=2,d=3,p=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,f=/[\x85\u2028\u2029]/,g=/[,\[\]{}]/,h=/^(?:!|!!|![0-9A-Za-z-]+!)$/,w=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function b(y){return Object.prototype.toString.call(y)}function k(y){return y===10||y===13}function $(y){return y===9||y===32}function x(y){return y===9||y===32||y===10||y===13}function R(y){return y===44||y===91||y===93||y===123||y===125}function P(y){if(y>=48&&y<=57)return y-48;let N=y|32;return N>=97&&N<=102?N-97+10:-1}function I(y){return y===120?2:y===117?4:y===85?8:0}function A(y){return y>=48&&y<=57?y-48:-1}function B(y){switch(y){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
108
- `;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"\x85";case 95:return"\xA0";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function C(y){return y<=65535?String.fromCharCode(y):String.fromCharCode((y-65536>>10)+55296,(y-65536&1023)+56320)}function q(y,N,K){N==="__proto__"?Object.defineProperty(y,N,{configurable:!0,enumerable:!0,writable:!0,value:K}):y[N]=K}let L=new Array(256),M=new Array(256);for(let y=0;y<256;y++)L[y]=B(y)?1:0,M[y]=B(y);function _(y,N){this.input=y,this.filename=N.filename||null,this.schema=N.schema||i,this.onWarning=N.onWarning||null,this.legacy=N.legacy||!1,this.json=N.json||!1,this.listener=N.listener||null,this.maxDepth=typeof N.maxDepth=="number"?N.maxDepth:100,this.maxTotalMergeKeys=typeof N.maxTotalMergeKeys=="number"?N.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=y.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function T(y,N){let K={name:y.filename,buffer:y.input.slice(0,-1),position:y.position,line:y.line,column:y.position-y.lineStart};return K.snippet=n(K),new t(N,K)}function W(y,N){throw T(y,N)}function ve(y,N){y.onWarning&&y.onWarning.call(null,T(y,N))}function re(y,N,K){let Q=y.anchorMapTransactions;if(Q.length!==0){let H=Q[Q.length-1];r.call(H,N)||(H[N]={existed:r.call(y.anchorMap,N),value:y.anchorMap[N]})}y.anchorMap[N]=K}function be(y){y.anchorMapTransactions.push(Object.create(null))}function Be(y){let N=y.anchorMapTransactions.pop(),K=y.anchorMapTransactions;if(K.length===0)return;let Q=K[K.length-1],H=Object.keys(N);for(let S=0,G=H.length;S<G;S+=1){let J=H[S];r.call(Q,J)||(Q[J]=N[J])}}function dt(y){let N=y.anchorMapTransactions.pop(),K=Object.keys(N);for(let Q=K.length-1;Q>=0;Q-=1){let H=N[K[Q]];H.existed?y.anchorMap[K[Q]]=H.value:delete y.anchorMap[K[Q]]}}function ne(y){return{position:y.position,line:y.line,lineStart:y.lineStart,lineIndent:y.lineIndent,firstTabInLine:y.firstTabInLine,tag:y.tag,anchor:y.anchor,kind:y.kind,result:y.result}}function ye(y,N){y.position=N.position,y.line=N.line,y.lineStart=N.lineStart,y.lineIndent=N.lineIndent,y.firstTabInLine=N.firstTabInLine,y.tag=N.tag,y.anchor=N.anchor,y.kind=N.kind,y.result=N.result}let ge={YAML:function(N,K,Q){N.version!==null&&W(N,"duplication of %YAML directive"),Q.length!==1&&W(N,"YAML directive accepts exactly one argument");let H=/^([0-9]+)\.([0-9]+)$/.exec(Q[0]);H===null&&W(N,"ill-formed argument of the YAML directive");let S=parseInt(H[1],10),G=parseInt(H[2],10);S!==1&&W(N,"unacceptable YAML version of the document"),N.version=Q[0],N.checkLineBreaks=G<2,G!==1&&G!==2&&ve(N,"unsupported YAML version of the document")},TAG:function(N,K,Q){let H;Q.length!==2&&W(N,"TAG directive accepts exactly two arguments");let S=Q[0];H=Q[1],h.test(S)||W(N,"ill-formed tag handle (first argument) of the TAG directive"),r.call(N.tagMap,S)&&W(N,'there is a previously declared suffix for "'+S+'" tag handle'),w.test(H)||W(N,"ill-formed tag prefix (second argument) of the TAG directive");try{H=decodeURIComponent(H)}catch{W(N,"tag prefix is malformed: "+H)}N.tagMap[S]=H}};function oe(y,N,K,Q){if(N<K){let H=y.input.slice(N,K);if(Q)for(let S=0,G=H.length;S<G;S+=1){let J=H.charCodeAt(S);J===9||J>=32&&J<=1114111||W(y,"expected valid JSON character")}else p.test(H)&&W(y,"the stream contains non-printable characters");y.result+=H}}function Se(y){y.totalMergeKeys++,y.maxTotalMergeKeys!==-1&&y.totalMergeKeys>y.maxTotalMergeKeys&&W(y,"merge keys exceeded maxTotalMergeKeys ("+y.maxTotalMergeKeys+")")}function Ne(y,N,K,Q){e.isObject(K)||W(y,"cannot merge mappings; the provided source object is unacceptable"),Se(y);let H=Object.keys(K);for(let S=0,G=H.length;S<G;S+=1){let J=H[S];Se(y),r.call(N,J)||(q(N,J,K[J]),Q[J]=!0)}}function te(y,N,K,Q,H,S,G,J,ie){if(Array.isArray(H)){H=Array.prototype.slice.call(H);for(let se=0,ce=H.length;se<ce;se+=1)Array.isArray(H[se])&&W(y,"nested arrays are not supported inside keys"),typeof H=="object"&&b(H[se])==="[object Object]"&&(H[se]="[object Object]")}if(typeof H=="object"&&b(H)==="[object Object]"&&(H="[object Object]"),H=String(H),N===null&&(N={}),Q==="tag:yaml.org,2002:merge")if(Array.isArray(S)){S.length>100&&W(y,"abnormal merge sequence size");for(let se=0,ce=S.length;se<ce;se+=1)Ne(y,N,S[se],K)}else Ne(y,N,S,K);else!y.json&&!r.call(K,H)&&r.call(N,H)&&(y.line=G||y.line,y.lineStart=J||y.lineStart,y.position=ie||y.position,W(y,"duplicated mapping key")),q(N,H,S),delete K[H];return N}function Ve(y){let N=y.input.charCodeAt(y.position);N===10?y.position++:N===13?(y.position++,y.input.charCodeAt(y.position)===10&&y.position++):W(y,"a line break is expected"),y.line+=1,y.lineStart=y.position,y.firstTabInLine=-1}function z(y,N,K){let Q=0,H=y.input.charCodeAt(y.position);for(;H!==0;){for(;$(H);)H===9&&y.firstTabInLine===-1&&(y.firstTabInLine=y.position),H=y.input.charCodeAt(++y.position);if(N&&H===35)do H=y.input.charCodeAt(++y.position);while(H!==10&&H!==13&&H!==0);if(k(H))for(Ve(y),H=y.input.charCodeAt(y.position),Q++,y.lineIndent=0;H===32;)y.lineIndent++,H=y.input.charCodeAt(++y.position);else break}return K!==-1&&Q!==0&&y.lineIndent<K&&ve(y,"deficient indentation"),Q}function $e(y){let N=y.position,K=y.input.charCodeAt(N);return!!((K===45||K===46)&&K===y.input.charCodeAt(N+1)&&K===y.input.charCodeAt(N+2)&&(N+=3,K=y.input.charCodeAt(N),K===0||x(K)))}function Ie(y,N){N===1?y.result+=" ":N>1&&(y.result+=e.repeat(`
109
- `,N-1))}function et(y,N,K){let Q,H,S,G,J,ie,se=y.kind,ce=y.result,ee=y.input.charCodeAt(y.position);if(x(ee)||R(ee)||ee===35||ee===38||ee===42||ee===33||ee===124||ee===62||ee===39||ee===34||ee===37||ee===64||ee===96)return!1;if(ee===63||ee===45){let he=y.input.charCodeAt(y.position+1);if(x(he)||K&&R(he))return!1}for(y.kind="scalar",y.result="",Q=H=y.position,S=!1;ee!==0;){if(ee===58){let he=y.input.charCodeAt(y.position+1);if(x(he)||K&&R(he))break}else if(ee===35){let he=y.input.charCodeAt(y.position-1);if(x(he))break}else{if(y.position===y.lineStart&&$e(y)||K&&R(ee))break;if(k(ee))if(G=y.line,J=y.lineStart,ie=y.lineIndent,z(y,!1,-1),y.lineIndent>=N){S=!0,ee=y.input.charCodeAt(y.position);continue}else{y.position=H,y.line=G,y.lineStart=J,y.lineIndent=ie;break}}S&&(oe(y,Q,H,!1),Ie(y,y.line-G),Q=H=y.position,S=!1),$(ee)||(H=y.position+1),ee=y.input.charCodeAt(++y.position)}return oe(y,Q,H,!1),y.result?!0:(y.kind=se,y.result=ce,!1)}function ct(y,N){let K,Q,H=y.input.charCodeAt(y.position);if(H!==39)return!1;for(y.kind="scalar",y.result="",y.position++,K=Q=y.position;(H=y.input.charCodeAt(y.position))!==0;)if(H===39)if(oe(y,K,y.position,!0),H=y.input.charCodeAt(++y.position),H===39)K=y.position,y.position++,Q=y.position;else return!0;else k(H)?(oe(y,K,Q,!0),Ie(y,z(y,!1,N)),K=Q=y.position):y.position===y.lineStart&&$e(y)?W(y,"unexpected end of the document within a single quoted scalar"):(y.position++,$(H)||(Q=y.position));W(y,"unexpected end of the stream within a single quoted scalar")}function Vt(y,N){let K,Q,H,S=y.input.charCodeAt(y.position);if(S!==34)return!1;for(y.kind="scalar",y.result="",y.position++,K=Q=y.position;(S=y.input.charCodeAt(y.position))!==0;){if(S===34)return oe(y,K,y.position,!0),y.position++,!0;if(S===92){if(oe(y,K,y.position,!0),S=y.input.charCodeAt(++y.position),k(S))z(y,!1,N);else if(S<256&&L[S])y.result+=M[S],y.position++;else if((H=I(S))>0){let G=H,J=0;for(;G>0;G--)S=y.input.charCodeAt(++y.position),(H=P(S))>=0?J=(J<<4)+H:W(y,"expected hexadecimal character");y.result+=C(J),y.position++}else W(y,"unknown escape sequence");K=Q=y.position}else k(S)?(oe(y,K,Q,!0),Ie(y,z(y,!1,N)),K=Q=y.position):y.position===y.lineStart&&$e(y)?W(y,"unexpected end of the document within a double quoted scalar"):(y.position++,$(S)||(Q=y.position))}W(y,"unexpected end of the stream within a double quoted scalar")}function U(y,N){let K=!0,Q,H,S,G=y.tag,J,ie=y.anchor,se,ce,ee,he,Oe=Object.create(null),Ge,ze,He,nt=y.input.charCodeAt(y.position);if(nt===91)se=93,he=!1,J=[];else if(nt===123)se=125,he=!0,J={};else return!1;for(y.anchor!==null&&re(y,y.anchor,J),nt=y.input.charCodeAt(++y.position);nt!==0;){if(z(y,!0,N),nt=y.input.charCodeAt(y.position),nt===se)return y.position++,y.tag=G,y.anchor=ie,y.kind=he?"mapping":"sequence",y.result=J,!0;if(K?nt===44&&W(y,"expected the node content, but found ','"):W(y,"missed comma between flow collection entries"),ze=Ge=He=null,ce=ee=!1,nt===63){let wo=y.input.charCodeAt(y.position+1);x(wo)&&(ce=ee=!0,y.position++,z(y,!0,N))}Q=y.line,H=y.lineStart,S=y.position,fn(y,N,o,!1,!0),ze=y.tag,Ge=y.result,z(y,!0,N),nt=y.input.charCodeAt(y.position),(ee||y.line===Q)&&nt===58&&(ce=!0,nt=y.input.charCodeAt(++y.position),z(y,!0,N),fn(y,N,o,!1,!0),He=y.result),he?te(y,J,Oe,ze,Ge,He,Q,H,S):ce?J.push(te(y,null,Oe,ze,Ge,He,Q,H,S)):J.push(Ge),z(y,!0,N),nt=y.input.charCodeAt(y.position),nt===44?(K=!0,nt=y.input.charCodeAt(++y.position)):K=!1}W(y,"unexpected end of the stream within a flow collection")}function ke(y,N){let K,Q=l,H=!1,S=!1,G=N,J=0,ie=!1,se,ce=y.input.charCodeAt(y.position);if(ce===124)K=!1;else if(ce===62)K=!0;else return!1;for(y.kind="scalar",y.result="";ce!==0;)if(ce=y.input.charCodeAt(++y.position),ce===43||ce===45)l===Q?Q=ce===43?d:u:W(y,"repeat of a chomping mode identifier");else if((se=A(ce))>=0)se===0?W(y,"bad explicit indentation width of a block scalar; it cannot be less than one"):S?W(y,"repeat of an indentation width identifier"):(G=N+se-1,S=!0);else break;if($(ce)){do ce=y.input.charCodeAt(++y.position);while($(ce));if(ce===35)do ce=y.input.charCodeAt(++y.position);while(!k(ce)&&ce!==0)}for(;ce!==0;){for(Ve(y),y.lineIndent=0,ce=y.input.charCodeAt(y.position);(!S||y.lineIndent<G)&&ce===32;)y.lineIndent++,ce=y.input.charCodeAt(++y.position);if(!S&&y.lineIndent>G&&(G=y.lineIndent),k(ce)){J++;continue}if(!S&&G===0&&W(y,"missing indentation for block scalar"),y.lineIndent<G){Q===d?y.result+=e.repeat(`
108
+ `;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"\x85";case 95:return"\xA0";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function C(y){return y<=65535?String.fromCharCode(y):String.fromCharCode((y-65536>>10)+55296,(y-65536&1023)+56320)}function q(y,N,K){N==="__proto__"?Object.defineProperty(y,N,{configurable:!0,enumerable:!0,writable:!0,value:K}):y[N]=K}let L=new Array(256),M=new Array(256);for(let y=0;y<256;y++)L[y]=B(y)?1:0,M[y]=B(y);function _(y,N){this.input=y,this.filename=N.filename||null,this.schema=N.schema||i,this.onWarning=N.onWarning||null,this.legacy=N.legacy||!1,this.json=N.json||!1,this.listener=N.listener||null,this.maxDepth=typeof N.maxDepth=="number"?N.maxDepth:100,this.maxTotalMergeKeys=typeof N.maxTotalMergeKeys=="number"?N.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=y.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function T(y,N){let K={name:y.filename,buffer:y.input.slice(0,-1),position:y.position,line:y.line,column:y.position-y.lineStart};return K.snippet=n(K),new t(N,K)}function W(y,N){throw T(y,N)}function ke(y,N){y.onWarning&&y.onWarning.call(null,T(y,N))}function re(y,N,K){let Q=y.anchorMapTransactions;if(Q.length!==0){let H=Q[Q.length-1];r.call(H,N)||(H[N]={existed:r.call(y.anchorMap,N),value:y.anchorMap[N]})}y.anchorMap[N]=K}function be(y){y.anchorMapTransactions.push(Object.create(null))}function Be(y){let N=y.anchorMapTransactions.pop(),K=y.anchorMapTransactions;if(K.length===0)return;let Q=K[K.length-1],H=Object.keys(N);for(let S=0,G=H.length;S<G;S+=1){let J=H[S];r.call(Q,J)||(Q[J]=N[J])}}function dt(y){let N=y.anchorMapTransactions.pop(),K=Object.keys(N);for(let Q=K.length-1;Q>=0;Q-=1){let H=N[K[Q]];H.existed?y.anchorMap[K[Q]]=H.value:delete y.anchorMap[K[Q]]}}function ne(y){return{position:y.position,line:y.line,lineStart:y.lineStart,lineIndent:y.lineIndent,firstTabInLine:y.firstTabInLine,tag:y.tag,anchor:y.anchor,kind:y.kind,result:y.result}}function ye(y,N){y.position=N.position,y.line=N.line,y.lineStart=N.lineStart,y.lineIndent=N.lineIndent,y.firstTabInLine=N.firstTabInLine,y.tag=N.tag,y.anchor=N.anchor,y.kind=N.kind,y.result=N.result}let ge={YAML:function(N,K,Q){N.version!==null&&W(N,"duplication of %YAML directive"),Q.length!==1&&W(N,"YAML directive accepts exactly one argument");let H=/^([0-9]+)\.([0-9]+)$/.exec(Q[0]);H===null&&W(N,"ill-formed argument of the YAML directive");let S=parseInt(H[1],10),G=parseInt(H[2],10);S!==1&&W(N,"unacceptable YAML version of the document"),N.version=Q[0],N.checkLineBreaks=G<2,G!==1&&G!==2&&ke(N,"unsupported YAML version of the document")},TAG:function(N,K,Q){let H;Q.length!==2&&W(N,"TAG directive accepts exactly two arguments");let S=Q[0];H=Q[1],h.test(S)||W(N,"ill-formed tag handle (first argument) of the TAG directive"),r.call(N.tagMap,S)&&W(N,'there is a previously declared suffix for "'+S+'" tag handle'),w.test(H)||W(N,"ill-formed tag prefix (second argument) of the TAG directive");try{H=decodeURIComponent(H)}catch{W(N,"tag prefix is malformed: "+H)}N.tagMap[S]=H}};function oe(y,N,K,Q){if(N<K){let H=y.input.slice(N,K);if(Q)for(let S=0,G=H.length;S<G;S+=1){let J=H.charCodeAt(S);J===9||J>=32&&J<=1114111||W(y,"expected valid JSON character")}else p.test(H)&&W(y,"the stream contains non-printable characters");y.result+=H}}function Se(y){y.totalMergeKeys++,y.maxTotalMergeKeys!==-1&&y.totalMergeKeys>y.maxTotalMergeKeys&&W(y,"merge keys exceeded maxTotalMergeKeys ("+y.maxTotalMergeKeys+")")}function Ne(y,N,K,Q){e.isObject(K)||W(y,"cannot merge mappings; the provided source object is unacceptable"),Se(y);let H=Object.keys(K);for(let S=0,G=H.length;S<G;S+=1){let J=H[S];Se(y),r.call(N,J)||(q(N,J,K[J]),Q[J]=!0)}}function te(y,N,K,Q,H,S,G,J,ie){if(Array.isArray(H)){H=Array.prototype.slice.call(H);for(let se=0,ce=H.length;se<ce;se+=1)Array.isArray(H[se])&&W(y,"nested arrays are not supported inside keys"),typeof H=="object"&&b(H[se])==="[object Object]"&&(H[se]="[object Object]")}if(typeof H=="object"&&b(H)==="[object Object]"&&(H="[object Object]"),H=String(H),N===null&&(N={}),Q==="tag:yaml.org,2002:merge")if(Array.isArray(S)){S.length>100&&W(y,"abnormal merge sequence size");for(let se=0,ce=S.length;se<ce;se+=1)Ne(y,N,S[se],K)}else Ne(y,N,S,K);else!y.json&&!r.call(K,H)&&r.call(N,H)&&(y.line=G||y.line,y.lineStart=J||y.lineStart,y.position=ie||y.position,W(y,"duplicated mapping key")),q(N,H,S),delete K[H];return N}function Ve(y){let N=y.input.charCodeAt(y.position);N===10?y.position++:N===13?(y.position++,y.input.charCodeAt(y.position)===10&&y.position++):W(y,"a line break is expected"),y.line+=1,y.lineStart=y.position,y.firstTabInLine=-1}function z(y,N,K){let Q=0,H=y.input.charCodeAt(y.position);for(;H!==0;){for(;$(H);)H===9&&y.firstTabInLine===-1&&(y.firstTabInLine=y.position),H=y.input.charCodeAt(++y.position);if(N&&H===35)do H=y.input.charCodeAt(++y.position);while(H!==10&&H!==13&&H!==0);if(k(H))for(Ve(y),H=y.input.charCodeAt(y.position),Q++,y.lineIndent=0;H===32;)y.lineIndent++,H=y.input.charCodeAt(++y.position);else break}return K!==-1&&Q!==0&&y.lineIndent<K&&ke(y,"deficient indentation"),Q}function $e(y){let N=y.position,K=y.input.charCodeAt(N);return!!((K===45||K===46)&&K===y.input.charCodeAt(N+1)&&K===y.input.charCodeAt(N+2)&&(N+=3,K=y.input.charCodeAt(N),K===0||x(K)))}function Ie(y,N){N===1?y.result+=" ":N>1&&(y.result+=e.repeat(`
109
+ `,N-1))}function et(y,N,K){let Q,H,S,G,J,ie,se=y.kind,ce=y.result,ee=y.input.charCodeAt(y.position);if(x(ee)||R(ee)||ee===35||ee===38||ee===42||ee===33||ee===124||ee===62||ee===39||ee===34||ee===37||ee===64||ee===96)return!1;if(ee===63||ee===45){let he=y.input.charCodeAt(y.position+1);if(x(he)||K&&R(he))return!1}for(y.kind="scalar",y.result="",Q=H=y.position,S=!1;ee!==0;){if(ee===58){let he=y.input.charCodeAt(y.position+1);if(x(he)||K&&R(he))break}else if(ee===35){let he=y.input.charCodeAt(y.position-1);if(x(he))break}else{if(y.position===y.lineStart&&$e(y)||K&&R(ee))break;if(k(ee))if(G=y.line,J=y.lineStart,ie=y.lineIndent,z(y,!1,-1),y.lineIndent>=N){S=!0,ee=y.input.charCodeAt(y.position);continue}else{y.position=H,y.line=G,y.lineStart=J,y.lineIndent=ie;break}}S&&(oe(y,Q,H,!1),Ie(y,y.line-G),Q=H=y.position,S=!1),$(ee)||(H=y.position+1),ee=y.input.charCodeAt(++y.position)}return oe(y,Q,H,!1),y.result?!0:(y.kind=se,y.result=ce,!1)}function ct(y,N){let K,Q,H=y.input.charCodeAt(y.position);if(H!==39)return!1;for(y.kind="scalar",y.result="",y.position++,K=Q=y.position;(H=y.input.charCodeAt(y.position))!==0;)if(H===39)if(oe(y,K,y.position,!0),H=y.input.charCodeAt(++y.position),H===39)K=y.position,y.position++,Q=y.position;else return!0;else k(H)?(oe(y,K,Q,!0),Ie(y,z(y,!1,N)),K=Q=y.position):y.position===y.lineStart&&$e(y)?W(y,"unexpected end of the document within a single quoted scalar"):(y.position++,$(H)||(Q=y.position));W(y,"unexpected end of the stream within a single quoted scalar")}function Vt(y,N){let K,Q,H,S=y.input.charCodeAt(y.position);if(S!==34)return!1;for(y.kind="scalar",y.result="",y.position++,K=Q=y.position;(S=y.input.charCodeAt(y.position))!==0;){if(S===34)return oe(y,K,y.position,!0),y.position++,!0;if(S===92){if(oe(y,K,y.position,!0),S=y.input.charCodeAt(++y.position),k(S))z(y,!1,N);else if(S<256&&L[S])y.result+=M[S],y.position++;else if((H=I(S))>0){let G=H,J=0;for(;G>0;G--)S=y.input.charCodeAt(++y.position),(H=P(S))>=0?J=(J<<4)+H:W(y,"expected hexadecimal character");y.result+=C(J),y.position++}else W(y,"unknown escape sequence");K=Q=y.position}else k(S)?(oe(y,K,Q,!0),Ie(y,z(y,!1,N)),K=Q=y.position):y.position===y.lineStart&&$e(y)?W(y,"unexpected end of the document within a double quoted scalar"):(y.position++,$(S)||(Q=y.position))}W(y,"unexpected end of the stream within a double quoted scalar")}function U(y,N){let K=!0,Q,H,S,G=y.tag,J,ie=y.anchor,se,ce,ee,he,Oe=Object.create(null),Ge,ze,He,nt=y.input.charCodeAt(y.position);if(nt===91)se=93,he=!1,J=[];else if(nt===123)se=125,he=!0,J={};else return!1;for(y.anchor!==null&&re(y,y.anchor,J),nt=y.input.charCodeAt(++y.position);nt!==0;){if(z(y,!0,N),nt=y.input.charCodeAt(y.position),nt===se)return y.position++,y.tag=G,y.anchor=ie,y.kind=he?"mapping":"sequence",y.result=J,!0;if(K?nt===44&&W(y,"expected the node content, but found ','"):W(y,"missed comma between flow collection entries"),ze=Ge=He=null,ce=ee=!1,nt===63){let wo=y.input.charCodeAt(y.position+1);x(wo)&&(ce=ee=!0,y.position++,z(y,!0,N))}Q=y.line,H=y.lineStart,S=y.position,fn(y,N,o,!1,!0),ze=y.tag,Ge=y.result,z(y,!0,N),nt=y.input.charCodeAt(y.position),(ee||y.line===Q)&&nt===58&&(ce=!0,nt=y.input.charCodeAt(++y.position),z(y,!0,N),fn(y,N,o,!1,!0),He=y.result),he?te(y,J,Oe,ze,Ge,He,Q,H,S):ce?J.push(te(y,null,Oe,ze,Ge,He,Q,H,S)):J.push(Ge),z(y,!0,N),nt=y.input.charCodeAt(y.position),nt===44?(K=!0,nt=y.input.charCodeAt(++y.position)):K=!1}W(y,"unexpected end of the stream within a flow collection")}function xe(y,N){let K,Q=l,H=!1,S=!1,G=N,J=0,ie=!1,se,ce=y.input.charCodeAt(y.position);if(ce===124)K=!1;else if(ce===62)K=!0;else return!1;for(y.kind="scalar",y.result="";ce!==0;)if(ce=y.input.charCodeAt(++y.position),ce===43||ce===45)l===Q?Q=ce===43?d:u:W(y,"repeat of a chomping mode identifier");else if((se=A(ce))>=0)se===0?W(y,"bad explicit indentation width of a block scalar; it cannot be less than one"):S?W(y,"repeat of an indentation width identifier"):(G=N+se-1,S=!0);else break;if($(ce)){do ce=y.input.charCodeAt(++y.position);while($(ce));if(ce===35)do ce=y.input.charCodeAt(++y.position);while(!k(ce)&&ce!==0)}for(;ce!==0;){for(Ve(y),y.lineIndent=0,ce=y.input.charCodeAt(y.position);(!S||y.lineIndent<G)&&ce===32;)y.lineIndent++,ce=y.input.charCodeAt(++y.position);if(!S&&y.lineIndent>G&&(G=y.lineIndent),k(ce)){J++;continue}if(!S&&G===0&&W(y,"missing indentation for block scalar"),y.lineIndent<G){Q===d?y.result+=e.repeat(`
110
110
  `,H?1+J:J):Q===l&&H&&(y.result+=`
111
111
  `);break}K?$(ce)?(ie=!0,y.result+=e.repeat(`
112
112
  `,H?1+J:J)):ie?(ie=!1,y.result+=e.repeat(`
113
113
  `,J+1)):J===0?H&&(y.result+=" "):y.result+=e.repeat(`
114
114
  `,J):y.result+=e.repeat(`
115
- `,H?1+J:J),H=!0,S=!0,J=0;let ee=y.position;for(;!k(ce)&&ce!==0;)ce=y.input.charCodeAt(++y.position);oe(y,ee,y.position,!1)}return!0}function We(y,N){let K=y.tag,Q=y.anchor,H=[],S=!1;if(y.firstTabInLine!==-1)return!1;y.anchor!==null&&re(y,y.anchor,H);let G=y.input.charCodeAt(y.position);for(;G!==0&&(y.firstTabInLine!==-1&&(y.position=y.firstTabInLine,W(y,"tab characters must not be used in indentation")),G===45);){let J=y.input.charCodeAt(y.position+1);if(!x(J))break;if(S=!0,y.position++,z(y,!0,-1)&&y.lineIndent<=N){H.push(null),G=y.input.charCodeAt(y.position);continue}let ie=y.line;if(fn(y,N,a,!1,!0),H.push(y.result),z(y,!0,-1),G=y.input.charCodeAt(y.position),(y.line===ie||y.lineIndent>N)&&G!==0)W(y,"bad indentation of a sequence entry");else if(y.lineIndent<N)break}return S?(y.tag=K,y.anchor=Q,y.kind="sequence",y.result=H,!0):!1}function $t(y,N,K){let Q,H,S,G,J=y.tag,ie=y.anchor,se={},ce=Object.create(null),ee=null,he=null,Oe=null,Ge=!1,ze=!1;if(y.firstTabInLine!==-1)return!1;y.anchor!==null&&re(y,y.anchor,se);let He=y.input.charCodeAt(y.position);for(;He!==0;){!Ge&&y.firstTabInLine!==-1&&(y.position=y.firstTabInLine,W(y,"tab characters must not be used in indentation"));let nt=y.input.charCodeAt(y.position+1),wo=y.line;if((He===63||He===58)&&x(nt))He===63?(Ge&&(te(y,se,ce,ee,he,null,H,S,G),ee=he=Oe=null),ze=!0,Ge=!0,Q=!0):Ge?(Ge=!1,Q=!0):W(y,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),y.position+=1,He=nt;else{if(H=y.line,S=y.lineStart,G=y.position,!fn(y,K,s,!1,!0))break;if(y.line===wo){for(He=y.input.charCodeAt(y.position);$(He);)He=y.input.charCodeAt(++y.position);if(He===58)He=y.input.charCodeAt(++y.position),x(He)||W(y,"a whitespace character is expected after the key-value separator within a block mapping"),Ge&&(te(y,se,ce,ee,he,null,H,S,G),ee=he=Oe=null),ze=!0,Ge=!1,Q=!1,ee=y.tag,he=y.result;else if(ze)W(y,"can not read an implicit mapping pair; a colon is missed");else return y.tag=J,y.anchor=ie,!0}else if(ze)W(y,"can not read a block mapping entry; a multiline key may not be an implicit key");else return y.tag=J,y.anchor=ie,!0}if((y.line===wo||y.lineIndent>N)&&(Ge&&(H=y.line,S=y.lineStart,G=y.position),fn(y,N,c,!0,Q)&&(Ge?he=y.result:Oe=y.result),Ge||(te(y,se,ce,ee,he,Oe,H,S,G),ee=he=Oe=null),z(y,!0,-1),He=y.input.charCodeAt(y.position)),(y.line===wo||y.lineIndent>N)&&He!==0)W(y,"bad indentation of a mapping entry");else if(y.lineIndent<N)break}return Ge&&te(y,se,ce,ee,he,null,H,S,G),ze&&(y.tag=J,y.anchor=ie,y.kind="mapping",y.result=se),ze}function ht(y){let N=!1,K=!1,Q,H,S=y.input.charCodeAt(y.position);if(S!==33)return!1;y.tag!==null&&W(y,"duplication of a tag property"),S=y.input.charCodeAt(++y.position),S===60?(N=!0,S=y.input.charCodeAt(++y.position)):S===33?(K=!0,Q="!!",S=y.input.charCodeAt(++y.position)):Q="!";let G=y.position;if(N){do S=y.input.charCodeAt(++y.position);while(S!==0&&S!==62);y.position<y.length?(H=y.input.slice(G,y.position),S=y.input.charCodeAt(++y.position)):W(y,"unexpected end of the stream within a verbatim tag")}else{for(;S!==0&&!x(S);)S===33&&(K?W(y,"tag suffix cannot contain exclamation marks"):(Q=y.input.slice(G-1,y.position+1),h.test(Q)||W(y,"named tag handle cannot contain such characters"),K=!0,G=y.position+1)),S=y.input.charCodeAt(++y.position);H=y.input.slice(G,y.position),g.test(H)&&W(y,"tag suffix cannot contain flow indicator characters")}H&&!w.test(H)&&W(y,"tag name cannot contain such characters: "+H);try{H=decodeURIComponent(H)}catch{W(y,"tag name is malformed: "+H)}return N?y.tag=H:r.call(y.tagMap,Q)?y.tag=y.tagMap[Q]+H:Q==="!"?y.tag="!"+H:Q==="!!"?y.tag="tag:yaml.org,2002:"+H:W(y,'undeclared tag handle "'+Q+'"'),!0}function Mn(y){let N=y.input.charCodeAt(y.position);if(N!==38)return!1;y.anchor!==null&&W(y,"duplication of an anchor property"),N=y.input.charCodeAt(++y.position);let K=y.position;for(;N!==0&&!x(N)&&!R(N);)N=y.input.charCodeAt(++y.position);return y.position===K&&W(y,"name of an anchor node must contain at least one character"),y.anchor=y.input.slice(K,y.position),!0}function Mt(y){let N=y.input.charCodeAt(y.position);if(N!==42)return!1;N=y.input.charCodeAt(++y.position);let K=y.position;for(;N!==0&&!x(N)&&!R(N);)N=y.input.charCodeAt(++y.position);y.position===K&&W(y,"name of an alias node must contain at least one character");let Q=y.input.slice(K,y.position);return r.call(y.anchorMap,Q)||W(y,'unidentified alias "'+Q+'"'),y.result=y.anchorMap[Q],z(y,!0,-1),!0}function nn(y,N,K,Q){let H=ne(y);return be(y),ye(y,N),y.tag=null,y.anchor=null,y.kind=null,y.result=null,$t(y,K,Q)&&y.kind==="mapping"?(Be(y),!0):(dt(y),ye(y,H),!1)}function fn(y,N,K,Q,H){let S,G,J=1,ie=!1,se=!1,ce=null,ee,he,Oe;y.depth>=y.maxDepth&&W(y,"nesting exceeded maxDepth ("+y.maxDepth+")"),y.depth+=1,y.listener!==null&&y.listener("open",y),y.tag=null,y.anchor=null,y.kind=null,y.result=null;let Ge=S=G=c===K||a===K;if(Q&&z(y,!0,-1)&&(ie=!0,y.lineIndent>N?J=1:y.lineIndent===N?J=0:y.lineIndent<N&&(J=-1)),J===1)for(;;){let ze=y.input.charCodeAt(y.position),He=ne(y);if(ie&&(ze===33&&y.tag!==null||ze===38&&y.anchor!==null)||!ht(y)&&!Mn(y))break;ce===null&&(ce=He),z(y,!0,-1)?(ie=!0,G=Ge,y.lineIndent>N?J=1:y.lineIndent===N?J=0:y.lineIndent<N&&(J=-1)):G=!1}if(G&&(G=ie||H),J===1||c===K)if(o===K||s===K?he=N:he=N+1,Oe=y.position-y.lineStart,J===1)if(G&&(We(y,Oe)||$t(y,Oe,he))||U(y,he))se=!0;else{let ze=y.input.charCodeAt(y.position);ce!==null&&Ge&&!G&&ze!==124&&ze!==62&&nn(y,ce,ce.position-ce.lineStart,he)||S&&ke(y,he)||ct(y,he)||Vt(y,he)?se=!0:Mt(y)?(se=!0,(y.tag!==null||y.anchor!==null)&&W(y,"alias node should not have any properties")):et(y,he,o===K)&&(se=!0,y.tag===null&&(y.tag="?")),y.anchor!==null&&re(y,y.anchor,y.result)}else J===0&&(se=G&&We(y,Oe));if(y.tag===null)y.anchor!==null&&re(y,y.anchor,y.result);else if(y.tag==="?"){y.result!==null&&y.kind!=="scalar"&&W(y,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+y.kind+'"');for(let ze=0,He=y.implicitTypes.length;ze<He;ze+=1)if(ee=y.implicitTypes[ze],ee.resolve(y.result)){y.result=ee.construct(y.result),y.tag=ee.tag,y.anchor!==null&&re(y,y.anchor,y.result);break}}else if(y.tag!=="!"){if(r.call(y.typeMap[y.kind||"fallback"],y.tag))ee=y.typeMap[y.kind||"fallback"][y.tag];else{ee=null;let ze=y.typeMap.multi[y.kind||"fallback"];for(let He=0,nt=ze.length;He<nt;He+=1)if(y.tag.slice(0,ze[He].tag.length)===ze[He].tag){ee=ze[He];break}}ee||W(y,"unknown tag !<"+y.tag+">"),y.result!==null&&ee.kind!==y.kind&&W(y,"unacceptable node kind for !<"+y.tag+'> tag; it should be "'+ee.kind+'", not "'+y.kind+'"'),ee.resolve(y.result,y.tag)?(y.result=ee.construct(y.result,y.tag),y.anchor!==null&&re(y,y.anchor,y.result)):W(y,"cannot resolve a node with !<"+y.tag+"> explicit tag")}return y.listener!==null&&y.listener("close",y),y.depth-=1,y.tag!==null||y.anchor!==null||se}function Fn(y){let N=y.position,K=!1,Q;for(y.version=null,y.checkLineBreaks=y.legacy,y.tagMap=Object.create(null),y.anchorMap=Object.create(null);(Q=y.input.charCodeAt(y.position))!==0&&(z(y,!0,-1),Q=y.input.charCodeAt(y.position),!(y.lineIndent>0||Q!==37));){K=!0,Q=y.input.charCodeAt(++y.position);let H=y.position;for(;Q!==0&&!x(Q);)Q=y.input.charCodeAt(++y.position);let S=y.input.slice(H,y.position),G=[];for(S.length<1&&W(y,"directive name must not be less than one character in length");Q!==0;){for(;$(Q);)Q=y.input.charCodeAt(++y.position);if(Q===35){do Q=y.input.charCodeAt(++y.position);while(Q!==0&&!k(Q));break}if(k(Q))break;for(H=y.position;Q!==0&&!x(Q);)Q=y.input.charCodeAt(++y.position);G.push(y.input.slice(H,y.position))}Q!==0&&Ve(y),r.call(ge,S)?ge[S](y,S,G):ve(y,'unknown document directive "'+S+'"')}if(z(y,!0,-1),y.lineIndent===0&&y.input.charCodeAt(y.position)===45&&y.input.charCodeAt(y.position+1)===45&&y.input.charCodeAt(y.position+2)===45?(y.position+=3,z(y,!0,-1)):K&&W(y,"directives end mark is expected"),fn(y,y.lineIndent-1,c,!1,!0),z(y,!0,-1),y.checkLineBreaks&&f.test(y.input.slice(N,y.position))&&ve(y,"non-ASCII line breaks are interpreted as content"),y.documents.push(y.result),y.position===y.lineStart&&$e(y)){y.input.charCodeAt(y.position)===46&&(y.position+=3,z(y,!0,-1));return}y.position<y.length-1&&W(y,"end of the stream or a document separator is expected")}function lr(y,N){y=String(y),N=N||{},y.length!==0&&(y.charCodeAt(y.length-1)!==10&&y.charCodeAt(y.length-1)!==13&&(y+=`
116
- `),y.charCodeAt(0)===65279&&(y=y.slice(1)));let K=new _(y,N),Q=y.indexOf("\0");for(Q!==-1&&(K.position=Q,W(K,"null byte is not allowed in input")),K.input+="\0";K.input.charCodeAt(K.position)===32;)K.lineIndent+=1,K.position+=1;for(;K.position<K.length-1;)Fn(K);return K.documents}function Xn(y,N,K){N!==null&&typeof N=="object"&&typeof K>"u"&&(K=N,N=null);let Q=lr(y,K);if(typeof N!="function")return Q;for(let H=0,S=Q.length;H<S;H+=1)N(Q[H])}function Zs(y,N){let K=lr(y,N);if(K.length!==0){if(K.length===1)return K[0];throw new t("expected a single document in the stream, but found more")}}return Fk.loadAll=Xn,Fk.load=Zs,Fk}function Mwe(){if(S6)return vD;S6=1;let e=xg(),t=$g(),n=kD(),i=Object.prototype.toString,r=Object.prototype.hasOwnProperty,o=65279,s=9,a=10,c=13,l=32,u=33,d=34,p=35,f=37,g=38,h=39,w=42,b=44,k=45,$=58,x=61,R=62,P=63,I=64,A=91,B=93,C=96,q=123,L=124,M=125,_={};_[0]="\\0",_[7]="\\a",_[8]="\\b",_[9]="\\t",_[10]="\\n",_[11]="\\v",_[12]="\\f",_[13]="\\r",_[27]="\\e",_[34]='\\"',_[92]="\\\\",_[133]="\\N",_[160]="\\_",_[8232]="\\L",_[8233]="\\P";let T=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],W=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function ve(S,G){if(G===null)return{};let J={},ie=Object.keys(G);for(let se=0,ce=ie.length;se<ce;se+=1){let ee=ie[se],he=String(G[ee]);ee.slice(0,2)==="!!"&&(ee="tag:yaml.org,2002:"+ee.slice(2));let Oe=S.compiledTypeMap.fallback[ee];Oe&&r.call(Oe.styleAliases,he)&&(he=Oe.styleAliases[he]),J[ee]=he}return J}function re(S){let G,J,ie=S.toString(16).toUpperCase();if(S<=255)G="x",J=2;else if(S<=65535)G="u",J=4;else if(S<=4294967295)G="U",J=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+G+e.repeat("0",J-ie.length)+ie}let be=1,Be=2;function dt(S){this.schema=S.schema||n,this.indent=Math.max(1,S.indent||2),this.noArrayIndent=S.noArrayIndent||!1,this.skipInvalid=S.skipInvalid||!1,this.flowLevel=e.isNothing(S.flowLevel)?-1:S.flowLevel,this.styleMap=ve(this.schema,S.styles||null),this.sortKeys=S.sortKeys||!1,this.lineWidth=S.lineWidth||80,this.noRefs=S.noRefs||!1,this.noCompatMode=S.noCompatMode||!1,this.condenseFlow=S.condenseFlow||!1,this.quotingType=S.quotingType==='"'?Be:be,this.forceQuotes=S.forceQuotes||!1,this.replacer=typeof S.replacer=="function"?S.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function ne(S,G){let J=e.repeat(" ",G),ie=0,se="",ce=S.length;for(;ie<ce;){let ee,he=S.indexOf(`
115
+ `,H?1+J:J),H=!0,S=!0,J=0;let ee=y.position;for(;!k(ce)&&ce!==0;)ce=y.input.charCodeAt(++y.position);oe(y,ee,y.position,!1)}return!0}function We(y,N){let K=y.tag,Q=y.anchor,H=[],S=!1;if(y.firstTabInLine!==-1)return!1;y.anchor!==null&&re(y,y.anchor,H);let G=y.input.charCodeAt(y.position);for(;G!==0&&(y.firstTabInLine!==-1&&(y.position=y.firstTabInLine,W(y,"tab characters must not be used in indentation")),G===45);){let J=y.input.charCodeAt(y.position+1);if(!x(J))break;if(S=!0,y.position++,z(y,!0,-1)&&y.lineIndent<=N){H.push(null),G=y.input.charCodeAt(y.position);continue}let ie=y.line;if(fn(y,N,a,!1,!0),H.push(y.result),z(y,!0,-1),G=y.input.charCodeAt(y.position),(y.line===ie||y.lineIndent>N)&&G!==0)W(y,"bad indentation of a sequence entry");else if(y.lineIndent<N)break}return S?(y.tag=K,y.anchor=Q,y.kind="sequence",y.result=H,!0):!1}function $t(y,N,K){let Q,H,S,G,J=y.tag,ie=y.anchor,se={},ce=Object.create(null),ee=null,he=null,Oe=null,Ge=!1,ze=!1;if(y.firstTabInLine!==-1)return!1;y.anchor!==null&&re(y,y.anchor,se);let He=y.input.charCodeAt(y.position);for(;He!==0;){!Ge&&y.firstTabInLine!==-1&&(y.position=y.firstTabInLine,W(y,"tab characters must not be used in indentation"));let nt=y.input.charCodeAt(y.position+1),wo=y.line;if((He===63||He===58)&&x(nt))He===63?(Ge&&(te(y,se,ce,ee,he,null,H,S,G),ee=he=Oe=null),ze=!0,Ge=!0,Q=!0):Ge?(Ge=!1,Q=!0):W(y,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),y.position+=1,He=nt;else{if(H=y.line,S=y.lineStart,G=y.position,!fn(y,K,s,!1,!0))break;if(y.line===wo){for(He=y.input.charCodeAt(y.position);$(He);)He=y.input.charCodeAt(++y.position);if(He===58)He=y.input.charCodeAt(++y.position),x(He)||W(y,"a whitespace character is expected after the key-value separator within a block mapping"),Ge&&(te(y,se,ce,ee,he,null,H,S,G),ee=he=Oe=null),ze=!0,Ge=!1,Q=!1,ee=y.tag,he=y.result;else if(ze)W(y,"can not read an implicit mapping pair; a colon is missed");else return y.tag=J,y.anchor=ie,!0}else if(ze)W(y,"can not read a block mapping entry; a multiline key may not be an implicit key");else return y.tag=J,y.anchor=ie,!0}if((y.line===wo||y.lineIndent>N)&&(Ge&&(H=y.line,S=y.lineStart,G=y.position),fn(y,N,c,!0,Q)&&(Ge?he=y.result:Oe=y.result),Ge||(te(y,se,ce,ee,he,Oe,H,S,G),ee=he=Oe=null),z(y,!0,-1),He=y.input.charCodeAt(y.position)),(y.line===wo||y.lineIndent>N)&&He!==0)W(y,"bad indentation of a mapping entry");else if(y.lineIndent<N)break}return Ge&&te(y,se,ce,ee,he,null,H,S,G),ze&&(y.tag=J,y.anchor=ie,y.kind="mapping",y.result=se),ze}function ht(y){let N=!1,K=!1,Q,H,S=y.input.charCodeAt(y.position);if(S!==33)return!1;y.tag!==null&&W(y,"duplication of a tag property"),S=y.input.charCodeAt(++y.position),S===60?(N=!0,S=y.input.charCodeAt(++y.position)):S===33?(K=!0,Q="!!",S=y.input.charCodeAt(++y.position)):Q="!";let G=y.position;if(N){do S=y.input.charCodeAt(++y.position);while(S!==0&&S!==62);y.position<y.length?(H=y.input.slice(G,y.position),S=y.input.charCodeAt(++y.position)):W(y,"unexpected end of the stream within a verbatim tag")}else{for(;S!==0&&!x(S);)S===33&&(K?W(y,"tag suffix cannot contain exclamation marks"):(Q=y.input.slice(G-1,y.position+1),h.test(Q)||W(y,"named tag handle cannot contain such characters"),K=!0,G=y.position+1)),S=y.input.charCodeAt(++y.position);H=y.input.slice(G,y.position),g.test(H)&&W(y,"tag suffix cannot contain flow indicator characters")}H&&!w.test(H)&&W(y,"tag name cannot contain such characters: "+H);try{H=decodeURIComponent(H)}catch{W(y,"tag name is malformed: "+H)}return N?y.tag=H:r.call(y.tagMap,Q)?y.tag=y.tagMap[Q]+H:Q==="!"?y.tag="!"+H:Q==="!!"?y.tag="tag:yaml.org,2002:"+H:W(y,'undeclared tag handle "'+Q+'"'),!0}function Mn(y){let N=y.input.charCodeAt(y.position);if(N!==38)return!1;y.anchor!==null&&W(y,"duplication of an anchor property"),N=y.input.charCodeAt(++y.position);let K=y.position;for(;N!==0&&!x(N)&&!R(N);)N=y.input.charCodeAt(++y.position);return y.position===K&&W(y,"name of an anchor node must contain at least one character"),y.anchor=y.input.slice(K,y.position),!0}function Mt(y){let N=y.input.charCodeAt(y.position);if(N!==42)return!1;N=y.input.charCodeAt(++y.position);let K=y.position;for(;N!==0&&!x(N)&&!R(N);)N=y.input.charCodeAt(++y.position);y.position===K&&W(y,"name of an alias node must contain at least one character");let Q=y.input.slice(K,y.position);return r.call(y.anchorMap,Q)||W(y,'unidentified alias "'+Q+'"'),y.result=y.anchorMap[Q],z(y,!0,-1),!0}function nn(y,N,K,Q){let H=ne(y);return be(y),ye(y,N),y.tag=null,y.anchor=null,y.kind=null,y.result=null,$t(y,K,Q)&&y.kind==="mapping"?(Be(y),!0):(dt(y),ye(y,H),!1)}function fn(y,N,K,Q,H){let S,G,J=1,ie=!1,se=!1,ce=null,ee,he,Oe;y.depth>=y.maxDepth&&W(y,"nesting exceeded maxDepth ("+y.maxDepth+")"),y.depth+=1,y.listener!==null&&y.listener("open",y),y.tag=null,y.anchor=null,y.kind=null,y.result=null;let Ge=S=G=c===K||a===K;if(Q&&z(y,!0,-1)&&(ie=!0,y.lineIndent>N?J=1:y.lineIndent===N?J=0:y.lineIndent<N&&(J=-1)),J===1)for(;;){let ze=y.input.charCodeAt(y.position),He=ne(y);if(ie&&(ze===33&&y.tag!==null||ze===38&&y.anchor!==null)||!ht(y)&&!Mn(y))break;ce===null&&(ce=He),z(y,!0,-1)?(ie=!0,G=Ge,y.lineIndent>N?J=1:y.lineIndent===N?J=0:y.lineIndent<N&&(J=-1)):G=!1}if(G&&(G=ie||H),J===1||c===K)if(o===K||s===K?he=N:he=N+1,Oe=y.position-y.lineStart,J===1)if(G&&(We(y,Oe)||$t(y,Oe,he))||U(y,he))se=!0;else{let ze=y.input.charCodeAt(y.position);ce!==null&&Ge&&!G&&ze!==124&&ze!==62&&nn(y,ce,ce.position-ce.lineStart,he)||S&&xe(y,he)||ct(y,he)||Vt(y,he)?se=!0:Mt(y)?(se=!0,(y.tag!==null||y.anchor!==null)&&W(y,"alias node should not have any properties")):et(y,he,o===K)&&(se=!0,y.tag===null&&(y.tag="?")),y.anchor!==null&&re(y,y.anchor,y.result)}else J===0&&(se=G&&We(y,Oe));if(y.tag===null)y.anchor!==null&&re(y,y.anchor,y.result);else if(y.tag==="?"){y.result!==null&&y.kind!=="scalar"&&W(y,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+y.kind+'"');for(let ze=0,He=y.implicitTypes.length;ze<He;ze+=1)if(ee=y.implicitTypes[ze],ee.resolve(y.result)){y.result=ee.construct(y.result),y.tag=ee.tag,y.anchor!==null&&re(y,y.anchor,y.result);break}}else if(y.tag!=="!"){if(r.call(y.typeMap[y.kind||"fallback"],y.tag))ee=y.typeMap[y.kind||"fallback"][y.tag];else{ee=null;let ze=y.typeMap.multi[y.kind||"fallback"];for(let He=0,nt=ze.length;He<nt;He+=1)if(y.tag.slice(0,ze[He].tag.length)===ze[He].tag){ee=ze[He];break}}ee||W(y,"unknown tag !<"+y.tag+">"),y.result!==null&&ee.kind!==y.kind&&W(y,"unacceptable node kind for !<"+y.tag+'> tag; it should be "'+ee.kind+'", not "'+y.kind+'"'),ee.resolve(y.result,y.tag)?(y.result=ee.construct(y.result,y.tag),y.anchor!==null&&re(y,y.anchor,y.result)):W(y,"cannot resolve a node with !<"+y.tag+"> explicit tag")}return y.listener!==null&&y.listener("close",y),y.depth-=1,y.tag!==null||y.anchor!==null||se}function Fn(y){let N=y.position,K=!1,Q;for(y.version=null,y.checkLineBreaks=y.legacy,y.tagMap=Object.create(null),y.anchorMap=Object.create(null);(Q=y.input.charCodeAt(y.position))!==0&&(z(y,!0,-1),Q=y.input.charCodeAt(y.position),!(y.lineIndent>0||Q!==37));){K=!0,Q=y.input.charCodeAt(++y.position);let H=y.position;for(;Q!==0&&!x(Q);)Q=y.input.charCodeAt(++y.position);let S=y.input.slice(H,y.position),G=[];for(S.length<1&&W(y,"directive name must not be less than one character in length");Q!==0;){for(;$(Q);)Q=y.input.charCodeAt(++y.position);if(Q===35){do Q=y.input.charCodeAt(++y.position);while(Q!==0&&!k(Q));break}if(k(Q))break;for(H=y.position;Q!==0&&!x(Q);)Q=y.input.charCodeAt(++y.position);G.push(y.input.slice(H,y.position))}Q!==0&&Ve(y),r.call(ge,S)?ge[S](y,S,G):ke(y,'unknown document directive "'+S+'"')}if(z(y,!0,-1),y.lineIndent===0&&y.input.charCodeAt(y.position)===45&&y.input.charCodeAt(y.position+1)===45&&y.input.charCodeAt(y.position+2)===45?(y.position+=3,z(y,!0,-1)):K&&W(y,"directives end mark is expected"),fn(y,y.lineIndent-1,c,!1,!0),z(y,!0,-1),y.checkLineBreaks&&f.test(y.input.slice(N,y.position))&&ke(y,"non-ASCII line breaks are interpreted as content"),y.documents.push(y.result),y.position===y.lineStart&&$e(y)){y.input.charCodeAt(y.position)===46&&(y.position+=3,z(y,!0,-1));return}y.position<y.length-1&&W(y,"end of the stream or a document separator is expected")}function lr(y,N){y=String(y),N=N||{},y.length!==0&&(y.charCodeAt(y.length-1)!==10&&y.charCodeAt(y.length-1)!==13&&(y+=`
116
+ `),y.charCodeAt(0)===65279&&(y=y.slice(1)));let K=new _(y,N),Q=y.indexOf("\0");for(Q!==-1&&(K.position=Q,W(K,"null byte is not allowed in input")),K.input+="\0";K.input.charCodeAt(K.position)===32;)K.lineIndent+=1,K.position+=1;for(;K.position<K.length-1;)Fn(K);return K.documents}function Xn(y,N,K){N!==null&&typeof N=="object"&&typeof K>"u"&&(K=N,N=null);let Q=lr(y,K);if(typeof N!="function")return Q;for(let H=0,S=Q.length;H<S;H+=1)N(Q[H])}function Zs(y,N){let K=lr(y,N);if(K.length!==0){if(K.length===1)return K[0];throw new t("expected a single document in the stream, but found more")}}return Fk.loadAll=Xn,Fk.load=Zs,Fk}function Mwe(){if(S6)return vD;S6=1;let e=xg(),t=$g(),n=kD(),i=Object.prototype.toString,r=Object.prototype.hasOwnProperty,o=65279,s=9,a=10,c=13,l=32,u=33,d=34,p=35,f=37,g=38,h=39,w=42,b=44,k=45,$=58,x=61,R=62,P=63,I=64,A=91,B=93,C=96,q=123,L=124,M=125,_={};_[0]="\\0",_[7]="\\a",_[8]="\\b",_[9]="\\t",_[10]="\\n",_[11]="\\v",_[12]="\\f",_[13]="\\r",_[27]="\\e",_[34]='\\"',_[92]="\\\\",_[133]="\\N",_[160]="\\_",_[8232]="\\L",_[8233]="\\P";let T=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],W=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function ke(S,G){if(G===null)return{};let J={},ie=Object.keys(G);for(let se=0,ce=ie.length;se<ce;se+=1){let ee=ie[se],he=String(G[ee]);ee.slice(0,2)==="!!"&&(ee="tag:yaml.org,2002:"+ee.slice(2));let Oe=S.compiledTypeMap.fallback[ee];Oe&&r.call(Oe.styleAliases,he)&&(he=Oe.styleAliases[he]),J[ee]=he}return J}function re(S){let G,J,ie=S.toString(16).toUpperCase();if(S<=255)G="x",J=2;else if(S<=65535)G="u",J=4;else if(S<=4294967295)G="U",J=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+G+e.repeat("0",J-ie.length)+ie}let be=1,Be=2;function dt(S){this.schema=S.schema||n,this.indent=Math.max(1,S.indent||2),this.noArrayIndent=S.noArrayIndent||!1,this.skipInvalid=S.skipInvalid||!1,this.flowLevel=e.isNothing(S.flowLevel)?-1:S.flowLevel,this.styleMap=ke(this.schema,S.styles||null),this.sortKeys=S.sortKeys||!1,this.lineWidth=S.lineWidth||80,this.noRefs=S.noRefs||!1,this.noCompatMode=S.noCompatMode||!1,this.condenseFlow=S.condenseFlow||!1,this.quotingType=S.quotingType==='"'?Be:be,this.forceQuotes=S.forceQuotes||!1,this.replacer=typeof S.replacer=="function"?S.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function ne(S,G){let J=e.repeat(" ",G),ie=0,se="",ce=S.length;for(;ie<ce;){let ee,he=S.indexOf(`
117
117
  `,ie);he===-1?(ee=S.slice(ie),ie=ce):(ee=S.slice(ie,he+1),ie=he+1),ee.length&&ee!==`
118
118
  `&&(se+=J),se+=ee}return se}function ye(S,G){return`
119
- `+e.repeat(" ",S.indent*G)}function ge(S,G){for(let J=0,ie=S.implicitTypes.length;J<ie;J+=1)if(S.implicitTypes[J].resolve(G))return!0;return!1}function oe(S){return S===l||S===s}function Se(S){return S>=32&&S<=126||S>=161&&S<=55295&&S!==8232&&S!==8233||S>=57344&&S<=65533&&S!==o||S>=65536&&S<=1114111}function Ne(S){return Se(S)&&S!==o&&S!==c&&S!==a}function te(S,G,J){let ie=Ne(S),se=ie&&!oe(S);return(J?ie:ie&&S!==b&&S!==A&&S!==B&&S!==q&&S!==M)&&S!==p&&!(G===$&&!se)||Ne(G)&&!oe(G)&&S===p||G===$&&se}function Ve(S){return Se(S)&&S!==o&&!oe(S)&&S!==k&&S!==P&&S!==$&&S!==b&&S!==A&&S!==B&&S!==q&&S!==M&&S!==p&&S!==g&&S!==w&&S!==u&&S!==L&&S!==x&&S!==R&&S!==h&&S!==d&&S!==f&&S!==I&&S!==C}function z(S){return!oe(S)&&S!==$}function $e(S,G){let J=S.charCodeAt(G),ie;return J>=55296&&J<=56319&&G+1<S.length&&(ie=S.charCodeAt(G+1),ie>=56320&&ie<=57343)?(J-55296)*1024+ie-56320+65536:J}function Ie(S){return/^\n* /.test(S)}let et=1,ct=2,Vt=3,U=4,ke=5;function We(S,G,J,ie,se,ce,ee,he){let Oe,Ge=0,ze=null,He=!1,nt=!1,wo=ie!==-1,jc=-1,E=Ve($e(S,0))&&z($e(S,S.length-1));if(G||ee)for(Oe=0;Oe<S.length;Ge>=65536?Oe+=2:Oe++){if(Ge=$e(S,Oe),!Se(Ge))return ke;E=E&&te(Ge,ze,he),ze=Ge}else{for(Oe=0;Oe<S.length;Ge>=65536?Oe+=2:Oe++){if(Ge=$e(S,Oe),Ge===a)He=!0,wo&&(nt=nt||Oe-jc-1>ie&&S[jc+1]!==" ",jc=Oe);else if(!Se(Ge))return ke;E=E&&te(Ge,ze,he),ze=Ge}nt=nt||wo&&Oe-jc-1>ie&&S[jc+1]!==" "}return!He&&!nt?E&&!ee&&!se(S)?et:ce===Be?ke:ct:J>9&&Ie(S)?ke:ee?ce===Be?ke:ct:nt?U:Vt}function $t(S,G,J,ie,se){S.dump=(function(){if(G.length===0)return S.quotingType===Be?'""':"''";if(!S.noCompatMode&&(T.indexOf(G)!==-1||W.test(G)))return S.quotingType===Be?'"'+G+'"':"'"+G+"'";let ce=S.indent*Math.max(1,J),ee=S.lineWidth===-1?-1:Math.max(Math.min(S.lineWidth,40),S.lineWidth-ce),he=ie||S.flowLevel>-1&&J>=S.flowLevel;function Oe(Ge){return ge(S,Ge)}switch(We(G,he,S.indent,ee,Oe,S.quotingType,S.forceQuotes&&!ie,se)){case et:return G;case ct:return"'"+G.replace(/'/g,"''")+"'";case Vt:return"|"+ht(G,S.indent)+Mn(ne(G,ce));case U:return">"+ht(G,S.indent)+Mn(ne(Mt(G,ee),ce));case ke:return'"'+fn(G)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function ht(S,G){let J=Ie(S)?String(G):"",ie=S[S.length-1]===`
119
+ `+e.repeat(" ",S.indent*G)}function ge(S,G){for(let J=0,ie=S.implicitTypes.length;J<ie;J+=1)if(S.implicitTypes[J].resolve(G))return!0;return!1}function oe(S){return S===l||S===s}function Se(S){return S>=32&&S<=126||S>=161&&S<=55295&&S!==8232&&S!==8233||S>=57344&&S<=65533&&S!==o||S>=65536&&S<=1114111}function Ne(S){return Se(S)&&S!==o&&S!==c&&S!==a}function te(S,G,J){let ie=Ne(S),se=ie&&!oe(S);return(J?ie:ie&&S!==b&&S!==A&&S!==B&&S!==q&&S!==M)&&S!==p&&!(G===$&&!se)||Ne(G)&&!oe(G)&&S===p||G===$&&se}function Ve(S){return Se(S)&&S!==o&&!oe(S)&&S!==k&&S!==P&&S!==$&&S!==b&&S!==A&&S!==B&&S!==q&&S!==M&&S!==p&&S!==g&&S!==w&&S!==u&&S!==L&&S!==x&&S!==R&&S!==h&&S!==d&&S!==f&&S!==I&&S!==C}function z(S){return!oe(S)&&S!==$}function $e(S,G){let J=S.charCodeAt(G),ie;return J>=55296&&J<=56319&&G+1<S.length&&(ie=S.charCodeAt(G+1),ie>=56320&&ie<=57343)?(J-55296)*1024+ie-56320+65536:J}function Ie(S){return/^\n* /.test(S)}let et=1,ct=2,Vt=3,U=4,xe=5;function We(S,G,J,ie,se,ce,ee,he){let Oe,Ge=0,ze=null,He=!1,nt=!1,wo=ie!==-1,jc=-1,E=Ve($e(S,0))&&z($e(S,S.length-1));if(G||ee)for(Oe=0;Oe<S.length;Ge>=65536?Oe+=2:Oe++){if(Ge=$e(S,Oe),!Se(Ge))return xe;E=E&&te(Ge,ze,he),ze=Ge}else{for(Oe=0;Oe<S.length;Ge>=65536?Oe+=2:Oe++){if(Ge=$e(S,Oe),Ge===a)He=!0,wo&&(nt=nt||Oe-jc-1>ie&&S[jc+1]!==" ",jc=Oe);else if(!Se(Ge))return xe;E=E&&te(Ge,ze,he),ze=Ge}nt=nt||wo&&Oe-jc-1>ie&&S[jc+1]!==" "}return!He&&!nt?E&&!ee&&!se(S)?et:ce===Be?xe:ct:J>9&&Ie(S)?xe:ee?ce===Be?xe:ct:nt?U:Vt}function $t(S,G,J,ie,se){S.dump=(function(){if(G.length===0)return S.quotingType===Be?'""':"''";if(!S.noCompatMode&&(T.indexOf(G)!==-1||W.test(G)))return S.quotingType===Be?'"'+G+'"':"'"+G+"'";let ce=S.indent*Math.max(1,J),ee=S.lineWidth===-1?-1:Math.max(Math.min(S.lineWidth,40),S.lineWidth-ce),he=ie||S.flowLevel>-1&&J>=S.flowLevel;function Oe(Ge){return ge(S,Ge)}switch(We(G,he,S.indent,ee,Oe,S.quotingType,S.forceQuotes&&!ie,se)){case et:return G;case ct:return"'"+G.replace(/'/g,"''")+"'";case Vt:return"|"+ht(G,S.indent)+Mn(ne(G,ce));case U:return">"+ht(G,S.indent)+Mn(ne(Mt(G,ee),ce));case xe:return'"'+fn(G)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function ht(S,G){let J=Ie(S)?String(G):"",ie=S[S.length-1]===`
120
120
  `,ce=ie&&(S[S.length-2]===`
121
121
  `||S===`
122
122
  `)?"+":ie?"":"-";return J+ce+`
@@ -154,12 +154,12 @@ ${e.timestamp}`,"utf-8")}function yue(e,t,n){let i=`the approval of gate ${n.gat
154
154
  `).filter(Boolean),o=[],s;for(let a of r){let c={signers:qJ(e,a,i[0]),rotation:qJ(e,a,i[1])};if(c.signers===void 0){s&&o.push({version:0,commit:a,digest:"",threshold:0,signers:[],excluded:[],signedBy:[]}),s=void 0;continue}let l=Sve(s,c,a);if("code"in l)return{versions:o,broken:{commit:a,code:l.code,reason:l.reason}};l!==s&&o.push(l),s=l}return{versions:o}}var vve,$ve,Ove,ix,ZJ=v(()=>{"use strict";$n();En();Al();Go();Dg();vve="chant-signers";$ve=m.object({schema:m.literal(1),version:m.number().int().min(1),previous:m.string().regex(/^sha256:[0-9a-f]{64}$/).nullable(),threshold:m.number().int().min(1),signatures:m.array(m.object({principal:m.string().min(1),signature:m.string().min(1)}).strict())}).strict();Ove=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/,ix=class{constructor(t,n,i){this.repo=t;this.base=n;this.history=i;this.index=new Map;this.memo=new Map}isAncestor(t,n){try{return KJ("git",["merge-base","--is-ancestor",t,n],{cwd:this.repo,stdio:"ignore"}),!0}catch{return!1}}firstParents(){return this.line||(this.line=rx(this.repo,["rev-list","--first-parent",this.base]).split(`
155
155
  `).filter(Boolean),this.line.forEach((t,n)=>this.index.set(t,n))),this.line}entryIndex(){if(!this.entries){let t=this.firstParents(),n=new Map;for(let r of rx(this.repo,["rev-list","--parents",this.base]).split(`
156
156
  `)){let[o,...s]=r.trim().split(" ");o&&n.set(o,s)}let i=new Map;for(let r=t.length-1;r>=0;r--){let o=[t[r]];for(;o.length>0;){let s=o.pop();if(!i.has(s)){i.set(s,r);for(let a of n.get(s)??[])i.has(a)||o.push(a)}}}this.entries=i}return this.entries}entryOf(t){if(Ove.test(t))return this.entryIndex().get(t)??null;if(!this.isAncestor(t,this.base))return null;let n=this.firstParents(),i=0,r=n.length-1,o=0;for(;i<=r;){let s=i+r>>1;this.isAncestor(t,n[s])?(o=s,i=s+1):r=s-1}return o}versionFor(t){let n=this.memo.get(t);if(n!==void 0)return n;let i=this.lookup(t);return this.memo.set(t,i),i}lookup(t){if(this.history.broken)return null;let n=this.history.versions.at(-1)??null,i=this.entryOf(t);if(i===null)return n;let r=null,o=1/0;for(let s of this.history.versions){let a=s.commit?this.index.get(s.commit):void 0;a===void 0||a<=i||a<o&&(r=s,o=a)}return r}}});import{execFileSync as eZ}from"node:child_process";function qD(e,t){return eZ("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],maxBuffer:256*1024*1024})}function YJ(e,t){try{return qD(e,["rev-parse","--verify","--quiet",`${t}^{commit}`]).trim()||void 0}catch{return}}function ti(e,t){if(t!==void 0){let n=t.startsWith("-")?void 0:YJ(e,t);return n?{commit:n,from:"flag"}:{commit:null,from:null,problem:`--base ${t} names no commit in this repository`}}for(let[n,i]of[["refs/remotes/origin/HEAD","origin/HEAD"],["refs/heads/main","main"],["refs/heads/master","master"]]){let r=YJ(e,n);if(r)return{commit:r,from:i}}return{commit:null,from:null,problem:"no base revision: pass --base <rev> (there is no origin/HEAD, main or master)"}}function $i(e,t){if(!t.commit)return eo(null,t.problem?[t.problem]:[]);let n=Ha(xi(e,t.commit),t.commit);if(!n.active||n.problems.length>0)return n;let i=JJ(e,t.commit,n.signersPath);if(i.broken){let o=i.broken.commit?` at ${i.broken.commit.slice(0,8)}`:"";return{...n,problems:[`the signer history of ${n.signersPath} is broken${o}: ${i.broken.reason}`]}}let r=new ix(e,t.commit,i);return{...n,signersAt:o=>r.versionFor(o)}}function Ave(e,t,n){let i=new Map;if(n.length===0)return i;let r=qD(e,["--literal-pathspecs","log","-c","--name-only","--no-renames","--format=%x00%H",t,"--",...n]),o=new Set(n),s="";for(let a of r.split(`
157
- `))a.startsWith("\0")?s=a.slice(1).trim():a&&o.has(a)&&!i.has(a)&&i.set(a,s);return i}function Pve(e,t){if(t.length===0)return new Set;let n=qD(e,["--literal-pathspecs","status","--porcelain=v1","-z","--untracked-files=all","--",...t]),i=new Set,r=n.split("\0");for(let o=0;o<r.length;o++){let s=r[o];s.length<4||(i.add(s.slice(3)),(s[0]==="R"||s[0]==="C")&&o++)}return i}function XJ(e,t,n){try{return eZ("git",["merge-base","--is-ancestor",t,n],{cwd:e,stdio:"ignore"}),!0}catch{return!1}}function QJ(e,t,n){return t.adopted.some(i=>XJ(e,n,i.to)&&(i.from===void 0||!XJ(e,n,i.from)))}function Ng(e,t,n,i){let r=t;if(t.signersAt){let s=t.signersAt(n);if(r={...t,signers:s?.signers??[]},!s||s.version===0){let a="no signer set was in effect where this commit entered the base's history";return QJ(e,t,n)?{level:"adopted",commit:n,reason:`in a commit range the policy at base adopts; ${a}`}:{level:"unattested",commit:n,reason:a}}}let o=tx({repo:e,policy:r},n,i);return o.level==="unattested"&&QJ(e,t,n)?{level:"adopted",commit:n,attestor:o.attestor,reason:`in a commit range the policy at base adopts; ${o.reason}`}:{level:o.level,commit:n,attestor:o.attestor,...o.principal?{principal:o.principal}:{},...o.key?{key:o.key}:{},reason:o.reason}}function tZ(e){let t=new Map,n=o=>{for(let s of e.paths)t.set(s,{level:"unattested",commit:null,reason:o});return t};if(!e.repo)return n("not in a git repository");if(e.policy.problems.length>0)return n(e.policy.problems.join("; "));if(!e.policy.active)return n(`no signers file (${e.policy.signersPath}) at base ${e.policy.base?.slice(0,8)}; attestation is off`);let i=e.at===null?Pve(e.repo,e.paths):new Set,r=Ave(e.repo,e.at??"HEAD",e.paths.filter(o=>!i.has(o)));for(let o of e.paths){if(i.has(o)){t.set(o,{level:"unattested",commit:null,reason:"the working tree has uncommitted changes to this file"});continue}let s=r.get(o);if(!s){t.set(o,{level:"unattested",commit:null,reason:"no commit holds this file"});continue}let a=Ng(e.repo,e.policy,s,e.attestors);t.set(o,e.revisit?.(o,a)??a)}return t}var Pl=v(()=>{"use strict";Qi();lp();Go();ZJ()});function ox(e,t){if(typeof e!="string")return!1;let n=e.match(_ve);return!!n&&(t===void 0||n[1]===t)}var Cve,fHe,_ve,KD=v(()=>{"use strict";Cve={"declaration-missing":"No chant.workspace.json or .jsonc between the directory and the git root.","declaration-ambiguous":"Both chant.workspace.json and chant.workspace.jsonc exist.","declaration-unparseable":"The declaration is not valid JSON, or not valid JSONC for .jsonc.","declaration-invalid":"The declaration does not match its schema, repeats a name, or --member names no entry.","placement-invalid":"A member or group match breaks a placement rule.","reader-too-old":"The declaration's minReader is newer than the chant reading it.","root-chant-required":"The declaration pins a chant version other than the reader's, and that chant is not installed at the workspace root.","not-a-git-repository":"--at, or a ledger read, needs a git repository and there is none.","revision-unknown":"--at names no commit.","live-at-revision":"graph was given --live and --at: a live read is of the account now, not of a revision.","environment-invalid":"An environment name that can't name a ledger directory.","dir-missing":"The member's directory does not exist.","unknown-kind":"No built-in kind or pinned package supplies the member's kind.","kind-probe-failed":"The member's directory is not what its kind reads.","no-matches":"An example group matches no directory holding a chant project.","kind-not-run":"The member's kind is one the per-member commands don't run, such as other.","command-failed":"The member's own command exited with a failure, or the lexicon that reads the member through its kind's graph block isn't installed where the workspace resolves its pin.","output-unreadable":"The member's command printed something that isn't the document asked for.","ir-version-unsupported":"The member's IR has a version this chant can't read.","ledger-unreadable":"Reading the ledger failed, so nothing from it is listed.","ledger-malformed":"Some lines of the ledger aren't release records; the rest are listed.","gates-no-ledger":"The checkout has no chant/lifecycle branch, so there is no gate ledger to read.","gates-no-gate-ledger":"The branch has no gate ledger for the member: no run of it has reached a gate.","gates-ledger-unreadable":"Reading the member's gate ledger failed, so no gate is listed.","stewards-unreadable":"An *.op.ts file could not be imported, so a steward it declares may be missing.","stewards-conflict":"A steward was dropped: its name, or an Op it lists, belongs to another steward.","steward-runs-unreadable":"Reading an Op's run ledger, or a ConvergeOp's converge ledger, failed, so its last run or last tick is null.","record-unparseable":"No front matter, a YAML error or a value outside the JSON subset of YAML, or for a JSON kind a file that is not one object or repeats a member name.","record-schema-invalid":"The record's front matter, or its JSON object, does not match the kind's schema.","record-id-duplicate":"Another record earlier in path order has the same id.","record-supersedes-unknown":"A supersedes link names an id no record has.","record-supersedes-conflict":"A second closed record supersedes a record another one already superseded.","record-remediates-unknown":"A remediates link names an id no record has.","record-remediates-not-closed":"A remediates link names a record that isn't closed; a record still open is amended instead.","record-seal-mismatch":"A closed record's seal is not the whole-file seal of its text now: the record changed after it closed.","session-seal-mismatch":"A closed session's seal is not the whole-file seal of its text now: the session changed after it closed, or was sealed by the rule before #2546.","session-verdict-unknown-record":"A session's verdict names a record that none of the session kind's subject records has.","asset-drift":"A file the record pins by hash has changed: its bytes no longer hash to the pinned sha256.","asset-missing":"A file the record pins by hash does not exist in the tree read.","asset-stale":"A file the record pins is unchanged at the hash a record it supersedes pinned: the decision changed and the artifact did not follow.","record-supersedes-pending":"A supersedes link from a record whose state is weaker than the record it names, so the link has no effect yet.","record-no-evidence":"The record's evidence list is empty: it cites nothing and pins no file. Information for a reviewer, never an error.","review-undigested":"A verdict names no digest of the text it judged. It still counts, and an amendment does not stop it counting.","source-transcript-drift":"The record's source block pins a transcript by hash, the file it names can be read here, and its bytes hash to something else: it is not the transcript the record means.","work-needs-unknown":"A work record's needs list names a work id no record has, so the item stays blocked.","work-implements-unknown":"A work record's implements list names a decision id no decision has.","work-needs-cycle":"A work record needs itself through its needs links, so it can never be ready.","work-implements-undecided":"A work record implements a decision whose state is not approved, such as proposed.","work-done-unpinned":"A work record is done and its evidence list is empty: nothing shows the work was done.","work-closed-without-date":"A work record is done or dropped and has no closing date.","work-done-gap-open":"A work record is done, and the finding it came from still fires on its region. graph --intent raises it, and records does by walking that region.","work-acceptance-unmet":"A work record is done, and one of its acceptance criteria has no passing evidence of the verification it expects. check fails on it (WSP117).","work-acceptance-self-verified":"A passing manual verdict on a work record's criterion names the record's implementer, so it does not count: a manual verdict comes from someone else.","work-contract-unknown":"A work record names a contract that no record of its kind's contract kind has.","work-contract-undecided":"A work record names a contract whose state is not approved, such as a draft.","work-tier-unknown":"A work record names a builder tier that its kind's work.tier.tiers does not list.","flag-work-unknown":"A flag record names a work item that no record of its kind's work kind has.","flag-stale":"Every decision a flag's work item implements is confirmed, so the flag is due for removal. check reports it (WSP118).","answer-points-unreadable":"The points file the answer kind names can't be read, or is not valid.","answer-point-unknown":"The answer's point is not declared in the points file the answer kind names.","answer-point-changed":"The point's declaration changed since the question was asked, so the answer is to an older version of the question.","review-decider":"The verdict is the decider's own, and the quorum counts verdicts besides the decider's.","review-agent":"The reviewer holds the agent role in the trust policy at base.","review-duplicate":"A later verdict by the same principal replaces this one. Names are compared after NFKC, trimming and lower-casing.","review-older-digest":"The verdict names a digest other than the record's text now: the record changed after the verdict.","review-unattested":"An attestation policy is active at base, and the verdict carries no seal that verifies for its reviewer.","seal-missing":"The verdict, or the record, carries no seal.","seal-signer-unlisted":"The reviewer, or the record's author, has no key in the signers file at base, so the seal can't count.","seal-signature-invalid":"The seal is malformed, names a signer other than the reviewer or author, or its signature does not verify over the verdict or record.","seal-unverifiable":"Nothing here can say whose seal it is: there is no signers file at base, ssh-keygen is not installed, or the record came back in a return sealed by a signer no admission lists yet.","record-unattested":"A signers file is active at base, and the record names an author whose seal does not verify: it has none, the author has no key in the file, or the signature fails.","record-ratified-below-quorum":"The record is in its kind's ratified state (reviews.ratified), and its quorum is not met: it was written to that state by hand, past the check of records new and amend. It is still read, and stays valid.","kind-unreadable":"The record kind file is missing or could not be imported.","kind-invalid":"The record kind file exports no recordKind, or its shape is wrong.","schema-unreadable":"The schema file the record kind names is missing or is not JSON.","schema-id-mismatch":"The schema's $id differs from the id the record kind names.","schema-invalid":"The record schema itself does not compile.","location-missing":"The records directory does not exist, in the tree or at the revision.","write-usage-invalid":"The command line lacks a value the write needs, or gives one it does not take.","write-input-invalid":"The fields given with --from or --set can't be read, are not JSON, or are not a JSON object.","record-not-found":"No record of the kind has the id given.","record-id-taken":"The id given for a new record is already used, by a record or a file name.","record-id-unallocatable":"No id was given and none can be allocated: the records share no single prefix and --prefix names none.","record-path-unmatched":"The file name made from the record's id and title does not match the kind's location.","record-closed":"The record is in a closed state, so nothing in it changes; a new record supersedes it instead.","amend-id-immutable":"An amendment changes the record's id, and ids are never renumbered.","amend-supersede-instead":"The record is approved, and the amendment changes a field the approval rule does not let change in place; a new record supersedes it instead.","review-unsupported":"The kind's schema has no reviews field, so its records take no review.","review-note-required":"A dissent was given with no note: a dissent needs a reason.","review-sign-failed":"--sign was given and no seal could be made: the key can't be read or used, git names no ssh signing key, or ssh-keygen is not installed.","record-state-not-initial":"A record written through chant serve mcp gives a state other than the kind's first: a new record opens proposed, and a person moves it on.","source-harvest-not-proposed":"A harvested record (source.via harvest) was written in a state other than the kind's first: a harvest proposes, and a person decides.","ratify-quorum-not-met":"The write puts a record in its kind's ratified state (reviews.ratified), and the record's quorum is not met: too few agreeing verdicts count.","record-sign-failed":"--sign was given and no author seal could be made: the record names no author, the key can't be read or used, git names no ssh signing key, or ssh-keygen is not installed.","record-conflict":"--expect named a digest the record no longer has: another write changed it after the caller read it. The refusal names the digest it has now; re-read the record and write again.","write-lock-timeout":"Another write held the working tree's write lock for longer than the write waits (CHANT_WRITE_LOCK_WAIT_MS); the refusal names the holder. Run the write again.","write-lock-not-held":"CHANT_WRITE_LOCK names a batch's lock token that no longer holds the working tree's write lock: the batch released it, or it expired and another writer took it.","write-scope-member":"The write is to a file, or to a record kind, of a member outside the writer's scope: an agent session writes only the members it is bound to, and writeScope.<class>.members leaves the member out.","write-scope-kind":"The write is to a record kind writeScope.<class>.records does not list, with a verb it does not list for the kind, or deletes a record.","write-scope-protected":"The write is to a file writeScope.<class>.protected lists, or one under a directory it lists, outside the top-level keys or JSON Pointers the entry's except allows (#3146, #3308).","write-scope-class-unknown":"The declaration's writeScope at base names a principal class no pinned package supplies, and the writer is judged human, so it may be in that class; the write is refused until the package is installed at the pinned version or the entry removed (#3080).","agent-unknown":"CHANT_AGENT, or a commit's Chant-Agent trailer, names an agent session the declaration at base does not declare.","principal-unidentified":"chant.workspace.json at base sets identity.attribution to identified, and the write names a person by a bare name: --by, an author field or a decision point's answerer must be a forge identity (github:<login>, gitlab:<login>, <forge>@<host>:<login>), a principal the signers file at base lists, or an agent, runner or service principal (#3163).","session-unknown":"--session names no session of a session kind whose subjects are the record's kind.","session-not-open":"--session names a session in a closed state, which takes no more verdicts.","points-undeclared":"No record kind with an answers block is declared, or given with --kind, so there is no points file to ask.","points-invalid":"The points file an answer kind names can't be read, or does not match decision-points.schema.json and the rules checked in code.","point-unknown":"No points file declares the point asked, or the one an answer names.","point-inputs-invalid":"The inputs given to an ask are not a JSON object of the point's declared inputs.","point-decider-failed":"A model decider that fails closed (unreachable: fail) could not answer, so the ask wrote nothing.","answer-not-candidate":"The people's answer is not one of the question's candidates.","quorum-not-met":"Too few of the people who answered count toward the point's quorum: distinct, not holding the agent role, not the steward that asked, and holding one of its roles when it names any. Nobody named over MCP or ACP counts (#3817).","answer-in-steward-turn":"The answer was given during a steward's turn, or by a process it started: a steward never answers a decision point, and a person answers it through hud or at a shell.","answer-never-over-mcp":"The answer or retraction came over MCP or ACP, or from a process a session on one started, and the question constrains a gate that is never resolved there: a person answers it at a shell or through hud (#3817).","answer-not-answered":"points retract names a question that has no answer to retract: it is escalated or proposed, and people answer it instead (#3351).","answer-field-unsupported":"The answer kind's copy of point-answer.schema.json predates a field the write needs, a note, a relay, a retraction, an ad-hoc question's asked or a withdrawal: copy the schema anew to turn it on (#3351, #3402, #3403, #2888).","point-candidates-invalid":"points ask names an ad-hoc point without --candidates, a declared point with them, or candidates that are not a question and criteria of the point's question type (#3403).","since-rev-unknown":"--since names no commit, or a session with no opening revision and no commit that added it.","since-session-unknown":"--since has the shape of a session id and names no commit, and no session the kind or the declaration reads has that id.","since-session-open":"--since names a session that is still open, so the comparison runs to the working tree.","intent-region-invalid":"The region's path, or its line range, does not exist in the tree read.","intent-record-unknown":"graph --intent --record names an id that no record of a decision kind read has.","intent-symbol-unsupported":"The region names a symbol, path#symbol, in a file no symbol resolver reads; a line range still works.","intent-symbol-unknown":"The region names a symbol the file does not declare in the tree read.","intent-symbol-ambiguous":"The region names a symbol that matches more than one declaration in the file; its qualified name picks one.","intent-history-shallow":"The repository is a shallow clone, so the region's history stops at the clone's boundary.","intent-plugin-failed":"A kind file's commitJoins, which joins commits to units, contracts and evidence, failed for a commit.","squash-unfollowed":"A squash commit's pull request ref (refs/pull/<n>/head) is not in the clone and could not be fetched from origin, so its original commits are not followed; the read keeps its answer without them.","intent-commit-undecided":"A commit changed the region when no decision constrained it at path granularity.","intent-commit-bare":"A commit names no unit, carries no record through its Chant-Record or Chant-Lease trailer, and has no pull request and no decision covering the region at its time.","intent-pin-drifted":"A decision's pinned artifact no longer hashes to the pin.","intent-pin-missing":"A decision's pinned artifact does not exist in the tree read.","intent-pin-stale":"A current decision pins an artifact at the hash a record it supersedes pinned, and the artifact has not changed since: the decision moved on and the artifact did not.","intent-artifact-unpinned":"An artifact decisions in the graph pinned, which no current decision pins.","intent-decision-superseded-live":"Every decision constraining the region is superseded.","intent-decision-provisional":"The current decisions constraining the region are all in states their kind does not close, such as decided.","intent-decision-contested":"A current decision constraining the region has an open concern: a dissent neither addressed nor withdrawn.","intent-constraint-coarse":"The region is constrained only through its member, not by path.","intent-constraint-lost":"A decision's path constraint names a path that does not exist in the tree read.","intent-evidence-unpinned":"A decision's evidence has no hash: a URL, or a path with no sha256.","intent-trailer-unverified":"A commit carries a trailer a plugin says claims authorship, and the commit is not attested.","intent-region-unconstrained":"No decision constrains the region at any granularity.","intent-decision-unimplemented":"A decided decision constrains the region, no work item that is not dropped implements it, and no commit falls in its window.","intent-work-blocked":"A work item constraining the region has commits in its window while a work item it needs is not done.","intent-work-open-decided-code":"Commits in the region are a decision's own work while the work item implementing that decision is still open.","intent-commit-join-conflict":"A commit joined to an agent run by its Chant-Run trailer or the run's record has the patch-id of a commit another run recorded, so it is not joined to that run by content.","intent-why-no-decision":"No current decision governs the region at any granularity, and none is carried out by the commits or runs that made its current lines.","intent-why-no-run":"None of the region's current lines was made by a commit an agent run is joined to.","intent-why-uncommitted":"Some of the region's lines are not committed yet.","intent-why-run-ambiguous":"Some lines come from a commit several agent runs made, and no run's recorded hunks say which wrote them.","change-uncovered":"A path the diff changes is covered by no current decided record and no open work item, by path or by its member.","change-out-of-scope":"A record in hand for the change, such as the work item it is for or a decision that item implements, lists a path the diff changes in its out_of_scope.","commit-unlinked":"A trunk commit in the range names no work item: it has no Chant-Record trailer of a work kind and no Chant-Lease trailer.","commit-wrongly-linked":"A trunk commit in the range names a work item that is not there: a Chant-Record whose id no work kind has or whose kind is not a work kind, a malformed Chant-Record, or a Chant-Lease that resolves to no work item, and no other trailer links it.","patch-path-invalid":"workspace patch --path names a path that is not relative and inside the workspace.","composites-no-chant-member":"No member of kind chant was read, so nothing declares a composite instance or a component.","composites-none-declared":"The members read declare no composite instance.","composites-no-component":"The members read declare no component, so no composite instance has one.","runtimes-config-unreadable":"The member's chant.config.ts could not be read, so only the built-in local runtime is listed, and no environment from the config.","runtimes-lexicon-unreadable":"A lexicon the member's config lists could not be loaded, so it is not listed as a runtime.","environments-none-declared":"The member's chant.config.ts declares no environments, so only local and the environments in its ledger are listed.","environments-ledger-undeclared":"The member's ledger has releases in an environment its config's environments don't cover, so chant run --env would refuse it and it is not listed.","environments-ledger-unreadable":"The chant/lifecycle branch exists and the member's ledger environments could not be listed.","environments-component-undeclared":"A component declares an environment its member's chant.config.ts environments don't cover, so chant run --env would refuse it and it is not listed (#3153).","diagram-source-missing":"A declared diagram's source file does not exist in the tree read.","diagram-render-missing":"A declared diagram's render file does not exist in the tree read.","diagram-render-drift":"A declared diagram records a sourceHash, and the source's bytes now hash to something else: the render is stale for its source.","security-signers-missing":"The workspace opts into verified-releases, and there is no .chant/allowed_signers to verify a release's signature against.","security-release-gate-missing":"Under verified-releases, identity.gates has no release entry, or it names no class, so a cut is not held to a class of signers.","security-publish-allows-unsigned":"Under verified-releases, a pipeline file runs release publish with --allow-unsigned.","security-sbom-disabled":"Under supply-chain, a member's chant.config.ts sets sbom: false on a publish target.","security-sbom-unsourced":"Under supply-chain, a member publishes, names no sbom file and has no package-lock.json, pom.xml or Cargo.lock to write one from.","security-publish-no-provenance":"Under supply-chain, a pipeline file runs release publish without --require-provenance.","security-component-no-sbom":"Under supply-chain, a member's components have no generate-sbom step.","security-component-no-verify":"Under supply-chain, a member's components have no verify step.","security-signed-since-unset":"Under who-ran-it, ci.green sets no signedSince, or there is no ci.green block.","security-runner-untrusted":"Under who-ran-it, .chant/trust.json lists no runner key.","security-tick-no-key":"Under who-ran-it, a pipeline file runs ci tick with no runner key.","security-review-not-required":"Under review-rules, an apply job passes --no-require-review, which the group overrides.","security-attribution-any":"Under review-rules, identity.attribution is not identified.","security-gate-unsigned":"Under review-rules, an apply job names a gate identity.gates does not list, or identity.gates lists none.","security-runner-start-no-key":"Under isolated-runners, .chant/trust.json lists no key under runners for a provisioner to sign runner-start statements with.","security-runner-start-no-role":"Under isolated-runners, no principal under runners in .chant/trust.json holds the runner role.","security-trust-unreadable":"Under isolated-runners, .chant/trust.json can't be read, so no runner-start statement can be checked.","box-credential-declared":"A file in a box member's directory carries a literal secret: a credential's shape, or a literal where a credential goes. A variable or secret-manager reference is not one.","box-capability-unbrokered":"A capability in a member's box block names no broker, so the box would hold its credential.","box-fountain-callback-undeclared":"A box member builds a fountain Box, whose sandbox fountain gives a callback token scoped to its owner, and the member's box block does not declare the fountain-callback capability brokered by fountain with scope owner.","box-intent-unknown":"A box block names an intent, and no record of a declared kind named decision has that id.","box-intent-unconstrained":"The decision record a box names as its intent constrains no member or path of this workspace: no member: entry for a declared member and no path: entry at, above or inside one's directory.","box-none":"No member's box block declares services, so the workspace has no box for a host to plant.","box-several":"More than one member's box block declares services, and a planted workspace runs one box.","work-kind-missing":"No work kind to find the item in: --kind names a kind with no work block, or the declaration names no work kind.","work-kind-ambiguous":"More than one declared work kind has a record with the id, so --kind must name one.","work-item-unknown":"No work record has the id, so there is nothing to lease.","work-item-closed":"A claim on a work item in a closed state, such as done or dropped: there is no work left to claim.","work-criterion-unknown":"The work record lists no acceptance criterion with the id the evidence names, or its kind has no acceptance criteria.","lease-held":"Someone holds a live lease on the work item: another worker, or, for a claim, the same one.","lease-not-held":"Nobody holds a live lease on the work item: it expired, was released or was never claimed.","lease-token-mismatch":"The live lease on the work item carries another fencing token than the one given.","lease-race":"Another writer changed the lease between this command's read and its write.","lease-push-rejected":"The remote refused the lease push: another clone claimed the item first, or the remote could not be reached.","run-exists":"runs start or runs record was given a run id the ledger already has.","run-unknown":"runs end names a run the ledger has no start for.","run-ended":"runs end names a run whose end is already recorded.","runs-no-ledger":"The checkout has no chant/lifecycle branch, so there are no agent runs to read.","runs-ledger-malformed":"Some lines of the agent run ledger aren't run events; the rest are read.","run-not-ended":"runs sign or runs statement names a run with no end recorded. A statement is signed over the run's whole record.","run-statement-invalid":"The envelope's payload is not an in-toto Statement v1 with chant's agent-run predicate, or has a field the predicate does not define.","run-statement-signer-mismatch":"The statement names a signer other than the runner whose key signed it.","run-statement-mismatch":"A listed runner key signed the statement, and it does not match the run's record: another run, a record that hashes differently, or another unit, harness, model, provider or principal.","listing-member-unknown":"box listing set names a member the declaration does not declare.","listing-box-missing":"box listing set names a member whose entry declares no box block, so it has no listing.","listing-cover-invalid":"The cover can't be read, is not a PNG, JPEG or WebP picture, is larger than 5 MiB, has a path outside the workspace, or has an extension other than its picture format's.","member-exists":"member add names a member the declaration already has, with an entry other than the one given.","member-unknown":"member remove names a member the declaration does not declare.","trust-config-invalid":".chant/trust.json in the working tree is not JSON or does not match its schema, or the write would make it so.","trust-conflict":"--expect named a digest .chant/trust.json no longer has: another write changed it after the caller read it. The refusal names the digest it has now.","runner-exists":"trust runner add names a principal .chant/trust.json already lists with another key or class, or gives a key it lists for another principal.","runner-unknown":"trust runner remove names a principal .chant/trust.json lists no runner for.","factory-member-unknown":"box factory set names a member the declaration does not declare.","factory-box-missing":"box factory set names a member whose entry declares no box block, so it has no factory.","publish-member-unknown":"box publish names a member the declaration does not declare.","publish-none":"box publish names a member whose box block names no publisher, or which declares no box block.","publish-refused":"The box's publisher refused (it exited 2): nothing was published, and its message says why.","publish-failed":"The box's publisher could not be run, failed (a nonzero exit other than 2) or ran out of time; its message says what it had done.","publish-answer-invalid":"The box's publisher exited 0 and printed no JSON object, or one box-publish.schema.json does not allow.","publish-unrecorded":"The commit the publisher named is not in the repository, or lacks the apply record of ws-075: Chant-Applied-By naming --by, Chant-Applied-At, Chant-Applied-Commit and a Chant-Record for the item, or a Chant-Record for each record sent.","wip-no-branch":"HEAD is detached, or names a branch with no commit yet, so there is no branch to keep work in progress for.","wip-none":"wip restore was given no snapshot, and the branch has none under refs/chant/wip/<branch>.","wip-snapshot-unknown":"wip restore names something that is not a work-in-progress snapshot chant took.","wip-branch-other":"wip restore names a snapshot taken on another branch than the one checked out.","wip-race":"Another writer moved refs/chant/wip/<branch> between this command's read and its write.","wip-policy-none":"wip push or wip fetch was run, and no box block declares replicate, so there is no remote.","wip-remote-unknown":"The replicate policy names a git remote the checkout does not have; the host adds it, with its credential, before chant pushes.","ci-green-undeclared":"The declaration has no ci.green block, so chant does not know which check runs make a commit green.","ci-branch-unknown":"The checkout has no ref for the branch ci.green names: neither the remote-tracking branch nor a local one.","box-isolation-collision":"Two boxes on one host resolve to the same port, state path or cookie name, or two ports in one box share an offset.","box-isolation-literal":"A host's stateRoot or a box's state entry is a literal machine path instead of one derived from an environment reference and the box's name.","signers-file-missing":"There is no signers file at the base revision, so there is no signer history to read.","signers-removed":"The signers file was removed. Commits merged before the removal keep the set they were judged by; nothing after it verifies.","rotation-unparseable":"The rotation file beside the signers file is not JSON.","rotation-invalid":"The rotation file does not match its shape: schema 1, a version, the previous set's digest, a threshold and signatures.","rotation-first-version":"The first signer set's rotation file names a version other than 1, or a previous digest.","rotation-missing":"The signer set or its threshold changed and no rotation file signed by the set before it came with the change.","rotation-version-skew":"The rotation names a version other than the one after the set it replaces, as a replayed or skipped rotation does.","rotation-previous-mismatch":"The rotation names a previous digest other than the set it replaces, as a rollback to an older set does.","rotation-threshold-unsatisfiable":"The new threshold is more than the number of distinct signers in the new set, so no later rotation could meet it.","rotation-threshold-not-met":"Fewer distinct signers of the set before signed the rotation, in the chant-signers namespace, than that set's threshold.","trust-policy-unreadable":"The trust policy at base can't be read, or its signer history is broken, so no runner key is trusted.","envelope-unreadable":"The --envelope file can't be read, or is not JSON.","envelope-invalid":"The file is not a DSSE envelope: payloadType, payload in canonical base64, and signatures with keyid and sig.","envelope-untrusted":"No signature in the envelope verifies against a runner key the policy at base lists.","evidence-payload-type":"The envelope's payload type is not application/vnd.in-toto+json.","evidence-statement-invalid":"The payload is not an in-toto Statement v1 with chant's runner-evidence predicate, or has a field the predicate does not define.","evidence-runner-mismatch":"The statement names a runner other than the one whose key signed it.","runner-key-invalid":"The key given to evidence sign or runs sign is not an Ed25519 private key in PEM, or the key given to trust runner add is not an ssh-ed25519 public key or an Ed25519 key in PEM.","runner-key-is-signer":"The key given to evidence sign, runs sign or trust runner add is a person's key in the signers file, or trust runner add names a signer. Evidence and run statements are signed by a service or CI identity.","runner-key-unlisted":"The policy at base lists no runner with the key given to evidence sign or runs sign.","lock-invalid":"The lineage lock can't be read.","manual-step-open":"A scope in the lineage lock has an open manual step."},fHe=Object.keys(Cve),_ve=/^plugin:([^:\s]+):([a-z0-9]+(?:-[a-z0-9]+)*)$/});function nZ(e){let t=e.commitJoins,n=e.commitJoinsName;if(t===void 0)return n===void 0?void 0:"commitJoinsName: a kind file with no commitJoins has no findings to name";if(n!==void 0&&(typeof n!="string"||!Ive.test(n)))return"commitJoinsName: a string with no colon or space, the <name> of plugin:<name>:<code>";let i=n===void 0?{}:{name:n};if(typeof t=="function")return{form:"function",join:t,...i};let r=Tve.safeParse(t);return r.success?{form:"data",data:r.data,...i}:r.error.issues.map(o=>`commitJoins${o.path.length?`.${o.path.join(".")}`:""}: ${o.message}`).join("; ")}function pp(e,t){let n=t.toLowerCase(),i=[];for(let[r,o]of Object.entries(e))if(r.toLowerCase()===n)for(let s of o){let a=s.trim();a&&!i.includes(a)&&i.push(a)}return i}function Ka(e,t){return pp(e,t)[0]}function ZD(e,t){let n=t.toLowerCase();return Object.keys(e).some(i=>i.toLowerCase()===n)}function Dve(e,t,n){if(!e)return{};let i=n.read(e.split("{id}").join(t));if(i===void 0)return{};let r;try{r=JSON.parse(i)}catch{throw new Error(`${e.split("{id}").join(t)} is not JSON`)}if(r===null||typeof r!="object"||Array.isArray(r))return{};let{id:o,...s}=r;return s}function jve(e,t,n){let i={},r=(a,c)=>({...Dve(e.records?.[a],c,n),id:c});for(let a of["unit","contract"]){let c=e.trailers[a],l=c?Ka(t.trailers,c):void 0;l&&(i[a]=r(a,l))}let o=e.trailers.evidence?pp(t.trailers,e.trailers.evidence):[];o.length>0&&(i.evidence=o.map(a=>r("evidence",a)));let s=(e.authorship??[]).filter(a=>ZD(t.trailers,a));return s.length>0&&(i.authorship=s),i}function fp(e){let t=e?.decisions;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n!==""):[]}async function ax(e,t,n,i){if(e.form==="data")return jve(e.data,t,n);let r=await e.join(t,n);if(r==null)return{};if(typeof r!="object")throw new Error("commitJoins returned something that is not an object");let o=(l,u)=>{if(l!=null){if(typeof l!="object"||Array.isArray(l)||typeof l.id!="string"||l.id==="")throw new Error(`commitJoins returned a ${u} with no string id`);return l}},s={},a=o(r.unit,"unit"),c=o(r.contract,"contract");if(a&&(s.unit=a),c&&(s.contract=c),r.evidence!==void 0&&r.evidence!==null){let l=Array.isArray(r.evidence)?r.evidence:[r.evidence];s.evidence=l.map(u=>o(u,"evidence")).filter(Boolean)}if(r.authorship!==void 0){if(!Array.isArray(r.authorship)||!r.authorship.every(l=>typeof l=="string"))throw new Error("commitJoins returned authorship that is not a list of trailer keys");s.authorship=r.authorship}if(r.findings!==void 0&&r.findings!==null){if(!Array.isArray(r.findings))throw new Error("commitJoins returned findings that are not a list");s.findings=r.findings.map(l=>{if(l===null||typeof l!="object"||Array.isArray(l))throw new Error("commitJoins returned a finding that is not an object");let{code:u,message:d,refs:p}=l;if(!ox(u,i))throw new Error(`commitJoins returned the finding code ${JSON.stringify(u)}, and a plugin's codes are plugin:${i}:<code>, with <code> in lower case words joined by dashes`);if(typeof d!="string"||d==="")throw new Error(`commitJoins returned the finding ${u} with no message`);if(p!==void 0&&(!Array.isArray(p)||!p.every(f=>typeof f=="string")))throw new Error(`commitJoins returned the finding ${u} with refs that are not a list of strings`);return{code:u,message:d,refs:p??[]}})}return s}var sx,JD,Tve,Ive,Lg=v(()=>{"use strict";$n();KD();sx=m.string().regex(/^[A-Za-z0-9][A-Za-z0-9-]*$/,"a trailer key holds letters, digits and dashes"),JD=m.string().min(1).refine(e=>e.includes("{id}")&&!e.startsWith("/")&&!e.split("/").includes(".."),"a record path is relative to the workspace root and holds {id}"),Tve=m.object({trailers:m.object({unit:sx.optional(),contract:sx.optional(),evidence:sx.optional()}).strict(),records:m.object({unit:JD.optional(),contract:JD.optional(),evidence:JD.optional()}).strict().optional(),authorship:m.array(sx).optional()}).strict(),Ive=/^[^:\s]+$/});function Gg(e){let t=e.indexOf(":");if(t<=0)return;let n=e.slice(0,t).trim(),i=e.slice(t+1).trim();return Fve.test(n)&&Gve.test(i)?{kind:n,id:i}:void 0}function iZ(e){let t=[];for(let r of pp(e,mp)){let o=Gg(r);o&&!t.some(s=>s.kind===o.kind&&s.id===o.id)&&t.push(o)}let n=Ka(e,Nve)??null,i=Ka(e,Mve)??null;return{agent:Ka(e,Mg)??null,lease:Ka(e,Fg)??null,run:Ka(e,rZ)??null,records:t,applied:n===null?null:{by:n,at:Ka(e,Lve)??null,commit:i!==null&&Wve.test(i)?i:null}}}var Mg,Fg,rZ,mp,Nve,Lve,Mve,Fve,Gve,Wve,gp=v(()=>{"use strict";Lg();Mg="Chant-Agent",Fg="Chant-Lease",rZ="Chant-Run",mp="Chant-Record",Nve="Chant-Applied-By",Lve="Chant-Applied-At",Mve="Chant-Applied-Commit",Fve=/^[a-z][a-z0-9-]*$/,Gve=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Wve=/^[0-9a-f]{40,64}$/});import{spawn as Bve}from"node:child_process";import{existsSync as zve,readFileSync as Uve,realpathSync as oZ}from"node:fs";import{join as YD,relative as sZ,resolve as Vve}from"node:path";function qt(e,t){let n=vs(e);if(t!==void 0){if(!n)throw new xe("not-a-git-repository","--at reads git objects, and this directory is not in a git repository");let o=H_(n,t);if(!o)throw new xe("revision-unknown",`--at ${t} names no commit in this repository`);let s=cd(n,o),a=aZ(sZ(n,oZ(Vve(e)))),c=SI(s,a.startsWith("..")?"":a);if(c===void 0)throw new xe("declaration-missing",`no chant.workspace.json or .jsonc between ${a||"."} and the git root at ${o.slice(0,8)}`);return{tree:c===""?s:cd(n,o,c),root:c===""?".":c,rootOnDisk:YD(n,...c.split("/")),at:o,top:n}}let i=tr(e);if(!i)throw new xe("declaration-missing",n?"no chant.workspace.json or .jsonc between this directory and the git root; chant workspace init proposes one":"no chant.workspace.json or .jsonc in this directory; chant workspace init proposes one");let r=n?aZ(sZ(n,oZ(i.dir))):i.dir;return{tree:Rn(i.dir),root:r===""?".":r,rootOnDisk:i.dir,at:null,top:n}}function Hve(e,t){let n=ba(Dd,e);if(!n)return;let i;try{i=JSON.parse(Uve(YD(n,"package.json"),"utf-8"))}catch{return}if(i.version!==t)return;let r=typeof i.bin=="string"?i.bin:i.bin?.chant;if(typeof r!="string")return;let o=YD(n,r);return zve(o)?o:void 0}function qve(e){let t=Id.find(r=>e.tree.stat(r)==="file");if(!t)return;let n;try{n=e.tree.read(t)}catch{return}let i=Ca(n,{jsonc:t.endsWith(".jsonc")});if(!(!i.ok||i.value===null||typeof i.value!="object"||Array.isArray(i.value)))return mk(i.value)?.version}async function cx(e,t,n=process.argv.slice(2)){if(process.env[cZ])return;let i;try{i=qt(e,t)}catch{return}let r=qve(i);if(r===void 0||r===en())return;let o=Hve(i.rootOnDisk,r);if(o)return new Promise(s=>{let a=Bve(o,n,{stdio:"inherit",env:{...process.env,[cZ]:r}});a.on("error",c=>{process.stderr.write(`could not start the root's chant ${r} at ${o}: ${c.message}
158
- `),s(1)}),a.on("close",c=>s(c??1))})}var aZ,cZ,Wr=v(()=>{"use strict";Mi();Tt();Td();qi();on();aZ=e=>e.split("\\").join("/");cZ="CHANT_WORKSPACE_ROOT_CHANT"});var oj={};_e(oj,{AGENT_ENV:()=>QD,AGENT_TRAILER:()=>Mg,FACTORY_CHECK_LOG:()=>bZ,SCOPE_FINDING_CODES:()=>Zve,WRITE_SCOPE_CODES:()=>Za,WriteScopeError:()=>Os,checkWriteScope:()=>Qve,classesOf:()=>kg,declaredSessions:()=>rj,judgePath:()=>vZ,judgeRecord:()=>nj,onlyKeysChanged:()=>wZ,principalClass:()=>mZ,protectedEntry:()=>hZ,refuseRecordWrite:()=>ij,resolveWriter:()=>ej,roleGrants:()=>Hd,scopeOf:()=>dx,scopeSource:()=>to,scopedKind:()=>xZ,unknownClassVerdict:()=>tj});import{execFileSync as Kve}from"node:child_process";import{posix as lZ,relative as uZ,sep as dZ}from"node:path";import{isDeepStrictEqual as Jve}from"node:util";function mZ(e,t,n=Wa()){return e6(e,t,n)}function ej(e,t,n,i=Wa()){let r=n.principal??null,o=e?.agents??[];if(n.agent!==void 0&&n.agent!==null){let s=o.find(a=>a.name===n.agent);if(!s){let a=o.map(c=>c.name).join(", ");throw new Os("agent-unknown",e===null?`agent session ${JSON.stringify(n.agent)} is not declared: there is no workspace declaration`:`agent session ${JSON.stringify(n.agent)} is not declared: the declaration's agents ${a?`are ${a}`:"list none"}`)}return{principal:r,class:"agent",agent:s}}if(r!==null){let s=An(r),a=o.find(c=>c.principals.some(l=>An(l)===s));if(a)return{principal:r,class:"agent",agent:a}}return{principal:r,class:mZ(t,r,i),agent:null}}function tj(e,t,n){if(t.class!=="human")return Ja;let i=YI(e?.writeScope??null,n);if(i.length===0)return Ja;let r=i.map(o=>`writeScope.${o}`).join(", ");return{ok:!1,code:"write-scope-class-unknown",message:`${Cl(t)} may be in ${i.length===1?"a class":"classes"} no pinned package supplies (${r}), so its scope can't be told; install the package that supplies ${i.length===1?"it":"them"} at the pinned version, or remove the entry (known classes: ${n.names().join(", ")})`}}function dx(e,t){let n=e?.writeScope?.[t.class];return t.class==="agent"?{members:null,records:n?.records??null,protected:n?.protected??[],pointer:n?.pointer??"/agents"}:n??null}function Cl(e){if(e.agent){let n=e.agent.members;return`agent session ${e.agent.name}, bound to ${n.length===1?"member":"members"} ${n.join(", ")},`}let t=e.principal!==null?`${e.principal} (${e.class})`:`a ${e.class} writer`;return e.class==="agent"?`${t}, which no agent session lists,`:t}function gZ(e,t,n){return e.class==="agent"?n!==null&&(e.agent?.members.includes(n)??!1):t.members===null||n!==null&&t.members.includes(n)}function nj(e,t,n,i){let r=dx(e,t);if(r===null)return Ja;if(!(n.declared&&n.member===null?!0:gZ(t,r,n.member))){let c=n.member===null?"in no member":`of member ${n.member}`;return{ok:!1,code:"write-scope-member",message:`${Cl(t)} may not write ${n.name} records, which are ${c}: ${t.class==="agent"?"an agent session writes only the members it is bound to":`writeScope.${t.class}.members leaves it out`}`}}if(i==="delete")return{ok:!1,code:"write-scope-kind",message:`${Cl(t)} may not delete a ${n.name} record: a record is never deleted, and a new one supersedes it`};if(r.records===null)return Ja;let a=[n.name,...n.declaredName!==null&&n.declaredName!==n.name?[n.declaredName]:[]].flatMap(c=>r.records[c]??[]);return a.includes(i)?Ja:{ok:!1,code:"write-scope-kind",message:a.length===0?`${Cl(t)} may not write ${n.name} records: writeScope.${t.class}.records does not list the kind`:`${Cl(t)} may ${[...new Set(a)].join(", ")} ${n.name} records, and not ${i} them (writeScope.${t.class}.records)`}}function hZ(e,t){if(e.length===0)return null;let n=t.split("/"),i=n.map((r,o)=>n.slice(0,o+1).join("/"));for(let r of e){let o=(0,fZ.default)(r.path,{dot:!0});if(i.some(s=>o(s)))return r}return null}function yZ(e,t){if(t.length===0||e===null||typeof e!="object")return;let[n,...i]=t,r=e,o=n==="*"?Object.keys(r):Object.prototype.hasOwnProperty.call(r,n)?[n]:[];for(let s of o)i.length>0?yZ(r[s],i):Array.isArray(e)?e[Number(s)]=Yve:delete r[s]}function wZ(e,t,n){if(e===null||t===null||n.length===0)return!1;let i=s=>{let a=Ca(s,{jsonc:!0});if(!a.ok)return null;let c=a.value;if(c===null||typeof c!="object"||Array.isArray(c))return null;let l=structuredClone(c);for(let u of n)u.startsWith("/")?yZ(l,u.slice(1).split("/").map(d=>d.replace(/~1/g,"/").replace(/~0/g,"~"))):delete l[u];return l},r=i(e),o=i(t);return r!==null&&o!==null&&Jve(r,o)}function vZ(e,t,n,i){let r=dx(e,t);if(r===null)return Ja;let o=Fr(n,e?.members??[]);if(!(o===null&&bZ.test(n))&&!gZ(t,r,o)){let l=o===null?"is in no member":`is in member ${o}`;return{ok:!1,code:"write-scope-member",message:`${Cl(t)} may not write ${n}, which ${l}: ${t.class==="agent"?"an agent session writes only the members it is bound to":`writeScope.${t.class}.members leaves it out`}`}}let a=hZ(r.protected,n);if(a===null||a.except.length>0&&i&&wZ(i.before(),i.after(),a.except))return Ja;let c=a.except.length>0?`, outside what its except allows (${a.except.join(", ")})`:"";return{ok:!1,code:"write-scope-protected",message:`${Cl(t)} may not write ${n}${c}: writeScope.${t.class}.protected lists ${a.path}`}}function kZ(e,t){try{let n=qt(e,t);return{declaration:_t(n.tree),rootOnDisk:n.rootOnDisk,root:n.root,tree:n.tree}}catch(n){if(n instanceof xe)return n;throw n}}function XD(e,t){let n=kZ(e,t);return n instanceof xe?null:n}function to(e,t){let n=cr(e),i=n?ti(n,t):null,r=n&&i?$i(n,i):eo(null),o=a=>{let{tree:c,...l}=a;return{...l,classes:t6(a.declaration.pins,a.rootOnDisk,{tree:c}).registry}};if(i?.commit){let a=XD(e,i.commit);if(a)return{...o(a),from:"base",policy:r}}let s=kZ(e);return s instanceof xe?{declaration:null,from:null,rootOnDisk:null,root:null,policy:r,classes:Wa(),failure:s}:{...o(s),from:"working-tree",policy:r}}function xZ(e,t,n,i){let r=e.declaration;if(!r||e.rootOnDisk===null)return{name:t,declaredName:null,member:null,declared:!1};let o=pZ(uZ(e.rootOnDisk,n)),s=[...r.records,...r.members.flatMap(c=>c.records)].find(c=>c.path===o);if(s)return{name:t,declaredName:s.name,member:s.member,declared:!0};let a=pZ(uZ(e.rootOnDisk,i));return{name:t,declaredName:null,member:a.startsWith("..")?null:Fr(a===""?".":a,r.members),declared:!1}}function rj(e){let t=cr(e),n=t?ti(t):null;if(n?.commit){let r=XD(e,n.commit);if(r)return{agents:r.declaration.agents,from:"base"}}let i=XD(e);return i?{agents:i.declaration.agents,from:"working-tree"}:null}function ij(e,t){let n=to(e);if(n.declaration===null&&(t.agent===void 0||t.agent===null))return n;let i=ej(n.declaration,n.policy,{agent:t.agent,principal:t.principal},n.classes),r=tj(n.declaration,i,n.classes);if(!r.ok)throw new Os(r.code,r.message);let o=nj(n.declaration,i,xZ(n,t.kindName,t.kindFile,t.recordsDir),t.verb);if(!o.ok)throw new Os(o.code,o.message);return n}function lx(e,t){return Kve("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],maxBuffer:512*1024*1024})}function ux(e,t,n){try{return lx(e,["show",`${t}:${n}`])}catch{return null}}function Xve(e,t,n,i){if(i.format!=="markdown-front-matter")return"amend";let r=ux(e,`${t}^`,n),o=ux(e,t,n);if(r===null||o===null)return"amend";let s=Ss(r),a=Ss(o);if(!s.ok||!a.ok)return"amend";let l=[...new Set([...Object.keys(s.value),...Object.keys(a.value)])].filter(u=>JSON.stringify(s.value[u])!==JSON.stringify(a.value[u]));if(i.session){let u=a.value[i.session.stateField];return typeof u=="string"&&i.session.closed.includes(u)&&s.value[i.session.stateField]!==u?"close":l.every(d=>i.reviewFields.includes(d)||i.session.fills.includes(d))?"review":"amend"}return l.length>0&&l.every(u=>i.reviewFields.includes(u))?"review":"amend"}async function Qve(e){let{top:t,base:n,head:i,prefix:r,declaration:o}=e,s=e.classes??Wa();if(o.writeScope===null&&o.agents.length===0)return null;let a=$i(t,{commit:n,from:"flag"}),{activeAttestors:c}=await Promise.resolve().then(()=>(lp(),BJ)),l=await c(),u=g=>o.writeScope?.[g]!==void 0||g==="agent"&&o.agents.length>0,d=[...s.names().filter(u),...YI(o.writeScope,s)],p={base:n,restricted:d,agents:o.agents.map(g=>g.name),commits:[],findings:[]},f=lx(t,["rev-list","--reverse","--no-merges",`${n}..${i}`]).split(`
157
+ `))a.startsWith("\0")?s=a.slice(1).trim():a&&o.has(a)&&!i.has(a)&&i.set(a,s);return i}function Pve(e,t){if(t.length===0)return new Set;let n=qD(e,["--literal-pathspecs","status","--porcelain=v1","-z","--untracked-files=all","--",...t]),i=new Set,r=n.split("\0");for(let o=0;o<r.length;o++){let s=r[o];s.length<4||(i.add(s.slice(3)),(s[0]==="R"||s[0]==="C")&&o++)}return i}function XJ(e,t,n){try{return eZ("git",["merge-base","--is-ancestor",t,n],{cwd:e,stdio:"ignore"}),!0}catch{return!1}}function QJ(e,t,n){return t.adopted.some(i=>XJ(e,n,i.to)&&(i.from===void 0||!XJ(e,n,i.from)))}function Ng(e,t,n,i){let r=t;if(t.signersAt){let s=t.signersAt(n);if(r={...t,signers:s?.signers??[]},!s||s.version===0){let a="no signer set was in effect where this commit entered the base's history";return QJ(e,t,n)?{level:"adopted",commit:n,reason:`in a commit range the policy at base adopts; ${a}`}:{level:"unattested",commit:n,reason:a}}}let o=tx({repo:e,policy:r},n,i);return o.level==="unattested"&&QJ(e,t,n)?{level:"adopted",commit:n,attestor:o.attestor,reason:`in a commit range the policy at base adopts; ${o.reason}`}:{level:o.level,commit:n,attestor:o.attestor,...o.principal?{principal:o.principal}:{},...o.key?{key:o.key}:{},reason:o.reason}}function tZ(e){let t=new Map,n=o=>{for(let s of e.paths)t.set(s,{level:"unattested",commit:null,reason:o});return t};if(!e.repo)return n("not in a git repository");if(e.policy.problems.length>0)return n(e.policy.problems.join("; "));if(!e.policy.active)return n(`no signers file (${e.policy.signersPath}) at base ${e.policy.base?.slice(0,8)}; attestation is off`);let i=e.at===null?Pve(e.repo,e.paths):new Set,r=Ave(e.repo,e.at??"HEAD",e.paths.filter(o=>!i.has(o)));for(let o of e.paths){if(i.has(o)){t.set(o,{level:"unattested",commit:null,reason:"the working tree has uncommitted changes to this file"});continue}let s=r.get(o);if(!s){t.set(o,{level:"unattested",commit:null,reason:"no commit holds this file"});continue}let a=Ng(e.repo,e.policy,s,e.attestors);t.set(o,e.revisit?.(o,a)??a)}return t}var Pl=v(()=>{"use strict";Qi();lp();Go();ZJ()});function ox(e,t){if(typeof e!="string")return!1;let n=e.match(_ve);return!!n&&(t===void 0||n[1]===t)}var Cve,fHe,_ve,KD=v(()=>{"use strict";Cve={"declaration-missing":"No chant.workspace.json or .jsonc between the directory and the git root.","declaration-ambiguous":"Both chant.workspace.json and chant.workspace.jsonc exist.","declaration-unparseable":"The declaration is not valid JSON, or not valid JSONC for .jsonc.","declaration-invalid":"The declaration does not match its schema, repeats a name, or --member names no entry.","placement-invalid":"A member or group match breaks a placement rule.","reader-too-old":"The declaration's minReader is newer than the chant reading it.","root-chant-required":"The declaration pins a chant version other than the reader's, and that chant is not installed at the workspace root.","not-a-git-repository":"--at, or a ledger read, needs a git repository and there is none.","revision-unknown":"--at names no commit.","live-at-revision":"graph was given --live and --at: a live read is of the account now, not of a revision.","environment-invalid":"An environment name that can't name a ledger directory.","dir-missing":"The member's directory does not exist.","unknown-kind":"No built-in kind or pinned package supplies the member's kind.","kind-probe-failed":"The member's directory is not what its kind reads.","no-matches":"An example group matches no directory holding a chant project.","kind-not-run":"The member's kind is one the per-member commands don't run, such as other.","command-failed":"The member's own command exited with a failure, or the lexicon that reads the member through its kind's graph block isn't installed where the workspace resolves its pin.","output-unreadable":"The member's command printed something that isn't the document asked for.","ir-version-unsupported":"The member's IR has a version this chant can't read.","ledger-unreadable":"Reading the ledger failed, so nothing from it is listed.","ledger-malformed":"Some lines of the ledger aren't release records; the rest are listed.","gates-no-ledger":"The checkout has no chant/lifecycle branch, so there is no gate ledger to read.","gates-no-gate-ledger":"The branch has no gate ledger for the member: no run of it has reached a gate.","gates-ledger-unreadable":"Reading the member's gate ledger failed, so no gate is listed.","stewards-unreadable":"An *.op.ts file could not be imported, so a steward it declares may be missing.","stewards-conflict":"A steward was dropped: its name, or an Op it lists, belongs to another steward.","steward-runs-unreadable":"Reading an Op's run ledger, or a ConvergeOp's converge ledger, failed, so its last run or last tick is null.","record-unparseable":"No front matter, a YAML error or a value outside the JSON subset of YAML, or for a JSON kind a file that is not one object or repeats a member name.","record-schema-invalid":"The record's front matter, or its JSON object, does not match the kind's schema.","record-id-duplicate":"Another record earlier in path order has the same id.","record-supersedes-unknown":"A supersedes link names an id no record has.","record-supersedes-conflict":"A second closed record supersedes a record another one already superseded.","record-remediates-unknown":"A remediates link names an id no record has.","record-remediates-not-closed":"A remediates link names a record that isn't closed; a record still open is amended instead.","record-seal-mismatch":"A closed record's seal is not the whole-file seal of its text now: the record changed after it closed.","session-seal-mismatch":"A closed session's seal is not the whole-file seal of its text now: the session changed after it closed, or was sealed by the rule before #2546.","session-verdict-unknown-record":"A session's verdict names a record that none of the session kind's subject records has.","asset-drift":"A file the record pins by hash has changed: its bytes no longer hash to the pinned sha256.","asset-missing":"A file the record pins by hash does not exist in the tree read.","asset-stale":"A file the record pins is unchanged at the hash a record it supersedes pinned: the decision changed and the artifact did not follow.","record-supersedes-pending":"A supersedes link from a record whose state is weaker than the record it names, so the link has no effect yet.","record-no-evidence":"The record's evidence list is empty: it cites nothing and pins no file. Information for a reviewer, never an error.","review-undigested":"A verdict names no digest of the text it judged. It still counts, and an amendment does not stop it counting.","source-transcript-drift":"The record's source block pins a transcript by hash, the file it names can be read here, and its bytes hash to something else: it is not the transcript the record means.","work-needs-unknown":"A work record's needs list names a work id no record has, so the item stays blocked.","work-implements-unknown":"A work record's implements list names a decision id no decision has.","work-needs-cycle":"A work record needs itself through its needs links, so it can never be ready.","work-implements-undecided":"A work record implements a decision whose state is not approved, such as proposed.","work-done-unpinned":"A work record is done and its evidence list is empty: nothing shows the work was done.","work-closed-without-date":"A work record is done or dropped and has no closing date.","work-done-gap-open":"A work record is done, and the finding it came from still fires on its region. graph --intent raises it, and records does by walking that region.","work-acceptance-unmet":"A work record is done, and one of its acceptance criteria has no passing evidence of the verification it expects. check fails on it (WSP117).","work-acceptance-self-verified":"A passing manual verdict on a work record's criterion names the record's implementer, so it does not count: a manual verdict comes from someone else.","work-contract-unknown":"A work record names a contract that no record of its kind's contract kind has.","work-contract-undecided":"A work record names a contract whose state is not approved, such as a draft.","work-tier-unknown":"A work record names a builder tier that its kind's work.tier.tiers does not list.","flag-work-unknown":"A flag record names a work item that no record of its kind's work kind has.","flag-stale":"Every decision a flag's work item implements is confirmed, so the flag is due for removal. check reports it (WSP118).","answer-points-unreadable":"The points file the answer kind names can't be read, or is not valid.","answer-point-unknown":"The answer's point is not declared in the points file the answer kind names.","answer-point-changed":"The point's declaration changed since the question was asked, so the answer is to an older version of the question.","review-decider":"The verdict is the decider's own, and the quorum counts verdicts besides the decider's.","review-agent":"The reviewer holds the agent role in the trust policy at base.","review-duplicate":"A later verdict by the same principal replaces this one. Names are compared after NFKC, trimming and lower-casing.","review-older-digest":"The verdict names a digest other than the record's text now: the record changed after the verdict.","review-unattested":"An attestation policy is active at base, and the verdict carries no seal that verifies for its reviewer.","seal-missing":"The verdict, or the record, carries no seal.","seal-signer-unlisted":"The reviewer, or the record's author, has no key in the signers file at base, so the seal can't count.","seal-signature-invalid":"The seal is malformed, names a signer other than the reviewer or author, or its signature does not verify over the verdict or record.","seal-unverifiable":"Nothing here can say whose seal it is: there is no signers file at base, ssh-keygen is not installed, or the record came back in a return sealed by a signer no admission lists yet.","record-unattested":"A signers file is active at base, and the record names an author whose seal does not verify: it has none, the author has no key in the file, or the signature fails.","record-ratified-below-quorum":"The record is in its kind's ratified state (reviews.ratified), and its quorum is not met: it was written to that state by hand, past the check of records new and amend. It is still read, and stays valid.","kind-unreadable":"The record kind file is missing or could not be imported.","kind-invalid":"The record kind file exports no recordKind, or its shape is wrong.","schema-unreadable":"The schema file the record kind names is missing or is not JSON.","schema-id-mismatch":"The schema's $id differs from the id the record kind names.","schema-invalid":"The record schema itself does not compile.","location-missing":"The records directory does not exist, in the tree or at the revision.","write-usage-invalid":"The command line lacks a value the write needs, or gives one it does not take.","write-input-invalid":"The fields given with --from or --set can't be read, are not JSON, or are not a JSON object.","record-not-found":"No record of the kind has the id given.","record-id-taken":"The id given for a new record is already used, by a record or a file name.","record-id-unallocatable":"No id was given and none can be allocated: the records share no single prefix and --prefix names none.","record-path-unmatched":"The file name made from the record's id and title does not match the kind's location.","record-closed":"The record is in a closed state, so nothing in it changes; a new record supersedes it instead.","amend-id-immutable":"An amendment changes the record's id, and ids are never renumbered.","amend-supersede-instead":"The record is approved, and the amendment changes a field the approval rule does not let change in place; a new record supersedes it instead.","review-unsupported":"The kind's schema has no reviews field, so its records take no review.","review-note-required":"A dissent was given with no note: a dissent needs a reason.","review-sign-failed":"--sign was given and no seal could be made: the key can't be read or used, git names no ssh signing key, or ssh-keygen is not installed.","record-state-not-initial":"A record written through chant serve mcp gives a state other than the kind's first: a new record opens proposed, and a person moves it on.","source-harvest-not-proposed":"A harvested record (source.via harvest) was written in a state other than the kind's first: a harvest proposes, and a person decides.","ratify-quorum-not-met":"The write puts a record in its kind's ratified state (reviews.ratified), and the record's quorum is not met: too few agreeing verdicts count.","record-sign-failed":"--sign was given and no author seal could be made: the record names no author, the key can't be read or used, git names no ssh signing key, or ssh-keygen is not installed.","record-conflict":"--expect named a digest the record no longer has: another write changed it after the caller read it. The refusal names the digest it has now; re-read the record and write again.","write-lock-timeout":"Another write held the working tree's write lock for longer than the write waits (CHANT_WRITE_LOCK_WAIT_MS); the refusal names the holder. Run the write again.","write-lock-not-held":"CHANT_WRITE_LOCK names a batch's lock token that no longer holds the working tree's write lock: the batch released it, or it expired and another writer took it.","write-scope-member":"The write is to a file, or to a record kind, of a member outside the writer's scope: an agent session writes only the members it is bound to, and writeScope.<class>.members leaves the member out.","write-scope-kind":"The write is to a record kind writeScope.<class>.records does not list, with a verb it does not list for the kind, or deletes a record.","write-scope-protected":"The write is to a file writeScope.<class>.protected lists, or one under a directory it lists, outside the top-level keys or JSON Pointers the entry's except allows (#3146, #3308).","write-scope-class-unknown":"The declaration's writeScope at base names a principal class no pinned package supplies, and the writer is judged human, so it may be in that class; the write is refused until the package is installed at the pinned version or the entry removed (#3080).","agent-unknown":"CHANT_AGENT, or a commit's Chant-Agent trailer, names an agent session the declaration at base does not declare.","principal-unidentified":"chant.workspace.json at base sets identity.attribution to identified, and the write names a person by a bare name: --by, an author field or a decision point's answerer must be a forge identity (github:<login>, gitlab:<login>, <forge>@<host>:<login>), a principal the signers file at base lists, or an agent, runner or service principal (#3163).","session-unknown":"--session names no session of a session kind whose subjects are the record's kind.","session-not-open":"--session names a session in a closed state, which takes no more verdicts.","points-undeclared":"No record kind with an answers block is declared, or given with --kind, so there is no points file to ask.","points-invalid":"The points file an answer kind names can't be read, or does not match decision-points.schema.json and the rules checked in code.","point-unknown":"No points file declares the point asked, or the one an answer names.","point-inputs-invalid":"The inputs given to an ask are not a JSON object of the point's declared inputs.","point-decider-failed":"A model decider that fails closed (unreachable: fail) could not answer, so the ask wrote nothing.","answer-not-candidate":"The people's answer is not one of the question's candidates.","quorum-not-met":"Too few of the people who answered count toward the point's quorum: distinct, not holding the agent role, not the steward that asked, and holding one of its roles when it names any. Nobody named over MCP or ACP counts (#3817).","answer-in-steward-turn":"The answer was given during a steward's turn, or by a process it started: a steward never answers a decision point, and a person answers it through hud or at a shell.","answer-never-over-mcp":"The answer or retraction came over MCP or ACP, or from a process a session on one started, and the question constrains a gate that is never resolved there: a person answers it at a shell or through hud (#3817).","answer-not-answered":"points retract names a question that has no answer to retract: it is escalated or proposed, and people answer it instead (#3351).","answer-field-unsupported":"The answer kind's copy of point-answer.schema.json predates a field the write needs, a note, a relay, a retraction, an ad-hoc question's asked or a withdrawal: copy the schema anew to turn it on (#3351, #3402, #3403, #2888).","point-candidates-invalid":"points ask names an ad-hoc point without --candidates, a declared point with them, or candidates that are not a question and criteria of the point's question type (#3403).","since-rev-unknown":"--since names no commit, or a session with no opening revision and no commit that added it.","since-session-unknown":"--since has the shape of a session id and names no commit, and no session the kind or the declaration reads has that id.","since-session-open":"--since names a session that is still open, so the comparison runs to the working tree.","intent-region-invalid":"The region's path, or its line range, does not exist in the tree read.","intent-record-unknown":"graph --intent --record names an id that no record of a decision kind read has.","intent-symbol-unsupported":"The region names a symbol, path#symbol, in a file no symbol resolver reads; a line range still works.","intent-symbol-unknown":"The region names a symbol the file does not declare in the tree read.","intent-symbol-ambiguous":"The region names a symbol that matches more than one declaration in the file; its qualified name picks one.","intent-history-shallow":"The repository is a shallow clone, so the region's history stops at the clone's boundary.","intent-plugin-failed":"A kind file's commitJoins, which joins commits to units, contracts and evidence, failed for a commit.","squash-unfollowed":"A squash commit's pull request ref (refs/pull/<n>/head) is not in the clone and could not be fetched from origin, so its original commits are not followed; the read keeps its answer without them.","intent-commit-undecided":"A commit changed the region when no decision constrained it at path granularity.","intent-commit-bare":"A commit names no unit, carries no record through its Chant-Record or Chant-Lease trailer, and has no pull request and no decision covering the region at its time.","intent-pin-drifted":"A decision's pinned artifact no longer hashes to the pin.","intent-pin-missing":"A decision's pinned artifact does not exist in the tree read.","intent-pin-stale":"A current decision pins an artifact at the hash a record it supersedes pinned, and the artifact has not changed since: the decision moved on and the artifact did not.","intent-artifact-unpinned":"An artifact decisions in the graph pinned, which no current decision pins.","intent-decision-superseded-live":"Every decision constraining the region is superseded.","intent-decision-provisional":"The current decisions constraining the region are all in states their kind does not close, such as decided.","intent-decision-contested":"A current decision constraining the region has an open concern: a dissent neither addressed nor withdrawn.","intent-constraint-coarse":"The region is constrained only through its member, not by path.","intent-constraint-lost":"A decision's path constraint names a path that does not exist in the tree read.","intent-evidence-unpinned":"A decision's evidence has no hash: a URL, or a path with no sha256.","intent-trailer-unverified":"A commit carries a trailer a plugin says claims authorship, and the commit is not attested.","intent-region-unconstrained":"No decision constrains the region at any granularity.","intent-decision-unimplemented":"A decided decision constrains the region, no work item that is not dropped implements it, and no commit falls in its window.","intent-work-blocked":"A work item constraining the region has commits in its window while a work item it needs is not done.","intent-work-open-decided-code":"Commits in the region are a decision's own work while the work item implementing that decision is still open.","intent-commit-join-conflict":"A commit joined to an agent run by its Chant-Run trailer or the run's record has the patch-id of a commit another run recorded, so it is not joined to that run by content.","intent-why-no-decision":"No current decision governs the region at any granularity, and none is carried out by the commits or runs that made its current lines.","intent-why-no-run":"None of the region's current lines was made by a commit an agent run is joined to.","intent-why-uncommitted":"Some of the region's lines are not committed yet.","intent-why-run-ambiguous":"Some lines come from a commit several agent runs made, and no run's recorded hunks say which wrote them.","change-uncovered":"A path the diff changes is covered by no current decided record and no open work item, by path or by its member.","change-out-of-scope":"A record in hand for the change, such as the work item it is for or a decision that item implements, lists a path the diff changes in its out_of_scope.","commit-unlinked":"A trunk commit in the range names no work item: it has no Chant-Record trailer of a work kind and no Chant-Lease trailer.","commit-wrongly-linked":"A trunk commit in the range names a work item that is not there: a Chant-Record whose id no work kind has or whose kind is not a work kind, a malformed Chant-Record, or a Chant-Lease that resolves to no work item, and no other trailer links it.","patch-path-invalid":"workspace patch --path names a path that is not relative and inside the workspace.","composites-no-chant-member":"No member of kind chant was read, so nothing declares a composite instance or a component.","composites-none-declared":"The members read declare no composite instance.","composites-no-component":"The members read declare no component, so no composite instance has one.","runtimes-config-unreadable":"The member's chant.config.ts could not be read, so only the built-in local runtime is listed, and no environment from the config.","runtimes-lexicon-unreadable":"A lexicon the member's config lists could not be loaded, so it is not listed as a runtime.","environments-none-declared":"The member's chant.config.ts declares no environments, so only local and the environments in its ledger are listed.","environments-ledger-undeclared":"The member's ledger has releases in an environment its config's environments don't cover, so chant run --env would refuse it and it is not listed.","environments-ledger-unreadable":"The chant/lifecycle branch exists and the member's ledger environments could not be listed.","environments-component-undeclared":"A component declares an environment its member's chant.config.ts environments don't cover, so chant run --env would refuse it and it is not listed (#3153).","diagram-source-missing":"A declared diagram's source file does not exist in the tree read.","diagram-render-missing":"A declared diagram's render file does not exist in the tree read.","diagram-render-drift":"A declared diagram records a sourceHash, and the source's bytes now hash to something else: the render is stale for its source.","security-signers-missing":"The workspace opts into verified-releases, and there is no .chant/allowed_signers to verify a release's signature against.","security-release-gate-missing":"Under verified-releases, identity.gates has no release entry, or it names no class, so a cut is not held to a class of signers.","security-publish-allows-unsigned":"Under verified-releases, a pipeline file runs release publish with --allow-unsigned.","security-sbom-disabled":"Under supply-chain, a member's chant.config.ts sets sbom: false on a publish target.","security-sbom-unsourced":"Under supply-chain, a member publishes, names no sbom file and has no package-lock.json, pom.xml or Cargo.lock to write one from.","security-publish-no-provenance":"Under supply-chain, a pipeline file runs release publish without --require-provenance.","security-component-no-sbom":"Under supply-chain, a member's components have no generate-sbom step.","security-component-no-verify":"Under supply-chain, a member's components have no verify step.","security-signed-since-unset":"Under who-ran-it, ci.green sets no signedSince, or there is no ci.green block.","security-runner-untrusted":"Under who-ran-it, .chant/trust.json lists no runner key.","security-tick-no-key":"Under who-ran-it, a pipeline file runs ci tick with no runner key.","security-review-not-required":"Under review-rules, an apply job passes --no-require-review, which the group overrides.","security-attribution-any":"Under review-rules, identity.attribution is not identified.","security-gate-unsigned":"Under review-rules, an apply job names a gate identity.gates does not list, or identity.gates lists none.","security-runner-start-no-key":"Under isolated-runners, .chant/trust.json lists no key under runners for a provisioner to sign runner-start statements with.","security-runner-start-no-role":"Under isolated-runners, no principal under runners in .chant/trust.json holds the runner role.","security-trust-unreadable":"Under isolated-runners, .chant/trust.json can't be read, so no runner-start statement can be checked.","ci-workflow-green-undeclared":"Under ci.workflow, the declaration has no ci.green block, so no commit gets a verdict and no release can be cut.","ci-workflow-no-pre-merge":"Under ci.workflow, ci.green.preMerge names no phase, so nothing says which checks run before the branch moves.","ci-workflow-apply-in-green":"Under ci.workflow, a phase in ci.green.require matches an apply job, which would wait on its own verdict.","ci-workflow-no-components":"Under ci.workflow, a member declares no component, so nothing of it can be cut or promoted.","ci-workflow-no-environments":"Under ci.workflow, a member's chant.config.ts declares no environments, so a release has nowhere to be promoted to.","ci-workflow-ungated-env":"Under ci.workflow, a component has no gate, so a promote to the last environment waits on no approval.","ci-workflow-pipeline-missing":"Under ci.workflow, no pipeline file runs the plan job, the merge job or chant ci tick.","ci-workflow-pipeline-differs":"Under ci.workflow, the merge job does not match the workflow: it applies under trunk-curated, or records under trunk-curated+apply-on-merge.","ci-workflow-publish-missing":"Under ci.workflow, no pipeline file runs chant release publish.","box-credential-declared":"A file in a box member's directory carries a literal secret: a credential's shape, or a literal where a credential goes. A variable or secret-manager reference is not one.","box-capability-unbrokered":"A capability in a member's box block names no broker, so the box would hold its credential.","box-fountain-callback-undeclared":"A box member builds a fountain Box, whose sandbox fountain gives a callback token scoped to its owner, and the member's box block does not declare the fountain-callback capability brokered by fountain with scope owner.","box-intent-unknown":"A box block names an intent, and no record of a declared kind named decision has that id.","box-intent-unconstrained":"The decision record a box names as its intent constrains no member or path of this workspace: no member: entry for a declared member and no path: entry at, above or inside one's directory.","box-none":"No member's box block declares services, so the workspace has no box for a host to plant.","box-several":"More than one member's box block declares services, and a planted workspace runs one box.","work-kind-missing":"No work kind to find the item in: --kind names a kind with no work block, or the declaration names no work kind.","work-kind-ambiguous":"More than one declared work kind has a record with the id, so --kind must name one.","work-item-unknown":"No work record has the id, so there is nothing to lease.","work-item-closed":"A claim on a work item in a closed state, such as done or dropped: there is no work left to claim.","work-criterion-unknown":"The work record lists no acceptance criterion with the id the evidence names, or its kind has no acceptance criteria.","lease-held":"Someone holds a live lease on the work item: another worker, or, for a claim, the same one.","lease-not-held":"Nobody holds a live lease on the work item: it expired, was released or was never claimed.","lease-token-mismatch":"The live lease on the work item carries another fencing token than the one given.","lease-race":"Another writer changed the lease between this command's read and its write.","lease-push-rejected":"The remote refused the lease push: another clone claimed the item first, or the remote could not be reached.","run-exists":"runs start or runs record was given a run id the ledger already has.","run-unknown":"runs end names a run the ledger has no start for.","run-ended":"runs end names a run whose end is already recorded.","runs-no-ledger":"The checkout has no chant/lifecycle branch, so there are no agent runs to read.","runs-ledger-malformed":"Some lines of the agent run ledger aren't run events; the rest are read.","run-not-ended":"runs sign or runs statement names a run with no end recorded. A statement is signed over the run's whole record.","run-statement-invalid":"The envelope's payload is not an in-toto Statement v1 with chant's agent-run predicate, or has a field the predicate does not define.","run-statement-signer-mismatch":"The statement names a signer other than the runner whose key signed it.","run-statement-mismatch":"A listed runner key signed the statement, and it does not match the run's record: another run, a record that hashes differently, or another unit, harness, model, provider or principal.","listing-member-unknown":"box listing set names a member the declaration does not declare.","listing-box-missing":"box listing set names a member whose entry declares no box block, so it has no listing.","listing-cover-invalid":"The cover can't be read, is not a PNG, JPEG or WebP picture, is larger than 5 MiB, has a path outside the workspace, or has an extension other than its picture format's.","member-exists":"member add names a member the declaration already has, with an entry other than the one given.","member-unknown":"member remove names a member the declaration does not declare.","trust-config-invalid":".chant/trust.json in the working tree is not JSON or does not match its schema, or the write would make it so.","trust-conflict":"--expect named a digest .chant/trust.json no longer has: another write changed it after the caller read it. The refusal names the digest it has now.","runner-exists":"trust runner add names a principal .chant/trust.json already lists with another key or class, or gives a key it lists for another principal.","runner-unknown":"trust runner remove names a principal .chant/trust.json lists no runner for.","factory-member-unknown":"box factory set names a member the declaration does not declare.","factory-box-missing":"box factory set names a member whose entry declares no box block, so it has no factory.","publish-member-unknown":"box publish names a member the declaration does not declare.","publish-none":"box publish names a member whose box block names no publisher, or which declares no box block.","publish-refused":"The box's publisher refused (it exited 2): nothing was published, and its message says why.","publish-failed":"The box's publisher could not be run, failed (a nonzero exit other than 2) or ran out of time; its message says what it had done.","publish-answer-invalid":"The box's publisher exited 0 and printed no JSON object, or one box-publish.schema.json does not allow.","publish-unrecorded":"The commit the publisher named is not in the repository, or lacks the apply record of ws-075: Chant-Applied-By naming --by, Chant-Applied-At, Chant-Applied-Commit and a Chant-Record for the item, or a Chant-Record for each record sent.","wip-no-branch":"HEAD is detached, or names a branch with no commit yet, so there is no branch to keep work in progress for.","wip-none":"wip restore was given no snapshot, and the branch has none under refs/chant/wip/<branch>.","wip-snapshot-unknown":"wip restore names something that is not a work-in-progress snapshot chant took.","wip-branch-other":"wip restore names a snapshot taken on another branch than the one checked out.","wip-race":"Another writer moved refs/chant/wip/<branch> between this command's read and its write.","wip-policy-none":"wip push or wip fetch was run, and no box block declares replicate, so there is no remote.","wip-remote-unknown":"The replicate policy names a git remote the checkout does not have; the host adds it, with its credential, before chant pushes.","ci-green-undeclared":"The declaration has no ci.green block, so chant does not know which check runs make a commit green.","ci-branch-unknown":"The checkout has no ref for the branch ci.green names: neither the remote-tracking branch nor a local one.","box-isolation-collision":"Two boxes on one host resolve to the same port, state path or cookie name, or two ports in one box share an offset.","box-isolation-literal":"A host's stateRoot or a box's state entry is a literal machine path instead of one derived from an environment reference and the box's name.","signers-file-missing":"There is no signers file at the base revision, so there is no signer history to read.","signers-removed":"The signers file was removed. Commits merged before the removal keep the set they were judged by; nothing after it verifies.","rotation-unparseable":"The rotation file beside the signers file is not JSON.","rotation-invalid":"The rotation file does not match its shape: schema 1, a version, the previous set's digest, a threshold and signatures.","rotation-first-version":"The first signer set's rotation file names a version other than 1, or a previous digest.","rotation-missing":"The signer set or its threshold changed and no rotation file signed by the set before it came with the change.","rotation-version-skew":"The rotation names a version other than the one after the set it replaces, as a replayed or skipped rotation does.","rotation-previous-mismatch":"The rotation names a previous digest other than the set it replaces, as a rollback to an older set does.","rotation-threshold-unsatisfiable":"The new threshold is more than the number of distinct signers in the new set, so no later rotation could meet it.","rotation-threshold-not-met":"Fewer distinct signers of the set before signed the rotation, in the chant-signers namespace, than that set's threshold.","trust-policy-unreadable":"The trust policy at base can't be read, or its signer history is broken, so no runner key is trusted.","envelope-unreadable":"The --envelope file can't be read, or is not JSON.","envelope-invalid":"The file is not a DSSE envelope: payloadType, payload in canonical base64, and signatures with keyid and sig.","envelope-untrusted":"No signature in the envelope verifies against a runner key the policy at base lists.","evidence-payload-type":"The envelope's payload type is not application/vnd.in-toto+json.","evidence-statement-invalid":"The payload is not an in-toto Statement v1 with chant's runner-evidence predicate, or has a field the predicate does not define.","evidence-runner-mismatch":"The statement names a runner other than the one whose key signed it.","runner-key-invalid":"The key given to evidence sign or runs sign is not an Ed25519 private key in PEM, or the key given to trust runner add is not an ssh-ed25519 public key or an Ed25519 key in PEM.","runner-key-is-signer":"The key given to evidence sign, runs sign or trust runner add is a person's key in the signers file, or trust runner add names a signer. Evidence and run statements are signed by a service or CI identity.","runner-key-unlisted":"The policy at base lists no runner with the key given to evidence sign or runs sign.","lock-invalid":"The lineage lock can't be read.","manual-step-open":"A scope in the lineage lock has an open manual step."},fHe=Object.keys(Cve),_ve=/^plugin:([^:\s]+):([a-z0-9]+(?:-[a-z0-9]+)*)$/});function nZ(e){let t=e.commitJoins,n=e.commitJoinsName;if(t===void 0)return n===void 0?void 0:"commitJoinsName: a kind file with no commitJoins has no findings to name";if(n!==void 0&&(typeof n!="string"||!Ive.test(n)))return"commitJoinsName: a string with no colon or space, the <name> of plugin:<name>:<code>";let i=n===void 0?{}:{name:n};if(typeof t=="function")return{form:"function",join:t,...i};let r=Tve.safeParse(t);return r.success?{form:"data",data:r.data,...i}:r.error.issues.map(o=>`commitJoins${o.path.length?`.${o.path.join(".")}`:""}: ${o.message}`).join("; ")}function pp(e,t){let n=t.toLowerCase(),i=[];for(let[r,o]of Object.entries(e))if(r.toLowerCase()===n)for(let s of o){let a=s.trim();a&&!i.includes(a)&&i.push(a)}return i}function Ka(e,t){return pp(e,t)[0]}function ZD(e,t){let n=t.toLowerCase();return Object.keys(e).some(i=>i.toLowerCase()===n)}function Dve(e,t,n){if(!e)return{};let i=n.read(e.split("{id}").join(t));if(i===void 0)return{};let r;try{r=JSON.parse(i)}catch{throw new Error(`${e.split("{id}").join(t)} is not JSON`)}if(r===null||typeof r!="object"||Array.isArray(r))return{};let{id:o,...s}=r;return s}function jve(e,t,n){let i={},r=(a,c)=>({...Dve(e.records?.[a],c,n),id:c});for(let a of["unit","contract"]){let c=e.trailers[a],l=c?Ka(t.trailers,c):void 0;l&&(i[a]=r(a,l))}let o=e.trailers.evidence?pp(t.trailers,e.trailers.evidence):[];o.length>0&&(i.evidence=o.map(a=>r("evidence",a)));let s=(e.authorship??[]).filter(a=>ZD(t.trailers,a));return s.length>0&&(i.authorship=s),i}function fp(e){let t=e?.decisions;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n!==""):[]}async function ax(e,t,n,i){if(e.form==="data")return jve(e.data,t,n);let r=await e.join(t,n);if(r==null)return{};if(typeof r!="object")throw new Error("commitJoins returned something that is not an object");let o=(l,u)=>{if(l!=null){if(typeof l!="object"||Array.isArray(l)||typeof l.id!="string"||l.id==="")throw new Error(`commitJoins returned a ${u} with no string id`);return l}},s={},a=o(r.unit,"unit"),c=o(r.contract,"contract");if(a&&(s.unit=a),c&&(s.contract=c),r.evidence!==void 0&&r.evidence!==null){let l=Array.isArray(r.evidence)?r.evidence:[r.evidence];s.evidence=l.map(u=>o(u,"evidence")).filter(Boolean)}if(r.authorship!==void 0){if(!Array.isArray(r.authorship)||!r.authorship.every(l=>typeof l=="string"))throw new Error("commitJoins returned authorship that is not a list of trailer keys");s.authorship=r.authorship}if(r.findings!==void 0&&r.findings!==null){if(!Array.isArray(r.findings))throw new Error("commitJoins returned findings that are not a list");s.findings=r.findings.map(l=>{if(l===null||typeof l!="object"||Array.isArray(l))throw new Error("commitJoins returned a finding that is not an object");let{code:u,message:d,refs:p}=l;if(!ox(u,i))throw new Error(`commitJoins returned the finding code ${JSON.stringify(u)}, and a plugin's codes are plugin:${i}:<code>, with <code> in lower case words joined by dashes`);if(typeof d!="string"||d==="")throw new Error(`commitJoins returned the finding ${u} with no message`);if(p!==void 0&&(!Array.isArray(p)||!p.every(f=>typeof f=="string")))throw new Error(`commitJoins returned the finding ${u} with refs that are not a list of strings`);return{code:u,message:d,refs:p??[]}})}return s}var sx,JD,Tve,Ive,Lg=v(()=>{"use strict";$n();KD();sx=m.string().regex(/^[A-Za-z0-9][A-Za-z0-9-]*$/,"a trailer key holds letters, digits and dashes"),JD=m.string().min(1).refine(e=>e.includes("{id}")&&!e.startsWith("/")&&!e.split("/").includes(".."),"a record path is relative to the workspace root and holds {id}"),Tve=m.object({trailers:m.object({unit:sx.optional(),contract:sx.optional(),evidence:sx.optional()}).strict(),records:m.object({unit:JD.optional(),contract:JD.optional(),evidence:JD.optional()}).strict().optional(),authorship:m.array(sx).optional()}).strict(),Ive=/^[^:\s]+$/});function Gg(e){let t=e.indexOf(":");if(t<=0)return;let n=e.slice(0,t).trim(),i=e.slice(t+1).trim();return Fve.test(n)&&Gve.test(i)?{kind:n,id:i}:void 0}function iZ(e){let t=[];for(let r of pp(e,mp)){let o=Gg(r);o&&!t.some(s=>s.kind===o.kind&&s.id===o.id)&&t.push(o)}let n=Ka(e,Nve)??null,i=Ka(e,Mve)??null;return{agent:Ka(e,Mg)??null,lease:Ka(e,Fg)??null,run:Ka(e,rZ)??null,records:t,applied:n===null?null:{by:n,at:Ka(e,Lve)??null,commit:i!==null&&Wve.test(i)?i:null}}}var Mg,Fg,rZ,mp,Nve,Lve,Mve,Fve,Gve,Wve,gp=v(()=>{"use strict";Lg();Mg="Chant-Agent",Fg="Chant-Lease",rZ="Chant-Run",mp="Chant-Record",Nve="Chant-Applied-By",Lve="Chant-Applied-At",Mve="Chant-Applied-Commit",Fve=/^[a-z][a-z0-9-]*$/,Gve=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Wve=/^[0-9a-f]{40,64}$/});import{spawn as Bve}from"node:child_process";import{existsSync as zve,readFileSync as Uve,realpathSync as oZ}from"node:fs";import{join as YD,relative as sZ,resolve as Vve}from"node:path";function qt(e,t){let n=vs(e);if(t!==void 0){if(!n)throw new ve("not-a-git-repository","--at reads git objects, and this directory is not in a git repository");let o=H_(n,t);if(!o)throw new ve("revision-unknown",`--at ${t} names no commit in this repository`);let s=cd(n,o),a=aZ(sZ(n,oZ(Vve(e)))),c=SI(s,a.startsWith("..")?"":a);if(c===void 0)throw new ve("declaration-missing",`no chant.workspace.json or .jsonc between ${a||"."} and the git root at ${o.slice(0,8)}`);return{tree:c===""?s:cd(n,o,c),root:c===""?".":c,rootOnDisk:YD(n,...c.split("/")),at:o,top:n}}let i=tr(e);if(!i)throw new ve("declaration-missing",n?"no chant.workspace.json or .jsonc between this directory and the git root; chant workspace init proposes one":"no chant.workspace.json or .jsonc in this directory; chant workspace init proposes one");let r=n?aZ(sZ(n,oZ(i.dir))):i.dir;return{tree:Rn(i.dir),root:r===""?".":r,rootOnDisk:i.dir,at:null,top:n}}function Hve(e,t){let n=ba(Dd,e);if(!n)return;let i;try{i=JSON.parse(Uve(YD(n,"package.json"),"utf-8"))}catch{return}if(i.version!==t)return;let r=typeof i.bin=="string"?i.bin:i.bin?.chant;if(typeof r!="string")return;let o=YD(n,r);return zve(o)?o:void 0}function qve(e){let t=Id.find(r=>e.tree.stat(r)==="file");if(!t)return;let n;try{n=e.tree.read(t)}catch{return}let i=Ca(n,{jsonc:t.endsWith(".jsonc")});if(!(!i.ok||i.value===null||typeof i.value!="object"||Array.isArray(i.value)))return mk(i.value)?.version}async function cx(e,t,n=process.argv.slice(2)){if(process.env[cZ])return;let i;try{i=qt(e,t)}catch{return}let r=qve(i);if(r===void 0||r===en())return;let o=Hve(i.rootOnDisk,r);if(o)return new Promise(s=>{let a=Bve(o,n,{stdio:"inherit",env:{...process.env,[cZ]:r}});a.on("error",c=>{process.stderr.write(`could not start the root's chant ${r} at ${o}: ${c.message}
158
+ `),s(1)}),a.on("close",c=>s(c??1))})}var aZ,cZ,Wr=v(()=>{"use strict";Mi();Tt();Td();qi();on();aZ=e=>e.split("\\").join("/");cZ="CHANT_WORKSPACE_ROOT_CHANT"});var oj={};_e(oj,{AGENT_ENV:()=>QD,AGENT_TRAILER:()=>Mg,FACTORY_CHECK_LOG:()=>bZ,SCOPE_FINDING_CODES:()=>Zve,WRITE_SCOPE_CODES:()=>Za,WriteScopeError:()=>Os,checkWriteScope:()=>Qve,classesOf:()=>kg,declaredSessions:()=>rj,judgePath:()=>vZ,judgeRecord:()=>nj,onlyKeysChanged:()=>wZ,principalClass:()=>mZ,protectedEntry:()=>hZ,refuseRecordWrite:()=>ij,resolveWriter:()=>ej,roleGrants:()=>Hd,scopeOf:()=>dx,scopeSource:()=>to,scopedKind:()=>xZ,unknownClassVerdict:()=>tj});import{execFileSync as Kve}from"node:child_process";import{posix as lZ,relative as uZ,sep as dZ}from"node:path";import{isDeepStrictEqual as Jve}from"node:util";function mZ(e,t,n=Wa()){return e6(e,t,n)}function ej(e,t,n,i=Wa()){let r=n.principal??null,o=e?.agents??[];if(n.agent!==void 0&&n.agent!==null){let s=o.find(a=>a.name===n.agent);if(!s){let a=o.map(c=>c.name).join(", ");throw new Os("agent-unknown",e===null?`agent session ${JSON.stringify(n.agent)} is not declared: there is no workspace declaration`:`agent session ${JSON.stringify(n.agent)} is not declared: the declaration's agents ${a?`are ${a}`:"list none"}`)}return{principal:r,class:"agent",agent:s}}if(r!==null){let s=An(r),a=o.find(c=>c.principals.some(l=>An(l)===s));if(a)return{principal:r,class:"agent",agent:a}}return{principal:r,class:mZ(t,r,i),agent:null}}function tj(e,t,n){if(t.class!=="human")return Ja;let i=YI(e?.writeScope??null,n);if(i.length===0)return Ja;let r=i.map(o=>`writeScope.${o}`).join(", ");return{ok:!1,code:"write-scope-class-unknown",message:`${Cl(t)} may be in ${i.length===1?"a class":"classes"} no pinned package supplies (${r}), so its scope can't be told; install the package that supplies ${i.length===1?"it":"them"} at the pinned version, or remove the entry (known classes: ${n.names().join(", ")})`}}function dx(e,t){let n=e?.writeScope?.[t.class];return t.class==="agent"?{members:null,records:n?.records??null,protected:n?.protected??[],pointer:n?.pointer??"/agents"}:n??null}function Cl(e){if(e.agent){let n=e.agent.members;return`agent session ${e.agent.name}, bound to ${n.length===1?"member":"members"} ${n.join(", ")},`}let t=e.principal!==null?`${e.principal} (${e.class})`:`a ${e.class} writer`;return e.class==="agent"?`${t}, which no agent session lists,`:t}function gZ(e,t,n){return e.class==="agent"?n!==null&&(e.agent?.members.includes(n)??!1):t.members===null||n!==null&&t.members.includes(n)}function nj(e,t,n,i){let r=dx(e,t);if(r===null)return Ja;if(!(n.declared&&n.member===null?!0:gZ(t,r,n.member))){let c=n.member===null?"in no member":`of member ${n.member}`;return{ok:!1,code:"write-scope-member",message:`${Cl(t)} may not write ${n.name} records, which are ${c}: ${t.class==="agent"?"an agent session writes only the members it is bound to":`writeScope.${t.class}.members leaves it out`}`}}if(i==="delete")return{ok:!1,code:"write-scope-kind",message:`${Cl(t)} may not delete a ${n.name} record: a record is never deleted, and a new one supersedes it`};if(r.records===null)return Ja;let a=[n.name,...n.declaredName!==null&&n.declaredName!==n.name?[n.declaredName]:[]].flatMap(c=>r.records[c]??[]);return a.includes(i)?Ja:{ok:!1,code:"write-scope-kind",message:a.length===0?`${Cl(t)} may not write ${n.name} records: writeScope.${t.class}.records does not list the kind`:`${Cl(t)} may ${[...new Set(a)].join(", ")} ${n.name} records, and not ${i} them (writeScope.${t.class}.records)`}}function hZ(e,t){if(e.length===0)return null;let n=t.split("/"),i=n.map((r,o)=>n.slice(0,o+1).join("/"));for(let r of e){let o=(0,fZ.default)(r.path,{dot:!0});if(i.some(s=>o(s)))return r}return null}function yZ(e,t){if(t.length===0||e===null||typeof e!="object")return;let[n,...i]=t,r=e,o=n==="*"?Object.keys(r):Object.prototype.hasOwnProperty.call(r,n)?[n]:[];for(let s of o)i.length>0?yZ(r[s],i):Array.isArray(e)?e[Number(s)]=Yve:delete r[s]}function wZ(e,t,n){if(e===null||t===null||n.length===0)return!1;let i=s=>{let a=Ca(s,{jsonc:!0});if(!a.ok)return null;let c=a.value;if(c===null||typeof c!="object"||Array.isArray(c))return null;let l=structuredClone(c);for(let u of n)u.startsWith("/")?yZ(l,u.slice(1).split("/").map(d=>d.replace(/~1/g,"/").replace(/~0/g,"~"))):delete l[u];return l},r=i(e),o=i(t);return r!==null&&o!==null&&Jve(r,o)}function vZ(e,t,n,i){let r=dx(e,t);if(r===null)return Ja;let o=Fr(n,e?.members??[]);if(!(o===null&&bZ.test(n))&&!gZ(t,r,o)){let l=o===null?"is in no member":`is in member ${o}`;return{ok:!1,code:"write-scope-member",message:`${Cl(t)} may not write ${n}, which ${l}: ${t.class==="agent"?"an agent session writes only the members it is bound to":`writeScope.${t.class}.members leaves it out`}`}}let a=hZ(r.protected,n);if(a===null||a.except.length>0&&i&&wZ(i.before(),i.after(),a.except))return Ja;let c=a.except.length>0?`, outside what its except allows (${a.except.join(", ")})`:"";return{ok:!1,code:"write-scope-protected",message:`${Cl(t)} may not write ${n}${c}: writeScope.${t.class}.protected lists ${a.path}`}}function kZ(e,t){try{let n=qt(e,t);return{declaration:_t(n.tree),rootOnDisk:n.rootOnDisk,root:n.root,tree:n.tree}}catch(n){if(n instanceof ve)return n;throw n}}function XD(e,t){let n=kZ(e,t);return n instanceof ve?null:n}function to(e,t){let n=cr(e),i=n?ti(n,t):null,r=n&&i?$i(n,i):eo(null),o=a=>{let{tree:c,...l}=a;return{...l,classes:t6(a.declaration.pins,a.rootOnDisk,{tree:c}).registry}};if(i?.commit){let a=XD(e,i.commit);if(a)return{...o(a),from:"base",policy:r}}let s=kZ(e);return s instanceof ve?{declaration:null,from:null,rootOnDisk:null,root:null,policy:r,classes:Wa(),failure:s}:{...o(s),from:"working-tree",policy:r}}function xZ(e,t,n,i){let r=e.declaration;if(!r||e.rootOnDisk===null)return{name:t,declaredName:null,member:null,declared:!1};let o=pZ(uZ(e.rootOnDisk,n)),s=[...r.records,...r.members.flatMap(c=>c.records)].find(c=>c.path===o);if(s)return{name:t,declaredName:s.name,member:s.member,declared:!0};let a=pZ(uZ(e.rootOnDisk,i));return{name:t,declaredName:null,member:a.startsWith("..")?null:Fr(a===""?".":a,r.members),declared:!1}}function rj(e){let t=cr(e),n=t?ti(t):null;if(n?.commit){let r=XD(e,n.commit);if(r)return{agents:r.declaration.agents,from:"base"}}let i=XD(e);return i?{agents:i.declaration.agents,from:"working-tree"}:null}function ij(e,t){let n=to(e);if(n.declaration===null&&(t.agent===void 0||t.agent===null))return n;let i=ej(n.declaration,n.policy,{agent:t.agent,principal:t.principal},n.classes),r=tj(n.declaration,i,n.classes);if(!r.ok)throw new Os(r.code,r.message);let o=nj(n.declaration,i,xZ(n,t.kindName,t.kindFile,t.recordsDir),t.verb);if(!o.ok)throw new Os(o.code,o.message);return n}function lx(e,t){return Kve("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],maxBuffer:512*1024*1024})}function ux(e,t,n){try{return lx(e,["show",`${t}:${n}`])}catch{return null}}function Xve(e,t,n,i){if(i.format!=="markdown-front-matter")return"amend";let r=ux(e,`${t}^`,n),o=ux(e,t,n);if(r===null||o===null)return"amend";let s=Ss(r),a=Ss(o);if(!s.ok||!a.ok)return"amend";let l=[...new Set([...Object.keys(s.value),...Object.keys(a.value)])].filter(u=>JSON.stringify(s.value[u])!==JSON.stringify(a.value[u]));if(i.session){let u=a.value[i.session.stateField];return typeof u=="string"&&i.session.closed.includes(u)&&s.value[i.session.stateField]!==u?"close":l.every(d=>i.reviewFields.includes(d)||i.session.fills.includes(d))?"review":"amend"}return l.length>0&&l.every(u=>i.reviewFields.includes(u))?"review":"amend"}async function Qve(e){let{top:t,base:n,head:i,prefix:r,declaration:o}=e,s=e.classes??Wa();if(o.writeScope===null&&o.agents.length===0)return null;let a=$i(t,{commit:n,from:"flag"}),{activeAttestors:c}=await Promise.resolve().then(()=>(lp(),BJ)),l=await c(),u=g=>o.writeScope?.[g]!==void 0||g==="agent"&&o.agents.length>0,d=[...s.names().filter(u),...YI(o.writeScope,s)],p={base:n,restricted:d,agents:o.agents.map(g=>g.name),commits:[],findings:[]},f=lx(t,["rev-list","--reverse","--no-merges",`${n}..${i}`]).split(`
159
159
  `).filter(Boolean);for(let g of f){let[h,w,b]=lx(t,["log","-1",`--format=%s%x00%ae%x00%(trailers:key=${Mg},valueonly,separator=%x01)`,g]).split("\0"),k=(b??"").split("").map(C=>C.trim()).filter(Boolean)[0]??null,$=a.active?Ng(t,a,g,l):null,x=$?.level==="attested"&&$.principal!==void 0,R=x?$.principal:w.trim(),P=lx(t,["diff-tree","--no-commit-id","-r","--name-status","--no-renames","-z",g]).split("\0").filter(Boolean),I=[];for(let C=0;C+1<P.length;C+=2){let q=P[C+1];r!==""&&!q.startsWith(`${r}/`)||I.push({status:P[C],path:q})}let A;try{A=ej(o,a,{agent:k,principal:R},s)}catch(C){if(!(C instanceof Os))throw C;p.commits.push({commit:g,subject:h,principal:R,attested:x,class:"agent",agent:k,paths:I.length}),p.findings.push({id:`finding:${C.code}:${g}`,code:C.code,commit:g,path:null,principal:R,class:"agent",agent:k,verb:null,message:`${g.slice(0,8)} has ${Mg}: ${k}: ${C.message}`});continue}p.commits.push({commit:g,subject:h,principal:R,attested:x,class:A.class,agent:A.agent?.name??null,paths:I.length});let B=tj(o,A,s);if(!B.ok){p.findings.push({id:`finding:${B.code}:${g}`,code:B.code,commit:g,path:null,principal:R,class:A.class,agent:null,verb:null,message:`${g.slice(0,8)}: ${B.message}`});continue}if(dx(o,A)!==null)for(let C of I){let q=r===""?C.path:C.path.slice(r.length+1),L=e.kinds.find(T=>lZ.dirname(C.path)===T.dir&&T.match.test(lZ.basename(C.path))),M=null,_;L?(M=C.status==="A"?"new":C.status==="D"?"delete":Xve(t,g,C.path,L),_=nj(o,A,L.scoped,M)):_=vZ(o,A,q,{before:()=>C.status==="A"?null:ux(t,`${g}^`,C.path),after:()=>C.status==="D"?null:ux(t,g,C.path)}),!_.ok&&p.findings.push({id:`finding:${_.code}:${g}:${q}`,code:_.code,commit:g,path:q,principal:R,class:A.class,agent:A.agent?.name??null,verb:M,message:`${g.slice(0,8)} ${C.status==="D"?"deletes":C.status==="A"?"adds":"changes"} ${q}: ${_.message}`})}}return p}var fZ,QD,Za,Zve,Os,Ja,Yve,bZ,pZ,Bo=v(()=>{"use strict";fZ=Ye(vm(),1);Tt();XI();Td();No();Qi();un();Go();Pl();gp();Wr();QD="CHANT_AGENT",Za=["write-scope-member","write-scope-kind","write-scope-class-unknown","agent-unknown"],Zve=[...Za,"write-scope-protected"];Os=class extends Error{constructor(n,i){super(i);this.code=n;this.name="WriteScopeError"}};Ja={ok:!0};Yve=Symbol("except");bZ=/^\.chant\/factory\/[^/]+\/check\.log$/;pZ=e=>dZ==="/"?e:e.split(dZ).join("/")});var aj={};_e(aj,{FORGES:()=>RZ,IDENTITY_CODES:()=>_l,IdentityError:()=>As,forgePrincipal:()=>tke,gateAdmission:()=>rke,gateAdmissionFrom:()=>sj,identify:()=>OZ,parseForgeIdentity:()=>EZ,refuseUnidentified:()=>zo,releaseRuleFrom:()=>AZ});function EZ(e){let t=eke.exec(An(e));if(!t)return null;let n=t[1],i=t[2]??SZ[n];return i===null?null:{forge:n,host:i,login:t[3]}}function tke(e){return e.host===SZ[e.forge]?`${e.forge}:${e.login}`:`${e.forge}@${e.host}:${e.login}`}function OZ(e,t,n=null){let i=An(e),r=EZ(e);return t.active&&t.signers.some(s=>An(s.principal)===i)?{principal:e,form:"signer",forge:r}:r?{principal:e,form:"forge",forge:r}:(n?.agents??[]).some(s=>s.principals.some(a=>An(a)===i))||kg(Wa(),t,e).some(s=>nke.has(s))?{principal:e,form:"role",forge:null}:{principal:e,form:"name",forge:null}}function zo(e,t,n,i={}){if(e.declaration?.identity?.attribution==="identified"&&!(i.agent!==void 0&&i.agent!==null&&e.declaration.agents.some(r=>r.name===i.agent))){for(let r of t)if(OZ(r,e.policy,e.declaration).form==="name")throw new As(`${n} ${JSON.stringify(r)} names no identity the workspace can check: chant.workspace.json at base sets identity.attribution to identified, so a person is named by a forge identity (github:<login>, gitlab:<login>, or <forge>@<host>:<login>) or by a principal ${e.policy.signersPath} lists at base`)}}function sj(e,t){let n=e.declaration?.identity?.gates[t];if(!n)return null;let{policy:i,classes:r}=e,o={gate:t,class:n.class,signers:i,roles:Hd(i),classes:r.all()};return{requirement:n,refuses:s=>dd(o,s)}}function AZ(e){let t=e.declaration?.identity?.gates[t0]??null,{policy:n,classes:i}=e;return{requirement:t,rule:{gate:t0,class:t?.class??null,signers:n,roles:Hd(n),classes:i.all()}}}function rke(e,t,n){return sj(to(e,n),t)}var RZ,SZ,$Z,eke,nke,_l,As,Tl=v(()=>{"use strict";ks();XI();un();Bo();RZ=["github","gitlab","forgejo","gitea"],SZ={github:"github.com",gitlab:"gitlab.com",forgejo:null,gitea:null},$Z="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",eke=new RegExp(`^(${RZ.join("|")})(?:@(${$Z}(?:\\.${$Z})+))?:([a-z0-9](?:[a-z0-9._-]{0,98}[a-z0-9_])?)$`);nke=new Set(["agent","runner","service"]);_l=["principal-unidentified"],As=class extends Error{constructor(n){super(n);this.code="principal-unidentified";this.name="IdentityError"}}});function Xa(e){return{async read(t){await Lr(e);let{resolutions:n,pending:i}=await Kn(t,e);return{resolutions:n,pending:i}},async approvalRule(t,n){let{gateAdmission:i}=await Promise.resolve().then(()=>(Tl(),aj));return i(e?.cwd??process.cwd(),t,n?.base)},async appendResolution(t){let{record:n}=await yg(t,e);return{record:n,...await Ia(e)}},async appendPending(t){let{record:n}=await zd(t,e);return{record:n,...await Ia(e)}},async writeCheckpoint(t){await Z4(t,e)},async readCheckpoint(t,n){return await Lr(e),Y4(t,n,e)},async readApplied(t){await Lr(e);let{dir:n,file:i}=yl(t),r=await At(n,i,e);return r?_k(r):[]},async appendApplied(t){let{dir:n,file:i}=yl(t.op),r=JSON.stringify(t,Gt);await Lr(e);let o;for(let s=1;s<=5;s++)try{let a=await gn(n,i,e),c=a?await hn(a,e):null;return await mn(n,i,c?`${c.replace(/\n$/,"")}
160
160
  ${r}
161
161
  `:`${r}
162
- `,`Applied under ${t.gate}`,{...e,expectPriorPathSha:a}),Ia(e)}catch(a){if(!(a instanceof Ot))throw a;o=a}throw o}}}function hp(e){return e.approver?e.approver:{kind:di(e.origin)?"agent":"human"}}function Ya(e,t,n,i,r,o=n){let s=new Date(n).getTime(),a=Math.min(s,new Date(o).getTime()),c=h=>new Date(h.timestamp).getTime(),l=r.quorum?.roles,u=bg(r.context),d=new Map,p,f;for(let h of e){if(h.gate!==t||c(h)<a)continue;if(i!==void 0&&!mt(h.planDigest,i)){c(h)>=s&&(!f||c(h)>=c(f))&&(f=h);continue}let w=h.policyDecision;c(h)>=s&&r.mode==="enforce"&&r.policy&&w?.decision==="allow"&&w.mode==="enforce"&&w.version===r.policy.version&&w.contextDigest===u&&(!p||c(h)>=c(p))&&(p=h);let k=hp(h);if(k.kind!=="human"||l&&!(k.roles??[]).some(x=>l.includes(x)))continue;let $=d.get(h.resolvedBy);(!$||c(h)>=c($))&&d.set(h.resolvedBy,h)}return{counted:[...d.values()].sort((h,w)=>c(h)-c(w)),need:r.quorum?.count??1,...p?{permit:p}:{},...f?{mismatched:f}:{}}}function Qa(e,t){let n=a=>new Date(a.timestamp).getTime(),i=a=>a.approval?.policy?.version,r=a=>mt(a.planDigest,t.planDigest)&&i(a)===i(t),o=e.filter(a=>a!==t&&a.gate===t.gate&&a.environment===t.environment&&n(a)<=n(t)).sort((a,c)=>n(c)-n(a)),s=t;for(let a of o){if(!r(a)||On(a,s.timestamp))break;s=a}return s.timestamp}function ike(e,t,n=[t]){let i=new Date(t.approval?Qa(n,t):t.timestamp).getTime();return e.filter(r=>r.gate===t.gate&&r.environment===t.environment&&mt(r.planDigest,t.planDigest)&&new Date(r.timestamp).getTime()>=i)}function PZ(e,t,n,i){return{op:t,gate:n,resolvedBy:e.resolvedBy,...e.relayedBy!==void 0?{relayedBy:e.relayedBy}:{},timestamp:i,...e.note?{note:e.note}:{},...e.url?{url:e.url}:{},...e.planDigest!==void 0?{planDigest:e.planDigest}:{},...e.environment!==void 0?{environment:e.environment}:{},...e.releaseDigest!==void 0?{releaseDigest:e.releaseDigest}:{},...e.origin?{origin:e.origin}:{},...e.sameOriginOverride?{sameOriginOverride:!0}:{},approver:hp(e),...e.seal?{seal:e.seal}:{},carriedFrom:{op:e.op,gate:e.gate,timestamp:e.timestamp,...e.checkpointDigest!==void 0?{checkpointDigest:e.checkpointDigest}:{}}}}async function oke(e,t,n,i,r,o){let s=d=>new Date(d).getTime(),a=n.filter(d=>d.gate===t.gate&&d.carriedFrom!==void 0),c=d=>a.some(p=>p.carriedFrom.op===d.op&&p.carriedFrom.gate===d.gate&&s(p.carriedFrom.timestamp)===s(d.timestamp)&&p.resolvedBy===d.resolvedBy),l=new Map,u=[];for(let d of t.aliases){let p=l.get(d.op);p||l.set(d.op,p=await e.read(d.op));let f=p.pending.filter(w=>w.environment===t.environment),g=yn(f,d.gate);if(!g||On(g,r)||!mt(g.planDigest,t.planDigest))continue;let h=d.op===t.op&&t.spent?t.spent:await e.readApplied?.(d.op)??[];for(let w of ike(p.resolutions,g,f)){if(w.carriedFrom!==void 0||hp(w).kind!=="human"||sr(h,w)||c(w))continue;let b=i?.refuses(w)??null;if(b!==null){o.push({resolution:w,reason:`carried from ${d.op}/${d.gate}: ${b}`});continue}u.push(w)}}return u.sort((d,p)=>s(d.timestamp)-s(p.timestamp))}async function CZ(e){let t=e.runId??vl(),n=e.gitSha??await Nk();return{...t?{runId:t}:{},...n?{gitSha:n}:{}}}function ske(e,t){return JSON.stringify(e??null,Gt)===JSON.stringify(t??null,Gt)}async function yp(e,t){kk(t.op,t.gate);let n=t.now??new Date().toISOString(),i=await e.read(t.op),r=t.environment,o=r===void 0?i.pending:i.pending.filter(M=>M.environment===r),s=M=>M.gate===t.gate&&M.releaseDigest!==t.releaseDigest,a=await e.approvalRule?.(t.gate)??null,c=yn(o,t.gate),l=c?.timestamp??ake,u=r===void 0?i.resolutions:i.resolutions.filter(M=>M.environment===r);if(t.verifyEmpty&&t.planDigest!==void 0){let M=u.filter(T=>T.empty===!0&&T.gate===t.gate&&!s(T)&&mt(T.planDigest,t.planDigest)&&new Date(T.timestamp).getTime()>=new Date(l).getTime()&&(t.spent===void 0||!sr(t.spent,T))).sort((T,W)=>new Date(T.timestamp).getTime()-new Date(W.timestamp).getTime()),_=M[M.length-1];if(_&&await t.verifyEmpty(t.planDigest))return{satisfied:!0,resolution:_,via:"empty"}}let d=t.planDigest!==void 0&&e.appendResolution?t.aliases??[]:[],p=M=>d.some(_=>_.op===M.op&&_.gate===M.gate),f=[],g=[],h=(r===void 0?i.resolutions:i.resolutions.filter(M=>M.environment===void 0||M.environment===r)).filter(M=>M.empty!==!0).filter(M=>s(M)?(g.push(M),!1):!0).filter(M=>M.gate!==t.gate||M.carriedFrom===void 0||p(M.carriedFrom)).filter(M=>t.spent===void 0||M.gate!==t.gate||!sr(t.spent,M)).filter(M=>{if(a===null||M.gate!==t.gate)return!0;let _=a.refuses(M);return _===null?!0:(mt(M.planDigest,t.planDigest)&&new Date(M.timestamp).getTime()>=new Date(l).getTime()&&f.push({resolution:M,reason:_}),!1)}),w=d.length>0?await oke(e,{...t,aliases:d},i.resolutions,a,n,f):[];f.sort((M,_)=>new Date(M.resolution.timestamp).getTime()-new Date(_.resolution.timestamp).getTime());let b=async M=>{let _=[];if(M.length===0)return _;let T=await CZ(t);for(let W of M)_.push((await e.appendResolution({...PZ(W,t.op,t.gate,n),...T})).record);return _},k,$;if(t.approval){let M=c&&mt(c.planDigest,t.planDigest)&&c.approval?.policy?.version===t.approval.policy?.version?Qa(o,c):l,_=Ya(h,t.gate,l,t.planDigest,t.approval,M);if(_.permit)return{satisfied:!0,resolution:_.permit,via:"policy",approvals:_.counted};if(_.counted.length>=_.need)return{satisfied:!0,resolution:_.counted[_.counted.length-1],via:"quorum",approvals:_.counted};k=_.mismatched,$={approvers:_.counted.map(ve=>ve.resolvedBy),need:_.need};let T=new Set(_.counted.map(ve=>ve.resolvedBy)),W=w.filter(ve=>!T.has(ve.resolvedBy));if(W.length>0){let ve=new Map(W.map(be=>[{version:1,...PZ(be,t.op,t.gate,n)},be])),re=Ya([...h,...ve.keys()],t.gate,l,t.planDigest,t.approval,M);if(re.counted.length>=re.need){let be=await b(re.counted.filter(dt=>ve.has(dt)).map(dt=>ve.get(dt))),Be=[...re.counted.filter(dt=>!ve.has(dt)),...be];return{satisfied:!0,resolution:be[be.length-1],via:"alias",approvals:Be,carried:be}}$={approvers:re.counted.map(be=>be.resolvedBy),need:re.need}}}else{let M=Qr(h,t.gate,l,t.planDigest);if(M.resolution)return{satisfied:!0,resolution:M.resolution};let _=w[w.length-1];if(_){let T=await b([_]);return{satisfied:!0,resolution:T[0],via:"alias",carried:T}}k=M.mismatched}if(!k&&t.planDigest!==void 0){let M=new Date(l).getTime();k=g.filter(_=>new Date(_.timestamp).getTime()>=M).sort((_,T)=>new Date(_.timestamp).getTime()-new Date(T.timestamp).getTime()).at(-1)}let x=k?{...k.planDigest!==void 0?{approved:k.planDigest}:{},planned:t.planDigest,resolvedBy:k.resolvedBy,timestamp:k.timestamp,...r!==void 0?{environment:r}:{}}:void 0,R={...x?{mismatch:x}:{},...$?{quorum:$}:{},...f.length>0?{refused:f}:{}};if(c&&!On(c,n)&&mt(c.planDigest,t.planDigest)&&c.releaseDigest===t.releaseDigest&&ske(c.approval,t.approval)&&(t.checkpoint===void 0||e.writeCheckpoint===void 0||c.checkpointDigest!==void 0))return{satisfied:!1,pending:c,recorded:!1,...R};let P;t.checkpoint!==void 0&&e.writeCheckpoint&&(P=qI(t.checkpoint),await e.writeCheckpoint(t.checkpoint));let I=ja(),A=Fa(),B=await CZ(t),{record:C,pushed:q,pushWarning:L}=await e.appendPending({...t.fields,op:t.op,gate:t.gate,timestamp:n,expiresAt:new Date(new Date(n).getTime()+vi(t.timeout??"48h")).toISOString(),...t.description?{description:t.description}:{},...B,...I?{url:I}:{},...A?{resume:A}:{},...t.planDigest!==void 0?{planDigest:t.planDigest}:{},...P!==void 0?{checkpointDigest:P}:{},...r!==void 0?{environment:r}:{},...t.releaseDigest!==void 0?{releaseDigest:t.releaseDigest}:{},...t.approval?{approval:t.approval}:{},...t.neverOverMcp?{neverOverMcp:!0}:{}});return{satisfied:!1,pending:C,recorded:!0,pushed:q,...L?{pushWarning:L}:{},...R}}function wp(e,t,n,i,r=!1){return`chant approve ${e} ${t}`+(n===void 0?"":` --env ${n}`)+(i===void 0?"":` --plan ${i}`)+(r?" --sign":"")}var ake,Uo=v(()=>{"use strict";Mr();Dn();el();Ma();Wt();vg();Pt();Do();Ga();Lk();Nd();JI();ake=new Date(0).toISOString()});function cj(e,t,n){return(e??px).replaceAll("{gate}",t).replaceAll("{k}",String(n))}function lj(e,t,n,i){let r=[...e].sort((l,u)=>{let d=i(l),p=i(u);return d<p?-1:d>p?1:0}),o=Math.floor(r.length/n),s=r.length%n,a=(t-1)*o+Math.min(t-1,s),c=o+(t<=s?1:0);return r.slice(a,a+c)}var px,uj=v(()=>{"use strict";px="{gate}-wave-{k}"});function TZ(e){return`${e.member}\0${e.address}\0${e.deposed??""}\0${e.action}`}function dj(e){let t=e.filter(n=>n.provisional!==!0).map(n=>({member:n.member,planDigest:n.planDigest})).sort((n,i)=>bp(n.member,i.member));for(let n=1;n<t.length;n++)if(t[n-1].member===t[n].member)throw new Error(`the change set names member ${t[n].member} twice`);return gl("change-set",t)}function lke(e){let t=new Set(e.members.filter(s=>s.provisional===!0).map(s=>s.member)),n=e.members.filter(s=>!t.has(s.member)).map(s=>({member:s.member,status:s.status,holes:s.holes})).sort((s,a)=>bp(s.member,a.member)),i=e.entries.filter(s=>!t.has(s.member)).map(({node:s,source:a,...c})=>c).sort((s,a)=>bp(TZ(s),TZ(a))),r=(e.sideEffects??[]).filter(s=>!t.has(s.member)).sort(cke),o=e.releaseDigest!==void 0||e.environment!==void 0?{planned:{releaseDigest:e.releaseDigest??null,environment:e.environment??null}}:{};return gl("change-set-document",{set:dj(e.members),members:n,entries:i,sideEffects:r,...o})}function pj(e){try{return lke(e)===e.digest}catch{return!1}}var fx,mx,bp,cke,fj=v(()=>{"use strict";Dn();fx="https://intentius.io/chant/schemas/workspace/change-set/v1/change-set.schema.json",mx=1,bp=(e,t)=>e<t?-1:e>t?1:0;cke=(e,t)=>bp(e.member,t.member)||bp(e.address,t.address)||bp(e.trigger??"",t.trigger??"")});function gj(e){let t=e.filter(n=>n.provisional===!0).map(n=>n.member);if(t.length>0)throw new mj([...new Set(t)].sort());return dj(e)}function hj(e,t={}){let n=t.over==="changing"?e.filter(i=>i.empty!==!0):[];return[...n.length>0?n:e,...t.extras??[]]}var mj,IZ=v(()=>{"use strict";fj();mj=class extends Error{constructor(n){super(`a wave cannot be gated on a provisional plan: ${n.join(", ")} planned before what it reads applied. Plan it again in its own wave, after its upstream applied`);this.members=n;this.name="ProvisionalWaveMemberError"}}});import{dirname as uke}from"node:path";import{mkdirSync as dke,renameSync as pke,writeFileSync as fke}from"node:fs";function DZ(e,t){return yp(e,{op:t.op,gate:t.gate,planDigest:t.digest,description:t.description,...t.timeout?{timeout:t.timeout}:{},...t.now!==void 0?{now:t.now}:{},...t.spent?{spent:t.spent}:{},...t.fields?{fields:t.fields}:{},...t.neverOverMcp?{neverOverMcp:!0}:{}})}function jZ(e,t){dke(uke(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;fke(n,JSON.stringify(t,null,2)+`
162
+ `,`Applied under ${t.gate}`,{...e,expectPriorPathSha:a}),Ia(e)}catch(a){if(!(a instanceof Ot))throw a;o=a}throw o}}}function hp(e){return e.approver?e.approver:{kind:di(e.origin)?"agent":"human"}}function Ya(e,t,n,i,r,o=n){let s=new Date(n).getTime(),a=Math.min(s,new Date(o).getTime()),c=h=>new Date(h.timestamp).getTime(),l=r.quorum?.roles,u=bg(r.context),d=new Map,p,f;for(let h of e){if(h.gate!==t||c(h)<a)continue;if(i!==void 0&&!mt(h.planDigest,i)){c(h)>=s&&(!f||c(h)>=c(f))&&(f=h);continue}let w=h.policyDecision;c(h)>=s&&r.mode==="enforce"&&r.policy&&w?.decision==="allow"&&w.mode==="enforce"&&w.version===r.policy.version&&w.contextDigest===u&&(!p||c(h)>=c(p))&&(p=h);let k=hp(h);if(k.kind!=="human"||l&&!(k.roles??[]).some(x=>l.includes(x)))continue;let $=d.get(h.resolvedBy);(!$||c(h)>=c($))&&d.set(h.resolvedBy,h)}return{counted:[...d.values()].sort((h,w)=>c(h)-c(w)),need:r.quorum?.count??1,...p?{permit:p}:{},...f?{mismatched:f}:{}}}function Qa(e,t){let n=a=>new Date(a.timestamp).getTime(),i=a=>a.approval?.policy?.version,r=a=>mt(a.planDigest,t.planDigest)&&i(a)===i(t),o=e.filter(a=>a!==t&&a.gate===t.gate&&a.environment===t.environment&&n(a)<=n(t)).sort((a,c)=>n(c)-n(a)),s=t;for(let a of o){if(!r(a)||On(a,s.timestamp))break;s=a}return s.timestamp}function ike(e,t,n=[t]){let i=new Date(t.approval?Qa(n,t):t.timestamp).getTime();return e.filter(r=>r.gate===t.gate&&r.environment===t.environment&&mt(r.planDigest,t.planDigest)&&new Date(r.timestamp).getTime()>=i)}function PZ(e,t,n,i){return{op:t,gate:n,resolvedBy:e.resolvedBy,...e.relayedBy!==void 0?{relayedBy:e.relayedBy}:{},timestamp:i,...e.note?{note:e.note}:{},...e.url?{url:e.url}:{},...e.planDigest!==void 0?{planDigest:e.planDigest}:{},...e.environment!==void 0?{environment:e.environment}:{},...e.releaseDigest!==void 0?{releaseDigest:e.releaseDigest}:{},...e.origin?{origin:e.origin}:{},...e.sameOriginOverride?{sameOriginOverride:!0}:{},approver:hp(e),...e.seal?{seal:e.seal}:{},carriedFrom:{op:e.op,gate:e.gate,timestamp:e.timestamp,...e.checkpointDigest!==void 0?{checkpointDigest:e.checkpointDigest}:{}}}}async function oke(e,t,n,i,r,o){let s=d=>new Date(d).getTime(),a=n.filter(d=>d.gate===t.gate&&d.carriedFrom!==void 0),c=d=>a.some(p=>p.carriedFrom.op===d.op&&p.carriedFrom.gate===d.gate&&s(p.carriedFrom.timestamp)===s(d.timestamp)&&p.resolvedBy===d.resolvedBy),l=new Map,u=[];for(let d of t.aliases){let p=l.get(d.op);p||l.set(d.op,p=await e.read(d.op));let f=p.pending.filter(w=>w.environment===t.environment),g=yn(f,d.gate);if(!g||On(g,r)||!mt(g.planDigest,t.planDigest))continue;let h=d.op===t.op&&t.spent?t.spent:await e.readApplied?.(d.op)??[];for(let w of ike(p.resolutions,g,f)){if(w.carriedFrom!==void 0||hp(w).kind!=="human"||sr(h,w)||c(w))continue;let b=i?.refuses(w)??null;if(b!==null){o.push({resolution:w,reason:`carried from ${d.op}/${d.gate}: ${b}`});continue}u.push(w)}}return u.sort((d,p)=>s(d.timestamp)-s(p.timestamp))}async function CZ(e){let t=e.runId??vl(),n=e.gitSha??await Nk();return{...t?{runId:t}:{},...n?{gitSha:n}:{}}}function ske(e,t){return JSON.stringify(e??null,Gt)===JSON.stringify(t??null,Gt)}async function yp(e,t){kk(t.op,t.gate);let n=t.now??new Date().toISOString(),i=await e.read(t.op),r=t.environment,o=r===void 0?i.pending:i.pending.filter(M=>M.environment===r),s=M=>M.gate===t.gate&&M.releaseDigest!==t.releaseDigest,a=await e.approvalRule?.(t.gate)??null,c=yn(o,t.gate),l=c?.timestamp??ake,u=r===void 0?i.resolutions:i.resolutions.filter(M=>M.environment===r);if(t.verifyEmpty&&t.planDigest!==void 0){let M=u.filter(T=>T.empty===!0&&T.gate===t.gate&&!s(T)&&mt(T.planDigest,t.planDigest)&&new Date(T.timestamp).getTime()>=new Date(l).getTime()&&(t.spent===void 0||!sr(t.spent,T))).sort((T,W)=>new Date(T.timestamp).getTime()-new Date(W.timestamp).getTime()),_=M[M.length-1];if(_&&await t.verifyEmpty(t.planDigest))return{satisfied:!0,resolution:_,via:"empty"}}let d=t.planDigest!==void 0&&e.appendResolution?t.aliases??[]:[],p=M=>d.some(_=>_.op===M.op&&_.gate===M.gate),f=[],g=[],h=(r===void 0?i.resolutions:i.resolutions.filter(M=>M.environment===void 0||M.environment===r)).filter(M=>M.empty!==!0).filter(M=>s(M)?(g.push(M),!1):!0).filter(M=>M.gate!==t.gate||M.carriedFrom===void 0||p(M.carriedFrom)).filter(M=>t.spent===void 0||M.gate!==t.gate||!sr(t.spent,M)).filter(M=>{if(a===null||M.gate!==t.gate)return!0;let _=a.refuses(M);return _===null?!0:(mt(M.planDigest,t.planDigest)&&new Date(M.timestamp).getTime()>=new Date(l).getTime()&&f.push({resolution:M,reason:_}),!1)}),w=d.length>0?await oke(e,{...t,aliases:d},i.resolutions,a,n,f):[];f.sort((M,_)=>new Date(M.resolution.timestamp).getTime()-new Date(_.resolution.timestamp).getTime());let b=async M=>{let _=[];if(M.length===0)return _;let T=await CZ(t);for(let W of M)_.push((await e.appendResolution({...PZ(W,t.op,t.gate,n),...T})).record);return _},k,$;if(t.approval){let M=c&&mt(c.planDigest,t.planDigest)&&c.approval?.policy?.version===t.approval.policy?.version?Qa(o,c):l,_=Ya(h,t.gate,l,t.planDigest,t.approval,M);if(_.permit)return{satisfied:!0,resolution:_.permit,via:"policy",approvals:_.counted};if(_.counted.length>=_.need)return{satisfied:!0,resolution:_.counted[_.counted.length-1],via:"quorum",approvals:_.counted};k=_.mismatched,$={approvers:_.counted.map(ke=>ke.resolvedBy),need:_.need};let T=new Set(_.counted.map(ke=>ke.resolvedBy)),W=w.filter(ke=>!T.has(ke.resolvedBy));if(W.length>0){let ke=new Map(W.map(be=>[{version:1,...PZ(be,t.op,t.gate,n)},be])),re=Ya([...h,...ke.keys()],t.gate,l,t.planDigest,t.approval,M);if(re.counted.length>=re.need){let be=await b(re.counted.filter(dt=>ke.has(dt)).map(dt=>ke.get(dt))),Be=[...re.counted.filter(dt=>!ke.has(dt)),...be];return{satisfied:!0,resolution:be[be.length-1],via:"alias",approvals:Be,carried:be}}$={approvers:re.counted.map(be=>be.resolvedBy),need:re.need}}}else{let M=Qr(h,t.gate,l,t.planDigest);if(M.resolution)return{satisfied:!0,resolution:M.resolution};let _=w[w.length-1];if(_){let T=await b([_]);return{satisfied:!0,resolution:T[0],via:"alias",carried:T}}k=M.mismatched}if(!k&&t.planDigest!==void 0){let M=new Date(l).getTime();k=g.filter(_=>new Date(_.timestamp).getTime()>=M).sort((_,T)=>new Date(_.timestamp).getTime()-new Date(T.timestamp).getTime()).at(-1)}let x=k?{...k.planDigest!==void 0?{approved:k.planDigest}:{},planned:t.planDigest,resolvedBy:k.resolvedBy,timestamp:k.timestamp,...r!==void 0?{environment:r}:{}}:void 0,R={...x?{mismatch:x}:{},...$?{quorum:$}:{},...f.length>0?{refused:f}:{}};if(c&&!On(c,n)&&mt(c.planDigest,t.planDigest)&&c.releaseDigest===t.releaseDigest&&ske(c.approval,t.approval)&&(t.checkpoint===void 0||e.writeCheckpoint===void 0||c.checkpointDigest!==void 0))return{satisfied:!1,pending:c,recorded:!1,...R};let P;t.checkpoint!==void 0&&e.writeCheckpoint&&(P=qI(t.checkpoint),await e.writeCheckpoint(t.checkpoint));let I=ja(),A=Fa(),B=await CZ(t),{record:C,pushed:q,pushWarning:L}=await e.appendPending({...t.fields,op:t.op,gate:t.gate,timestamp:n,expiresAt:new Date(new Date(n).getTime()+vi(t.timeout??"48h")).toISOString(),...t.description?{description:t.description}:{},...B,...I?{url:I}:{},...A?{resume:A}:{},...t.planDigest!==void 0?{planDigest:t.planDigest}:{},...P!==void 0?{checkpointDigest:P}:{},...r!==void 0?{environment:r}:{},...t.releaseDigest!==void 0?{releaseDigest:t.releaseDigest}:{},...t.approval?{approval:t.approval}:{},...t.neverOverMcp?{neverOverMcp:!0}:{}});return{satisfied:!1,pending:C,recorded:!0,pushed:q,...L?{pushWarning:L}:{},...R}}function wp(e,t,n,i,r=!1){return`chant approve ${e} ${t}`+(n===void 0?"":` --env ${n}`)+(i===void 0?"":` --plan ${i}`)+(r?" --sign":"")}var ake,Uo=v(()=>{"use strict";Mr();Dn();el();Ma();Wt();vg();Pt();Do();Ga();Lk();Nd();JI();ake=new Date(0).toISOString()});function cj(e,t,n){return(e??px).replaceAll("{gate}",t).replaceAll("{k}",String(n))}function lj(e,t,n,i){let r=[...e].sort((l,u)=>{let d=i(l),p=i(u);return d<p?-1:d>p?1:0}),o=Math.floor(r.length/n),s=r.length%n,a=(t-1)*o+Math.min(t-1,s),c=o+(t<=s?1:0);return r.slice(a,a+c)}var px,uj=v(()=>{"use strict";px="{gate}-wave-{k}"});function TZ(e){return`${e.member}\0${e.address}\0${e.deposed??""}\0${e.action}`}function dj(e){let t=e.filter(n=>n.provisional!==!0).map(n=>({member:n.member,planDigest:n.planDigest})).sort((n,i)=>bp(n.member,i.member));for(let n=1;n<t.length;n++)if(t[n-1].member===t[n].member)throw new Error(`the change set names member ${t[n].member} twice`);return gl("change-set",t)}function lke(e){let t=new Set(e.members.filter(s=>s.provisional===!0).map(s=>s.member)),n=e.members.filter(s=>!t.has(s.member)).map(s=>({member:s.member,status:s.status,holes:s.holes})).sort((s,a)=>bp(s.member,a.member)),i=e.entries.filter(s=>!t.has(s.member)).map(({node:s,source:a,...c})=>c).sort((s,a)=>bp(TZ(s),TZ(a))),r=(e.sideEffects??[]).filter(s=>!t.has(s.member)).sort(cke),o=e.releaseDigest!==void 0||e.environment!==void 0?{planned:{releaseDigest:e.releaseDigest??null,environment:e.environment??null}}:{};return gl("change-set-document",{set:dj(e.members),members:n,entries:i,sideEffects:r,...o})}function pj(e){try{return lke(e)===e.digest}catch{return!1}}var fx,mx,bp,cke,fj=v(()=>{"use strict";Dn();fx="https://intentius.io/chant/schemas/workspace/change-set/v1/change-set.schema.json",mx=1,bp=(e,t)=>e<t?-1:e>t?1:0;cke=(e,t)=>bp(e.member,t.member)||bp(e.address,t.address)||bp(e.trigger??"",t.trigger??"")});function gj(e){let t=e.filter(n=>n.provisional===!0).map(n=>n.member);if(t.length>0)throw new mj([...new Set(t)].sort());return dj(e)}function hj(e,t={}){let n=t.over==="changing"?e.filter(i=>i.empty!==!0):[];return[...n.length>0?n:e,...t.extras??[]]}var mj,IZ=v(()=>{"use strict";fj();mj=class extends Error{constructor(n){super(`a wave cannot be gated on a provisional plan: ${n.join(", ")} planned before what it reads applied. Plan it again in its own wave, after its upstream applied`);this.members=n;this.name="ProvisionalWaveMemberError"}}});import{dirname as uke}from"node:path";import{mkdirSync as dke,renameSync as pke,writeFileSync as fke}from"node:fs";function DZ(e,t){return yp(e,{op:t.op,gate:t.gate,planDigest:t.digest,description:t.description,...t.timeout?{timeout:t.timeout}:{},...t.now!==void 0?{now:t.now}:{},...t.spent?{spent:t.spent}:{},...t.fields?{fields:t.fields}:{},...t.neverOverMcp?{neverOverMcp:!0}:{}})}function jZ(e,t){dke(uke(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;fke(n,JSON.stringify(t,null,2)+`
163
163
  `),pke(n,e)}async function NZ(e){for(let t=e.first;;t++){let n,i;for(let r=0;;r++){let o={k:t,pass:r,...i!==void 0?{prior:i}:{}};if(n=await mke(e,o),!e.replan?.(o,n))break;if(r+1>=(e.maxPasses??1)){n=e.passesSpent?e.passesSpent(o,n):n;break}e.replanning?.(o,n),i=n}if(!e.onward(t,n))return n}}async function mke(e,t){let n=await e.plan(t);if("end"in n)return n.end;let i=e.digest(t,n.go),r=await e.decide(t,n.go,i);return"end"in r?r.end:e.apply(t,n.go,r.go)}var LZ=v(()=>{"use strict";Uo();uj();IZ()});function vp(e=process.env){let t=e.CI?.trim().toLowerCase();return t&&t!=="false"&&t!=="0"?"ledger":void 0}function gx(e){if(e!==void 0)return typeof e=="string"?{name:e}:e}function Il(e,t=!1){let n=[];t&&n.push("a gate that asks a decision point takes its quorum from the point: give `approval` or `point`, not both");let i=typeof e=="string"?{name:e}:e;if(i===null||typeof i!="object"||Array.isArray(i))return[...n,"`point` is a decision point's name or { name, inputs?, pass?, store? }"];let{name:r,inputs:o,pass:s,store:a,...c}=i;if((typeof r!="string"||!gke.test(r))&&n.push("`point.name` is a decision point's name: lower case letters, digits and hyphens, starting with a letter"),o!==void 0&&(o===null||typeof o!="object"||Array.isArray(o))&&n.push("`point.inputs` is an object of input name to value"),o&&typeof o=="object"){let u=Object.keys(o).filter(d=>d in Wg);u.length>0&&n.push(`\`point.inputs\` gives ${u.join(", ")}, which the gate passes itself`)}s!==void 0&&(!Array.isArray(s)||s.length===0||s.some(u=>typeof u!="string"&&typeof u!="boolean"))&&n.push("`point.pass` is a non-empty list of the answers that pass the gate"),a!==void 0&&a!=="tree"&&a!=="ledger"&&n.push("`point.store` is tree or ledger: where the question is held");let l=Object.keys(c);return l.length>0&&n.push(`\`point\` takes name, inputs, pass and store, not ${l.join(", ")}`),n}function Dl(e,t,n,i={}){if(n.planDigest!==null&&!t.includes("gate.planDigest"))throw new Error(`gate "${n.name}" binds a plan and asks decision point ${e}, which does not declare the input gate.planDigest: declare it in the points file, so each plan is its own question and an answer for one plan never passes another`);let r={};for(let[o,s]of Object.entries(Wg))t.includes(o)&&n[s]!==null&&(r[o]=n[s]);return{...i,...r}}function Bg(e,t,n){return`gate:${e}/${t}${n?`@${n}`:""}`}function hx(e){if(!e||!e.startsWith("gate:"))return;let t=e.slice(5),n=t.lastIndexOf("@"),i=n>0?t.slice(0,n):t,r=i.indexOf("/");if(!(r<=0||r===i.length-1))return{op:i.slice(0,r),gate:i.slice(r+1),...n>0?{env:t.slice(n+1)}:{}}}var kp,gke,Wg,Ps=v(()=>{"use strict";kp=[!0];gke=/^[a-z][a-z0-9-]*$/;Wg={"gate.component":"component","gate.name":"name","gate.env":"env","gate.planDigest":"planDigest"}});function hke(e){if(e!==void 0)return typeof e=="string"?{name:e}:e}function yx(e){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&"timeout"in e){let{timeout:t,...n}=e,i=Il(n);return(typeof t!="string"||!/^(\d+(ms|s|m|h|d))+$/.test(t))&&i.push('`point.timeout` is a duration such as "48h"'),i}return Il(e)}function vj(e,t){let n=e.waves.find(i=>i.name===t);return hke(n?.point??e.point)}function kj(e,t){return cj(e.gateName,e.gate??e.name,t)}function bx(e,t){return`.chant/op-waves/${e.name}/wave-${t}.json`}function Vg(e){let t=`Op waves "${e.name}"`;if(!wj.test(e.name))throw new Error(`${t}: the name must be lowercase letters, digits, "-" and "_"`);if(!e.op)throw new Error(`${t} names no \`op\`. Name the Op a run runs when it names none.`);if(e.plan!==void 0&&e.planWave!==void 0)throw new Error(`${t} has both \`plan\` and \`planWave\`. A wave is planned one run at a time or all at once; give one.`);if(e.apply!==void 0&&e.applyWave!==void 0)throw new Error(`${t} has both \`apply\` and \`applyWave\`. A wave is applied one run at a time or all at once; give one.`);if(e.planWave!==void 0){if(zg(t,"planWave",e.planWave),!e.planWave.some(i=>i.includes("{plans}")))throw new Error(`${t}: the \`planWave\` command never names {plans}, the file it writes each run's plan digest to.`)}else{if(!Array.isArray(e.plan)||e.plan.length===0)throw new Error(`${t} has no \`plan\` command. Each wave plans its runs to bind its gate to their plan digests; give \`plan\` or \`planWave\`.`);if(zg(t,"plan",e.plan),!e.plan.some(i=>i.includes("{plan}")))throw new Error(`${t}: the \`plan\` command never names {plan}, the file it writes the plan digest to.`)}if(e.apply!==void 0&&zg(t,"apply",e.apply),e.applyWave!==void 0&&(zg(t,"applyWave",e.applyWave),!e.applyWave.some(i=>i.includes("{runs}"))))throw new Error(`${t}: the \`applyWave\` command never names {runs}, the file listing the approved runs it applies.`);if(xp(t,e.hooks),e.waves.length===0)throw new Error(`${t} has no waves.`);if(e.resume!==void 0&&(typeof e.resume.schedule!="string"||e.resume.schedule.trim().split(/\s+/).length!==5))throw new Error(`${t}: resume.schedule must be a five-field cron expression, such as "*/10 * * * *".`);if(e.approvals!==void 0){let i=e.approvals;if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`${t}: \`approvals\` must be { "spend"?: true | false }.`);for(let[r,o]of Object.entries(i)){if(r!=="spend")throw new Error(`${t}: approvals.${r} is not a setting; the one there is approvals.spend.`);if(typeof o!="boolean")throw new Error(`${t}: approvals.spend must be true or false.`)}}if(e.gateName!==void 0){if(typeof e.gateName!="string"||!e.gateName.includes("{k}")||/\s/.test(e.gateName))throw new Error(`${t}: gateName must be a pattern with {k}, the wave's number, and no spaces, such as "${FZ}" or "wave-{k}".`);let i=e.gateName.replaceAll("{gate}","").replaceAll("{k}","").match(/\{[^}]*\}/);if(i)throw new Error(`${t}: gateName names ${i[0]}; the pattern fills in {gate} and {k} only.`)}if(e.digest!==void 0){let i=e.digest;if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`${t}: \`digest\` must be { "over"?: "all" | "changing" }.`);for(let[r,o]of Object.entries(i)){if(r!=="over")throw new Error(`${t}: digest.${r} is not a setting; the one there is digest.over.`);if(!yke.includes(o))throw new Error(`${t}: digest.over is ${JSON.stringify(o)}; use "all" or "changing".`)}}if(e.override!==void 0){let i=e.override;if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`${t}: \`override\` must be { "overriders"?: "<file at base>" }.`);for(let[r,o]of Object.entries(i)){if(r!=="overriders")throw new Error(`${t}: override.${r} is not a setting; the one there is override.overriders.`);if(typeof o!="string"||o.trim()==="")throw new Error(`${t}: override.overriders must be a path, such as ".chant/overriders".`)}}if(e.point!==void 0){let i=yx(e.point);if(i.length>0)throw new Error(`${t}: ${i.join("; ")}.`)}if(e.neverOverMcp!==void 0&&typeof e.neverOverMcp!="boolean")throw new Error(`${t}: neverOverMcp must be true or false.`);if(e.runner!==void 0&&bj(t,"runner",e.runner),e.notify!==void 0){let i=wv(e.notify,"notify");if(i)throw new Error(`${t}: ${i}`)}let n=new Set;for(let i of e.waves){if(!wj.test(i.name))throw new Error(`${t}: wave "${i.name}" must be named with lowercase letters, digits, "-" and "_"`);if(n.has(i.name))throw new Error(`${t} names wave "${i.name}" twice.`);if(n.add(i.name),i.gate!==void 0&&!Ug.includes(i.gate))throw new Error(`${t}: wave "${i.name}" has gate "${i.gate}"; use ${Ug.join(", ")}.`);if(i.approval!==void 0&&!ec.includes(i.approval))throw new Error(`${t}: wave "${i.name}" has approval "${i.approval}"; use ${ec.join(", ")}.`);if(xp(`${t}, wave "${i.name}"`,i.hooks),i.point!==void 0){let s=yx(i.point);if(s.length>0)throw new Error(`${t}: wave "${i.name}": ${s.join("; ")}.`)}if(i.runner!==void 0&&bj(t,`wave "${i.name}" runner`,i.runner),i.idTokens!==void 0&&GZ(t,`wave "${i.name}" idTokens`,i.idTokens),i.jobs!==void 0&&bke(t,i),i.discover!==void 0&&typeof i.discover!="boolean")throw new Error(`${t}: wave "${i.name}" has discover ${JSON.stringify(i.discover)}; use true or false.`);if(i.rest!==void 0&&typeof i.rest!="boolean")throw new Error(`${t}: wave "${i.name}" has rest ${JSON.stringify(i.rest)}; use true or false.`);if(i.discover){if(e.planWave===void 0)throw new Error(`${t}: wave "${i.name}" discovers its runs, which only \`planWave\` can report. Give planWave.`);if((i.runs??[]).length>0)throw new Error(`${t}: wave "${i.name}" discovers its runs, so it lists none.`)}if(i.rest){if(!i.discover)throw new Error(`${t}: wave "${i.name}" has rest, which follows the waves planWave discovers; set discover too.`);if(i!==e.waves[e.waves.length-1])throw new Error(`${t}: wave "${i.name}" has rest, which only the last wave can have.`);if((i.shares??1)>1)throw new Error(`${t}: wave "${i.name}" has rest and shares; the waves after it run in its one job, so it cannot be split.`)}if(i.discover){let s=i.shares??1;if(!Number.isInteger(s)||s<1)throw new Error(`${t}: wave "${i.name}" has shares ${i.shares}; use a whole number from 1.`);continue}if(!Array.isArray(i.runs)||i.runs.length===0)throw new Error(`${t}: wave "${i.name}" has no runs.`);let r=new Set;for(let s of i.runs){if(!s.target)throw new Error(`${t}: wave "${i.name}" has a run with no target.`);if(r.has(s.target))throw new Error(`${t}: wave "${i.name}" names target "${s.target}" twice.`);r.add(s.target)}let o=i.shares??1;if(!Number.isInteger(o)||o<1)throw new Error(`${t}: wave "${i.name}" has shares ${i.shares}; use a whole number from 1.`);if(o>i.runs.length)throw new Error(`${t}: wave "${i.name}" has ${o} shares for ${i.runs.length} runs, so a share would apply nothing.`);if(i.jobs!==void 0){let s=$j(i,i.runs.map(a=>a.target));if(s)throw new Error(`${t}: ${s}.`)}}}function bj(e,t,n){let i=r=>Array.isArray(r)&&r.length>0&&r.every(o=>typeof o=="string"&&o.trim()!=="");if(!(typeof n=="string"&&n.trim()!=="")&&!i(n)){if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let{group:r,labels:o,...s}=n,a=Object.keys(s)[0];if(a!==void 0)throw new Error(`${e}: ${t}.${a} is not a setting; a runner group is { "group": "<name>", "labels"?: [...] }.`);if(typeof r=="string"&&r.trim()!==""&&(o===void 0||i(o)))return}throw new Error(`${e}: ${t} must be a runner label, a non-empty list of labels, or { "group": "<name>", "labels"?: [...] } (GitHub only).`)}}function GZ(e,t,n){if(n===null||typeof n!="object"||Array.isArray(n)||Object.keys(n).length===0)throw new Error(`${e}: ${t} must be { "<variable>": "<audience>" }, with at least one token.`);for(let[i,r]of Object.entries(n)){if(!wke.test(i))throw new Error(`${e}: ${t} names "${i}", which is not a variable name (letters, digits and "_", not starting with a digit).`);if(typeof r!="string"||r.trim()==="")throw new Error(`${e}: ${t}.${i} must be an audience, a non-empty string.`)}}function bke(e,t){let n=`wave "${t.name}"`;if(!Array.isArray(t.jobs)||t.jobs.length===0)throw new Error(`${e}: ${n} jobs must be a non-empty list of job groups.`);if((t.shares??1)>1)throw new Error(`${e}: ${n} has jobs and shares; split each job group with its own shares.`);if(t.rest)throw new Error(`${e}: ${n} has jobs and rest; the waves after it run in its one job, so its apply cannot be split into groups.`);let i=new Set;t.jobs.forEach((r,o)=>{if(r===null||typeof r!="object")throw new Error(`${e}: ${n} jobs[${o}] must be { "name", "runs", ... }.`);let s=`${n} jobs[${o}]${typeof r.name=="string"?` (${r.name})`:""}`;if(typeof r.name!="string"||!wj.test(r.name))throw new Error(`${e}: ${s} must be named with lowercase letters, digits, "-" and "_".`);if(r.name==="decide"||/^share-\d+$/.test(r.name))throw new Error(`${e}: ${s} is named like the wave's own jobs (decide, share-<i>); name it another way.`);if(i.has(r.name))throw new Error(`${e}: ${n} names job group "${r.name}" twice.`);i.add(r.name);let a=new Set(["name","runs","shares","runner","environment","variables","setup","idTokens"]),c=Object.keys(r).find(u=>!a.has(u));if(c!==void 0)throw new Error(`${e}: ${s}.${c} is not a setting; a job group takes ${[...a].join(", ")}.`);if(!Array.isArray(r.runs)||r.runs.length===0||!r.runs.every(u=>typeof u=="string"&&u.trim()!==""))throw new Error(`${e}: ${s} runs must be a non-empty list of targets or patterns.`);let l=r.shares??1;if(!Number.isInteger(l)||l<1)throw new Error(`${e}: ${s} has shares ${r.shares}; use a whole number from 1.`);if(r.runner!==void 0&&bj(e,`${s} runner`,r.runner),r.idTokens!==void 0&&GZ(e,`${s} idTokens`,r.idTokens),r.variables!==void 0&&(r.variables===null||typeof r.variables!="object"||Array.isArray(r.variables)||!Object.values(r.variables).every(u=>typeof u=="string")))throw new Error(`${e}: ${s} variables must be { "<name>": "<value>" }.`);if(r.setup!==void 0&&!Array.isArray(r.setup))throw new Error(`${e}: ${s} setup must be a list of steps.`);if(r.environment!==void 0&&(r.environment===null||typeof r.environment!="object"||typeof r.environment.name!="string"))throw new Error(`${e}: ${s} environment must be { "name", "url"? }.`)})}function WZ(e,t){if(!e.includes("*"))return e===t;let n="";for(let i=0;i<e.length;i++){let r=e[i];r==="*"&&e[i+1]==="*"?(n+=".*",i++):r==="*"?n+="[^/]*":n+=r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}return new RegExp(`^${n}$`).test(t)}function BZ(e,t){return t.filter(n=>e.runs.some(i=>WZ(i,n.target)))}function $j(e,t){for(let n of t){let i=(e.jobs??[]).filter(r=>r.runs.some(o=>WZ(o,n))).map(r=>`"${r.name}"`);if(i.length>1)return`wave "${e.name}" jobs: run "${n}" is in job groups ${i.join(" and ")}; each run is in exactly one`;if(i.length===0)return`wave "${e.name}" jobs: run "${n}" is in no job group; each run is in exactly one`}}function zg(e,t,n){if(!Array.isArray(n)||n.length===0||!n.every(i=>typeof i=="string")||n[0]==="")throw new Error(`${e}: \`${t}\` must be a command as argv, a non-empty array of strings.`)}function xp(e,t){if(t!==void 0){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e}: \`hooks\` must be { "before"?: { "plan"?, "apply"? }, "after"?: { "plan"?, "apply"? } }.`);for(let[n,i]of Object.entries(t)){if(n==="apply"){let r=i?.runBy;if(i===null||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(o=>o!=="runBy"))throw new Error(`${e}: hooks.apply must be { "runBy"?: "chant" | "apply" }.`);if(r!==void 0&&!yj.includes(r))throw new Error(`${e}: hooks.apply.runBy is ${JSON.stringify(r)}; use ${yj.map(o=>`"${o}"`).join(" or ")}.`);continue}if(n!=="before"&&n!=="after")throw new Error(`${e}: hooks.${n} is not a moment; use hooks.before or hooks.after (or hooks.apply.runBy).`);if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`${e}: hooks.${n} must be { "plan"?: [...], "apply"?: [...] }.`);for(let[r,o]of Object.entries(i)){let s=`hooks.${n}.${r}`;if(r==="gate"&&n==="before")throw new Error(`${e}: ${s} is not a moment; a hook runs after the gate (hooks.after.gate), or before the plan or the apply.`);if(r!=="plan"&&r!=="apply"&&r!=="gate")throw new Error(`${e}: ${s} is not a stage; a hook runs before or after plan or apply, or after the gate.`);if(!Array.isArray(o))throw new Error(`${e}: ${s} must be a list of hooks.`);o.forEach((a,c)=>{let l=`${s}[${c}]${a&&typeof a=="object"&&typeof a.name=="string"?` (${a.name})`:""}`;if(!a||typeof a!="object")throw new Error(`${e}: ${l} must be { "command": [...], "onFailure"?, "perRun"? }.`);if(zg(e,`${l}.command`,a.command),a.onFailure!==void 0&&!MZ.includes(a.onFailure))throw new Error(`${e}: ${l} has onFailure "${a.onFailure}"; use ${MZ.join(" or ")}.`);if(a.onFailure==="approve"&&n==="after"&&r==="apply")throw new Error(`${e}: ${l} has onFailure "approve", but after the apply there is nothing left to hold. Use "fail".`);if(a.onFailure==="approve"&&r==="gate")throw new Error(`${e}: ${l} has onFailure "approve", but the gate has already decided when it runs. Use "fail", or hold the wave from an after.plan hook.`);if(a.perRun!==void 0&&typeof a.perRun!="boolean")throw new Error(`${e}: ${l}.perRun must be true or false.`);if(a.perRun){if(n==="before"&&r==="plan"&&a.command.some(u=>u.includes("{plan}")))throw new Error(`${e}: ${l} runs before the plan, so it has no {plan} yet.`)}else{let u=a.command.find(d=>d.includes("{target}")||d.includes("{plan}"));if(u)throw new Error(`${e}: ${l} runs once for the wave, so it has no {target} or {plan} ("${u}"). Set "perRun": true, or read the runs from {runs}.`)}})}}}}function vx(e,t){let n=e.waves.find(r=>r.name===t),i=(r,o)=>{let[s,a]=o.split("-");return r?.[s]?.[a]??[]};return Object.fromEntries(wx.map(r=>[r,[...i(e.hooks,r),...i(n?.hooks,r)]]))}function kx(e,t){return e.waves.find(i=>i.name===t)?.hooks?.apply?.runBy??e.hooks?.apply?.runBy??"chant"}function Rj(e,t,n){return lj(e,t,n,i=>i.target)}var Ug,ec,MZ,wx,yj,yke,FZ,xj,wj,wke,$p=v(()=>{"use strict";Ps();bv();uj();bv();Ug=["always","on-destructive","never"],ec=["ledger","pr-review","sealed"];MZ=["fail","approve"],wx=["before-plan","after-plan","after-gate","before-apply","after-apply"],yj=["chant","apply"],yke=["all","changing"],FZ=px;xj=["chant","run","{op}","--env","{target}"];wj=/^[a-z0-9][a-z0-9_-]*$/;wke=/^[A-Za-z_][A-Za-z0-9_]*$/});function Sj(e,t,n){let i=t.toLowerCase(),r=n.toLowerCase();return i===vke[e]?`${e}:${r}`:`${e}@${i}:${r}`}var tc,vke,Ej=v(()=>{"use strict";tc=class extends Error{constructor(n,i,r,o){super(`${n} ${i} answered ${r}${o?`: ${o.slice(0,300)}`:""}`);this.method=n;this.url=i;this.status=r;this.detail=o;this.name="ForgeApiError"}},vke={github:"github.com",gitlab:"gitlab.com",forgejo:null}});var VZ={};_e(VZ,{HEAD_PLANS_DIR:()=>Hg,headPlansPath:()=>qg,listWavePlanSpecs:()=>$ke,parseHeadPlans:()=>Oj,readAllHeadPlans:()=>zZ,readHeadPlanDigests:()=>xke,readHeadPlans:()=>kke,waveDigests:()=>UZ});function qg(e,t){return{dir:`${Hg}/${e}`,file:`${t}.json`}}function Oj(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}if(t===null||typeof t!="object")return null;let n=t;if(n.version!==1||typeof n.name!="string"||typeof n.head!="string"||typeof n.timestamp!="string"||!Array.isArray(n.waves))return null;let i=[];for(let r of n.waves){if(r===null||typeof r!="object")return null;let{wave:o,name:s,digest:a}=r;if(typeof o!="number"||typeof s!="string"||typeof a!="string")return null;i.push({wave:o,name:s,digest:a})}return{version:1,name:n.name,head:n.head,timestamp:n.timestamp,waves:i}}async function kke(e,t,n){let{dir:i,file:r}=qg(t,n);return Oj(await e.read(i,r))}async function zZ(e,t){let n=new Map,{dir:i}=qg(t,"");for(let r of(await e.list(i)).sort()){if(!r.endsWith(".json"))continue;let o=Oj(await e.read(i,r));o&&n.set(r.slice(0,-5),o)}return n}function UZ(e){return new Map(e.waves.map(t=>[t.wave,t.digest]))}async function xke(e,t){let n=new Map;for(let[i,r]of await zZ(e,t))n.set(i,UZ(r));return n}async function $ke(e){return(await e.list(Hg)).sort()}var Hg,Aj=v(()=>{"use strict";Hg="_wave-plans"});var Kg={};_e(Kg,{GATE_APPROVAL_SOURCES:()=>ec,HEAD_PLANS_DIR:()=>Hg,bothRules:()=>Oke,forgejoReviews:()=>YZ,githubReviews:()=>ZZ,gitlabReviews:()=>XZ,headPlansPath:()=>qg,pullRequestHeadFromEnv:()=>Pke,reviewSourceFromEnv:()=>Ake,sealedApprovalRule:()=>Eke,trustPolicyAt:()=>Ske});import{readFileSync as Rke}from"node:fs";function Ske(e,t){return Ha(xi(e,t),t)}function Eke(e,t){return{requirement:{gate:e,class:null},refuses(n){return ya(t,n)}}}function Oke(e,t){return e?t?{requirement:e.requirement,refuses:n=>e.refuses(n)??t.refuses(n)}:e:t}function KZ(e,t,n){return async i=>{let r=`${qZ(e)}${i}`,o=await n(r,{method:"GET",headers:t}),s=await o.text();if(!o.ok)throw new tc("GET",r,o.status,s);return s?JSON.parse(s):null}}function JZ(e,t){let n=KZ(t.apiBase,e==="github"?{Authorization:`Bearer ${t.token}`,Accept:"application/vnd.github+json"}:{Authorization:`token ${t.token}`,Accept:"application/json"},t.fetch??globalThis.fetch),i=`/repos/${t.repo}`,r=c=>Sj(e,t.host,c),o=e==="github"?"per_page=100":"limit=50";async function s(c){if(e==="forgejo")try{let p=await n(`${i}/commits/${c}/pull`);return jn(p)&&typeof p.number=="number"?p.number:null}catch(p){if(p instanceof tc&&p.status===404)return null;throw p}let l=await n(`${i}/commits/${c}/pulls`);if(!Array.isArray(l))return null;let u=l.filter(p=>jn(p)&&p.merged_at),d=u.find(p=>jn(p)&&p.merge_commit_sha===c)??u[0];return d&&typeof d.number=="number"?d.number:null}async function a(c){let l=await n(`${i}/collaborators/${encodeURIComponent(c)}/permission`);return jn(l)&&["admin","maintain","write","owner"].includes(String(l.role_name??l.permission))}return{kind:e,async mergedReview(c){let l=await s(c);if(l===null)return null;let u=await n(`${i}/pulls/${l}`);if(!jn(u)||!jn(u.user)||!jn(u.head))throw new Error(`pull request #${l} came back without its author or head`);let d=String(u.user.login),p=String(u.head.sha),f=await n(`${i}/pulls/${l}/reviews?${o}`),g=new Map;for(let k of Array.isArray(f)?f:[]){if(!jn(k)||!jn(k.user)||typeof k.state!="string")continue;let $=k.state.toUpperCase();$==="COMMENTED"||$==="COMMENT"||$==="PENDING"||g.set(String(k.user.login),k)}let h=[],w=[],b=!1;for(let[k,$]of g){let x=$.dismissed===!0?"DISMISSED":String($.state).toUpperCase();if(k.toLowerCase()===d.toLowerCase()){x==="APPROVED"&&w.push(`${r(k)} is the author, whose own review never counts`);continue}let R=e==="forgejo"?$.official===!0:await a(k);if(x==="REQUEST_CHANGES"||x==="CHANGES_REQUESTED"){R&&(b=!0),w.push(`${r(k)} requests changes`);continue}x==="APPROVED"&&(R?$.commit_id!==p||$.stale===!0?w.push(`${r(k)} approved ${String($.commit_id??"another commit").slice(0,12)}, not the head ${p.slice(0,12)}`):h.push(r(k)):w.push(`${r(k)} approved without write access${e==="forgejo"?" (the review is not official)":""}`))}return{pr:l,...typeof u.html_url=="string"?{url:u.html_url}:{},author:r(d),head:p,approvers:b?[]:h.sort(),refused:w}}}}function ZZ(e){return JZ("github",e)}function YZ(e){return JZ("forgejo",e)}function XZ(e){let t=KZ(e.apiBase,{"PRIVATE-TOKEN":e.token},e.fetch??globalThis.fetch),n=`/projects/${encodeURIComponent(decodeURIComponent(e.repo))}`,i=r=>Sj("gitlab",e.host,r);return{kind:"gitlab",async mergedReview(r){let o=await t(`${n}/repository/commits/${r}/merge_requests`),s=Array.isArray(o)?o.find(w=>jn(w)&&w.state==="merged"&&(w.merge_commit_sha===r||w.squash_commit_sha===r))??o.find(w=>jn(w)&&w.state==="merged"):void 0;if(!jn(s)||typeof s.iid!="number")return null;let a=s.iid,c=jn(s.author)?String(s.author.username):"",l=String(s.sha),u=await t(`${n}/approvals`),d=jn(u)&&u.reset_approvals_on_push===!0,p=await t(`${n}/merge_requests/${a}/approvals`),f=jn(p)&&Array.isArray(p.approved_by)?p.approved_by:[],g=[],h=[];for(let w of f){let b=jn(w)&&jn(w.user)?w.user:void 0;if(!b||typeof b.username!="string")continue;let k=b.username;if(k.toLowerCase()===c.toLowerCase()){h.push(`${i(k)} is the author, whose own approval never counts`);continue}if(!d){h.push(`${i(k)}'s approval names no commit, and the project keeps approvals after a new push (turn on "Remove all approvals when commits are added")`);continue}let $=await t(`${n}/members/all/${String(b.id)}`).catch(x=>{if(x instanceof tc&&x.status===404)return null;throw x});if(!jn($)||typeof $.access_level!="number"||$.access_level<30){h.push(`${i(k)} approved without the Developer role`);continue}g.push(i(k))}return{pr:a,...typeof s.web_url=="string"?{url:s.web_url}:{},author:i(c),head:l,approvers:g.sort(),refused:h}}}}function Ake(e=process.env,t){let n=t?{fetch:t}:{};if(e.GITLAB_CI==="true"){let a=e.CHANT_FORGE_TOKEN??e.GITLAB_TOKEN;if(!e.CI_API_V4_URL||!e.CI_PROJECT_ID||!a)throw new Error("a pr-review gate on GitLab needs CI_API_V4_URL, CI_PROJECT_ID and CHANT_FORGE_TOKEN (a token with read_api)");return XZ({apiBase:e.CI_API_V4_URL,repo:e.CI_PROJECT_ID,token:a,host:e.CI_SERVER_HOST??HZ(e.CI_SERVER_URL,"gitlab.com"),...n})}let i=e.CHANT_FORGE_TOKEN??e.GITHUB_TOKEN??e.GH_TOKEN;if(!e.GITHUB_REPOSITORY||!i)throw new Error("a pr-review gate needs GITHUB_REPOSITORY and a token (GITHUB_TOKEN with pull-requests: read, or CHANT_FORGE_TOKEN)");let r=e.FORGEJO_ACTIONS==="true"||e.GITEA_ACTIONS==="true",o=HZ(e.GITHUB_SERVER_URL,"github.com"),s={apiBase:e.GITHUB_API_URL??(r?`${qZ(e.GITHUB_SERVER_URL??"")}/api/v1`:"https://api.github.com"),repo:e.GITHUB_REPOSITORY,token:i,host:o,...n};return r?YZ(s):ZZ(s)}function Pke(e=process.env){if(e.GITLAB_CI==="true")return e.CI_MERGE_REQUEST_IID&&(e.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||e.CI_COMMIT_SHA)||void 0;if(e.GITHUB_EVENT_PATH)try{let n=JSON.parse(Rke(e.GITHUB_EVENT_PATH,"utf-8")).pull_request?.head?.sha;return typeof n=="string"&&n!==""?n:void 0}catch{return}}var jn,qZ,HZ,Jg=v(()=>{"use strict";wa();Go();Qi();Ej();$p();Aj();jn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qZ=e=>e.replace(/\/+$/,"");HZ=(e,t)=>{try{return e?new URL(e).host.toLowerCase():t}catch{return t}}});var Tj={};_e(Tj,{OVERRIDERS_PATH:()=>Rp,OVERRIDE_APPLIED:()=>e5,OVERRIDE_LEDGER:()=>Tke,OVERRIDE_OP:()=>Zn,appliedOverride:()=>Dke,decideOverride:()=>Ike,overrideAuditApplies:()=>jke,overrideCommand:()=>xx,overrideDigest:()=>Pj,overridePending:()=>t5,overrideRefusal:()=>r5,overridersAt:()=>Cj,parseAppliedOverrides:()=>_j,parseOverriders:()=>n5,recordedDenials:()=>$x,sortedRules:()=>nc});import{createHash as Cke}from"node:crypto";import{spawnSync as _ke}from"node:child_process";function nc(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function Pj(e,t,n){let i=[Zn,e,t,...nc(n)].join(`
164
164
  `);return`sha256:${Cke("sha256").update(i).digest("hex")}`}function xx(e,t,n=!1){return`chant approve ${Zn} ${e} ${nc(t).map(i=>`--rule ${i}`).join(" ")} --reason "<why>"${n?" --sign":""}`}function t5(e){let t=nc(e.rules);return{version:1,kind:"pending",op:Zn,gate:e.subject,timestamp:e.timestamp,expiresAt:e.expiresAt,planDigest:Pj(e.subject,e.planDigest,t),plan:e.planDigest,rules:t,description:e.description??`the policy denied this plan (${t.join(", ")})`,...e.runId?{runId:e.runId}:{},...e.url?{url:e.url}:{}}}function $x(e){let t=new Map;for(let n of e){if(n.op!==Zn||!n.planDigest)continue;let i=t.get(n.gate);(!i||Vo(n.timestamp)>=Vo(i.timestamp))&&t.set(n.gate,n)}return[...t.values()].map(n=>{let i=n;return{...n,plan:typeof i.plan=="string"?i.plan:"",rules:Array.isArray(i.rules)?nc(i.rules.filter(r=>typeof r=="string")):[]}}).sort((n,i)=>n.gate<i.gate?-1:n.gate>i.gate?1:0)}function n5(e){let t=[];for(let n of e.split(`
165
165
  `)){let i=n.replace(/#.*$/,"").trim();i&&!t.includes(i)&&t.push(i)}return t}function Cj(e,t,n=Rp){let i=_ke("git",["cat-file","blob",`${t}:${n}`],{cwd:e,encoding:"utf-8"});return i.status!==0?{base:t,path:n,active:!1,principals:[]}:{base:t,path:n,active:!0,principals:n5(i.stdout)}}function _j(e){let t=[];for(let n of e.split(`
@@ -180,7 +180,7 @@ ${r}`,"utf-8")}function lN(e,t,n,i){return Buffer.from(`${e}
180
180
  ${t}
181
181
  ${n}
182
182
  ${i??""}`,"utf-8")}function e$e(e,t){let n=t.record===null||t.digest===null||typeof t.on!="string";return uN(e,{principal:t.reviewer,what:`the verdict by ${t.reviewer}`,role:"reviewer",namespace:aN,seal:t.seal,payload:n?`a seal covers the record id, the verdict's digest and on, and the verdict by ${t.reviewer} lacks one`:cN(t.record,t.digest,t.verdict,t.reviewer,t.on)})}function t$e(e,t){let n=t.record??"the record";return t.author===null&&(t.seal===void 0||t.seal===null)?{attested:null,code:"seal-missing",message:`${n} names no ${t.authorField}, so it claims no author to seal`}:uN(e,{principal:t.author??"",what:n,role:t.authorField,namespace:Dx,seal:t.seal,payload:t.record===null||t.author===null?`a record's seal covers its id and its ${t.authorField}, and ${n} lacks one`:lN(t.record,t.digest,t.author,t.state)})}function n$e(e,t){return uN(e,{principal:t.resolvedBy,what:`the approval of gate ${t.gate} by ${t.resolvedBy}`,role:"approver",namespace:Un,seal:t.seal,payload:Ao(t)})}function uN(e,t){let n=`${e.signersPath} at base`;if(t.seal===void 0||t.seal===null)return e.active?{attested:!1,code:"seal-missing",message:`${t.what} carries no seal`}:{attested:null,code:"seal-missing",message:`${t.what} carries no seal; there is no signers file at base, so none is needed`};let i=t.seal;if(typeof i!="object"||Array.isArray(i)||typeof i.signer!="string"||typeof i.signature!="string")return{attested:!1,code:"seal-signature-invalid",message:`the seal on ${t.what} is malformed: it needs signer and signature`};if(Ix(i.signer)!==Ix(t.principal))return{attested:!1,code:"seal-signature-invalid",message:t.role==="reviewer"?`the seal is by ${i.signer}, and the verdict is ${t.principal}'s`:`the seal on ${t.what} is by ${i.signer}, and its ${t.role} is ${t.principal||"empty"}`};if(typeof t.payload=="string")return{attested:!1,code:"seal-signature-invalid",message:t.payload};if(!e.active)return K5(t.principal,t.payload,i.signature,t.namespace);let r=e.signers.filter(s=>Ix(s.principal)===Ix(t.principal));if(r.length===0&&e.returnedFrom!==void 0){let s=K5(t.principal,t.payload,i.signature,t.namespace);return s.attested===!1?s:{attested:null,code:"seal-unverifiable",message:`${t.what} came back in return ${e.returnedFrom}, sealed by ${t.principal}${s.key?` with ${s.key}`:""}, whom neither ${n} nor an admission for that return lists; it counts once an admin admits the signer (chant workspace admit ${e.returnedFrom})`,...s.key?{key:s.key}:{}}}if(r.length===0)return{attested:!1,code:"seal-signer-unlisted",message:`${t.principal} has no key in ${n}, so the seal can't count`};let o=t.namespace===Un?r$e(r,t.payload,i.signature):cp(r,t.payload,i.signature,t.namespace);return o.ok?{attested:!0,message:`sealed by ${o.principal}${o.key?` with ${o.key}`:""}, a signer ${n} lists`,...o.key?{key:o.key}:{}}:o.missing?{attested:null,code:"seal-unverifiable",message:`the seal by ${t.principal} can't be checked here: ${o.reason}`}:{attested:!1,code:"seal-signature-invalid",message:`the seal does not verify for ${t.principal} against ${n}: ${o.reason}`}}function r$e(e,t,n){let i=e.filter(o=>Em(o.namespaces,Un)).map(o=>Buffer.from(o.key.split(" ")[1]??"","base64")),r=ha(n,t,Un,i);return r.ok?{ok:!0,principal:e[0].principal,key:r.key}:{ok:!1,reason:r.reason}}function K5(e,t,n,i){if(i===Un){let o=Q_(n),s=o?ha(n,t,i,[o]):{ok:!1,reason:"it is not an SSHSIG"};return s.ok?{attested:null,code:"seal-unverifiable",message:`the signature is intact (${s.key}), and there is no signers file at base to say whose key it is`,key:s.key}:{attested:!1,code:"seal-signature-invalid",message:`the seal by ${e} does not verify over this approval, even without a signers file`}}let r=rN(Gl(sN(),"chant-seal-"));try{let o=Gl(r,"signature");oN(o,n);let s=qa(["-Y","check-novalidate","-n",i,"-s",o],t);if(s.missing)return{attested:null,code:"seal-unverifiable",message:`the seal by ${e} can't be checked here: ssh-keygen is not installed`};if(s.status!==0)return{attested:!1,code:"seal-signature-invalid",message:`the seal by ${e} does not verify over ${i===Dx?"this record":i===Un?"this approval":"this verdict"}, even without a signers file`};let a=Z5.exec(s.stdout+s.stderr)?.[1];return{attested:null,code:"seal-unverifiable",message:`the signature is intact${a?` (${a})`:""}, and there is no signers file at base to say whose key it is`,...a?{key:a}:{}}}finally{iN(r,{recursive:!0,force:!0})}}function i$e(e,t){let n={cleanup:()=>{}};if(e!==!0)return{file:q5(t,J5(e)),...n};let i=l=>{try{return Qxe("git",["config","--get",l],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}},r=i("gpg.format"),o=i("user.signingkey");if(r!=="ssh"||o===void 0)throw new Fl(`--sign with no key file uses git's user.signingkey when gpg.format is ssh, and git has ${r==="ssh"?"no user.signingkey":`gpg.format ${r??"unset"}`}; pass --sign <key file>`);let s=o.startsWith("key::")?o.slice(5):o.startsWith("ssh-")||o.startsWith("ecdsa-")||o.startsWith("sk-")?o:void 0;if(s===void 0)return{file:q5(t,J5(o)),...n};let a=rN(Gl(sN(),"chant-sign-")),c=Gl(a,"key.pub");return oN(c,`${s}
183
- `),{file:c,cleanup:()=>iN(a,{recursive:!0,force:!0})}}function J5(e){return e==="~"?H5():e.startsWith("~/")?Gl(H5(),e.slice(2)):e}function o$e(e,t){return jx(e,cN(t.record,t.digest,t.verdict,t.reviewer,t.on),aN,t.reviewer)}function s$e(e,t){return jx(e,lN(t.record,t.digest,t.author,t.state),Dx,t.author)}function a$e(e,t){return jx(e,Ao(t),Un,t.resolvedBy)}function c$e(e,t){return jx(e,QV(t),XV,t.actor)}function jx(e,t,n,i){let r=qa(["-q","-Y","sign","-n",n,"-f",e],t);if(r.missing)throw new Fl("--sign needs ssh-keygen, and it is not installed here");if(r.status!==0||!r.stdout.startsWith("-----BEGIN SSH SIGNATURE-----"))throw new Fl(`ssh-keygen could not sign with ${e}: ${r.stderr.trim()||`exit ${r.status}`}`);let o=rN(Gl(sN(),"chant-seal-"));try{let s=Gl(o,"signature");oN(s,r.stdout);let a=qa(["-Y","check-novalidate","-n",n,"-s",s],t),c=Z5.exec(a.stdout+a.stderr)?.[1];if(a.status!==0||!c)throw new Fl(`the signature ssh-keygen made with ${e} does not check: ${a.stderr.trim()}`);return{signer:i,key:c,signature:r.stdout}}finally{iN(o,{recursive:!0,force:!0})}}var aN,Dx,Ix,Z5,Fl,Op=v(()=>{"use strict";Dg();wa();ks();wa();aN="chant-review",Dx="chant-record";Ix=e=>e.normalize("NFKC").trim().toLowerCase(),Z5=/key (SHA256:[A-Za-z0-9+/=]+)/;Fl=class extends Error{constructor(t){super(t),this.name="SealError"}}});import{execFileSync as l$e}from"node:child_process";import{dirname as u$e,resolve as dN}from"node:path";async function ah(e,t=[]){let n=[...t.map(o=>dN(e,o))];try{n.push(...Si(e).map(o=>o.file))}catch(o){if(!(o instanceof xe))throw o}let i=new Set,r=[];for(let o of n){let s=Yn(o);if(!i.has(s)){i.add(s);try{let a=await Ht(o,e);a.kind.session&&r.push(a)}catch(a){if(!(a instanceof Xe))throw a}}}return r}async function X5(e,t){let n=Yn(dN(t,e));return(await ah(t)).filter(i=>Sg(i.kind.session).some(r=>Yn(dN(u$e(i.file),r))===n))}function ch(e){let t=cr(Yn(e));if(!t)return null;try{return Ol(t,"HEAD")}catch(n){if(n instanceof Xe)return null;throw n}}function Nx(e,t,n){try{return l$e("git",["log",...n,"--format=%H","--",t],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).split(`
183
+ `),{file:c,cleanup:()=>iN(a,{recursive:!0,force:!0})}}function J5(e){return e==="~"?H5():e.startsWith("~/")?Gl(H5(),e.slice(2)):e}function o$e(e,t){return jx(e,cN(t.record,t.digest,t.verdict,t.reviewer,t.on),aN,t.reviewer)}function s$e(e,t){return jx(e,lN(t.record,t.digest,t.author,t.state),Dx,t.author)}function a$e(e,t){return jx(e,Ao(t),Un,t.resolvedBy)}function c$e(e,t){return jx(e,QV(t),XV,t.actor)}function jx(e,t,n,i){let r=qa(["-q","-Y","sign","-n",n,"-f",e],t);if(r.missing)throw new Fl("--sign needs ssh-keygen, and it is not installed here");if(r.status!==0||!r.stdout.startsWith("-----BEGIN SSH SIGNATURE-----"))throw new Fl(`ssh-keygen could not sign with ${e}: ${r.stderr.trim()||`exit ${r.status}`}`);let o=rN(Gl(sN(),"chant-seal-"));try{let s=Gl(o,"signature");oN(s,r.stdout);let a=qa(["-Y","check-novalidate","-n",n,"-s",s],t),c=Z5.exec(a.stdout+a.stderr)?.[1];if(a.status!==0||!c)throw new Fl(`the signature ssh-keygen made with ${e} does not check: ${a.stderr.trim()}`);return{signer:i,key:c,signature:r.stdout}}finally{iN(o,{recursive:!0,force:!0})}}var aN,Dx,Ix,Z5,Fl,Op=v(()=>{"use strict";Dg();wa();ks();wa();aN="chant-review",Dx="chant-record";Ix=e=>e.normalize("NFKC").trim().toLowerCase(),Z5=/key (SHA256:[A-Za-z0-9+/=]+)/;Fl=class extends Error{constructor(t){super(t),this.name="SealError"}}});import{execFileSync as l$e}from"node:child_process";import{dirname as u$e,resolve as dN}from"node:path";async function ah(e,t=[]){let n=[...t.map(o=>dN(e,o))];try{n.push(...Si(e).map(o=>o.file))}catch(o){if(!(o instanceof ve))throw o}let i=new Set,r=[];for(let o of n){let s=Yn(o);if(!i.has(s)){i.add(s);try{let a=await Ht(o,e);a.kind.session&&r.push(a)}catch(a){if(!(a instanceof Xe))throw a}}}return r}async function X5(e,t){let n=Yn(dN(t,e));return(await ah(t)).filter(i=>Sg(i.kind.session).some(r=>Yn(dN(u$e(i.file),r))===n))}function ch(e){let t=cr(Yn(e));if(!t)return null;try{return Ol(t,"HEAD")}catch(n){if(n instanceof Xe)return null;throw n}}function Nx(e,t,n){try{return l$e("git",["log",...n,"--format=%H","--",t],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).split(`
184
184
  `).filter(Boolean)}catch{return[]}}var Y5,Lx=v(()=>{"use strict";Tt();Qi();un();Ei();Y5=/^[A-Za-z][A-Za-z0-9]*-[0-9]+$/});var Q5={};_e(Q5,{CLOSE_ERROR_CODES:()=>d$e,RECORDS_CLOSE_SCHEMA_ID:()=>Mx,closeRecord:()=>f$e});function p$e(e){return e.toISOString().replace(/\.\d{3}Z$/,"Z")}async function f$e(e){try{if(e.expect!==void 0&&!/^[0-9a-f]{64}$/.test(e.expect))throw new Ee("write-usage-invalid",`--expect takes a record's digest, 64 lowercase hex digits as records --json prints it, not ${JSON.stringify(e.expect)}`);return await no(e.cwd,io("records close",e),e.dryRun,()=>m$e(e))}catch(t){return Zo(Mx,t)}}async function m$e(e){try{let t=await Ts(e.kind,e.cwd);Wl(t,"close",e.cwd,e);let{kind:n}=t.loaded,i=n.session;if(!i||n.stateField===void 0)throw new Ee("write-usage-invalid",`the ${n.name} kind has no session block, and records close closes a review session; amend sets the state of other records`);let r=(n.closedStates??[])[0];if(r===void 0)throw new Ee("write-usage-invalid",`the ${n.name} kind lists no closed state, so a session of it can't close`);let o=await ro(t,t.source),s=Ap(o,e.id,n.name);if(lh(t,s,e.id,e.expect),s.state!==null&&(n.closedStates??[]).includes(s.state))throw new Ee("record-closed",`${e.id} is already ${s.state}, and a closed session is sealed and stays as it is`);if(s.data===null)throw new Ee("record-unparseable",`${s.path} can't be read, so it can't be closed`);let a=s.data,c=ch(t.root),l={...uh(n,a,t.root),[n.stateField]:r,...i.closedOn?{[i.closedOn]:p$e(e.now??new Date)}:{},...i.closedRev?{[i.closedRev]:c}:{}},u={...a,...l};delete u[i.seal];let d=_s(t.source.read(s.path),l,u);if(d===void 0)throw new Ee("record-unparseable",`${s.path}: its fields can't be rewritten in place without changing the rest of the file`);let p=Gk(d,i.seal,n.format);if(p===null)throw new Ee("record-unparseable",`${s.path} can't be read, so it can't be sealed`);let f=_s(d,{[i.seal]:p},{...u,[i.seal]:p});if(f===void 0||Gk(f,i.seal,n.format)!==p)throw new Ee("record-unparseable",`${s.path}: the ${i.seal} line can't be added without changing the text it seals`);let g=await uc(t,o,s.path,f);e.dryRun||(Ml(Jo(t,s.path),f),Cs(t.root,[{path:s.path,text:f}],io("records close",e)));let h={...u,[i.seal]:p};return{$schema:Mx,contract:Ko,kind:t.view,path:s.path,id:e.id,changed:Object.keys(h).filter(w=>bn(a[w])!==bn(h[w])),seal:{field:i.seal,digest:p},closedRev:c,dryRun:!!e.dryRun,warnings:g.warnings,digest:g.digest,...e.dryRun?{text:f}:{}}}catch(t){return Zo(Mx,t)}}var Mx,d$e,e9=v(()=>{"use strict";RD();un();dh();oh();Lx();Bo();Mx="https://intentius.io/chant/schemas/workspace/records-close/v1/records-close.schema.json",d$e=[...lc,"write-usage-invalid","record-not-found","record-closed","record-conflict",...ac,...Za,...Ua]});var $9={};_e($9,{AMEND_ERROR_CODES:()=>b$e,LOAD_ERROR_CODES:()=>lc,NEW_ERROR_CODES:()=>w$e,RECORDS_AMEND_SCHEMA_ID:()=>ph,RECORDS_NEW_SCHEMA_ID:()=>dc,RECORDS_REVIEW_SCHEMA_ID:()=>fh,RECORDS_WRITE_CONTRACT_VERSION:()=>Ko,REVIEW_ERROR_CODES:()=>v$e,RecordWriteError:()=>Ee,VERDICTS:()=>gN,WRITE_USAGE:()=>k9,abs:()=>Jo,allocateId:()=>h9,amendRecord:()=>b9,declaredSessionKind:()=>x9,declaredWriteKind:()=>yN,failure:()=>Zo,findRecord:()=>Ap,isContentAddressed:()=>Fx,newRecord:()=>w9,open:()=>Ts,openedRevFill:()=>uh,overlay:()=>mh,pick:()=>pc,readAll:()=>ro,refuseOutOfScope:()=>Wl,refuseStale:()=>lh,removeField:()=>a9,renderRecord:()=>Is,replaceFields:()=>_s,resolveWriteKind:()=>Cp,reviewRecord:()=>v9,runRecordsWrite:()=>D$e,schemaOrder:()=>Tp,slug:()=>hN,stableJson:()=>bn,toYaml:()=>Pp,validateWrite:()=>Gx,validatedEntry:()=>uc,writeWho:()=>io});import{createHash as g$e}from"node:crypto";import{readFileSync as h$e,statSync as y$e,writeFileSync as o9}from"node:fs";import{join as wN,posix as _p,relative as t9,resolve as s9}from"node:path";function pN(e){return k$e.test(e)&&!x$e.has(e)?e:JSON.stringify(e)}function fN(e){return e===null||typeof e!="object"}function n9(e){return Array.isArray(e)?e.length===0:e!==null&&typeof e=="object"&&Object.keys(e).length===0}function Pp(e,t=0){let n=" ".repeat(t);if(Array.isArray(e))return e.length===0?`${n}[]`:e.map(r=>fN(r)?`${n}- ${mN(r)}`:n9(r)?`${n}- ${r9(r)}`:Array.isArray(r)?`${n}-
185
185
  ${Pp(r,t+2)}`:`${n}- ${Pp(r,t+2).slice(t+2)}`).join(`
186
186
  `);if(fN(e))return`${n}${mN(e)}`;let i=[];for(let[r,o]of Object.entries(e))fN(o)?i.push(`${n}${pN(r)}: ${mN(o)}`):n9(o)?i.push(`${n}${pN(r)}: ${r9(o)}`):i.push(`${n}${pN(r)}:
@@ -200,7 +200,7 @@ ${t}`}function $$e(e){let t=e.replace(/\r\n?/g,`
200
200
  # ${f}
201
201
  `:""),$;e.sign!==void 0&&({text:k,seal:$}=await g9(t,k,p,l,e.sign,e.cwd)),{text:k}=f9(t,k,$?{...p,[wn]:$}:p,l);let x=await uc(t,a,b,k);await l9(t,x,l);let R=x.warnings;return e.dryRun||(o9(Jo(t,b),k,{flag:"wx"}),Cs(t.root,[{path:b,text:k}],io("records new",e))),{$schema:dc,contract:Ko,kind:t.view,path:b,id:l,...$?{seal:$}:{},dryRun:!!e.dryRun,warnings:R,digest:x.digest,...e.dryRun?{text:k}:{}}}catch(t){return Zo(dc,t)}}async function P$e(e,t,n){let{kind:i,schema:r}=e.loaded;if(n.prefix!==void 0)throw new Ee("write-usage-invalid",`the ${i.name} kind's ids are the sha256 of each record's bytes, so --prefix allocates nothing`);if(n.sign!==void 0)throw new Ee("write-usage-invalid",`the ${i.name} kind names no author to seal: its records are named for the sha256 of their bytes`);let o=pc(t,Tp(t,r)),s=`${JSON.stringify(o,null,2)}
202
202
  `,a=g$e("sha256").update(s,"utf-8").digest("hex"),c=`${a}.json`;if(!new RegExp(i.location.match).test(c))throw new Ee("record-path-unmatched",`the kind's location.match ${i.location.match} does not match ${c}`);let l=e.dirRel==="."?c:`${e.dirRel}/${c}`;if(e.source.list(e.dirRel)?.includes(c))throw new Ee("record-id-taken",`${l} already exists, with the same bytes: the record is already written`);let u=await ro(e,e.source),d=await uc(e,u,l,s);return n.dryRun||(o9(Jo(e,l),s,{flag:"wx"}),Cs(e.root,[{path:l,text:s}],io("records new",n))),{$schema:dc,contract:Ko,kind:e.view,path:l,id:a,dryRun:!!n.dryRun,warnings:d.warnings,digest:d.digest,...n.dryRun?{text:s}:{}}}async function b9(e){try{return u9(e.expect),await no(e.cwd,io("records amend",e),e.dryRun,()=>C$e(e))}catch(t){return Zo(ph,t)}}async function C$e(e){try{let t=await Ts(e.kind,e.cwd),n=Wl(t,"amend",e.cwd,e),i=y9(t,d9(e.fields,"--set"),e,!1,"--set"),{kind:r}=t.loaded;c9(n,r,i,"--set",e.agent),p9(t,i,"--set");let o=await ro(t,t.source),s=Ap(o,e.id,r.name);lh(t,s,e.id,e.expect);let a=s.data;m9(r,i,a,"--set");let l={...s.state!==null&&(r.closedStates??[]).includes(s.state)?{}:uh(r,a,t.root),...i},u=Object.keys(l).filter(A=>!(A in a)),d=pc({...a,...l},[...Object.keys(a),...Tp(pc(l,u),t.loaded.schema)]),p=Object.keys(d).filter(A=>bn(a[A])!==bn(d[A]));if(p.includes(r.idField))throw new Ee("amend-id-immutable",`${r.idField} never changes: ids are never renumbered. Write a new record that supersedes ${e.id} instead`);let f=s.state,g=r.supersedes?.key===void 0?JSON.stringify(e.id):`[{"${r.supersedes.key}": "${e.id}"}]`,h=r.supersedes?`chant workspace records new with ${r.supersedes.field}: ${g}`:"chant workspace records new";if((p.length>0||e.sign!==void 0)&&f!==null&&(r.closedStates??[]).includes(f))throw new Ee("record-closed",`${e.id} is ${f}, a closed state, so nothing in it changes. ${S$e(t,e.id,h)}`);let w=A=>typeof A=="string"?r.approval?.[A]??0:0;if(p.length>0&&r.approval&&w(f)>0){let A=[r.stateField,r.pins?.field,r.reviews?.field].filter(q=>typeof q=="string"),B=(r.states??[]).filter(q=>w(q)>=w(f)),C=p.filter(q=>!A.includes(q));if(C.length>0)throw new Ee("amend-supersede-instead",`${e.id} is ${f}, so ${C.join(", ")} can't change in place: only ${A.join(", ")} may. Write the change as a new record that supersedes it (${h}); it replaces ${e.id} once it is ${B.filter(q=>w(q)>0).join(" or ")}`);if(r.stateField!==void 0&&p.includes(r.stateField)&&w(d[r.stateField])<w(f))throw new Ee("amend-supersede-instead",`${e.id} is ${f}, and ${JSON.stringify(d[r.stateField])} is approved less strongly: a state only moves to ${B.join(", ")}. Write a new record that supersedes it (${h})`)}let b=t.source.read(s.path),k=p.length===0?b:_s(b,pc(d,p),d)??Is(d,$$e(b)),$,x,R=r.reviews!==void 0&&wn in a;if(e.sign!==void 0)({text:k,seal:$}=await g9(t,k,d,e.id,e.sign,e.cwd)),d[wn]=$;else if(R&&(El(k,Sl(r),r.format)!==El(b,Sl(r),r.format)||r.stateField!==void 0&&bn(a[r.stateField])!==bn(d[r.stateField]))){let A=a[wn]?.signer;delete d[wn];let B=a9(k,wn,d);if(B===void 0)throw new Ee("record-unparseable",`${s.path}: the ${wn} block can't be removed without changing the rest of the file`);k=B,x=`${e.id} was sealed${typeof A=="string"?` by ${A}`:""}, and the amendment moves its digest or its state, so the seal was removed: seal it again with records amend ${e.id} --sign`}if(bn(a[wn])!==bn(d[wn])&&p.push(wn),p.length>0&&r.seal&&!r.session){let A=f9(t,k,d,e.id);k=A.text,bn(a[r.seal.field])!==bn(A.data[r.seal.field])&&p.push(r.seal.field)}let P=s.warnings,I=s.digest;if(p.length>0){let A=await uc(t,o,s.path,k);r.stateField!==void 0&&p.includes(r.stateField)&&await l9(t,A,e.id),P=A.warnings,I=A.digest}return!e.dryRun&&p.length>0&&(Ml(Jo(t,s.path),k),Cs(t.root,[{path:s.path,text:k}],io("records amend",e))),{$schema:ph,contract:Ko,kind:t.view,path:s.path,id:e.id,changed:p,...$?{seal:$}:{},...x?{sealDropped:x}:{},dryRun:!!e.dryRun,warnings:P,digest:I,...e.dryRun?{text:k}:{}}}catch(t){return Zo(ph,t)}}async function v9(e){try{return u9(e.expect),await no(e.cwd,io("records review",e),e.dryRun,()=>_$e(e))}catch(t){return Zo(fh,t)}}async function _$e(e){try{if(!gN.includes(e.verdict))throw new Ee("write-usage-invalid",`--verdict takes ${gN.join(", ")}, not ${JSON.stringify(e.verdict)}`);if(e.by.trim()==="")throw new Ee("write-usage-invalid","--by needs the reviewer's name");if(e.session!==void 0&&e.session==="")throw new Ee("write-usage-invalid","--session needs a session id");let t=await Ts(e.kind,e.cwd);Wl(t,"review",e.cwd,e);let{kind:n}=t.loaded;if(!n.reviews)throw new Ee("review-unsupported",`the ${n.name} kind declares no reviews field, so its records take no review`);let i=n.reviews.field,r=await ro(t,t.source),o=Ap(r,e.id,n.name);if(lh(t,o,e.id,e.expect),o.state!==null&&(n.closedStates??[]).includes(o.state))throw new Ee("record-closed",`${e.id} is ${o.state}, a closed state, so it takes no more reviews`);if(e.verdict==="dissent"&&!(e.note??"").trim())throw new Ee("review-note-required","a dissent needs a reason: pass --note <text> with the concern");let s=e.session!==void 0?await T$e(t,e.session,e.cwd):void 0;s&&Wl(s.so,"review",e.cwd,e);let a=o.data[i]??[];if(!Array.isArray(a))throw new Ee("record-schema-invalid",`${o.path}: ${i} is not a list`);let c=t.source.read(o.path),l={reviewer:e.by,verdict:e.verdict,...e.note!==void 0?{note:e.note}:{},on:e.on??E$e(),digest:El(c,Sl(n),n.format),...e.session!==void 0?{session:e.session}:{}};e.sign!==void 0&&(l.seal=await I$e(e.sign,e.cwd,{record:e.id,digest:l.digest,verdict:e.verdict,reviewer:e.by,on:l.on}));let u=[...a,l],d=_s(c,{[i]:u},{...o.data,[i]:u});if(d===void 0)throw new Ee("record-unparseable",`${o.path}: the ${i} block can't be rewritten in place without changing the rest of the file`);let p=await uc(t,r,o.path,d),f=p.warnings,g;if(s){let{so:h,before:w,target:b}=s,k=h.loaded.kind.session,$=b.data[k.verdicts]??[];if(!Array.isArray($))throw new Ee("record-schema-invalid",`${b.path}: ${k.verdicts} is not a list`);let x={record:e.id,principal:e.by,verdict:e.verdict,digest:l.digest},R={...uh(h.loaded.kind,b.data,h.root),[k.verdicts]:[...$,x]},P=_s(h.source.read(b.path),R,{...b.data,...R});if(P===void 0)throw new Ee("record-unparseable",`${b.path}: the ${k.verdicts} block can't be rewritten in place without changing the rest of the file`);await Gx(h,w,b.path,P,mh(t.source,o.path,d)),g={path:b.path,text:P,out:{id:e.session,path:b.path,verdict:x,...e.dryRun?{text:P}:{}}}}return e.dryRun||(Ml(Jo(t,o.path),d),g&&Ml(Jo(t,g.path),g.text),Cs(t.root,[{path:o.path,text:d},...g?[{path:g.path,text:g.text}]:[]],io("records review",e))),{$schema:fh,contract:Ko,kind:t.view,path:o.path,id:e.id,review:l,...g?{session:g.out}:{},dryRun:!!e.dryRun,warnings:f,digest:p.digest,...e.dryRun?{text:d}:{}}}catch(t){return Zo(fh,t)}}async function T$e(e,t,n){let i=await X5(e.loaded.file,n);for(let r of i){let o=await Ts(r.file,n),s=await ro(o,o.source);if(!s.some(c=>c.id===t))continue;let a=Ap(s,t,o.view.name);if(a.data===null)throw new Ee("record-unparseable",`session ${t} (${a.path}) can't be read, so the verdict can't be added to it`);if(a.state!==null&&(o.loaded.kind.closedStates??[]).includes(a.state))throw new Ee("session-not-open",`session ${t} is ${a.state}, so it takes no more verdicts: give the verdict in an open session, or without --session`);return{so:o,before:s,target:a}}throw new Ee("session-unknown",i.length===0?`no session kind the workspace declaration names has ${e.view.file} as its subjects, so there is no session ${t} to give the verdict in`:`no ${i.map(r=>r.kind.name).join(" or ")} record has id ${t}`)}async function I$e(e,t,n){let{resolveSigningKey:i,sealVerdict:r,SealError:o}=await Promise.resolve().then(()=>(Op(),Ep));try{let s=i(e,t);try{return{...r(s.file,n)}}finally{s.cleanup()}}catch(s){throw s instanceof o?new Ee("review-sign-failed",s.message):s}}function ni(e,t){return{$schema:e,contract:Ko,error:{code:"write-usage-invalid",message:`${t}
203
- ${k9}`}}}function yN(e,t,n){let i;try{i=Si(t)}catch(r){if(!(r instanceof xe))throw r;return ni(e,`${n}; the declaration can't name one: ${r.code}: ${r.describe()}`)}return i.length===0?ni(e,n):i.length>1?ni(e,`the declaration names ${i.length} record kinds (${i.map(r=>r.declared.path).join(", ")}), so name the one to write with --kind`):i[0].file}function Cp(e,t){try{if(y$e(s9(t,e)).isFile())return e}catch{}let n;try{n=Si(t)}catch{return e}let i=n.filter(r=>(r.declared.name??_p.basename(r.declared.path).replace(/(?:\.kind)?\.[cm]?[jt]s$/,""))===e);return i.length===1?i[0].file:e}function i9(e,t,n,i){if(n===void 0||n==="")return ni(e,`${t} <file|-> is required`);try{return h$e(n==="-"?0:s9(i,n),"utf-8")}catch(r){return{$schema:e,contract:Ko,error:{code:"write-input-invalid",message:`${t} ${n} could not be read: ${r instanceof Error?r.message:String(r)}`}}}}async function x9(e,t){let n=(await ah(t)).map(i=>i.file);return n.length===1?n[0]:n.length===0?ni(e,"--kind <session kind file> is required: the declaration names no session kind"):ni(e,`the declaration names ${n.length} session kinds (${n.join(", ")}), so name the one to close with --kind`)}async function D$e(e){let{args:t}=e,n=process.cwd(),i=t.extraPositional,r=process.env[QD]||void 0,o=l=>(console.log(JSON.stringify(l,null,2)),"error"in l?1:0);if(i==="close"){let{closeRecord:l,RECORDS_CLOSE_SCHEMA_ID:u}=await Promise.resolve().then(()=>(e9(),Q5));if(t.sign!==void 0)return o(ni(u,"--sign is not taken by close: the seal close writes is the digest of the session text"));let d=t.extraPositional2;if(!d)return o(ni(u,"close needs the session's id"));let p=t.kind!==void 0?Cp(t.kind,n):await x9(u,n);return o(typeof p!="string"?p:await l({kind:p,id:d,dryRun:t.dryRun,cwd:n,agent:r,expect:t.expect}))}if(i==="new"){let l=t.extraPositional2??t.kind,u=l!==void 0?Cp(l,n):yN(dc,n,"new needs the kind file");if(typeof u!="string")return o(u);if(t.expect!==void 0)return o(ni(dc,"--expect is not taken by new: a new record has no digest yet, and its id is allocated under the write lock"));let d=i9(dc,"--from",t.migrateFrom,n);return o(typeof d!="string"?d:await w9({kind:u,fields:d,prefix:t.prefix,by:t.by,sign:t.sign,dryRun:t.dryRun,cwd:n,agent:r}))}let s=i==="amend"?ph:fh,a=t.extraPositional2;if(!a)return o(ni(s,`${i} needs the record's id`));let c=t.kind!==void 0?Cp(t.kind,n):yN(s,n,"--kind <kind file> is required");if(typeof c!="string")return o(c);if(i==="amend"){if(t.by!==void 0)return o(ni(s,"--by is not taken by amend: set decided_by, or a kind's proposedBy field, with --set"));let l=i9(s,"--set",t.set,n);return o(typeof l!="string"?l:await b9({kind:c,id:a,fields:l,sign:t.sign,dryRun:t.dryRun,cwd:n,agent:r,expect:t.expect}))}return t.verdict===void 0?o(ni(s,"--verdict agree|dissent|abstain is required")):t.by===void 0?o(ni(s,"--by <principal> is required")):o(await v9({kind:c,id:a,verdict:t.verdict,by:t.by,note:t.note,session:t.session,sign:t.sign,dryRun:t.dryRun,cwd:n,agent:r,expect:t.expect}))}var Ko,dc,ph,fh,lc,w$e,b$e,v$e,gN,Ee,k$e,x$e,mN,r9,O$e,k9,dh=v(()=>{"use strict";Qi();un();Ei();Pl();Tt();Lx();on();Bo();Tl();oh();Ko=1,dc="https://intentius.io/chant/schemas/workspace/records-new/v1/records-new.schema.json",ph="https://intentius.io/chant/schemas/workspace/records-amend/v1/records-amend.schema.json",fh="https://intentius.io/chant/schemas/workspace/records-review/v1/records-review.schema.json",lc=["kind-unreadable","kind-invalid","schema-unreadable","schema-id-mismatch","schema-invalid","location-missing"],w$e=[...lc,"write-usage-invalid","write-input-invalid","record-id-taken","record-id-unallocatable","record-path-unmatched","record-sign-failed","source-harvest-not-proposed","record-state-not-initial","ratify-quorum-not-met",...ac,...Za,..._l,...Ua],b$e=[...lc,"write-usage-invalid","write-input-invalid","record-not-found","amend-id-immutable","record-closed","amend-supersede-instead","record-sign-failed","ratify-quorum-not-met","record-conflict",...ac,...Za,..._l,...Ua],v$e=[...lc,"write-usage-invalid","record-not-found","review-unsupported","record-closed","review-note-required","review-sign-failed","session-unknown","session-not-open","record-conflict",...ac,...Za,..._l,...Ua],gN=["agree","dissent","abstain"],Ee=class extends Error{constructor(n,i,r){super(i);this.code=n;this.conflict=r;this.name="RecordWriteError"}},k$e=/^[A-Za-z_][A-Za-z0-9_-]*$/,x$e=new Set(["true","false","null"]);mN=e=>e===null?"null":JSON.stringify(e),r9=e=>Array.isArray(e)?"[]":"{}";O$e=/^([A-Za-z][A-Za-z0-9]*)-([0-9]+)$/;k9=["chant workspace records new [<kind file or declared kind>] --from <file|-> [--prefix <prefix>] [--by <name>] [--sign [<key file>]] [--dry-run]","chant workspace records amend <id> [--kind <kind file>] --set <file|-> [--expect <digest>] [--sign [<key file>]] [--dry-run]","chant workspace records review <id> [--kind <kind file>] --verdict agree|dissent|abstain --by <principal> [--note <text>] [--session <id>] [--expect <digest>] [--sign [<key file>]] [--dry-run]","chant workspace records close <session id> [--kind <session kind file>] [--expect <digest>] [--dry-run]"].join(`
203
+ ${k9}`}}}function yN(e,t,n){let i;try{i=Si(t)}catch(r){if(!(r instanceof ve))throw r;return ni(e,`${n}; the declaration can't name one: ${r.code}: ${r.describe()}`)}return i.length===0?ni(e,n):i.length>1?ni(e,`the declaration names ${i.length} record kinds (${i.map(r=>r.declared.path).join(", ")}), so name the one to write with --kind`):i[0].file}function Cp(e,t){try{if(y$e(s9(t,e)).isFile())return e}catch{}let n;try{n=Si(t)}catch{return e}let i=n.filter(r=>(r.declared.name??_p.basename(r.declared.path).replace(/(?:\.kind)?\.[cm]?[jt]s$/,""))===e);return i.length===1?i[0].file:e}function i9(e,t,n,i){if(n===void 0||n==="")return ni(e,`${t} <file|-> is required`);try{return h$e(n==="-"?0:s9(i,n),"utf-8")}catch(r){return{$schema:e,contract:Ko,error:{code:"write-input-invalid",message:`${t} ${n} could not be read: ${r instanceof Error?r.message:String(r)}`}}}}async function x9(e,t){let n=(await ah(t)).map(i=>i.file);return n.length===1?n[0]:n.length===0?ni(e,"--kind <session kind file> is required: the declaration names no session kind"):ni(e,`the declaration names ${n.length} session kinds (${n.join(", ")}), so name the one to close with --kind`)}async function D$e(e){let{args:t}=e,n=process.cwd(),i=t.extraPositional,r=process.env[QD]||void 0,o=l=>(console.log(JSON.stringify(l,null,2)),"error"in l?1:0);if(i==="close"){let{closeRecord:l,RECORDS_CLOSE_SCHEMA_ID:u}=await Promise.resolve().then(()=>(e9(),Q5));if(t.sign!==void 0)return o(ni(u,"--sign is not taken by close: the seal close writes is the digest of the session text"));let d=t.extraPositional2;if(!d)return o(ni(u,"close needs the session's id"));let p=t.kind!==void 0?Cp(t.kind,n):await x9(u,n);return o(typeof p!="string"?p:await l({kind:p,id:d,dryRun:t.dryRun,cwd:n,agent:r,expect:t.expect}))}if(i==="new"){let l=t.extraPositional2??t.kind,u=l!==void 0?Cp(l,n):yN(dc,n,"new needs the kind file");if(typeof u!="string")return o(u);if(t.expect!==void 0)return o(ni(dc,"--expect is not taken by new: a new record has no digest yet, and its id is allocated under the write lock"));let d=i9(dc,"--from",t.migrateFrom,n);return o(typeof d!="string"?d:await w9({kind:u,fields:d,prefix:t.prefix,by:t.by,sign:t.sign,dryRun:t.dryRun,cwd:n,agent:r}))}let s=i==="amend"?ph:fh,a=t.extraPositional2;if(!a)return o(ni(s,`${i} needs the record's id`));let c=t.kind!==void 0?Cp(t.kind,n):yN(s,n,"--kind <kind file> is required");if(typeof c!="string")return o(c);if(i==="amend"){if(t.by!==void 0)return o(ni(s,"--by is not taken by amend: set decided_by, or a kind's proposedBy field, with --set"));let l=i9(s,"--set",t.set,n);return o(typeof l!="string"?l:await b9({kind:c,id:a,fields:l,sign:t.sign,dryRun:t.dryRun,cwd:n,agent:r,expect:t.expect}))}return t.verdict===void 0?o(ni(s,"--verdict agree|dissent|abstain is required")):t.by===void 0?o(ni(s,"--by <principal> is required")):o(await v9({kind:c,id:a,verdict:t.verdict,by:t.by,note:t.note,session:t.session,sign:t.sign,dryRun:t.dryRun,cwd:n,agent:r,expect:t.expect}))}var Ko,dc,ph,fh,lc,w$e,b$e,v$e,gN,Ee,k$e,x$e,mN,r9,O$e,k9,dh=v(()=>{"use strict";Qi();un();Ei();Pl();Tt();Lx();on();Bo();Tl();oh();Ko=1,dc="https://intentius.io/chant/schemas/workspace/records-new/v1/records-new.schema.json",ph="https://intentius.io/chant/schemas/workspace/records-amend/v1/records-amend.schema.json",fh="https://intentius.io/chant/schemas/workspace/records-review/v1/records-review.schema.json",lc=["kind-unreadable","kind-invalid","schema-unreadable","schema-id-mismatch","schema-invalid","location-missing"],w$e=[...lc,"write-usage-invalid","write-input-invalid","record-id-taken","record-id-unallocatable","record-path-unmatched","record-sign-failed","source-harvest-not-proposed","record-state-not-initial","ratify-quorum-not-met",...ac,...Za,..._l,...Ua],b$e=[...lc,"write-usage-invalid","write-input-invalid","record-not-found","amend-id-immutable","record-closed","amend-supersede-instead","record-sign-failed","ratify-quorum-not-met","record-conflict",...ac,...Za,..._l,...Ua],v$e=[...lc,"write-usage-invalid","record-not-found","review-unsupported","record-closed","review-note-required","review-sign-failed","session-unknown","session-not-open","record-conflict",...ac,...Za,..._l,...Ua],gN=["agree","dissent","abstain"],Ee=class extends Error{constructor(n,i,r){super(i);this.code=n;this.conflict=r;this.name="RecordWriteError"}},k$e=/^[A-Za-z_][A-Za-z0-9_-]*$/,x$e=new Set(["true","false","null"]);mN=e=>e===null?"null":JSON.stringify(e),r9=e=>Array.isArray(e)?"[]":"{}";O$e=/^([A-Za-z][A-Za-z0-9]*)-([0-9]+)$/;k9=["chant workspace records new [<kind file or declared kind>] --from <file|-> [--prefix <prefix>] [--by <name>] [--sign [<key file>]] [--dry-run]","chant workspace records amend <id> [--kind <kind file>] --set <file|-> [--expect <digest>] [--sign [<key file>]] [--dry-run]","chant workspace records review <id> [--kind <kind file>] --verdict agree|dissent|abstain --by <principal> [--note <text>] [--session <id>] [--expect <digest>] [--sign [<key file>]] [--dry-run]","chant workspace records close <session id> [--kind <session kind file>] [--expect <digest>] [--dry-run]"].join(`
204
204
  `)});var vN={};_e(vN,{ANSWERS_LEDGER_DIR:()=>S9,answersLedgerDir:()=>O9,readLedgerAnswers:()=>hh,refreshLedger:()=>zx,withLedgerAnswers:()=>yh,writeLedgerAnswer:()=>bN});import{basename as j$e,dirname as R9}from"node:path";function O9(e){return`${S9}/${e.replace(/[^A-Za-z0-9._-]/g,"_")}`}function N$e(e,t){return e==="."?t:`${e}/${t}`}async function hh(e){let t=R9(e.file),n=O9(e.name),i={cwd:t,dir:n,dirRel:e.dirRel,byPath:new Map};try{let r=(await Zi(n,{cwd:t})).filter(s=>s.endsWith(".md"));if(r.length===0)return i;let o=await qn(n,{cwd:t});for(let s of r){let a=await gn(n,s,{cwd:t}),c=a?await hn(a,{cwd:t}):null;if(a===null||c===null)continue;let l=N$e(e.dirRel,s);i.byPath.set(l,{path:l,ledger:`${E9}:${o}/${s}`,text:c,sha:a})}}catch{}return i}function yh(e,t){let n=e;for(let i of t.byPath.values())n=mh(n,i.path,i.text);return n}async function zx(e){await Yi({cwd:R9(e)}).catch(()=>{})}async function bN(e,t,n,i,r){let o=j$e(t);await mn(e.dir,o,n,i,{cwd:e.cwd,expectPriorPathSha:r});let s=await Ld({cwd:e.cwd}).catch(()=>!1);return{ledger:`${E9}:${await qn(e.dir,{cwd:e.cwd})}/${o}`,pushed:s}}var S9,E9,wh=v(()=>{"use strict";Pt();dh();S9="_answers",E9="chant/lifecycle"});import{randomUUID as L$e}from"node:crypto";function Ux(e,t=""){return`${kN}${t}${e}`}function M$e(e,t=""){return`${xN}${t}${e}`}async function RN(e,t){let{prefix:n}=await Xr(t?.cwd??process.cwd());return{ref:Ux(e,n),trackingRef:M$e(e,n)}}function A9(e){return e?`${e.acquiredAt} ${e.expiresAt}`:""}function F$e(e,t){return new Date(e.expiresAt).getTime()<=t.getTime()}function G$e(e){try{let t=JSON.parse(e);return typeof t.op=="string"&&typeof t.holder=="string"&&typeof t.token=="string"&&typeof t.acquiredAt=="string"&&typeof t.expiresAt=="string"?t:void 0}catch{return}}async function P9(e,t){let n=await Da(e,t);return{sha:n,record:n?G$e(await hn(n,t)??""):void 0}}async function fc(e,t){let{ref:n,trackingRef:i}=await RN(e,t);if(await Rk(n,i,t).catch(()=>"failed")==="missing"){let u=await Da(i,t);u&&await Fd(i,u,t).catch(()=>{})}let{sha:o,record:s}=await P9(n,t),{sha:a,record:c}=await P9(i,t),l=A9(c)>A9(s)?c:s;return{sha:o,record:l,remoteSha:a}}async function bh(e,t,n){let i=Date.now()+(n?.lockWaitMs??0);for(;;)try{return await W$e(e,t,n)}catch(r){if(!(r instanceof fl)||Date.now()>=i)throw r;await new Promise(o=>setTimeout(o,20+Math.floor(Math.random()*60)))}}async function W$e(e,t,n){let i=n?.ttlMs??$N,r=n?.now?.()??new Date,o=n?.mode??"acquire",{sha:s,record:a,remoteSha:c}=await fc(e,n),l=!a||F$e(a,r),u=a?.holder===t;if(o==="renew"){if(!a||l||!u)return{acquired:!1,reason:a&&!l?"held":"not-held",...a?{heldBy:a}:{}};if(n?.token!==void 0&&a.token!==n.token)return{acquired:!1,reason:"token-mismatch",heldBy:a}}else if(a&&!l&&(!u||o==="claim"))return{acquired:!1,heldBy:a,reason:"held"};let d=!!a&&u&&!l,p={op:e,holder:t,token:d?a.token:L$e(),acquiredAt:d?a.acquiredAt:r.toISOString(),expiresAt:new Date(r.getTime()+i).toISOString()},{ref:f,trackingRef:g}=await RN(e,n),h=await NI(JSON.stringify(p),n);try{await Md(f,h,s,n)}catch(b){if(b instanceof Ot)return{acquired:!1,heldBy:(await fc(e,n)).record,reason:"race"};throw b}let w=await mg(f,{...n,expect:c}).catch(()=>"rejected");if(w==="pushed")await Md(g,h,c,n).catch(()=>{});else if(w==="rejected"&&n?.requirePush){await(s===null?Fd(f,h,n):Md(f,s,h,n)).catch(()=>{});let b=await fc(e,n),k=b.record&&b.record.token!==p.token?b.record:void 0;return{acquired:!1,reason:"push-rejected",...k?{heldBy:k}:{}}}return{acquired:!0,lease:p}}async function Vx(e,t,n,i){let{sha:r,record:o,remoteSha:s}=await fc(e,i);if(!o||o.holder!==t||o.token!==n)return!1;let{ref:a,trackingRef:c}=await RN(e,i);if(r)try{await Fd(a,r,i)}catch{return!1}let l=await mg(a,{...i,expect:s}).catch(()=>"rejected");return l==="pushed"&&s&&await Fd(c,s,i).catch(()=>{}),r!==null||l==="pushed"}var kN,xN,$N,Ip=v(()=>{"use strict";Pt();Io();kN="refs/chant/lease/",xN="refs/chant/lease-remote/",$N=5*6e4});var F9={};_e(F9,{ATTEMPT_OUTCOMES:()=>T9,DEFAULT_WORK_LEASE_TTL_MS:()=>qx,KEPT_REF_PREFIX:()=>ON,LEASES_DIR:()=>kh,WORK_ITEM_ID_PATTERN:()=>ih,WORK_LEASE_KEY_PREFIX:()=>Hx,WORK_LEASE_OUTCOMES:()=>EN,WORK_LEASE_REFUSALS:()=>H$e,activeWorkLeases:()=>Z$e,claimWorkLease:()=>D9,isWorkItemId:()=>Bj,isWorkLeaseOutcome:()=>Kx,keptAttemptPrefix:()=>AN,keptAttemptRef:()=>I9,leaseHistoryPath:()=>_9,listKeptAttempts:()=>V$e,listWorkLeases:()=>Yx,outcomeCountsAsAttempt:()=>U$e,parseLeaseHistory:()=>Zx,readLeaseHistory:()=>K$e,releaseWorkLease:()=>L9,renewWorkLease:()=>j9,workItemIdProblem:()=>Sp,workLeaseKey:()=>$h,workLeaseRef:()=>SN});import{dirname as B$e}from"node:path";function $h(e){return`${Hx}${e}`}function SN(e,t=""){return Ux($h(e),t)}function _9(e,t=""){return`${t}${kh}/${e}.jsonl`}function Kx(e){return typeof e=="string"&&EN.includes(e)}function U$e(e){return Kx(e)?T9.includes(e):!0}function I9(e,t,n=[]){return`${AN(e,n)}${t}`}function AN(e,t=[]){return`${ON}${t.length?`${t.join("/")}/`:""}${e}/`}async function V$e(e,t){let n=AN(e,t.members??[]),i=await bt().spawn(["git","for-each-ref","--format=%(refname) %(objectname)",n],{cwd:t.cwd});return i.exitCode!==0?[]:i.stdout.split(`
205
205
  `).filter(Boolean).map(r=>{let[o,s]=r.split(" ");return{token:o.slice(n.length),ref:o,commit:s}}).filter(r=>r.token!==""&&!r.token.includes("/")).sort((r,o)=>r.ref<o.ref?-1:r.ref>o.ref?1:0)}function xh(e,t){return{item:e,holder:t.holder,token:t.token,acquiredAt:t.acquiredAt,expiresAt:t.expiresAt}}function Jx(e){let t=Sp(e);if(t)throw new Error(t)}function vh(e,t,n){let i=n?`${n.holder} until ${n.expiresAt}`:void 0;switch(t){case"lease-held":return`${e} is held by ${i}`;case"lease-not-held":return`${e} is not held${n?` by the caller: ${i}`:""}; claim it again`;case"lease-token-mismatch":return`${e} is held with another token (${n?.token}) by ${i}`;case"lease-race":return`${e} changed while it was being written${i?`: it is held by ${i}`:""}`;case"lease-push-rejected":return`the remote refused the lease on ${e}${i?`: it is held there by ${i}`:", or could not be reached"}`}}async function D9(e,t,n){Jx(e);let i=await bh($h(e),t,{cwd:n.cwd,ttlMs:n.ttlMs??qx,now:n.now,mode:"claim",requirePush:!0,lockWaitMs:C9});return N9(e,"claim",t,i,n)}async function j9(e,t,n){Jx(e);let i=await bh($h(e),t,{cwd:n.cwd,ttlMs:n.ttlMs??qx,now:n.now,mode:"renew",token:n.token,requirePush:!0,lockWaitMs:C9});return N9(e,"renew",t,i,n)}async function N9(e,t,n,i,r){if(!i.acquired||!i.lease){let c=q$e[i.reason??"race"],l=i.heldBy?xh(e,i.heldBy):void 0;return{ok:!1,reason:c,message:vh(e,c,l),...l?{heldBy:l}:{}}}let o=xh(e,i.lease),s=r.now?.()??new Date,a=await M9({version:1,event:t,item:e,holder:n,by:n,token:o.token,acquiredAt:o.acquiredAt,expiresAt:o.expiresAt,timestamp:s.toISOString(),...r.note?{note:r.note}:{}},r);return{ok:!0,lease:o,history:a}}async function L9(e,t,n){if(Jx(e),n.outcome!==void 0&&!Kx(n.outcome))throw new Error(`${JSON.stringify(n.outcome)} is not a work lease outcome: use one of ${EN.join(", ")}`);let i=$h(e),r=n.now?.()??new Date,{record:o}=await fc(i,{cwd:n.cwd});if(!o)return{ok:!1,reason:"lease-not-held",message:vh(e,"lease-not-held",void 0)};let s=xh(e,o);if(new Date(o.expiresAt).getTime()>r.getTime()&&o.holder!==t)return{ok:!1,reason:"lease-held",message:vh(e,"lease-held",s),heldBy:s};if(n.token!==void 0&&o.token!==n.token)return{ok:!1,reason:"lease-token-mismatch",message:vh(e,"lease-token-mismatch",s),heldBy:s};if(!await Vx(i,o.holder,o.token,{cwd:n.cwd})){let l=(await fc(i,{cwd:n.cwd})).record,u=l?xh(e,l):void 0;return{ok:!1,reason:"lease-race",message:vh(e,"lease-race",u),...u?{heldBy:u}:{}}}let c=await M9({version:1,event:"release",item:e,holder:o.holder,by:t,token:o.token,acquiredAt:o.acquiredAt,expiresAt:o.expiresAt,timestamp:r.toISOString(),...n.outcome?{outcome:n.outcome}:{},...n.note?{note:n.note}:{}},n);return{ok:!0,lease:s,history:c}}async function M9(e,t){await Yi(t).catch(()=>{});let n=`${e.item}.jsonl`,i=JSON.stringify(e,Gt),r,o;for(let c=1;c<=z$e&&r===void 0;c++)try{let l=await gn(kh,n,t),u=l?await hn(l,t):null,d=`${u?`${u.replace(/\n$/,"")}
206
206
  `:""}${i}
@@ -254,7 +254,7 @@ ${i}`)}return t}async function tX(e,t={}){let n=t.lexicon,{config:i}=await fv(e)
254
254
  `)){let s=o.startsWith(`${Cy}:`)?o.slice(Cy.length+1):"",a=s.match(/(?:^|\/)_leases\/([^/]+)\.jsonl$/);if(!a)continue;let c=nF(e,["show",`${Cy}:${s}`]);for(let l of Zx(c??"").records)i.includes(l.token)&&l.item===a[1]&&!n.has(l.token)&&n.set(l.token,l.item)}return n}function lf(e,t){let n=t.map(o=>({sha:o.sha,trailers:iZ(o.trailers)})),i=GTe(e,n.map(o=>o.trailers.lease).filter(o=>o!==null)),r=new Map;for(let{sha:o,trailers:s}of n)r.set(o,{trailers:s,joins:{agent:s.agent,lease:s.lease===null?null:{token:s.lease,item:i.get(s.lease)??null},run:s.run,records:s.records.map(a=>({kind:a.kind,id:a.id,node:null})),applied:s.applied}});return r}var Cy,BR=v(()=>{"use strict";Bl();gp();Cy="refs/heads/chant/lifecycle"});var hee={};_e(hee,{COMMIT_UNLINKED_FIX:()=>WTe,hasLeaseLedger:()=>zR,judgeCommitLink:()=>gee,judgeCommits:()=>_y,mergeCommits:()=>rF,readWorkIndex:()=>iF});import{execFileSync as mee}from"node:child_process";function BTe(e){return[...e.kinds.keys()].join(", ")||"none"}function gee(e,t,n){let i=[],r=[],o=!1,s=a=>{i.includes(a)||i.push(a)};for(let a of pp(e,mp)){let c=`${mp}: ${a}`,l=Gg(a);if(!l){r.push({trailer:c,message:`${a} is not <kind>:<id>`});continue}let u=n.kinds.get(l.kind);u?u.has(l.id)?s(`${l.kind}:${l.id}`):r.push({trailer:c,message:`the ${l.kind} kind has no record ${l.id}`}):r.push({trailer:c,message:`${l.kind} is not a work kind (the work kinds are ${BTe(n)})`})}if(t.lease){let a=`${Fg}: ${t.lease.token}`,c=t.lease.item;if(c===null)n.ledger?r.push({trailer:a,message:"no lease history on chant/lifecycle names this token"}):o=!0;else{let l=[...n.kinds].filter(([,u])=>u.has(c)).map(([u])=>u);l.length===1?s(`${l[0]}:${c}`):r.push({trailer:a,message:l.length===0?`the lease was taken on ${c}, which no work kind has a record for`:`the lease was taken on ${c}, which ${l.join(" and ")} both have, so it names no one work item`})}}return i.length>0||o?{state:"linked",ids:i,problems:[]}:r.length>0?{state:"wrong",ids:[],problems:r}:{state:"unlinked",ids:[],problems:[]}}function _y(e,t,n,i=new Set){let r=Ec(e,t),o=lf(e,t.map(a=>({sha:a,trailers:r.get(a)?.trailers??{}}))),s=new Map;for(let a of t){if(i.has(a)){s.set(a,{state:"merge",ids:[],problems:[]});continue}s.set(a,gee(r.get(a)?.trailers??{},o.get(a).joins,n))}return s}function zR(e){try{return mee("git",["rev-parse","--verify","--quiet","refs/heads/chant/lifecycle"],{cwd:e,stdio:"ignore"}),!0}catch{return!1}}function rF(e,t){let n=new Set;if(t.length===0)return n;let i=mee("git",["log","--no-walk=unsorted","--stdin","--format=%H %P"],{cwd:e,encoding:"utf-8",input:`${t.join(`
255
255
  `)}
256
256
  `,maxBuffer:256*1024*1024});for(let r of i.split(`
257
- `)){let[o,...s]=r.trim().split(" ");o&&s.length>1&&n.add(o)}return n}async function iF(e,t,n){try{let i=qt(e,n),r=_t(i.tree),o=new Map;for(let s of yr(r)){let a=Ri(s,i.rootOnDisk),c=await Ht(a,e);if(!c.kind.work)continue;let l=await ii({kind:a,cwd:e,...n!==void 0?{at:n}:{}}),u=o.get(c.kind.name)??new Set;for(let d of l.result.records)d.id!==null&&u.add(d.id);o.set(c.kind.name,u)}return o.size===0?null:{kinds:o,ledger:zR(t)}}catch(i){if(i instanceof xe||i instanceof Xe)return null;throw i}}var WTe,UR=v(()=>{"use strict";Tt();cc();Lg();Ty();un();Ei();BR();gp();Wr();WTe='add a `Chant-Record: work:<id>` trailer when the commit is made (git commit --trailer "Chant-Record: work:<id>"), naming the work item the commit carries out'});import{execFileSync as zTe}from"node:child_process";function Iy(e,t,n){let i=e.verdict;i&&(e.verdict=JR(i.phases.map(r=>r.phase===t?n(r):r)))}function xee(e){let{green:t,commits:n,now:i}=e,r={requests:[],retries:[],resolved:[]},o=new Set(n.map(a=>a.sha)),s=(a,c)=>{let l=e.requests.get(a);return l&&l.phases.includes(c)&&oF(l.at,i)<yee?l:void 0};for(let a of n){let c=e.requests.get(a.sha);if(!(!c||!a.verdict))for(let l of c.phases){let u=VR(a,l);!u||u.runs.length>0||Iy(a,l,d=>s(a.sha,l)?{...d,verdict:"pending",reason:"requested"}:{...d,verdict:"unbuilt",reason:"request-unserved"})}}for(let a of t.require){if(sF(t,a)!=="newest")continue;let c;for(let l of n){let u=VR(l,a);if(u){if(u.runs.length>0){c=l.sha;continue}c&&u.reason!=="requested"&&u.reason!=="request-unserved"&&Iy(l,a,d=>({...d,verdict:"unbuilt",reason:"superseded",coveredBy:c}))}}}if(e.retryVia)for(let a of n){if(a.before!=="none"||a.verdict?.verdict!=="fail")continue;let c=e.runs.get(a.sha)??[],l=e.records.get(a.sha)?.retried??{};for(let u of a.verdict.phases)for(let d of u.runs.filter(p=>p.verdict==="fail")){if(c.filter(f=>f.name===d.name).length>1)continue;let p=l[d.name];if(!(p&&p.run===d.id&&oF(p.at,i)>=UTe)){if(!p||p.run!==d.id){let f=c.find(g=>g.name===d.name&&g.id===d.id);e.retryVia==="forge"?r.retries.push({sha:a.sha,run:f}):!e.requests.has(a.sha)&&!r.requests.some(g=>g.commit===a.sha)&&r.requests.push(aF(t,a.sha,[u.phase],"retry",i))}Iy(a,u.phase,f=>{let g=f.runs.map(h=>h.name===d.name&&h.id===d.id?{...h,verdict:"pending"}:h);return{...f,runs:g,...KR(g,f.unmatched),reason:"retrying"}})}}}for(let a of t.require){let c=n.map(h=>VR(h,a)),l=c.findIndex(h=>wee(h?.verdict));if(l<0||c[l].verdict!=="fail")continue;let u=l,d=[],p=-1;for(let h=l+1;h<n.length;h++){let w=c[h]?.verdict;if(w==="fail")u=h,d=[];else if(w==="pass"){p=h;break}else w!==void 0&&d.push(h)}if(d.length===0){if(p<0)continue;let h=n[u].sha;for(let w=u;w>=0&&c[w]?.verdict!=="pass";w--)c[w]&&Iy(n[w],a,b=>({...b,culprit:h}));continue}if(sF(t,a)!=="newest"||d.some(h=>s(n[h].sha,a)))continue;let f=d.length>VTe?d[Math.floor(d.length/2)]:d[0],g=n[f].sha;e.requests.has(g)||r.requests.some(h=>h.commit===g)||(r.requests.push(aF(t,g,[a],"bisect",i)),Iy(n[f],a,h=>({...h,verdict:"pending",reason:"requested",coveredBy:void 0})))}for(let[a,c]of e.requests){let l=n.find(d=>d.sha===a);(!o.has(a)||oF(c.at,i)>=yee||l!==void 0&&(l.before==="revoked"||c.phases.every(d=>wee(VR(l,d)?.verdict))))&&r.resolved.push(c.tag)}return r}function aF(e,t,n,i,r){return{schema:1,tag:`${lu}${t}`,commit:t,branch:e.branch,phases:n,reason:i,at:Dy(r)}}function $ee(e){let{green:t,commit:n,previous:i,now:r}=e,o={...i?.retried??{}};for(let d of e.retries)d.sha===n.sha&&(o[d.run.name]={run:d.run.id,at:Dy(r)});let s=e.requests.get(n.sha),a={...Object.keys(o).length>0?{retried:o}:{},...s?{request:{tag:s.tag,reason:s.reason,phases:s.phases,at:s.at}}:{}};if(n.before==="revoked"||!n.verdict)return{schema:1,commit:n.sha,branch:t.branch,state:"red",at:Dy(r),revoked:!0,phases:i?.phases??{},...i?.failure?{failure:i.failure}:{},...a};let c=n.verdict,l=n.before==="green"?c.verdict==="fail"?"red":"green":c.verdict==="pass"?n.made?"green":"pending":c.verdict==="fail"?"red":c.verdict,u={};for(let d of c.phases)u[d.phase]={verdict:d.verdict,build:sF(t,d.phase),runs:d.runs.map(bee),...d.reason?{reason:d.reason}:{},...d.coveredBy?{coveredBy:d.coveredBy}:{},...d.culprit?{culprit:d.culprit}:{}};return{schema:1,commit:n.sha,branch:t.branch,state:l,at:Dy(r),phases:u,...c.failure?{failure:{phase:c.failure.phase,run:bee(c.failure.run)}}:{},...a}}function Ree(e,t){let n=Object.fromEntries(Object.entries(e.phases).map(([o,s])=>[o,s.verdict==="pending"?{...s,verdict:"unbuilt",reason:"aged-out"}:s])),{request:i,...r}=e;return{...r,state:"unbuilt",at:Dy(t),phases:n}}function See(e,t){if(!e)return!1;let{at:n,...i}=e,{at:r,...o}=t;return JSON.stringify(i)===JSON.stringify(o)}function cF(e,t){try{return zTe("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],maxBuffer:256*1024*1024}).trimEnd()}catch{return null}}function qTe(e){if(e)try{let t=JSON.parse(e);return t&&t.schema===1&&typeof t.commit=="string"&&typeof t.state=="string"?t:void 0}catch{return}}function KTe(e,t){return qTe(cF(e,["show",`${kee}:${HR(t)}`]))}function qR(e){let t=new Map,n=cF(e,["ls-tree","--name-only",`${kee}:${vee}`]);if(!n)return t;for(let i of n.split(`
257
+ `)){let[o,...s]=r.trim().split(" ");o&&s.length>1&&n.add(o)}return n}async function iF(e,t,n){try{let i=qt(e,n),r=_t(i.tree),o=new Map;for(let s of yr(r)){let a=Ri(s,i.rootOnDisk),c=await Ht(a,e);if(!c.kind.work)continue;let l=await ii({kind:a,cwd:e,...n!==void 0?{at:n}:{}}),u=o.get(c.kind.name)??new Set;for(let d of l.result.records)d.id!==null&&u.add(d.id);o.set(c.kind.name,u)}return o.size===0?null:{kinds:o,ledger:zR(t)}}catch(i){if(i instanceof ve||i instanceof Xe)return null;throw i}}var WTe,UR=v(()=>{"use strict";Tt();cc();Lg();Ty();un();Ei();BR();gp();Wr();WTe='add a `Chant-Record: work:<id>` trailer when the commit is made (git commit --trailer "Chant-Record: work:<id>"), naming the work item the commit carries out'});import{execFileSync as zTe}from"node:child_process";function Iy(e,t,n){let i=e.verdict;i&&(e.verdict=JR(i.phases.map(r=>r.phase===t?n(r):r)))}function xee(e){let{green:t,commits:n,now:i}=e,r={requests:[],retries:[],resolved:[]},o=new Set(n.map(a=>a.sha)),s=(a,c)=>{let l=e.requests.get(a);return l&&l.phases.includes(c)&&oF(l.at,i)<yee?l:void 0};for(let a of n){let c=e.requests.get(a.sha);if(!(!c||!a.verdict))for(let l of c.phases){let u=VR(a,l);!u||u.runs.length>0||Iy(a,l,d=>s(a.sha,l)?{...d,verdict:"pending",reason:"requested"}:{...d,verdict:"unbuilt",reason:"request-unserved"})}}for(let a of t.require){if(sF(t,a)!=="newest")continue;let c;for(let l of n){let u=VR(l,a);if(u){if(u.runs.length>0){c=l.sha;continue}c&&u.reason!=="requested"&&u.reason!=="request-unserved"&&Iy(l,a,d=>({...d,verdict:"unbuilt",reason:"superseded",coveredBy:c}))}}}if(e.retryVia)for(let a of n){if(a.before!=="none"||a.verdict?.verdict!=="fail")continue;let c=e.runs.get(a.sha)??[],l=e.records.get(a.sha)?.retried??{};for(let u of a.verdict.phases)for(let d of u.runs.filter(p=>p.verdict==="fail")){if(c.filter(f=>f.name===d.name).length>1)continue;let p=l[d.name];if(!(p&&p.run===d.id&&oF(p.at,i)>=UTe)){if(!p||p.run!==d.id){let f=c.find(g=>g.name===d.name&&g.id===d.id);e.retryVia==="forge"?r.retries.push({sha:a.sha,run:f}):!e.requests.has(a.sha)&&!r.requests.some(g=>g.commit===a.sha)&&r.requests.push(aF(t,a.sha,[u.phase],"retry",i))}Iy(a,u.phase,f=>{let g=f.runs.map(h=>h.name===d.name&&h.id===d.id?{...h,verdict:"pending"}:h);return{...f,runs:g,...KR(g,f.unmatched),reason:"retrying"}})}}}for(let a of t.require){let c=n.map(h=>VR(h,a)),l=c.findIndex(h=>wee(h?.verdict));if(l<0||c[l].verdict!=="fail")continue;let u=l,d=[],p=-1;for(let h=l+1;h<n.length;h++){let w=c[h]?.verdict;if(w==="fail")u=h,d=[];else if(w==="pass"){p=h;break}else w!==void 0&&d.push(h)}if(d.length===0){if(p<0)continue;let h=n[u].sha;for(let w=u;w>=0&&c[w]?.verdict!=="pass";w--)c[w]&&Iy(n[w],a,b=>({...b,culprit:h}));continue}if(sF(t,a)!=="newest"||d.some(h=>s(n[h].sha,a)))continue;let f=d.length>VTe?d[Math.floor(d.length/2)]:d[0],g=n[f].sha;e.requests.has(g)||r.requests.some(h=>h.commit===g)||(r.requests.push(aF(t,g,[a],"bisect",i)),Iy(n[f],a,h=>({...h,verdict:"pending",reason:"requested",coveredBy:void 0})))}for(let[a,c]of e.requests){let l=n.find(d=>d.sha===a);(!o.has(a)||oF(c.at,i)>=yee||l!==void 0&&(l.before==="revoked"||c.phases.every(d=>wee(VR(l,d)?.verdict))))&&r.resolved.push(c.tag)}return r}function aF(e,t,n,i,r){return{schema:1,tag:`${lu}${t}`,commit:t,branch:e.branch,phases:n,reason:i,at:Dy(r)}}function $ee(e){let{green:t,commit:n,previous:i,now:r}=e,o={...i?.retried??{}};for(let d of e.retries)d.sha===n.sha&&(o[d.run.name]={run:d.run.id,at:Dy(r)});let s=e.requests.get(n.sha),a={...Object.keys(o).length>0?{retried:o}:{},...s?{request:{tag:s.tag,reason:s.reason,phases:s.phases,at:s.at}}:{}};if(n.before==="revoked"||!n.verdict)return{schema:1,commit:n.sha,branch:t.branch,state:"red",at:Dy(r),revoked:!0,phases:i?.phases??{},...i?.failure?{failure:i.failure}:{},...a};let c=n.verdict,l=n.before==="green"?c.verdict==="fail"?"red":"green":c.verdict==="pass"?n.made?"green":"pending":c.verdict==="fail"?"red":c.verdict,u={};for(let d of c.phases)u[d.phase]={verdict:d.verdict,build:sF(t,d.phase),runs:d.runs.map(bee),...d.reason?{reason:d.reason}:{},...d.coveredBy?{coveredBy:d.coveredBy}:{},...d.culprit?{culprit:d.culprit}:{}};return{schema:1,commit:n.sha,branch:t.branch,state:l,at:Dy(r),phases:u,...c.failure?{failure:{phase:c.failure.phase,run:bee(c.failure.run)}}:{},...a}}function Ree(e,t){let n=Object.fromEntries(Object.entries(e.phases).map(([o,s])=>[o,s.verdict==="pending"?{...s,verdict:"unbuilt",reason:"aged-out"}:s])),{request:i,...r}=e;return{...r,state:"unbuilt",at:Dy(t),phases:n}}function See(e,t){if(!e)return!1;let{at:n,...i}=e,{at:r,...o}=t;return JSON.stringify(i)===JSON.stringify(o)}function cF(e,t){try{return zTe("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],maxBuffer:256*1024*1024}).trimEnd()}catch{return null}}function qTe(e){if(e)try{let t=JSON.parse(e);return t&&t.schema===1&&typeof t.commit=="string"&&typeof t.state=="string"?t:void 0}catch{return}}function KTe(e,t){return qTe(cF(e,["show",`${kee}:${HR(t)}`]))}function qR(e){let t=new Map,n=cF(e,["ls-tree","--name-only",`${kee}:${vee}`]);if(!n)return t;for(let i of n.split(`
258
258
  `)){let r=/^([0-9a-f]{40,64})\.json$/.exec(i);if(!r)continue;let o=KTe(e,r[1]);o&&t.set(r[1],o)}return t}function lF(e){let t=new Map,n=cF(e,["for-each-ref","--format=%(refname:lstrip=2)%00%(objecttype)%00%(contents)%01",`refs/tags/${lu}`]);if(!n)return t;for(let i of n.split("")){let[r,o,s]=i.replace(/^\n/,"").split("\0");if(!(!r||o!=="tag"||!s?.includes("{")))try{let a=JSON.parse(s.slice(s.indexOf("{"))),c=r.slice(lu.length);a.schema===1&&a.commit===c&&Array.isArray(a.phases)&&typeof a.at=="string"&&t.set(c,{...a,tag:r})}catch{}}return t}function uF(e){return`ci: build ${e.phases.join(", ")} at this commit (${e.reason})
259
259
 
260
260
  ${JSON.stringify(e,null,2)}
@@ -264,21 +264,21 @@ ${Hee(o,r)}
264
264
  `}function Kee(e,t,n,i,r){let o={schema:1,tag:"revoked",commit:t,branch:e.branch,at:YR(i),...Vee(e),phase:n.phase,run:Uee(n.run)},s=n.run.failureCode?`, ${n.run.failureCode}`:"";return`ci: phase ${n.phase} failed in ${n.run.name} (${n.run.conclusion??n.run.status}${s})
265
265
 
266
266
  ${Hee(o,r)}
267
- `}async function Jee(e){let t=[];for(let n of e.commits){let i=e.revokedTags.has(n.sha)?"revoked":e.greenTags.has(n.sha)?"green":"none";if(i==="revoked"){let c=e.ignored?.get(n.sha);t.push({...n,before:i,made:null,...c&&c.length>0?{ignored:[...c]}:{}});continue}let r=wF(e.green,await e.checkRuns(n.sha)),o=null;i==="none"&&r.verdict==="pass"?o={tag:`${uu}${n.sha}`,message:qee(e.green,n.sha,r,e.now,e.signer)}:i==="green"&&r.verdict==="fail"&&(o={tag:`${Ny}${n.sha}`,message:Kee(e.green,n.sha,r.failure,e.now,e.signer)});let s=e.ignored?.get(n.sha),a=o!==null&&s?.some(c=>c.tag===o.tag)?o.tag:void 0;t.push({...n,before:i,verdict:r,made:a?null:o,...s&&s.length>0?{ignored:[...s]}:{},...a?{blocked:a}:{}})}return t}function _n(e,t){return sIe("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0"},maxBuffer:256*1024*1024}).trimEnd()}function Rr(e,t){try{return _n(e,t)}catch{return null}}function dIe(e){let t=[],i=_n(e,["for-each-ref","--format=%(refname:lstrip=2)%00%(objecttype)%00%(objectname)%00%(*objectname)%00%(taggerdate:iso-strict)%00%(contents)%01",`refs/tags/${uu}`,`refs/tags/${Ny}`]);for(let r of i.split("")){let[o,s,a,c,l,u]=r.replace(/^\n/,"").split("\0");if(!o)continue;let d=s==="tag",p=null;if(d&&l&&u&&u.includes("{"))try{let g=JSON.parse(u.slice(u.indexOf("{")));g&&typeof g=="object"&&!Array.isArray(g)&&(p=g)}catch{p=null}let f=o.startsWith(uu);t.push({kind:f?"green":"revoked",sha:o.slice((f?uu:Ny).length),tag:o,tagged:l||null,record:p,target:(d?c:a)??""})}return t}function vF(e,t){if(Rr(e,["rev-parse","--verify","--quiet",`${t}^{commit}`])===null)throw new xe("declaration-invalid",`ci.green.signedSince names ${t}, which is not a commit in this repository; it must be the full sha of the first commit on the green branch whose tags must be signed (fetch the branch if it is newer than this clone)`);return new Set(_n(e,["rev-list","--first-parent",`${t}^@`]).split(`
268
- `).filter(Boolean))}function XR(e,t=null,n=null){let i={green:new Map,revoked:new Map,ignored:new Map},r=t?.signedSince?vF(e,t.signedSince):null,o,s=()=>o??=n?Ha(xi(e,n),n):eo(null);for(let a of dIe(e)){let c=p=>(a.kind==="green"?i.green:i.revoked).set(a.sha,{tagged:a.tagged,record:a.record,signer:p});if(r===null){c(null);continue}let l=(p,f)=>i.ignored.set(a.sha,[...i.ignored.get(a.sha)??[],{tag:a.tag,status:p,reason:f}]);if(a.target!==a.sha){l("mismatch",`${a.tag} points at ${a.target.slice(0,12)||"nothing"}, not at the commit its name gives`);continue}if(r.has(a.sha)){c(null);continue}let u=s(),d=Iee(a.record,{sha:a.sha,kind:a.kind,branch:t.branch},u.runners,u.roles);d.status==="signed"?c(d.signer):l(d.status,`${d.reason}; ci.green.signedSince is ${t.signedSince}, so a tag on a commit that is not a strict first-parent ancestor of it needs one`)}return i}function pIe(e){try{return _t(qt(e).tree).ci?.green?.signedSince??null}catch{return null}}function QR(e){let t=qt(e),n=_t(t.tree),i=n.ci?.green??null;if(!i)throw new Oc("ci-green-undeclared",`${n.file} declares no ci.green, so chant does not know which check runs make a commit green`);let r=t.top??vs(e);if(!r)throw new xe("not-a-git-repository","the ci tags are git tags, and this directory is not in a git repository");return{green:i,top:r,workspace:{name:n.name,root:t.root,file:n.file}}}function kF(e,t,n,i="the tags it signed"){let r;try{r=HJ(n)}catch(l){throw new Error(`the runner key is not an Ed25519 private key in PEM: ${l instanceof Error?l.message:String(l)}`)}let o=Ha(xi(e,t),t),s=`.chant/trust.json at ${t.slice(0,12)}`;if(o.signers.some(l=>l.key===r.publicKey))throw new Error(`the runner key is a signer's key in ${o.signersPath}; ci tags and runs are signed by a CI identity's key, never by a person's`);let a=o.runners.find(l=>l.key===r.publicKey);if(!a)throw new Error(`${s} lists no runner with this key, so ${i} would be ignored. Add it under "runners" first:
267
+ `}async function Jee(e){let t=[];for(let n of e.commits){let i=e.revokedTags.has(n.sha)?"revoked":e.greenTags.has(n.sha)?"green":"none";if(i==="revoked"){let c=e.ignored?.get(n.sha);t.push({...n,before:i,made:null,...c&&c.length>0?{ignored:[...c]}:{}});continue}let r=wF(e.green,await e.checkRuns(n.sha)),o=null;i==="none"&&r.verdict==="pass"?o={tag:`${uu}${n.sha}`,message:qee(e.green,n.sha,r,e.now,e.signer)}:i==="green"&&r.verdict==="fail"&&(o={tag:`${Ny}${n.sha}`,message:Kee(e.green,n.sha,r.failure,e.now,e.signer)});let s=e.ignored?.get(n.sha),a=o!==null&&s?.some(c=>c.tag===o.tag)?o.tag:void 0;t.push({...n,before:i,verdict:r,made:a?null:o,...s&&s.length>0?{ignored:[...s]}:{},...a?{blocked:a}:{}})}return t}function _n(e,t){return sIe("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0"},maxBuffer:256*1024*1024}).trimEnd()}function Rr(e,t){try{return _n(e,t)}catch{return null}}function dIe(e){let t=[],i=_n(e,["for-each-ref","--format=%(refname:lstrip=2)%00%(objecttype)%00%(objectname)%00%(*objectname)%00%(taggerdate:iso-strict)%00%(contents)%01",`refs/tags/${uu}`,`refs/tags/${Ny}`]);for(let r of i.split("")){let[o,s,a,c,l,u]=r.replace(/^\n/,"").split("\0");if(!o)continue;let d=s==="tag",p=null;if(d&&l&&u&&u.includes("{"))try{let g=JSON.parse(u.slice(u.indexOf("{")));g&&typeof g=="object"&&!Array.isArray(g)&&(p=g)}catch{p=null}let f=o.startsWith(uu);t.push({kind:f?"green":"revoked",sha:o.slice((f?uu:Ny).length),tag:o,tagged:l||null,record:p,target:(d?c:a)??""})}return t}function vF(e,t){if(Rr(e,["rev-parse","--verify","--quiet",`${t}^{commit}`])===null)throw new ve("declaration-invalid",`ci.green.signedSince names ${t}, which is not a commit in this repository; it must be the full sha of the first commit on the green branch whose tags must be signed (fetch the branch if it is newer than this clone)`);return new Set(_n(e,["rev-list","--first-parent",`${t}^@`]).split(`
268
+ `).filter(Boolean))}function XR(e,t=null,n=null){let i={green:new Map,revoked:new Map,ignored:new Map},r=t?.signedSince?vF(e,t.signedSince):null,o,s=()=>o??=n?Ha(xi(e,n),n):eo(null);for(let a of dIe(e)){let c=p=>(a.kind==="green"?i.green:i.revoked).set(a.sha,{tagged:a.tagged,record:a.record,signer:p});if(r===null){c(null);continue}let l=(p,f)=>i.ignored.set(a.sha,[...i.ignored.get(a.sha)??[],{tag:a.tag,status:p,reason:f}]);if(a.target!==a.sha){l("mismatch",`${a.tag} points at ${a.target.slice(0,12)||"nothing"}, not at the commit its name gives`);continue}if(r.has(a.sha)){c(null);continue}let u=s(),d=Iee(a.record,{sha:a.sha,kind:a.kind,branch:t.branch},u.runners,u.roles);d.status==="signed"?c(d.signer):l(d.status,`${d.reason}; ci.green.signedSince is ${t.signedSince}, so a tag on a commit that is not a strict first-parent ancestor of it needs one`)}return i}function pIe(e){try{return _t(qt(e).tree).ci?.green?.signedSince??null}catch{return null}}function QR(e){let t=qt(e),n=_t(t.tree),i=n.ci?.green??null;if(!i)throw new Oc("ci-green-undeclared",`${n.file} declares no ci.green, so chant does not know which check runs make a commit green`);let r=t.top??vs(e);if(!r)throw new ve("not-a-git-repository","the ci tags are git tags, and this directory is not in a git repository");return{green:i,top:r,workspace:{name:n.name,root:t.root,file:n.file}}}function kF(e,t,n,i="the tags it signed"){let r;try{r=HJ(n)}catch(l){throw new Error(`the runner key is not an Ed25519 private key in PEM: ${l instanceof Error?l.message:String(l)}`)}let o=Ha(xi(e,t),t),s=`.chant/trust.json at ${t.slice(0,12)}`;if(o.signers.some(l=>l.key===r.publicKey))throw new Error(`the runner key is a signer's key in ${o.signersPath}; ci tags and runs are signed by a CI identity's key, never by a person's`);let a=o.runners.find(l=>l.key===r.publicKey);if(!a)throw new Error(`${s} lists no runner with this key, so ${i} would be ignored. Add it under "runners" first:
269
269
  ${r.publicKey}`);if(!(o.roles[fo]??[]).some(l=>l.normalize("NFKC").trim().toLowerCase()===a.principal.normalize("NFKC").trim().toLowerCase()))throw new Error(`${a.principal} holds no ${fo} role in ${s}, so ${i} would be ignored. Grant it: "roles": { "${fo}": ["${a.principal}"] }`);return{principal:a.principal,key:r.key,publicKey:r.publicKey}}async function fIe(e){let t=QR(e.cwd),n=t.top,i={...t.green,source:e.source??t.green.source},r=i.source==="checks"?typeof e.forge=="function"?e.forge():e.forge:void 0;if(i.source==="checks"&&!r)throw new Error("ci.green.source is checks, so the tick reads check runs and needs a forge");let o=e.remote??"origin",s=e.now??new Date,a=`refs/remotes/${o}/${i.branch}`;try{_n(n,["fetch","--quiet","--no-tags","--prune",o,`+refs/heads/${i.branch}:${a}`,"+refs/tags/ci/*:refs/tags/ci/*"])}catch(q){throw new Error(`could not fetch ${i.branch} and the ci tags from ${o}: ${Ly(q)}`)}if(Rr(n,["rev-parse","--verify","--quiet",`${a}^{commit}`])===null)throw new Oc("ci-branch-unknown",`${o} has no branch ${i.branch}`);let c=Math.floor((s.getTime()-bF(i.window))/1e3),l=_n(n,["log","--first-parent",`--max-age=${c}`,"--format=%H %ct",a]).split(`
270
270
  `).filter(Boolean).map(q=>q.split(" ")).filter(([,q])=>Number(q)>=c).map(([q,L])=>({sha:q,committed:YR(new Date(Number(L)*1e3))})),u=_n(n,["rev-parse",`${a}^{commit}`]);if(i.signedSince&&e.runnerKey===void 0&&!e.dryRun)throw new Error(`ci.green.signedSince is ${i.signedSince}, so every tag the tick makes needs a statement signed by a runner key, and none was given: pass --key <runner key.pem> or set CHANT_RUNNER_KEY`);let d=e.runnerKey!==void 0?kF(n,u,e.runnerKey):void 0,p=await Yee(e.cwd,n,a,l.map(q=>q.sha)),f=XR(n,i,u),g=[],h,w=await Yi({cwd:n}),b=w.status!=="diverged"&&w.status!=="unreachable";if(!b){let q=`could not fetch chant/lifecycle from ${w.remote}: ${w.status==="diverged"?"the local branch and the remote's have diverged":w.stderr}`;if(i.source==="runs")throw new Error(q.replace("chant/lifecycle","chant/lifecycle, where the Op runs are recorded,"));g.push(`${q}; no _ci records were read or written`)}i.source==="runs"&&(h=await xF(e.cwd,n,u,i.signedSince));let k=new Map,$=await Jee({green:i,commits:l,greenTags:new Set(f.green.keys()),revokedTags:new Set(f.revoked.keys()),ignored:f.ignored,checkRuns:async q=>{let L=h?h.checkRuns(q):await r.checkRuns(q);return k.set(q,L),L},now:s,signer:d});if(p)for(let q of $)q.work=p.get(q.sha);if(h)for(let q of $){let L=h.ignored.get(q.sha);L&&L.length>0&&(q.ignoredRuns=L)}let x=b?qR(n):new Map,R=lF(n),P=i.source==="runs"?"request":r?.rerun?"forge":null,I=xee({green:i,commits:$,runs:k,requests:R,records:x,now:s,retryVia:P}),A=$.filter(q=>q.made!==null);if(!e.dryRun&&A.length>0){let q=$F(n);for(let L of A)_n(n,[...q,"tag","-a","-m",L.made.message,L.made.tag,L.sha]);try{_n(n,["push","--quiet",o,...A.map(L=>`refs/tags/${L.made.tag}`)])}catch(L){let M=Ly(L),_=eS(M);throw new Error(`could not push ${A.map(T=>T.made.tag).join(", ")} to ${o}: ${_?`${_}
271
271
  `:""}${M}`)}}let B=I.retries.map(q=>({sha:q.sha,run:q.run.name})),C=[];if(!e.dryRun){let q=await mIe({top:n,remote:o,green:i,forge:r,builds:I,requests:R,records:x,planned:$,warnings:g});C=b&&!Ki()?await gIe({top:n,green:i,planned:$,records:x,builds:I,requests:q.live,dispatched:q.dispatched,now:s,warnings:g}):[]}return{branch:i.branch,window:i.window,ref:a,commits:$,made:A.map(q=>q.made.tag),requested:I.requests,retried:B,recorded:C,warnings:g,signer:d?.principal??null,source:i.source}}async function mIe(e){let{top:t,remote:n,green:i,forge:r,builds:o,warnings:s}=e,a=new Map(e.requests);for(let l of o.resolved)a.delete(l.slice(lu.length));if(o.requests.length>0){let l=$F(t),u=[];for(let d of o.requests)Rr(t,[...l,"tag","-a","-m",uF(d),d.tag,d.commit])===null?s.push(`could not make ${d.tag}`):u.push(d);if(u.length>0)try{_n(t,["push","--quiet",n,...u.map(d=>`refs/tags/${d.tag}`)]);for(let d of u)a.set(d.commit,d)}catch(d){for(let f of u)Rr(t,["tag","-d",f.tag]);let p=Ly(d);s.push(`could not push ${u.map(f=>f.tag).join(", ")} to ${n}: ${eS(p)??p}`)}}let c=new Set;if(i.source==="checks"&&r?.dispatch){let l=pF(t,"");for(let u of a.values()){if(e.records.get(u.commit)?.request?.dispatched&&e.records.get(u.commit)?.request?.tag===u.tag)continue;if(e.planned.find(h=>h.sha===u.commit)?.verdict?.phases.some(h=>u.phases.includes(h.phase)&&h.runs.some(w=>w.status!=="completed"))){c.add(u.commit);continue}let{dispatchable:p,without:f}=dF(i,u.phases,l);for(let h of f)s.push(`${h} holds a run of ${u.phases.join(", ")} and has no workflow_dispatch trigger, so ${u.tag} can't start it; regenerate it with chant ci workflow`);let g=p.length>0;for(let h of p)try{await r.dispatch(h,u.tag)}catch(w){g=!1,s.push(`could not start ${h} at ${u.tag}: ${w instanceof Error?w.message:String(w)}`)}g&&c.add(u.commit)}}if(r?.rerun)for(let l of o.retries)try{await r.rerun(l.run)}catch(u){s.push(`could not run ${l.run.name} at ${l.sha.slice(0,12)} again, so its failure counts once the retry's hour is up: ${u instanceof Error?u.message:String(u)}`)}if(o.resolved.length>0){for(let l of o.resolved)Rr(t,["tag","-d",l]);Rr(t,["push","--quiet",n,...o.resolved.map(l=>`:refs/tags/${l}`)])===null&&s.push(`could not delete ${o.resolved.join(", ")} on ${n}; a done request asks for nothing, so they can stay`)}return{live:a,dispatched:c}}async function gIe(e){let{top:t,green:n,planned:i,records:r,builds:o,requests:s,now:a,warnings:c}=e,l=[],u=new Set(i.map(d=>d.sha));for(let d of i){let p=r.get(d.sha),f=$ee({green:n,commit:d,previous:p,retries:o.retries,requests:s,now:a});f.request&&(e.dispatched.has(d.sha)||p?.request?.tag===f.request.tag&&p.request.dispatched===!0)&&(f={...f,request:{...f.request,dispatched:!0}}),See(p,f)||l.push({path:HR(d.sha),content:`${JSON.stringify(f,null,2)}
272
272
  `})}for(let[d,p]of r)u.has(d)||p.state!=="pending"||l.push({path:HR(d),content:`${JSON.stringify(Ree(p,a),null,2)}
273
- `});if(l.length===0)return[];for(let d=0;d<2;d++){try{await Ji(l,`ci: ${l.length} commit record${l.length===1?"":"s"}`,{cwd:t})}catch(g){return c.push(`could not write the _ci records: ${g instanceof Error?g.message:String(g)}`),[]}let p=await Ta({cwd:t});if(p.status==="pushed"||p.status==="no-remote"||p.status==="not-recorded")return l.map(g=>g.path);if(p.status!=="stale"||d===1)return c.push(`could not push the _ci records: ${p.stderr}`),[];Rr(t,["update-ref","refs/heads/chant/lifecycle","refs/heads/chant/lifecycle^"]);let f=await Yi({cwd:t});if(f.status==="diverged"||f.status==="unreachable")return c.push("could not push the _ci records: chant/lifecycle moved on the remote and could not be fetched again"),[]}return[]}async function hIe(e){let t=QR(e.cwd),{green:n,top:i}=t,r=e.remote??"origin",o=`refs/remotes/${r}/${n.branch}`;try{_n(i,["fetch","--quiet","--no-tags",r,`+refs/heads/${n.branch}:${o}`,`+refs/tags/${lu}*:refs/tags/${lu}*`])}catch(p){throw new Error(`could not fetch ${n.branch} and the build requests from ${r}: ${Ly(p)}`)}if(e.at.startsWith("-")||Rr(i,["rev-parse","--verify","--quiet",`${e.at}^{commit}`])===null)throw new xe("revision-unknown",`--at ${e.at} names no commit in this repository`);let s=_n(i,["rev-parse",`${e.at}^{commit}`]);if(!_n(i,["rev-list","--first-parent",o]).split(`
273
+ `});if(l.length===0)return[];for(let d=0;d<2;d++){try{await Ji(l,`ci: ${l.length} commit record${l.length===1?"":"s"}`,{cwd:t})}catch(g){return c.push(`could not write the _ci records: ${g instanceof Error?g.message:String(g)}`),[]}let p=await Ta({cwd:t});if(p.status==="pushed"||p.status==="no-remote"||p.status==="not-recorded")return l.map(g=>g.path);if(p.status!=="stale"||d===1)return c.push(`could not push the _ci records: ${p.stderr}`),[];Rr(t,["update-ref","refs/heads/chant/lifecycle","refs/heads/chant/lifecycle^"]);let f=await Yi({cwd:t});if(f.status==="diverged"||f.status==="unreachable")return c.push("could not push the _ci records: chant/lifecycle moved on the remote and could not be fetched again"),[]}return[]}async function hIe(e){let t=QR(e.cwd),{green:n,top:i}=t,r=e.remote??"origin",o=`refs/remotes/${r}/${n.branch}`;try{_n(i,["fetch","--quiet","--no-tags",r,`+refs/heads/${n.branch}:${o}`,`+refs/tags/${lu}*:refs/tags/${lu}*`])}catch(p){throw new Error(`could not fetch ${n.branch} and the build requests from ${r}: ${Ly(p)}`)}if(e.at.startsWith("-")||Rr(i,["rev-parse","--verify","--quiet",`${e.at}^{commit}`])===null)throw new ve("revision-unknown",`--at ${e.at} names no commit in this repository`);let s=_n(i,["rev-parse",`${e.at}^{commit}`]);if(!_n(i,["rev-list","--first-parent",o]).split(`
274
274
  `).includes(s))throw new Error(`${s.slice(0,12)} is not a first-parent commit of ${r}/${n.branch}, and only those are judged green`);let c=lF(i).get(s),l=c??Eee(n,s,n.require,e.now??new Date),u=[];if(!c){_n(i,[...$F(i),"tag","-a","-m",uF(l),l.tag,s]);try{_n(i,["push","--quiet",r,`refs/tags/${l.tag}`])}catch(p){Rr(i,["tag","-d",l.tag]);let f=Ly(p);throw new Error(`could not push ${l.tag} to ${r}: ${eS(f)??f}`)}}let d=[];if(n.source==="checks"&&e.forge?.dispatch){let{dispatchable:p,without:f}=dF(n,l.phases,pF(i,""));for(let g of f)u.push(`${g} holds a run of a required phase and has no workflow_dispatch trigger, so it can't be started at ${l.tag}`);for(let g of p)try{await e.forge.dispatch(g,l.tag),d.push(g)}catch(h){u.push(`could not start ${g} at ${l.tag}: ${h instanceof Error?h.message:String(h)}; the next tick tries again`)}}return{request:l,existed:c!==void 0,dispatched:d,warnings:u}}function Zee(e,t){let n=e.status==="ok"||e.status==="fail",i=Date.parse(e.ended);return{id:Number.isFinite(i)?i:0,name:e.op,status:n?"completed":e.status,conclusion:n?e.status==="ok"?"success":"failure":null,completedAt:n?e.ended:null,url:e.runOrigin?.url??null,opRun:{id:e.id,env:e.env,signer:t,...t!==null&&e.statement?{statement:e.statement}:{}},...e.status==="fail"&&e.failure?{failureCode:e.failure.code}:{}}}async function xF(e,t,n,i=null){let r=Ha(xi(t,n),n),o=i?vF(t,i):null,s=new Map,a=new Map;for(let c of await fg({cwd:e}))for(let l of await Zi(c,{cwd:e})){let u=yIe.exec(l)?.[1];if(!u)continue;let{records:d}=await $y(c,u,{cwd:e});for(let p of d){if(!p.gitSha||p.runOrigin?.forge==="local")continue;let f=Mee(p,r.runners,r.roles);if(f.status==="signed"||f.status==="unsigned"&&(o===null||o.has(p.gitSha)))s.set(p.gitSha,[...s.get(p.gitSha)??[],Zee(p,f.status==="signed"?f.signer:null)]);else{let h=f.status==="unsigned"?`${f.reason}; ci.green.signedSince is ${i}, so a run on a commit that is not a strict first-parent ancestor of it needs one`:f.reason;a.set(p.gitSha,[...a.get(p.gitSha)??[],{run:p.id,op:p.op,env:p.env,status:f.status,reason:h}])}}}return{checkRuns:c=>s.get(c)??[],ignored:a}}function wIe(e,t){let n=vs(e);if(!n)throw new Error("a run is signed against .chant/trust.json at HEAD, and this directory is not in a git repository");let i=Rr(n,["rev-parse","--verify","--quiet","HEAD^{commit}"]);if(i===null)throw new Error("a run is signed against .chant/trust.json at HEAD, and this repository has no commit yet");let r=kF(n,i,t,"the runs it signed");return o=>Lee(o,r)}function eS(e){return/without [`']?workflows?[`']? (permission|scope)/i.test(e)?"GitHub refused the tag push because the tagged commit changes workflow files, and GITHUB_TOKEN can't update workflows: regenerate the workflow with --token-secret <NAME>, naming a secret that holds a fine-grained token with Contents and Workflows read and write, or with --app-id-var <VAR> --app-key-secret <NAME> for a GitHub App's token":null}function $F(e){let t=[];return Rr(e,["config","user.name"])===null&&t.push("-c","user.name=chant"),Rr(e,["config","user.email"])===null&&t.push("-c","user.email=chant@localhost"),t}function Ly(e){let t=e;return String(t.stderr??t.message??e).trim()}async function Yee(e,t,n,i){if(i.length!==0)try{let r=await iF(e,t,n);return r?_y(t,i,r,rF(t,i)):void 0}catch{return}}function RF(e){if(e){if(e.state==="unlinked")return"no Chant-Record or Chant-Lease trailer names a work item";if(e.state==="wrong")return`the work item named is not there: ${e.problems.map(t=>`${t.trailer} (${t.message})`).join("; ")}`}}function bIe(e,t=!1){let n=[`${e.branch}, commits within ${e.window}${e.source==="runs"?", judged from chant runs":""}: ${e.commits.length}`];for(let i of e.commits){let r=i.sha.slice(0,12),o=n.length;if(i.made)n.push(` ${r} ${t?"would make":"made"} ${i.made.tag.slice(0,i.made.tag.lastIndexOf("/"))}${i.verdict?.failure?`: phase ${i.verdict.failure.phase}, ${i.verdict.failure.run.name} ${i.verdict.failure.run.conclusion}`:""}`);else if(i.before==="revoked")n.push(` ${r} revoked`);else{let a=i.verdict,c=f=>`${f.phase}${f.reason?` (${f.reason}${f.coveredBy?`, covered by ${f.coveredBy.slice(0,12)}`:""})`:""}`,l=a.phases.filter(f=>f.verdict==="pending").map(c),u=a.phases.filter(f=>f.verdict==="unbuilt").map(c),d=a.phases.find(f=>f.culprit)?.culprit,p=i.before==="green"?"green":a.verdict==="fail"?`failed: phase ${a.failure.phase}, ${a.failure.run.name} ${a.failure.run.conclusion}${d?`; culprit ${d.slice(0,12)}`:""}`:a.verdict==="unbuilt"?`unbuilt: ${u.join(", ")}`:`undecided: ${l.join(", ")}`;n.push(` ${r} ${p}`)}let s=RF(i.work);s&&(n[o]+=`; why unknown: ${s}`);for(let a of i.ignored??[])n.push(` ignored ${a.tag} (${a.status}): ${a.reason}`);for(let a of i.ignoredRuns??[])n.push(` ignored run ${a.run} of ${a.op} in ${a.env} (${a.status}): ${a.reason}`);i.blocked&&n.push(` did not make ${i.blocked}: an ignored tag holds the name. Delete it to let the tick tag the commit: git push origin :refs/tags/${i.blocked}`)}e.signer&&e.made.length>0&&n.push(`signed as ${e.signer}`);for(let i of e.requested)n.push(`${t?"would ask":"asked"} for ${i.phases.join(", ")} at ${i.commit.slice(0,12)} (${i.reason}): ${i.tag}`);for(let i of e.retried)n.push(`${t?"would run":"ran"} ${i.run} at ${i.sha.slice(0,12)} again`);e.recorded.length>0&&n.push(`recorded ${e.recorded.length} commit${e.recorded.length===1?"":"s"} on chant/lifecycle`);for(let i of e.warnings)n.push(`warning: ${i}`);return n.join(`
275
- `)}function Xee(e,t,n="origin"){let i=[`refs/remotes/${n}/${t.branch}`,`refs/heads/${t.branch}`],r=i.find(o=>Rr(e,["rev-parse","--verify","--quiet",`${o}^{commit}`])!==null);if(!r)throw new Oc("ci-branch-unknown",`this repository has neither ${i.join(" nor ")}`);return r}function vIe(e){let t={$schema:Wee,contract:Gee,chant:en()};try{let{green:n,top:i,workspace:r}=QR(e.cwd),o=Xee(i,n,e.remote),s=o;if(e.from!==void 0){if(e.from.startsWith("-")||Rr(i,["rev-parse","--verify","--quiet",`${e.from}^{commit}`])===null)throw new xe("revision-unknown",`--from ${e.from} names no commit in this repository`);s=e.from}let a=XR(i,n,_n(i,["rev-parse",`${o}^{commit}`])),c=null,l=[],u=[],d=qR(i);if(a.green.size>0||a.ignored.size>0||d.size>0)for(let p of _n(i,["rev-list","--first-parent",s]).split(`
276
- `)){if(l.push(...a.ignored.get(p)??[]),!a.green.has(p)||a.revoked.has(p)){u.length<Qee&&u.push({sha:p,record:SF(n,d.get(p))});continue}c={sha:p,tag:`${uu}${p}`,tagged:a.green.get(p).tagged,committed:_n(i,["show","-s","--format=%cI",p])};break}return{...t,workspace:r,branch:n.branch,ref:s,commit:c,ignored:l,newer:c?u:[]}}catch(n){if(n instanceof Oc||n instanceof xe)return{...t,error:{code:n.code,message:n instanceof xe?n.describe():n.message}};throw n}}function SF(e,t){if(!t)return null;let n=e.require.map(a=>t.phases[a]).filter(a=>a!==void 0),i=a=>n.find(c=>c[a]!==void 0)?.[a],r=i("reason"),o=i("coveredBy"),s=i("culprit");return{state:t.state,...r?{reason:r}:{},...o?{coveredBy:o}:{},...s?{culprit:s}:{}}}function rte(e,t){return{tag:`${Ny}${e}`,tagged:t.tagged,phase:typeof t.record?.phase=="string"?t.record.phase:null,run:nte(t.record?.run),signer:t.signer}}function xIe(e,t){let n=e?.record?.phases?.[t];return Array.isArray(n)?{phase:t,result:"pass",runs:n.map(nte).filter(i=>i!==null)}:{phase:t,result:"unrecorded",runs:[]}}async function $Ie(e){let t={$schema:tte,contract:ete,chant:en()};try{let{green:n,top:i,workspace:r}=QR(e.cwd),o=Xee(i,n,e.remote),s=["log","--first-parent","--format=%H %ct"],a=0;if(e.since!==void 0){if(Rr(i,["rev-parse","--verify","--quiet",`${e.since}^{commit}`])===null)throw new xe("revision-unknown",`--since ${e.since} names no commit in this repository`);s.push(`${e.since}..${o}`)}else a=Math.floor(((e.now??new Date).getTime()-bF(n.window))/1e3),s.push(`--max-age=${a}`,o);let c=_n(i,s).split(`
277
- `).filter(Boolean).map(w=>w.split(" ")).filter(([,w])=>Number(w)>=a).map(([w,b])=>({sha:w,committed:YR(new Date(Number(b)*1e3))}));e.limit!==void 0&&(c=c.slice(0,e.limit));let l=await Yee(e.cwd,i,o,c.map(w=>w.sha)),u=_n(i,["rev-parse",`${o}^{commit}`]),d=XR(i,n,u),p=e.source??n.source;if(p==="runs"&&e.forge)throw new Error("--forge reads check runs, and the source is chant runs (ci.green.source or --source runs); drop one");let f=p==="runs"?await xF(e.cwd,i,u,n.signedSince):void 0,g=qR(i),h=[];for(let w of c){let b=d.green.get(w.sha),k=d.revoked.get(w.sha),$=k?"revoked":b?"green":"undecided",x=n.require.map(P=>xIe(b,P)),R=null;if(k){R=rte(w.sha,k);let{phase:P,run:I}=R;x=x.map(A=>A.phase===P?{phase:A.phase,result:"fail",runs:I?[I]:[]}:A)}else!b&&(f||e.forge)&&(x=wF(n,f?f.checkRuns(w.sha):await e.forge.checkRuns(w.sha)).phases.map(I=>({phase:I.phase,result:I.verdict,runs:I.runs.map(kIe)})));h.push({...w,state:$,green:b?{tag:`${uu}${w.sha}`,tagged:b.tagged,signer:b.signer}:null,revoked:R,phases:x,work:l?.get(w.sha)??null,ignored:d.ignored.get(w.sha)??[],...f?{ignoredRuns:f.ignored.get(w.sha)??[]}:{},record:SF(n,g.get(w.sha))})}return{...t,workspace:r,branch:n.branch,ref:o,window:e.since===void 0?n.window:null,since:e.since??null,require:[...n.require],commits:h}}catch(n){if(n instanceof Oc||n instanceof xe)return{...t,error:{code:n.code,message:n instanceof xe?n.describe():n.message}};throw n}}function ite(e){return[e.state,...e.reason?[e.reason]:[],...e.coveredBy?[`covered by ${e.coveredBy.slice(0,12)}`]:[],...e.culprit?[`culprit ${e.culprit.slice(0,12)}`]:[]].join(", ")}function RIe(e){let t=[`${e.branch}, ${e.since?`commits after ${e.since}`:`commits within ${e.window}`}: ${e.commits.length}`];for(let n of e.commits){let i=n.phases.map(o=>`${o.phase}=${o.result}`).join(" "),r=RF(n.work);t.push(` ${n.sha.slice(0,12)} ${n.state.padEnd(9)} ${i}${r?`; why unknown: ${r}`:""}`),n.record&&n.state==="undecided"&&t.push(` recorded ${ite(n.record)}`);for(let o of n.ignored)t.push(` ignored ${o.tag} (${o.status}): ${o.reason}`);for(let o of n.ignoredRuns??[])t.push(` ignored run ${o.run} of ${o.op} in ${o.env} (${o.status}): ${o.reason}`)}return t.join(`
275
+ `)}function Xee(e,t,n="origin"){let i=[`refs/remotes/${n}/${t.branch}`,`refs/heads/${t.branch}`],r=i.find(o=>Rr(e,["rev-parse","--verify","--quiet",`${o}^{commit}`])!==null);if(!r)throw new Oc("ci-branch-unknown",`this repository has neither ${i.join(" nor ")}`);return r}function vIe(e){let t={$schema:Wee,contract:Gee,chant:en()};try{let{green:n,top:i,workspace:r}=QR(e.cwd),o=Xee(i,n,e.remote),s=o;if(e.from!==void 0){if(e.from.startsWith("-")||Rr(i,["rev-parse","--verify","--quiet",`${e.from}^{commit}`])===null)throw new ve("revision-unknown",`--from ${e.from} names no commit in this repository`);s=e.from}let a=XR(i,n,_n(i,["rev-parse",`${o}^{commit}`])),c=null,l=[],u=[],d=qR(i);if(a.green.size>0||a.ignored.size>0||d.size>0)for(let p of _n(i,["rev-list","--first-parent",s]).split(`
276
+ `)){if(l.push(...a.ignored.get(p)??[]),!a.green.has(p)||a.revoked.has(p)){u.length<Qee&&u.push({sha:p,record:SF(n,d.get(p))});continue}c={sha:p,tag:`${uu}${p}`,tagged:a.green.get(p).tagged,committed:_n(i,["show","-s","--format=%cI",p])};break}return{...t,workspace:r,branch:n.branch,ref:s,commit:c,ignored:l,newer:c?u:[]}}catch(n){if(n instanceof Oc||n instanceof ve)return{...t,error:{code:n.code,message:n instanceof ve?n.describe():n.message}};throw n}}function SF(e,t){if(!t)return null;let n=e.require.map(a=>t.phases[a]).filter(a=>a!==void 0),i=a=>n.find(c=>c[a]!==void 0)?.[a],r=i("reason"),o=i("coveredBy"),s=i("culprit");return{state:t.state,...r?{reason:r}:{},...o?{coveredBy:o}:{},...s?{culprit:s}:{}}}function rte(e,t){return{tag:`${Ny}${e}`,tagged:t.tagged,phase:typeof t.record?.phase=="string"?t.record.phase:null,run:nte(t.record?.run),signer:t.signer}}function xIe(e,t){let n=e?.record?.phases?.[t];return Array.isArray(n)?{phase:t,result:"pass",runs:n.map(nte).filter(i=>i!==null)}:{phase:t,result:"unrecorded",runs:[]}}async function $Ie(e){let t={$schema:tte,contract:ete,chant:en()};try{let{green:n,top:i,workspace:r}=QR(e.cwd),o=Xee(i,n,e.remote),s=["log","--first-parent","--format=%H %ct"],a=0;if(e.since!==void 0){if(Rr(i,["rev-parse","--verify","--quiet",`${e.since}^{commit}`])===null)throw new ve("revision-unknown",`--since ${e.since} names no commit in this repository`);s.push(`${e.since}..${o}`)}else a=Math.floor(((e.now??new Date).getTime()-bF(n.window))/1e3),s.push(`--max-age=${a}`,o);let c=_n(i,s).split(`
277
+ `).filter(Boolean).map(w=>w.split(" ")).filter(([,w])=>Number(w)>=a).map(([w,b])=>({sha:w,committed:YR(new Date(Number(b)*1e3))}));e.limit!==void 0&&(c=c.slice(0,e.limit));let l=await Yee(e.cwd,i,o,c.map(w=>w.sha)),u=_n(i,["rev-parse",`${o}^{commit}`]),d=XR(i,n,u),p=e.source??n.source;if(p==="runs"&&e.forge)throw new Error("--forge reads check runs, and the source is chant runs (ci.green.source or --source runs); drop one");let f=p==="runs"?await xF(e.cwd,i,u,n.signedSince):void 0,g=qR(i),h=[];for(let w of c){let b=d.green.get(w.sha),k=d.revoked.get(w.sha),$=k?"revoked":b?"green":"undecided",x=n.require.map(P=>xIe(b,P)),R=null;if(k){R=rte(w.sha,k);let{phase:P,run:I}=R;x=x.map(A=>A.phase===P?{phase:A.phase,result:"fail",runs:I?[I]:[]}:A)}else!b&&(f||e.forge)&&(x=wF(n,f?f.checkRuns(w.sha):await e.forge.checkRuns(w.sha)).phases.map(I=>({phase:I.phase,result:I.verdict,runs:I.runs.map(kIe)})));h.push({...w,state:$,green:b?{tag:`${uu}${w.sha}`,tagged:b.tagged,signer:b.signer}:null,revoked:R,phases:x,work:l?.get(w.sha)??null,ignored:d.ignored.get(w.sha)??[],...f?{ignoredRuns:f.ignored.get(w.sha)??[]}:{},record:SF(n,g.get(w.sha))})}return{...t,workspace:r,branch:n.branch,ref:o,window:e.since===void 0?n.window:null,since:e.since??null,require:[...n.require],commits:h}}catch(n){if(n instanceof Oc||n instanceof ve)return{...t,error:{code:n.code,message:n instanceof ve?n.describe():n.message}};throw n}}function ite(e){return[e.state,...e.reason?[e.reason]:[],...e.coveredBy?[`covered by ${e.coveredBy.slice(0,12)}`]:[],...e.culprit?[`culprit ${e.culprit.slice(0,12)}`]:[]].join(", ")}function RIe(e){let t=[`${e.branch}, ${e.since?`commits after ${e.since}`:`commits within ${e.window}`}: ${e.commits.length}`];for(let n of e.commits){let i=n.phases.map(o=>`${o.phase}=${o.result}`).join(" "),r=RF(n.work);t.push(` ${n.sha.slice(0,12)} ${n.state.padEnd(9)} ${i}${r?`; why unknown: ${r}`:""}`),n.record&&n.state==="undecided"&&t.push(` recorded ${ite(n.record)}`);for(let o of n.ignored)t.push(` ignored ${o.tag} (${o.status}): ${o.reason}`);for(let o of n.ignoredRuns??[])t.push(` ignored run ${o.run} of ${o.op} in ${o.env} (${o.status}): ${o.reason}`)}return t.join(`
278
278
  `)}var aIe,uu,Ny,Gee,Wee,cIe,Oc,lIe,YR,Uee,Vee,yIe,Qee,ete,tte,nte,kIe,uf=v(()=>{"use strict";UR();Tt();Sc();Pt();Nd();Oee();Cee();Fee();on();Wr();Qi();Go();Al();hF();aIe="CHANT_RUNNER_KEY",uu="ci/green/",Ny="ci/revoked/",Gee=1,Wee="https://intentius.io/chant/schemas/workspace/ci-last-green/v1/ci-last-green.schema.json",cIe=[...yi,"ci-green-undeclared","ci-branch-unknown"],Oc=class extends Error{constructor(n,i){super(i);this.code=n;this.name="CiGreenError"}},lIe=new Set(["cancelled","stale"]);YR=e=>e.toISOString().replace(/\.\d{3}Z$/,"Z");Uee=e=>e.opRun?{name:e.name,id:null,conclusion:e.conclusion,url:e.url,opRun:{id:e.opRun.id,env:e.opRun.env,signer:e.opRun.signer,...e.opRun.statement?{statement:e.opRun.statement}:{}}}:{name:e.name,id:e.id,conclusion:e.conclusion,url:e.url},Vee=e=>e.source==="runs"?{source:"runs"}:{};yIe=/^runs__(.+)\.jsonl$/;Qee=50;ete=1,tte="https://intentius.io/chant/schemas/workspace/ci-list/v1/ci-list.schema.json";nte=e=>{if(!e||typeof e!="object")return null;let t=e;if(typeof t.name!="string")return null;let n=t.opRun,i=n&&typeof n=="object"?typeof n.signer=="string"?n.signer:n.signer===null?null:void 0:void 0,r=n&&typeof n=="object"&&typeof n.id=="string"&&typeof n.env=="string"&&i!==void 0?{opRun:{id:n.id,env:n.env,signer:i}}:{};return{name:t.name,id:typeof t.id=="number"?t.id:null,conclusion:typeof t.conclusion=="string"?t.conclusion:null,url:typeof t.url=="string"?t.url:null,...r}};kIe=e=>({name:e.name,id:e.opRun?null:e.id,conclusion:e.conclusion,url:e.url,...e.opRun?{opRun:{id:e.opRun.id,env:e.opRun.env,signer:e.opRun.signer}}:{}})});var AF={};_e(AF,{RELEASE_REVOKED_CODE:()=>ote,describeRevocation:()=>OF,judgedCiTags:()=>ste,readRevokedCommits:()=>EIe,revocationOf:()=>cte,revokedCommitsAt:()=>EF,revokedRefusal:()=>OIe,revokedReleaseLookup:()=>ate});import{execFileSync as SIe}from"node:child_process";function nS(e,t){try{return SIe("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim()}catch{return null}}async function ste(e,t){let{readCiTags:n}=await Promise.resolve().then(()=>(uf(),tS)),i=t?nS(e,["rev-parse","--verify","--quiet",`refs/remotes/origin/${t.branch}^{commit}`])??nS(e,["rev-parse","--verify","--quiet",`refs/heads/${t.branch}^{commit}`])??nS(e,["rev-parse","HEAD"]):null;return n(e,t,i)}async function EIe(e){let t=nS(e,["rev-parse","--show-toplevel"]);if(!t)return new Map;let{scopeSource:n}=await Promise.resolve().then(()=>(Bo(),oj));return EF(t,n(e).declaration?.ci?.green??null)}async function EF(e,t){let{revokedTagView:n}=await Promise.resolve().then(()=>(uf(),tS)),i=new Map;for(let[r,o]of(await ste(e,t)).revoked)i.set(r,{commit:r,...n(r,o)});return i}function ate(e,t){let n=new Map,i;return r=>{let o=n.get(r);return o||(o=(async()=>{let s=await t();if(s.size===0)return null;let{readRelease:a,readCuts:c,labelsByDigest:l}=await Promise.resolve().then(()=>(cu(),wy)),u={cwd:e},d=await a(r,u).catch(()=>null),p=d?cte(d,s):null;return p?(i??=c(u).then(f=>l(f.cuts),()=>new Map),{...p,releaseDigest:r,label:(await i).get(r)??null}):null})(),n.set(r,o)),o}}function cte(e,t){return t.get(e.commit)??null}function OF(e){let t=e.run?` in ${e.run.name}${e.run.opRun?` (Op run ${e.run.opRun.id} in ${e.run.opRun.env})`:e.run.id!==null?` (run ${e.run.id})`:""}`:"";return e.phase!==null?`phase ${e.phase} failed${t}`:`a required phase failed${t}`}function OIe(e,t,n){return{message:`release ${e.label??e.releaseDigest} was cut from commit ${t.commit.slice(0,12)}, which ${t.tag} revokes (${OF(t)}), so it is not deployed and no approval of it counts [${ote}]`,hint:n}}var ote,rS=v(()=>{"use strict";ote="release-revoked"});var dte={};_e(dte,{InvalidReleasePlanError:()=>iS,persistReleasePlan:()=>PIe,readReleasePlan:()=>ute});function AIe(e){return e.replace(/:/g,"_")}function lte(e){return`${AIe(e)}.json`}async function PIe(e,t){if(typeof e.digest!="string"||e.digest.length===0)throw new iS('release plan is missing its own "digest" field \u2014 a release plan is content-addressed by its own digest');let n=lte(e.digest);if(await At(PF,n,t)!==null)return{commit:null,written:!1};let r=JSON.stringify(e,Gt);try{return{commit:await mn(PF,n,r,"Release plan",{...t,expectPriorPathSha:null}),written:!0}}catch(o){if(o instanceof Ot)return{commit:null,written:!1};throw o}}async function ute(e,t){let n=`${t?.prefix??""}${PF}`,i=await At(n,lte(e),t);if(!i)return null;try{return JSON.parse(i)}catch{return null}}var PF,iS,CF=v(()=>{"use strict";Wt();Pt();PF="_plans",iS=class extends Error{constructor(t){super(t),this.name="InvalidReleasePlanError"}}});import{execFileSync as CIe}from"node:child_process";function pte(e,t){try{return CIe("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],maxBuffer:256*1024*1024})}catch{return}}function fte(e,t,n){let i=t?.green.get(e),r=t?.revoked.get(e),o=(s,a)=>({tag:`ci/${s}/${e}`,tagged:a.tagged,signer:a.signer,source:{ref:`refs/tags/ci/${s}/${e}`,field:"name",value:e}});return{state:r?"revoked":i?"green":"none",green:i?o("green",i):null,revoked:r?{...o("revoked",r),phase:n(e,r).phase,run:n(e,r).run}:null,ignored:t?.ignored.get(e)??[]}}async function mte(e){let{top:t}=e,n=[],i=e.commits.map(ne=>ne.sha),r=null,{revokedTagView:o}=await Promise.resolve().then(()=>(uf(),tS));try{let{judgedCiTags:ne}=await Promise.resolve().then(()=>(rS(),AF));r=await ne(t,e.green)}catch(ne){n.push({code:"declaration-invalid",message:`the ci tags could not be judged: ${ne instanceof Error?ne.message:String(ne)}`})}let{judgeCommitLink:s,hasLeaseLedger:a,mergeCommits:c}=await Promise.resolve().then(()=>(UR(),hee)),l=e.work?{...e.work.index,ledger:a(t)}:null,u=l?c(t,i):new Set,d=ne=>e.work?.nodes.get(ne)??null,p=pte(t,["rev-parse","--verify","--quiet","refs/heads/chant/lifecycle"])!==void 0,f=[],g=p?(pte(t,["ls-tree","-r","--name-only","--full-tree","refs/heads/chant/lifecycle"])??"").split(`
279
279
  `).filter(Boolean):[],h=ne=>g.some(ye=>ye.startsWith(ne)&&(ye.startsWith(`${ne}_releases/`)||/^[^/_][^/]*\/releases\.jsonl$/.test(ye.slice(ne.length))));if(p){let{resolveMemberLedger:ne}=await Promise.resolve().then(()=>(Io(),R4)),{readAllReleases:ye}=await Promise.resolve().then(()=>(cu(),wy)),{listReleaseEnvironments:ge,readReleaseLedger:oe}=await Promise.resolve().then(()=>(Hs(),B7));for(let Se of e.ledgers){if(Se.within!==null&&!g.some(te=>te.includes(Se.within)))continue;let Ne={cwd:Se.cwd};try{let te=(await ne(Se.cwd)).prefix;if(f.some($e=>$e.prefix===te)||!h(te))continue;let{releases:Ve}=await ye(Ne),z=[];for(let $e of await ge(Ne))for(let Ie of(await oe($e,Ne)).records)z.push({env:$e,record:Ie});f.push({member:Se.member,loc:Ne,prefix:te,releases:Ve,deploys:z})}catch(te){n.push({code:"ledger-unreadable",message:`${Se.member??"the workspace"}'s ledger on chant/lifecycle: ${te instanceof Error?te.message.split(`
280
280
  `)[0]:String(te)}`})}}}let w=new Map,b=new Map,k=new Map,$=(ne,ye,ge)=>`deploy:${ne.member??"."}/${ye}/${ge.component}/${ge.runId}@${ge.timestamp}`,x=new Map;if(f.some(ne=>ne.releases.length>0)){let{readCuts:ne}=await Promise.resolve().then(()=>(cu(),wy));for(let ye of f)if(ye.releases.length!==0)try{for(let ge of(await ne(ye.loc)).cuts)(!w.has(ge.releaseDigest)||Ac(ge.timestamp,w.get(ge.releaseDigest))<0)&&w.set(ge.releaseDigest,ge.timestamp)}catch{}}for(let ne of i){let ye=[],ge=[];for(let oe of f){let Se=z=>({ref:ss(`${oe.prefix}_releases/${_F(z.releaseDigest)}`),field:"commit",value:z.commit}),te=oe.releases.filter(z=>z.commit===ne).map(z=>({r:z,link:"cut-from"}));if(te.length===0){let z=oe.releases.filter($e=>e.contains(ne,$e.commit)).sort(($e,Ie)=>Ac(w.get($e.releaseDigest)??"\uFFFF",w.get(Ie.releaseDigest)??"\uFFFF")||Ac($e.releaseDigest,Ie.releaseDigest));z.length>0&&te.push({r:z[0],link:"contains"})}for(let{r:z,link:$e}of te)ye.push({release:z.releaseDigest,link:$e,source:Se(z)}),(b.get(oe)??b.set(oe,new Set).get(oe)).add(z.releaseDigest);let Ve=new Map;for(let z of oe.deploys){let $e=z.record.gitSha===ne?"built-from":e.contains(ne,z.record.gitSha)?"contains":null;if(!$e)continue;let Ie=Ve.get(z.env);(!Ie||Ac(z.record.timestamp,Ie.record.timestamp)<0)&&Ve.set(z.env,{...z,link:$e})}for(let[z,$e]of[...Ve].sort(([Ie],[et])=>Ac(Ie,et))){let Ie=$(oe,z,$e.record);k.set(Ie,{ledger:oe,env:z,record:$e.record}),ge.push({deploy:Ie,env:z,link:$e.link,source:{ref:ss(`${oe.prefix}${z}/releases.jsonl`),field:"gitSha",value:$e.record.gitSha}})}}x.set(ne,{releases:ye,deploys:ge})}let{joinRelease:R}=await Promise.resolve().then(()=>(by(),S1)),{readGateLedger:P}=await Promise.resolve().then(()=>(Mr(),UI)),{readStoredChangeSet:I,changeSetFile:A,CHANGE_SETS_DIR:B}=await Promise.resolve().then(()=>(ky(),E1)),C=new Map,q=(ne,ye)=>{let ge=`${ne.prefix}\0${ye}`,oe=C.get(ge);return oe||(oe=P(ye,ne.loc).then(Se=>Se.resolutions,()=>[]),C.set(ge,oe)),oe},L=new Map,M=async(ne,ye)=>{let ge;if(ye.planDigest){let Se=`${ne.prefix}\0${ye.planDigest}`;ge=L.get(Se),ge||(ge=I(ye.planDigest,ne.loc).then(Ne=>Ne.status==="found",()=>!1),L.set(Se,ge))}let oe=ge?await ge:!1;return{op:ye.op,gate:ye.gate,environment:ye.environment??null,resolvedBy:ye.resolvedBy,relayedBy:ye.relayedBy??null,channel:ye.origin??null,at:ye.timestamp,planDigest:ye.planDigest??null,changeSet:oe?ye.planDigest:null,changeSetSource:oe?{ref:ss(`${ne.prefix}${B}/${A(ye.planDigest)}`),field:"planDigest",value:ye.planDigest}:null,empty:ye.empty===!0,sealed:ye.seal!==void 0,url:ye.url??null,source:{ref:ss(`${ne.prefix}_gates/${ye.op}.jsonl`),field:ye.releaseDigest?"releaseDigest":"gate",value:ye.releaseDigest??ye.gate}}},_=[],T=new Map;for(let ne of f){let ye=b.get(ne);if(!ye||ye.size===0)continue;let ge=[...new Set(ne.releases.filter(Se=>ye.has(Se.releaseDigest)).map(Se=>Se.commit))],oe;try{oe=(await R({commits:ge},ne.loc)).releases}catch(Se){n.push({code:"ledger-unreadable",message:`joining ${ne.member??"the workspace"}'s releases: ${Se instanceof Error?Se.message.split(`
281
- `)[0]:String(Se)}`});continue}for(let Se of oe){for(let Ne of Se.deploys)T.set($(ne,Ne.env,Ne),{ledger:ne,env:Ne.env,record:Ne,release:Se});_.push({releaseDigest:Se.releaseDigest,label:Se.label,member:Se.release.member,commit:Se.commit,tag:fte(Se.commit,r,o),source:{ref:ss(`${ne.prefix}_releases/${_F(Se.releaseDigest)}`),field:"releaseDigest",value:Se.releaseDigest},cuts:Se.cuts.map(Ne=>({label:Ne.label,actor:Ne.actor,timestamp:Ne.timestamp,signed:Ne.signature!==null,runOrigin:Ne.runOrigin,source:{ref:ss(`${ne.prefix}_releases/cuts.jsonl`),field:"releaseDigest",value:Ne.releaseDigest}})),gates:await Promise.all([...Se.gates.resolutions].sort((Ne,te)=>Ac(Ne.timestamp,te.timestamp)).map(Ne=>M(ne,Ne))),deploys:Se.deploys.map(Ne=>$(ne,Ne.env,Ne))})}}let{readReleasePlan:W}=await Promise.resolve().then(()=>(CF(),dte)),ve=new Map,re=new Map([...k,...T]),be=new Map,Be=[];for(let[ne,ye]of[...re].sort(([,ge],[,oe])=>Ac(ge.record.timestamp,oe.record.timestamp)||Ac(ge.env,oe.env))){let ge=ye.record,oe=ye.ledger,Se=ge.releaseDigest??null,Ne=Se?{ref:ss(`${oe.prefix}${ye.env}/releases.jsonl`),field:"releaseDigest",value:Se}:null;if(!Se&&ge.admission?.op==="release"){be.has(oe)||be.set(oe,await q(oe,"release"));let{releaseOfDeploy:Ie}=await Promise.resolve().then(()=>(by(),S1));Se=Ie(ge,be.get(oe))??null,Se&&(Ne={ref:ss(`${oe.prefix}${ye.env}/releases.jsonl`),field:"admission",value:`${ge.admission.gate}@${ge.admission.resolvedAt}`})}let te=null;if(ge.admission){let Ie=(await q(oe,ge.admission.op)).find(et=>et.gate===ge.admission.gate&&et.timestamp===ge.admission.resolvedAt);Ie&&(te=await M(oe,Ie))}let Ve=`${oe.prefix}\0${ge.digest}`,z=ve.get(Ve);z||(z=W(ge.digest,oe.loc).catch(()=>null),ve.set(Ve,z));let $e=await z;Be.push({id:ne,member:oe.member,env:ye.env,component:ge.component,timestamp:ge.timestamp,actor:ge.actor,approver:ge.approver??null,runId:ge.runId,runOrigin:ge.runOrigin??null,gitSha:ge.gitSha,digest:ge.digest,release:Se,releaseSource:Ne,admittedBy:te,plan:$e?{document:$e,source:{ref:ss(`${oe.prefix}_plans/${_F(ge.digest)}`),field:"digest",value:ge.digest}}:null,source:{ref:ss(`${oe.prefix}${ye.env}/releases.jsonl`),field:"runId",value:ge.runId}})}return{commits:e.commits.map(ne=>{let ye=null;if(l){let Se=u.has(ne.sha)?{state:"merge",ids:[],problems:[]}:s(ne.trailers,ne.joins,l),Ne=Se.ids.map(te=>{let Ve=ne.joins.records.some(z=>`${z.kind}:${z.id}`===te);return{id:te,node:d(te),source:Ve?{ref:ne.sha,field:"Chant-Record",value:te}:{ref:ne.sha,field:"Chant-Lease",value:ne.joins.lease?.token??""}}});ye={state:Se.state,items:Ne,problems:Se.problems}}let ge=(e.windows.get(ne.sha)??[]).map(Se=>({id:Se.id,node:Se.node,source:{ref:Se.path,field:"window",value:"worked"}})),oe=x.get(ne.sha)??{releases:[],deploys:[]};return{commit:ne.id,sha:ne.sha,work:ye,windowMatches:ge,tag:fte(ne.sha,r,o),releases:oe.releases,deploys:oe.deploys}}),releases:_,deploys:Be,reasons:n}}var _F,ss,Ac,gte=v(()=>{"use strict";_F=e=>`${e.replace(/:/g,"_")}.json`,ss=e=>`chant/lifecycle:${e}`,Ac=(e,t)=>e<t?-1:e>t?1:0});import{createHash as _Ie}from"node:crypto";function TF(e){let t=e.members.filter(n=>(n.box?.services.length??0)>0);return t.length===1?{plantable:!0,box:t[0].name,reason:null}:t.length===0?{plantable:!1,box:null,reason:{code:"box-none",message:"no member's box block declares services, so there is no box to plant"}}:{plantable:!1,box:null,reason:{code:"box-several",message:`members ${t.map(n=>n.name).join(", ")} each declare box services, and a planted workspace runs one box`}}}function hte(e,t=[]){return e===null?null:{builds:[...e.builds],check:e.check===null?null:{...e.check},checks:e.checks,builders:e.builders,tiers:e.tiers.map(n=>({...n,kinds:n.kinds===null?null:[...n.kinds]})),builderFor:TIe(e,t),publish:e.publish===null?null:{...e.publish}}}function TIe(e,t){let n=[...new Set(e.tiers.map(r=>r.tier))],i={};for(let r of e.builds){let o=t.find(a=>a.name===r)?.kind,s={};for(let a of n){let c=e.tiers.find(l=>l.tier===a&&o!==void 0&&l.kinds?.includes(o))??e.tiers.find(l=>l.tier===a&&l.kinds===null);c&&(s[a]={agent:c.agent,session:c.session})}i[r]=s}return i}function yte(e,t){if(e===null)return null;let n=null;if(e.cover!==null){let i=t(e.cover);n={path:e.cover,sha256:i===null?null:_Ie("sha256").update(i).digest("hex")}}return{published:e.published,title:e.title,line:e.line,cover:n}}function wte(e){return t=>{try{return e.stat(t)!=="file"?null:e.bytes?e.bytes(t):new TextEncoder().encode(e.read(t))}catch{return null}}}function bte(e,t,n=[]){return e===null||e.factory===null&&e.listing===null?null:{factory:hte(e.factory,n),listing:yte(e.listing,wte(t))}}var IF=v(()=>{"use strict"});function pf(e){let t;try{t=JSON.parse(e)}catch{return{reason:{code:"output-unreadable",message:"chant graph --format ir printed something that is not JSON"}}}if(t===null||typeof t!="object"||!Array.isArray(t.nodes)||!Array.isArray(t.edges))return{reason:{code:"output-unreadable",message:"chant graph --format ir printed JSON with no nodes and edges"}};let n=t,i=n.version;if(i===void 0)n.version=1;else if(typeof i!="number"||i>ML)return{reason:{code:"ir-version-unsupported",message:`the member's chant printed IR version ${String(i)}, and this chant reads up to version ${ML}`}};return n.groups??={},{ir:n,irVersion:i===void 0?null:i}}function jIe(e,t){if(typeof t!="object"||t===null||!Array.isArray(t.pipelines))return null;let n=t;return{member:e,pipelines:DF(n.pipelines).map(i=>({id:String(i.id),signal:String(i.signal),receivers:qs(i.receivers),processors:qs(i.processors),exporters:qs(i.exporters)})),components:DF(n.components).map(i=>({id:String(i.id),kind:String(i.kind),type:String(i.type),endpoints:qs(i.endpoints),protocols:qs(i.protocols),pipelines:qs(i.pipelines)})),exporters:DF(n.exporters).map(i=>({id:String(i.id),type:String(i.type),endpoints:qs(i.endpoints),pipelines:qs(i.pipelines),signals:qs(i.signals)}))}}function jF(e,t){if(Array.isArray(e))return e.map(i=>jF(i,t));if(e===null||typeof e!="object")return e;let n={};for(let[i,r]of Object.entries(e))n[i]=i==="$ref"&&typeof r=="string"?Ii(t,r):jF(r,t);return n}function vte(e,t,n){(e[t]??=[]).push(...n)}function kte(e){let t={};for(let n of Object.keys(e).sort())t[n]=[...e[n]].sort();return t}function xte(e,t,n){let i=[],r=[],o=[],s=[],a={},c={byLexicon:{},byComposite:{}},l={byStack:{},byContainer:{},byWave:{},byPipeline:{}},u=[],d={},p=[];for(let{member:w,ir:b}of t){if(!b)continue;let k=w.name,$=[];for(let x of b.nodes){let R={...x,id:Ii(k,x.id),member:k,attrs:jF(x.attrs??{},k)};x.compositeInstance&&(R.compositeInstance=Ii(k,x.compositeInstance)),x.runtimeOwner&&(R.runtimeOwner=Ii(k,x.runtimeOwner)),i.push(R),$.push(R.id)}a[k]=$.sort();for(let x of b.edges)r.push({...x,from:Ii(k,x.from),to:Ii(k,x.to),member:k});for(let x of["byLexicon","byComposite"])for(let[R,P]of Object.entries(b.groups[x]??{}))vte(c[x],R,P.map(I=>Ii(k,I)));for(let x of oS)for(let[R,P]of Object.entries(b.groups[x]??{}))vte(l[x],Ii(k,R),P.map(I=>Ii(k,I)));for(let x of b.dangling??[])u.push({...x,from:Ii(k,x.from),member:k});for(let x of b.exports??[])o.push({...x,...x.node?{node:Ii(k,x.node)}:{},member:k});for(let x of b.imports??[])s.push({...x,node:Ii(k,x.node),member:k});for(let[x,R]of Object.entries(b.derivedAttrs??{}))for(let P of R)(d[x]??=new Set).add(P);if(b.meta){let{[DIe]:x,...R}=b.meta,P=jIe(k,x);P&&p.push(P),P?Object.keys(R).length>0&&(w.meta=R):w.meta=b.meta}b.pipeline&&(w.pipeline=b.pipeline)}i.sort((w,b)=>w.id.localeCompare(b.id));let f=w=>`${w.from}\0${w.to}\0${w.viaAttr??""}`;r.sort((w,b)=>f(w).localeCompare(f(b)));let g={byMember:a};for(let w of["byLexicon","byComposite"])Object.keys(c[w]).length&&(g[w]=kte(c[w]));for(let w of oS)Object.keys(l[w]).length&&(g[w]=kte(l[w]));let h={version:IIe,workspace:e,members:t.map(w=>w.member),nodes:i,edges:r,groups:g,exports:o,imports:s,links:n?n3(n.declaration,{composed:t.filter(w=>w.ir).map(w=>w.member.name),collectors:p,exports:o,imports:s},n.kinds,n.read):[],collectors:p,records:[]};return u.length&&(h.dangling=u.sort((w,b)=>My(w).localeCompare(My(b)))),Object.keys(d).length&&(h.derivedAttrs=Object.fromEntries(Object.keys(d).sort().map(w=>[w,[...d[w]].sort()]))),h}var IIe,DIe,Ii,qs,DF,oS,My,Fy=v(()=>{"use strict";Dp();U$();IIe=1,DIe="collector";Ii=(e,t)=>`${e}/${t}`,qs=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],DF=e=>Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[];oS=["byStack","byContainer","byWave","byPipeline"],My=e=>`${e.from}\0${e.path}\0${e.value}`});var $te=v(()=>{"use strict"});var Rte,NF=v(()=>{"use strict";Nl();Tt();on();Rte=".chant/generated.json"});function Ste(e){return e===".gitlab-ci.yml"?!0:/^(\.github\/workflows|\.forgejo\/workflows|\.gitea\/workflows|\.gitlab\/ci)\/[^/]+$/.test(e)}var Ete=v(()=>{"use strict";Dp();NF()});function LIe(e,t){let n;try{n=qd.load(t)}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n;if(e.startsWith(".gitlab/ci/")||e===".gitlab-ci.yml")return Object.entries(i).filter(([o,s])=>!o.startsWith(".")&&!NIe.has(o)&&s&&typeof s=="object"&&!Array.isArray(s)).map(([o])=>o);let r=i.jobs;return!r||typeof r!="object"||Array.isArray(r)?null:Object.entries(r).map(([o,s])=>{let a=s&&typeof s=="object"?s.name:void 0;return typeof a=="string"&&a!==""?a:o})}function Ote(e,t,n){let i=a=>qe(n,a),r=new Map,o=qe(e.dir,Rte);if(t.stat(o)==="file")try{let a=JSON.parse(t.read(o));for(let c of Array.isArray(a.files)?a.files:[])typeof c.path=="string"&&r.set(c.path,{path:c.path,command:typeof c.command=="string"?c.command:"",env:typeof c.env=="string"?c.env:null,jobs:null})}catch{}for(let a of e.generated){if(a.handWritten)continue;let c=i(qe(e.dir,a.path));r.set(c,{path:c,command:a.generator,env:r.get(c)?.env??null,jobs:null})}let s=n==="."?"":`${n}/`;for(let a of r.values()){if(!Ste(a.path)||!a.path.startsWith(s))continue;let c=a.path.slice(s.length);if(t.stat(c)==="file")try{a.jobs=LIe(a.path,t.read(c))}catch{a.jobs=null}}return[...r.values()].sort((a,c)=>a.path<c.path?-1:a.path>c.path?1:0)}var NIe,Ate=v(()=>{"use strict";xD();Ete();NF();on();NIe=new Set(["stages","variables","default","include","workflow","image","services","cache","before_script","after_script","pages"])});import{isAbsolute as MIe,resolve as yyt}from"node:path";function sS(e,t,n){if(t.stat(e.dir==="."?"":e.dir)!=="dir")return{code:"dir-missing",message:`${e.dir} is not a directory${t.label}`};let i=n.get(e.kind);return i?e4(i,t,e.dir==="."?"":e.dir)?null:{code:"kind-probe-failed",message:`${e.dir} is not ${i.description}`}:{code:"unknown-kind",message:`no built-in kind or pinned package supplies kind ${e.kind}; known kinds: ${n.names().join(", ")}`}}function Cte(e){return WIe(e).doc}function WIe(e){let t=en(),n={$schema:GIe,contract:FIe,chant:t};try{let i=qt(e.cwd,e.at),{tree:r,rootOnDisk:o,at:s}=i,a=_t(r,"",{rootChant:!0}),c=e.kinds??Pa(a.pins,o).registry,l=_a(a,r),u=MIe(i.root)?".":i.root,d=s!==null?{agents:a.agents,from:"at"}:rj(e.cwd)??{agents:a.agents,from:"working-tree"},p=a.members.map(w=>{let b=sS(w,r,c);return{name:w.name,dir:w.dir,kind:w.kind,roles:w.roles,upstream:w.upstream,because:w.because,readable:b===null,reason:b,records:Pte(w.records),generated:Ote(w,r,u),agents:d.agents.filter(k=>k.members.includes(w.name)).map(k=>k.name),...ag(a,w.pointer)}}),f=l.map(w=>({name:w.group.name,kind:"examples",glob:w.group.globs,matches:w.matches,skipped:w.skipped,reason:w.matches.length===0?{code:"no-matches",message:`no directory ${w.group.globs.join(" or ")} matches${r.label} holds a chant project`}:null})),g=RI(a).map(w=>({name:w.name,title:w.title,source:w.source,render:w.render,renderer:w.renderer,member:w.member}));return{doc:{...n,at:s,workspace:{name:a.name,root:i.root,file:a.file,schema:a.schema,minReader:a.minReader,pins:a.pins,records:Pte(a.records),agentsFrom:d.from,...ag(a,"")},members:p,groups:f,diagrams:g,ci:a.ci?{green:a.ci.green?{branch:a.ci.green.branch,window:a.ci.green.window,phases:a.ci.green.phases.map(w=>({name:w.name,runs:w.runs,skipped:w.skipped,...w.build?{build:w.build}:{}})),require:a.ci.green.require,...a.ci.green.signedSince!==null?{signedSince:a.ci.green.signedSince}:{},...a.ci.green.source==="runs"?{source:"runs"}:{}}:null,...a.ci.reportUrl!==null?{reportUrl:a.ci.reportUrl}:{}}:null,summary:{members:p.length,unreadable:p.filter(w=>!w.readable).length,groups:f.length,matches:f.reduce((w,b)=>w+b.matches.length,0)}},declaration:a,tree:r,rootOnDisk:o}}catch(i){if(!(i instanceof xe))throw i;return{doc:{...n,error:{code:i.code,message:i.message,location:i.location??null}}}}}var FIe,GIe,Pte,LF=v(()=>{"use strict";ur();Tt();Ate();qi();Wr();Bo();FIe=1,GIe="https://intentius.io/chant/schemas/workspace/ls/v1/ls.schema.json";Pte=e=>e.map(t=>({name:t.name,path:t.path,kind:null,reason:null,acceptance:null}))});var MF,_te,Tte=v(()=>{"use strict";um();Tt();MF="@@chant-member-run@@ ",_te=1});import{spawn as BIe}from"node:child_process";import{existsSync as zIe,mkdirSync as Nte,realpathSync as UIe,writeFileSync as VIe}from"node:fs";import{dirname as Wy,join as Gy,resolve as By}from"node:path";import{fileURLToPath as HIe}from"node:url";function Ite(){return By(Wy(HIe(import.meta.url)),"..","..","bin","chant")}function Lte(e){try{return UIe(e)}catch{return e}}function aS(){let e=process.argv[1]??"";return{command:/[\\/]cli[\\/]main\.(ts|js|mjs)$/.test(e)?[process.execPath,...process.execArgv,e]:[Ite()],identity:Lte(Ite()),source:"reader"}}function qIe(e,t,n=aS()){for(let i=e;;i=Wy(i)){let r=Gy(i,"node_modules",".bin","chant");if(zIe(r)){let o=Lte(r),s=i===t?"root":"member";return o===n.identity?{...n,source:s}:{command:[r],identity:o,source:s}}if(i===t||Wy(i)===i)break}return n}function cS(e,t,n={}){let i=n.tree??Rn(t),r=_t(i),o=_a(r,i),s=n.kinds??QK(),a=n.only?.length?new Set(n.only):void 0;if(a){let g=new Set(r.entries.map(w=>w.name)),h=[...a].filter(w=>!g.has(w));if(h.length>0)throw new xe("declaration-invalid",`--member names ${h.join(", ")}, which the declaration does not declare; it declares ${[...g].join(", ")}`)}let c=[],l=[],u=[],d=e==="build"||e==="lint";for(let g of r.entries){if(a&&!a.has(g.name))continue;if(g.type==="group"){let b=o.find(k=>k.group===g);if(!d){l.push({name:g.name,dir:null,kind:g.kind,reason:{code:"kind-not-run",message:`example groups are built and linted only; chant workspace ${e} leaves them out`}});continue}for(let k of b.matches)c.push({id:`${g.name}:${k}`,member:g.name,kind:g.kind,group:!0,dir:k,abs:Gy(t,k),exclude:[]});continue}let h=e==="graph"&&g.kind!=="chant"?s.get(g.kind):void 0;if(h?.graph&&h.packageDir){let b=sS(g,i,s);if(b){u.push({name:g.name,dir:g.dir,kind:g.kind,reason:b});continue}c.push({id:g.name,member:g.name,kind:g.kind,group:!1,dir:g.dir,abs:g.dir==="."?t:Gy(t,g.dir),exclude:[],reader:{...h.graph,packageDir:h.packageDir}});continue}if(g.kind!=="chant"){let b=g.kind==="workspace"?"a nested workspace runs its own chant workspace commands":g.kind==="design"?"a design member is data: chant reads its files for record pins and builds nothing":`chant workspace ${e} runs members of kind chant, and this one is kind ${g.kind}`;l.push({name:g.name,dir:g.dir,kind:g.kind,reason:{code:"kind-not-run",message:b}});continue}let w=sS(g,i,s);if(w){u.push({name:g.name,dir:g.dir,kind:g.kind,reason:w});continue}c.push({id:g.name,member:g.name,kind:g.kind,group:!1,dir:g.dir,abs:g.dir==="."?t:Gy(t,g.dir),exclude:g.dir==="."?gk(r,o).map(b=>b.dir):[]})}let p=n.reader??aS(),f=new Map;for(let g of c){let h=qIe(g.abs,t,p),w=f.get(h.identity)??{toolchain:h,units:[]};w.units.push(g),f.set(h.identity,w)}return{verb:e,workspace:{name:r.name,root:t,file:r.file},groups:[...f.values()],unreadable:u,skipped:l}}function Dte(e,t){return e==="graph"?"ir":e==="audit"?"json":e==="lint"?t.format==="sarif"||t.format==="json"?t.format:"stylish":t.format==="yaml"?"yaml":"json"}function FF(e,t,n){let i=e==="build"&&!n.format?[e,"."]:[e,".","--format",Dte(e,n)],r=()=>{for(let o of n.param??[])i.push("--param",o);n.paramsFile&&i.push("--params-file",By(n.paramsFile))};return e==="build"?(n.env&&i.push("--env",n.env),r(),n.lexicon&&i.push("--lexicon",n.lexicon),n.output&&i.push("--output",KIe(n.output,t,Dte(e,n)))):e==="lint"?(r(),n.fix&&i.push("--fix")):e==="audit"?(n.tier&&i.push("--tier",n.tier),n.failOn&&i.push("--fail-on",n.failOn),n.maxFiles!==void 0&&i.push("--max-files",String(n.maxFiles))):(n.env&&(!t.reader||n.live)&&i.push("--env",n.env),n.live&&i.push("--live"),n.overlay&&i.push("--overlay"),n.traffic&&i.push("--traffic",n.traffic)),i}function KIe(e,t,n){let i=n==="yaml"?"yaml":"json";return`${By(e,t.group?Gy(t.member,t.dir):t.member)}.${i}`}function jte(e,t,n,i){let[r,...o]=e;return new Promise(s=>{let a=BIe(r,[...o,...t],{cwd:n,stdio:["pipe","pipe","pipe"],env:process.env}),c=[],l=[];a.stdout.on("data",u=>c.push(u)),a.stderr.on("data",u=>l.push(u)),a.on("error",u=>s({exitCode:127,stdout:"",stderr:`could not start ${r}: ${u.message}
281
+ `)[0]:String(Se)}`});continue}for(let Se of oe){for(let Ne of Se.deploys)T.set($(ne,Ne.env,Ne),{ledger:ne,env:Ne.env,record:Ne,release:Se});_.push({releaseDigest:Se.releaseDigest,label:Se.label,member:Se.release.member,commit:Se.commit,tag:fte(Se.commit,r,o),source:{ref:ss(`${ne.prefix}_releases/${_F(Se.releaseDigest)}`),field:"releaseDigest",value:Se.releaseDigest},cuts:Se.cuts.map(Ne=>({label:Ne.label,actor:Ne.actor,timestamp:Ne.timestamp,signed:Ne.signature!==null,runOrigin:Ne.runOrigin,source:{ref:ss(`${ne.prefix}_releases/cuts.jsonl`),field:"releaseDigest",value:Ne.releaseDigest}})),gates:await Promise.all([...Se.gates.resolutions].sort((Ne,te)=>Ac(Ne.timestamp,te.timestamp)).map(Ne=>M(ne,Ne))),deploys:Se.deploys.map(Ne=>$(ne,Ne.env,Ne))})}}let{readReleasePlan:W}=await Promise.resolve().then(()=>(CF(),dte)),ke=new Map,re=new Map([...k,...T]),be=new Map,Be=[];for(let[ne,ye]of[...re].sort(([,ge],[,oe])=>Ac(ge.record.timestamp,oe.record.timestamp)||Ac(ge.env,oe.env))){let ge=ye.record,oe=ye.ledger,Se=ge.releaseDigest??null,Ne=Se?{ref:ss(`${oe.prefix}${ye.env}/releases.jsonl`),field:"releaseDigest",value:Se}:null;if(!Se&&ge.admission?.op==="release"){be.has(oe)||be.set(oe,await q(oe,"release"));let{releaseOfDeploy:Ie}=await Promise.resolve().then(()=>(by(),S1));Se=Ie(ge,be.get(oe))??null,Se&&(Ne={ref:ss(`${oe.prefix}${ye.env}/releases.jsonl`),field:"admission",value:`${ge.admission.gate}@${ge.admission.resolvedAt}`})}let te=null;if(ge.admission){let Ie=(await q(oe,ge.admission.op)).find(et=>et.gate===ge.admission.gate&&et.timestamp===ge.admission.resolvedAt);Ie&&(te=await M(oe,Ie))}let Ve=`${oe.prefix}\0${ge.digest}`,z=ke.get(Ve);z||(z=W(ge.digest,oe.loc).catch(()=>null),ke.set(Ve,z));let $e=await z;Be.push({id:ne,member:oe.member,env:ye.env,component:ge.component,timestamp:ge.timestamp,actor:ge.actor,approver:ge.approver??null,runId:ge.runId,runOrigin:ge.runOrigin??null,gitSha:ge.gitSha,digest:ge.digest,release:Se,releaseSource:Ne,admittedBy:te,plan:$e?{document:$e,source:{ref:ss(`${oe.prefix}_plans/${_F(ge.digest)}`),field:"digest",value:ge.digest}}:null,source:{ref:ss(`${oe.prefix}${ye.env}/releases.jsonl`),field:"runId",value:ge.runId}})}return{commits:e.commits.map(ne=>{let ye=null;if(l){let Se=u.has(ne.sha)?{state:"merge",ids:[],problems:[]}:s(ne.trailers,ne.joins,l),Ne=Se.ids.map(te=>{let Ve=ne.joins.records.some(z=>`${z.kind}:${z.id}`===te);return{id:te,node:d(te),source:Ve?{ref:ne.sha,field:"Chant-Record",value:te}:{ref:ne.sha,field:"Chant-Lease",value:ne.joins.lease?.token??""}}});ye={state:Se.state,items:Ne,problems:Se.problems}}let ge=(e.windows.get(ne.sha)??[]).map(Se=>({id:Se.id,node:Se.node,source:{ref:Se.path,field:"window",value:"worked"}})),oe=x.get(ne.sha)??{releases:[],deploys:[]};return{commit:ne.id,sha:ne.sha,work:ye,windowMatches:ge,tag:fte(ne.sha,r,o),releases:oe.releases,deploys:oe.deploys}}),releases:_,deploys:Be,reasons:n}}var _F,ss,Ac,gte=v(()=>{"use strict";_F=e=>`${e.replace(/:/g,"_")}.json`,ss=e=>`chant/lifecycle:${e}`,Ac=(e,t)=>e<t?-1:e>t?1:0});import{createHash as _Ie}from"node:crypto";function TF(e){let t=e.members.filter(n=>(n.box?.services.length??0)>0);return t.length===1?{plantable:!0,box:t[0].name,reason:null}:t.length===0?{plantable:!1,box:null,reason:{code:"box-none",message:"no member's box block declares services, so there is no box to plant"}}:{plantable:!1,box:null,reason:{code:"box-several",message:`members ${t.map(n=>n.name).join(", ")} each declare box services, and a planted workspace runs one box`}}}function hte(e,t=[]){return e===null?null:{builds:[...e.builds],check:e.check===null?null:{...e.check},checks:e.checks,builders:e.builders,tiers:e.tiers.map(n=>({...n,kinds:n.kinds===null?null:[...n.kinds]})),builderFor:TIe(e,t),publish:e.publish===null?null:{...e.publish}}}function TIe(e,t){let n=[...new Set(e.tiers.map(r=>r.tier))],i={};for(let r of e.builds){let o=t.find(a=>a.name===r)?.kind,s={};for(let a of n){let c=e.tiers.find(l=>l.tier===a&&o!==void 0&&l.kinds?.includes(o))??e.tiers.find(l=>l.tier===a&&l.kinds===null);c&&(s[a]={agent:c.agent,session:c.session})}i[r]=s}return i}function yte(e,t){if(e===null)return null;let n=null;if(e.cover!==null){let i=t(e.cover);n={path:e.cover,sha256:i===null?null:_Ie("sha256").update(i).digest("hex")}}return{published:e.published,title:e.title,line:e.line,cover:n}}function wte(e){return t=>{try{return e.stat(t)!=="file"?null:e.bytes?e.bytes(t):new TextEncoder().encode(e.read(t))}catch{return null}}}function bte(e,t,n=[]){return e===null||e.factory===null&&e.listing===null?null:{factory:hte(e.factory,n),listing:yte(e.listing,wte(t))}}var IF=v(()=>{"use strict"});function pf(e){let t;try{t=JSON.parse(e)}catch{return{reason:{code:"output-unreadable",message:"chant graph --format ir printed something that is not JSON"}}}if(t===null||typeof t!="object"||!Array.isArray(t.nodes)||!Array.isArray(t.edges))return{reason:{code:"output-unreadable",message:"chant graph --format ir printed JSON with no nodes and edges"}};let n=t,i=n.version;if(i===void 0)n.version=1;else if(typeof i!="number"||i>ML)return{reason:{code:"ir-version-unsupported",message:`the member's chant printed IR version ${String(i)}, and this chant reads up to version ${ML}`}};return n.groups??={},{ir:n,irVersion:i===void 0?null:i}}function jIe(e,t){if(typeof t!="object"||t===null||!Array.isArray(t.pipelines))return null;let n=t;return{member:e,pipelines:DF(n.pipelines).map(i=>({id:String(i.id),signal:String(i.signal),receivers:qs(i.receivers),processors:qs(i.processors),exporters:qs(i.exporters)})),components:DF(n.components).map(i=>({id:String(i.id),kind:String(i.kind),type:String(i.type),endpoints:qs(i.endpoints),protocols:qs(i.protocols),pipelines:qs(i.pipelines)})),exporters:DF(n.exporters).map(i=>({id:String(i.id),type:String(i.type),endpoints:qs(i.endpoints),pipelines:qs(i.pipelines),signals:qs(i.signals)}))}}function jF(e,t){if(Array.isArray(e))return e.map(i=>jF(i,t));if(e===null||typeof e!="object")return e;let n={};for(let[i,r]of Object.entries(e))n[i]=i==="$ref"&&typeof r=="string"?Ii(t,r):jF(r,t);return n}function vte(e,t,n){(e[t]??=[]).push(...n)}function kte(e){let t={};for(let n of Object.keys(e).sort())t[n]=[...e[n]].sort();return t}function xte(e,t,n){let i=[],r=[],o=[],s=[],a={},c={byLexicon:{},byComposite:{}},l={byStack:{},byContainer:{},byWave:{},byPipeline:{}},u=[],d={},p=[];for(let{member:w,ir:b}of t){if(!b)continue;let k=w.name,$=[];for(let x of b.nodes){let R={...x,id:Ii(k,x.id),member:k,attrs:jF(x.attrs??{},k)};x.compositeInstance&&(R.compositeInstance=Ii(k,x.compositeInstance)),x.runtimeOwner&&(R.runtimeOwner=Ii(k,x.runtimeOwner)),i.push(R),$.push(R.id)}a[k]=$.sort();for(let x of b.edges)r.push({...x,from:Ii(k,x.from),to:Ii(k,x.to),member:k});for(let x of["byLexicon","byComposite"])for(let[R,P]of Object.entries(b.groups[x]??{}))vte(c[x],R,P.map(I=>Ii(k,I)));for(let x of oS)for(let[R,P]of Object.entries(b.groups[x]??{}))vte(l[x],Ii(k,R),P.map(I=>Ii(k,I)));for(let x of b.dangling??[])u.push({...x,from:Ii(k,x.from),member:k});for(let x of b.exports??[])o.push({...x,...x.node?{node:Ii(k,x.node)}:{},member:k});for(let x of b.imports??[])s.push({...x,node:Ii(k,x.node),member:k});for(let[x,R]of Object.entries(b.derivedAttrs??{}))for(let P of R)(d[x]??=new Set).add(P);if(b.meta){let{[DIe]:x,...R}=b.meta,P=jIe(k,x);P&&p.push(P),P?Object.keys(R).length>0&&(w.meta=R):w.meta=b.meta}b.pipeline&&(w.pipeline=b.pipeline)}i.sort((w,b)=>w.id.localeCompare(b.id));let f=w=>`${w.from}\0${w.to}\0${w.viaAttr??""}`;r.sort((w,b)=>f(w).localeCompare(f(b)));let g={byMember:a};for(let w of["byLexicon","byComposite"])Object.keys(c[w]).length&&(g[w]=kte(c[w]));for(let w of oS)Object.keys(l[w]).length&&(g[w]=kte(l[w]));let h={version:IIe,workspace:e,members:t.map(w=>w.member),nodes:i,edges:r,groups:g,exports:o,imports:s,links:n?n3(n.declaration,{composed:t.filter(w=>w.ir).map(w=>w.member.name),collectors:p,exports:o,imports:s},n.kinds,n.read):[],collectors:p,records:[]};return u.length&&(h.dangling=u.sort((w,b)=>My(w).localeCompare(My(b)))),Object.keys(d).length&&(h.derivedAttrs=Object.fromEntries(Object.keys(d).sort().map(w=>[w,[...d[w]].sort()]))),h}var IIe,DIe,Ii,qs,DF,oS,My,Fy=v(()=>{"use strict";Dp();U$();IIe=1,DIe="collector";Ii=(e,t)=>`${e}/${t}`,qs=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],DF=e=>Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[];oS=["byStack","byContainer","byWave","byPipeline"],My=e=>`${e.from}\0${e.path}\0${e.value}`});var $te=v(()=>{"use strict"});var Rte,NF=v(()=>{"use strict";Nl();Tt();on();Rte=".chant/generated.json"});function Ste(e){return e===".gitlab-ci.yml"?!0:/^(\.github\/workflows|\.forgejo\/workflows|\.gitea\/workflows|\.gitlab\/ci)\/[^/]+$/.test(e)}var Ete=v(()=>{"use strict";Dp();NF()});function LIe(e,t){let n;try{n=qd.load(t)}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n;if(e.startsWith(".gitlab/ci/")||e===".gitlab-ci.yml")return Object.entries(i).filter(([o,s])=>!o.startsWith(".")&&!NIe.has(o)&&s&&typeof s=="object"&&!Array.isArray(s)).map(([o])=>o);let r=i.jobs;return!r||typeof r!="object"||Array.isArray(r)?null:Object.entries(r).map(([o,s])=>{let a=s&&typeof s=="object"?s.name:void 0;return typeof a=="string"&&a!==""?a:o})}function Ote(e,t,n){let i=a=>qe(n,a),r=new Map,o=qe(e.dir,Rte);if(t.stat(o)==="file")try{let a=JSON.parse(t.read(o));for(let c of Array.isArray(a.files)?a.files:[])typeof c.path=="string"&&r.set(c.path,{path:c.path,command:typeof c.command=="string"?c.command:"",env:typeof c.env=="string"?c.env:null,jobs:null})}catch{}for(let a of e.generated){if(a.handWritten)continue;let c=i(qe(e.dir,a.path));r.set(c,{path:c,command:a.generator,env:r.get(c)?.env??null,jobs:null})}let s=n==="."?"":`${n}/`;for(let a of r.values()){if(!Ste(a.path)||!a.path.startsWith(s))continue;let c=a.path.slice(s.length);if(t.stat(c)==="file")try{a.jobs=LIe(a.path,t.read(c))}catch{a.jobs=null}}return[...r.values()].sort((a,c)=>a.path<c.path?-1:a.path>c.path?1:0)}var NIe,Ate=v(()=>{"use strict";xD();Ete();NF();on();NIe=new Set(["stages","variables","default","include","workflow","image","services","cache","before_script","after_script","pages"])});import{isAbsolute as MIe,resolve as yyt}from"node:path";function sS(e,t,n){if(t.stat(e.dir==="."?"":e.dir)!=="dir")return{code:"dir-missing",message:`${e.dir} is not a directory${t.label}`};let i=n.get(e.kind);return i?e4(i,t,e.dir==="."?"":e.dir)?null:{code:"kind-probe-failed",message:`${e.dir} is not ${i.description}`}:{code:"unknown-kind",message:`no built-in kind or pinned package supplies kind ${e.kind}; known kinds: ${n.names().join(", ")}`}}function Cte(e){return WIe(e).doc}function WIe(e){let t=en(),n={$schema:GIe,contract:FIe,chant:t};try{let i=qt(e.cwd,e.at),{tree:r,rootOnDisk:o,at:s}=i,a=_t(r,"",{rootChant:!0}),c=e.kinds??Pa(a.pins,o).registry,l=_a(a,r),u=MIe(i.root)?".":i.root,d=s!==null?{agents:a.agents,from:"at"}:rj(e.cwd)??{agents:a.agents,from:"working-tree"},p=a.members.map(w=>{let b=sS(w,r,c);return{name:w.name,dir:w.dir,kind:w.kind,roles:w.roles,upstream:w.upstream,because:w.because,readable:b===null,reason:b,records:Pte(w.records),generated:Ote(w,r,u),agents:d.agents.filter(k=>k.members.includes(w.name)).map(k=>k.name),...ag(a,w.pointer)}}),f=l.map(w=>({name:w.group.name,kind:"examples",glob:w.group.globs,matches:w.matches,skipped:w.skipped,reason:w.matches.length===0?{code:"no-matches",message:`no directory ${w.group.globs.join(" or ")} matches${r.label} holds a chant project`}:null})),g=RI(a).map(w=>({name:w.name,title:w.title,source:w.source,render:w.render,renderer:w.renderer,member:w.member}));return{doc:{...n,at:s,workspace:{name:a.name,root:i.root,file:a.file,schema:a.schema,minReader:a.minReader,pins:a.pins,records:Pte(a.records),agentsFrom:d.from,...ag(a,"")},members:p,groups:f,diagrams:g,ci:a.ci?{green:a.ci.green?{branch:a.ci.green.branch,window:a.ci.green.window,phases:a.ci.green.phases.map(w=>({name:w.name,runs:w.runs,skipped:w.skipped,...w.build?{build:w.build}:{}})),require:a.ci.green.require,...a.ci.green.signedSince!==null?{signedSince:a.ci.green.signedSince}:{},...a.ci.green.source==="runs"?{source:"runs"}:{}}:null,...a.ci.reportUrl!==null?{reportUrl:a.ci.reportUrl}:{}}:null,summary:{members:p.length,unreadable:p.filter(w=>!w.readable).length,groups:f.length,matches:f.reduce((w,b)=>w+b.matches.length,0)}},declaration:a,tree:r,rootOnDisk:o}}catch(i){if(!(i instanceof ve))throw i;return{doc:{...n,error:{code:i.code,message:i.message,location:i.location??null}}}}}var FIe,GIe,Pte,LF=v(()=>{"use strict";ur();Tt();Ate();qi();Wr();Bo();FIe=1,GIe="https://intentius.io/chant/schemas/workspace/ls/v1/ls.schema.json";Pte=e=>e.map(t=>({name:t.name,path:t.path,kind:null,reason:null,acceptance:null}))});var MF,_te,Tte=v(()=>{"use strict";um();Tt();MF="@@chant-member-run@@ ",_te=1});import{spawn as BIe}from"node:child_process";import{existsSync as zIe,mkdirSync as Nte,realpathSync as UIe,writeFileSync as VIe}from"node:fs";import{dirname as Wy,join as Gy,resolve as By}from"node:path";import{fileURLToPath as HIe}from"node:url";function Ite(){return By(Wy(HIe(import.meta.url)),"..","..","bin","chant")}function Lte(e){try{return UIe(e)}catch{return e}}function aS(){let e=process.argv[1]??"";return{command:/[\\/]cli[\\/]main\.(ts|js|mjs)$/.test(e)?[process.execPath,...process.execArgv,e]:[Ite()],identity:Lte(Ite()),source:"reader"}}function qIe(e,t,n=aS()){for(let i=e;;i=Wy(i)){let r=Gy(i,"node_modules",".bin","chant");if(zIe(r)){let o=Lte(r),s=i===t?"root":"member";return o===n.identity?{...n,source:s}:{command:[r],identity:o,source:s}}if(i===t||Wy(i)===i)break}return n}function cS(e,t,n={}){let i=n.tree??Rn(t),r=_t(i),o=_a(r,i),s=n.kinds??QK(),a=n.only?.length?new Set(n.only):void 0;if(a){let g=new Set(r.entries.map(w=>w.name)),h=[...a].filter(w=>!g.has(w));if(h.length>0)throw new ve("declaration-invalid",`--member names ${h.join(", ")}, which the declaration does not declare; it declares ${[...g].join(", ")}`)}let c=[],l=[],u=[],d=e==="build"||e==="lint";for(let g of r.entries){if(a&&!a.has(g.name))continue;if(g.type==="group"){let b=o.find(k=>k.group===g);if(!d){l.push({name:g.name,dir:null,kind:g.kind,reason:{code:"kind-not-run",message:`example groups are built and linted only; chant workspace ${e} leaves them out`}});continue}for(let k of b.matches)c.push({id:`${g.name}:${k}`,member:g.name,kind:g.kind,group:!0,dir:k,abs:Gy(t,k),exclude:[]});continue}let h=e==="graph"&&g.kind!=="chant"?s.get(g.kind):void 0;if(h?.graph&&h.packageDir){let b=sS(g,i,s);if(b){u.push({name:g.name,dir:g.dir,kind:g.kind,reason:b});continue}c.push({id:g.name,member:g.name,kind:g.kind,group:!1,dir:g.dir,abs:g.dir==="."?t:Gy(t,g.dir),exclude:[],reader:{...h.graph,packageDir:h.packageDir}});continue}if(g.kind!=="chant"){let b=g.kind==="workspace"?"a nested workspace runs its own chant workspace commands":g.kind==="design"?"a design member is data: chant reads its files for record pins and builds nothing":`chant workspace ${e} runs members of kind chant, and this one is kind ${g.kind}`;l.push({name:g.name,dir:g.dir,kind:g.kind,reason:{code:"kind-not-run",message:b}});continue}let w=sS(g,i,s);if(w){u.push({name:g.name,dir:g.dir,kind:g.kind,reason:w});continue}c.push({id:g.name,member:g.name,kind:g.kind,group:!1,dir:g.dir,abs:g.dir==="."?t:Gy(t,g.dir),exclude:g.dir==="."?gk(r,o).map(b=>b.dir):[]})}let p=n.reader??aS(),f=new Map;for(let g of c){let h=qIe(g.abs,t,p),w=f.get(h.identity)??{toolchain:h,units:[]};w.units.push(g),f.set(h.identity,w)}return{verb:e,workspace:{name:r.name,root:t,file:r.file},groups:[...f.values()],unreadable:u,skipped:l}}function Dte(e,t){return e==="graph"?"ir":e==="audit"?"json":e==="lint"?t.format==="sarif"||t.format==="json"?t.format:"stylish":t.format==="yaml"?"yaml":"json"}function FF(e,t,n){let i=e==="build"&&!n.format?[e,"."]:[e,".","--format",Dte(e,n)],r=()=>{for(let o of n.param??[])i.push("--param",o);n.paramsFile&&i.push("--params-file",By(n.paramsFile))};return e==="build"?(n.env&&i.push("--env",n.env),r(),n.lexicon&&i.push("--lexicon",n.lexicon),n.output&&i.push("--output",KIe(n.output,t,Dte(e,n)))):e==="lint"?(r(),n.fix&&i.push("--fix")):e==="audit"?(n.tier&&i.push("--tier",n.tier),n.failOn&&i.push("--fail-on",n.failOn),n.maxFiles!==void 0&&i.push("--max-files",String(n.maxFiles))):(n.env&&(!t.reader||n.live)&&i.push("--env",n.env),n.live&&i.push("--live"),n.overlay&&i.push("--overlay"),n.traffic&&i.push("--traffic",n.traffic)),i}function KIe(e,t,n){let i=n==="yaml"?"yaml":"json";return`${By(e,t.group?Gy(t.member,t.dir):t.member)}.${i}`}function jte(e,t,n,i){let[r,...o]=e;return new Promise(s=>{let a=BIe(r,[...o,...t],{cwd:n,stdio:["pipe","pipe","pipe"],env:process.env}),c=[],l=[];a.stdout.on("data",u=>c.push(u)),a.stderr.on("data",u=>l.push(u)),a.on("error",u=>s({exitCode:127,stdout:"",stderr:`could not start ${r}: ${u.message}
282
282
  `})),a.on("close",u=>s({exitCode:u??1,stdout:Buffer.concat(c).toString("utf8"),stderr:Buffer.concat(l).toString("utf8")})),a.stdin.on("error",()=>{}),a.stdin.end(i??"")})}function JIe(e){let t,n=new Map,i=[];for(let r of e.split(`
283
283
  `)){if(!r.startsWith(MF)){r.trim()&&i.push(r);continue}let o;try{o=JSON.parse(r.slice(MF.length))}catch{continue}o.type==="header"&&!t?t=o:o.type==="result"&&t&&n.set(o.id,o)}return t?{chant:t.chant,results:n,stray:i.join(`
284
284
  `)}:void 0}async function ZIe(e,t,n,i,r){let{toolchain:o,units:s}=t,a=new Map(s.map(f=>[f.id,r?r(f):FF(e,f,i)]));for(let f of s){let g=a.get(f.id),h=g.indexOf("--output");h>=0&&Nte(Wy(g[h+1]),{recursive:!0})}let c={protocol:_te,units:s.map(f=>({id:f.id,dir:f.abs,argv:a.get(f.id),...f.exclude.length?{exclude:f.exclude}:{}}))},l=await jte(o.command,["workspace","member-run"],n,JSON.stringify(c)),u=new Date().toISOString(),d=JIe(l.stdout);if(d)return d.stray&&process.stderr.write(`${d.stray}
@@ -287,7 +287,7 @@ ${l.stderr}`}});let p=[];for(let f of s){let g=await jte(o.command,a.get(f.id),f
287
287
  `)}function Fte(e){return{verb:e.verb,workspace:e.workspace,toolchains:e.groups.map(t=>({...t.toolchain,units:t.units.map(n=>({id:n.id,member:n.member,dir:n.dir,group:n.group}))})),unreadable:e.unreadable,skipped:e.skipped}}function zy(e,t){let n=JSON.stringify(e,null,2);t?(Nte(Wy(By(t)),{recursive:!0}),VIe(By(t),`${n}
288
288
  `)):console.log(n)}function Uy(e,t,n,i,r,o){return{name:e,dir:t,kind:n,status:i,reason:r,chant:o,irVersion:null,live:!1}}var Vy=v(()=>{"use strict";ur();Mi();$te();Tt();qi();LF();Tte();on()});import{createHash as YIe,randomBytes as XIe}from"node:crypto";import{existsSync as QIe,mkdirSync as eDe,readdirSync as Gte,readFileSync as WF,realpathSync as tDe,renameSync as nDe,rmSync as rDe,statSync as BF,utimesSync as iDe,writeFileSync as oDe}from"node:fs";import{homedir as sDe}from"node:os";import{dirname as lS,join as Sr,relative as aDe,resolve as zF,sep as Wte}from"node:path";function gDe(e){return!e.some(t=>dDe.some(n=>t===n||t.startsWith(`${n}=`)))}function Hy(e){return YIe("sha256").update(e).digest("hex")}function hDe(e,t){let n=new Set(t.map(s=>zF(e,s))),i=[],r=0,o=s=>{for(let a of Gte(s,{withFileTypes:!0})){let c=Sr(s,a.name);if(a.isDirectory()){if(fDe.has(a.name)||a.name.startsWith(".")||n.has(c))continue;o(c)}else if(a.isFile()){let l=BF(c);i.push(`${aDe(e,c).split(Wte).join("/")}\0${l.mtimeMs}\0${l.size}`),l.mtimeMs>r&&(r=l.mtimeMs)}}};return o(e),i.sort(),{lines:i,newest:r}}function yDe(e){let t=[];for(let n=zF(e);;n=lS(n)){for(let i of mDe){let r=Sr(n,i);try{let o=BF(r);o.isFile()&&t.push(`${r}\0${o.mtimeMs}\0${o.size}`)}catch{}}if(lS(n)===n)break}return t}function VF(e,t=[],n){try{let i=yDe(e);if(n)return{value:`sha256:${Hy(["at",n.commit,n.dir,...i].join(`
289
289
  `))}`,newest:0};let{lines:r,newest:o}=hDe(e,t);return{value:`sha256:${Hy(["files",...r,"install",...i].join(`
290
- `))}`,newest:o}}catch{return}}function wDe(e){let t=lS(lS(e.identity)),n="";try{n=String(JSON.parse(WF(Sr(t,"package.json"),"utf-8")).version??"")}catch{}let i=e.identity.split(Wte).includes("node_modules"),r="";return!i&&QIe(Sr(t,"src"))&&(r=VF(Sr(t,"src"))?.value??`unstamped:${Date.now()}`),`${e.identity}\0${n}\0${r}`}function bDe(e){let t="";try{t=String(JSON.parse(WF(Sr(e.packageDir,"package.json"),"utf-8")).version??"")}catch{}return JSON.stringify([e.lexicon,e.config,e.packageDir,t])}function vDe(e=process.env){let t=Object.keys(e).filter(n=>!pDe.some(i=>typeof i=="string"?i===n:i.test(n))).sort();return Hy(t.map(n=>`${n}=${e[n]??""}`).join("\0"))}function kDe(e){return Hy(JSON.stringify([UF,e.member,e.dir,e.stamp,e.toolchain,e.argv,e.env]))}function xDe(e,t=process.env){let n=t[Bte]||Sr(t.XDG_CACHE_HOME||Sr(sDe(),".cache"),"chant"),i=zF(e);try{i=tDe(i)}catch{}return Sr(n,"workspace-graph",Hy(i).slice(0,16))}function zte(e,t=process.env){let n=xDe(e,t),i=r=>Sr(n,`${r}.json`);return{dir:n,get(r){try{let o=JSON.parse(WF(i(r),"utf-8"));if(o.format!==UF||o.key!==r||typeof o.stdout!="string")return;let s=new Date;return iDe(i(r),s,s),o}catch{return}},put(r){try{eDe(n,{recursive:!0});let o=Sr(n,`.${r.key}.${process.pid}.${XIe(4).toString("hex")}.tmp`);oDe(o,JSON.stringify(r)),nDe(o,i(r.key)),$De(n)}catch{}}}}function $De(e){let t=Gte(e).filter(i=>i.endsWith(".json")&&!i.startsWith(".")).map(i=>{try{let r=BF(Sr(e,i));return{path:Sr(e,i),mtime:r.mtimeMs,size:r.size}}catch{return}}).filter(i=>i!==void 0).sort((i,r)=>r.mtime-i.mtime),n=0;t.forEach((i,r)=>{n+=i.size,(r>=cDe||n>lDe)&&rDe(i.path,{force:!0})})}function Ute(e,t,n,i,r=o=>FF("graph",o,t)){let o=Date.now(),s=vDe(),a=[],c=new Map,l=new Map;for(let u of e.groups){let d=wDe(u.toolchain);for(let p of u.units){if(p.group)continue;let f=r(p);if(!gDe(f))continue;let g=p.reader?bDe(p.reader):"",h=p.dir==="."?e.workspace.root:Sr(e.workspace.root,...p.dir.split("/")),w=i?{commit:i,dir:p.dir}:void 0,b=VF(h,p.exclude,w);if(!b)continue;c.set(p.id,b.value);let k=kDe({member:p.member,dir:p.dir,stamp:b.value,toolchain:`${d}\0${g}`,argv:f,env:s}),$=n.get(k);$?a.push({unit:p,toolchain:u.toolchain,chant:$.chant,mode:"member-run",id:p.id,member:p.member,dir:p.dir,exclude:p.exclude,exitCode:0,stdout:$.stdout,stderr:""}):l.set(p.id,{key:k,stamp:b,abs:h,exclude:p.exclude,...w?{at:w}:{},member:p.member})}}return{hits:a,stamps:c,pending:l,started:o}}function uS(e,t){if(t.size===0)return e;let n=e.groups.map(i=>({...i,units:i.units.filter(r=>!t.has(r.id))})).filter(i=>i.units.length>0);return{...e,groups:n}}function Vte(e,t,n){for(let i of t){let r=e.pending.get(i.id);if(!r||i.exitCode!==0||"reason"in pf(i.stdout)||!r.at&&r.stamp.newest>e.started-uDe)continue;let o=VF(r.abs,r.exclude,r.at);!o||o.value!==r.stamp.value||n.put({format:UF,key:r.key,member:r.member,stamp:r.stamp.value,chant:i.chant,stdout:i.stdout})}}var UF,Bte,cDe,lDe,uDe,dDe,pDe,fDe,mDe,Hte=v(()=>{"use strict";Fy();Vy();UF=1,Bte="CHANT_CACHE_DIR",cDe=512,lDe=128*1024*1024,uDe=2e3,dDe=["--live","--overlay","--traffic"],pDe=["_","PWD","OLDPWD","SHLVL","COLUMNS","LINES","WINDOWID",/^TERM/,/^ITERM_/,/^TMUX/,/^SSH_/,/^VSCODE_/,/^npm_/,/^VITEST/,/^__/,Bte],fDe=new Set(["node_modules","dist",".git"]),mDe=[Sr("node_modules",".package-lock.json"),"package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lock","bun.lockb"]});import{posix as qte}from"node:path";function Yte(e){let{dir:t,tree:n,fields:i}=e,r=[],o=[],s={reader:"dbt-project",links:r,gaps:o,producerField:"sqlMember"},a=qe(t,HF),c=typeof i?.sqlMember=="string"&&i.sqlMember!==""?i.sqlMember:null,l=i?.dialect==="clickhouse"?"clickhouse":"postgres",u;try{u=ry(n.read(a))}catch(k){return o.push({file:a,line:k instanceof su?k.line:1,message:`${HF} could not be read (${k.message}), so no source was read`}),s}if(!du(u))return o.push({file:a,line:1,message:`${HF} is not a mapping, so no source was read`}),s;let d=Jte(n.read(a)),p=u["model-paths"]!==void 0?"model-paths":u["source-paths"]!==void 0?"source-paths":null,f=p?u[p]:RDe,g=[];if(!Array.isArray(f))return o.push({file:a,line:Ky(d,p??""),message:`${p} is not a list, so no source was read`}),s;for(let k of f){if(typeof k!="string"||ff(k)){o.push({file:a,line:Ky(d,p??""),message:`${p} entry ${JSON.stringify(k)} is not a plain path; its sources were not read`});continue}let $=qte.normalize(qe(t,k));if($.startsWith("../")||$===".."||qte.isAbsolute(k)){o.push({file:a,line:Ky(d,p??""),message:`${p} entry ${k} lies outside the workspace; its sources were not read`});continue}g.push($==="."?"":$)}let h=qF({schema:!0,identifier:!0},u.quoting,a,Ky(d,"quoting"),"dbt_project.yml quoting",o),w=new Set;for(let k of g)for(let $ of SDe(n,k))w.add($);let b=(k,$)=>l==="postgres"&&!$?k.toLowerCase():k;for(let k of[...w].sort()){let $,x;try{$=n.read(k),x=ry($)}catch(A){o.push({file:k,line:A instanceof su?A.line:1,message:`the file could not be read as YAML (${A.message}); any sources in it were not read`});continue}if(!du(x)||x.sources===void 0||x.sources===null)continue;let R=Jte($),P=Ky(R,"sources");if(!Array.isArray(x.sources)){o.push({file:k,line:P,message:"sources is not a list; its sources were not read"});continue}let I=P;for(let A of x.sources){if(!du(A))continue;let B=qy(A.name),C=KF(R,B,I);if(I=C,B===void 0){o.push({file:k,line:C,message:"a source has no name; its tables were not read"});continue}let q=`source ${B}`;if(ff(B)){o.push({file:k,line:C,message:`${q}: its name is a Jinja template, which chant does not render; its tables were not read`});continue}if(Kte(A,k,C,q,o)!==!0)continue;let M=A.schema===void 0||A.schema===null?B:qy(A.schema);if(M===void 0||ff(M)){o.push({file:k,line:Zte(R,"schema",C),message:`${q}: schema ${JSON.stringify(A.schema)} is a Jinja template or not a name; chant reads names as declared and never renders them for a target, so its tables were not read`});continue}let _=qF(h,A.quoting,k,C,`${q} quoting`,o);if(A.tables===void 0||A.tables===null)continue;if(!Array.isArray(A.tables)){o.push({file:k,line:C,message:`${q}: tables is not a list; its tables were not read`});continue}let T=C;for(let W of A.tables){if(!du(W))continue;let ve=qy(W.name),re=KF(R,ve,T);if(T=re,ve===void 0){o.push({file:k,line:re,message:`${q}: a table has no name; it was not read`});continue}let be=`${q} table ${ve}`;if(ff(ve)){o.push({file:k,line:re,message:`${be}: its name is a Jinja template, which chant does not render; it was not read`});continue}if(Kte(W,k,re,be,o)!==!0)continue;let Be=W.identifier===void 0||W.identifier===null?ve:qy(W.identifier);if(Be===void 0||ff(Be)){o.push({file:k,line:Zte(R,"identifier",re),message:`${be}: identifier ${JSON.stringify(W.identifier)} is a Jinja template or not a name, which chant does not render; it was not read`});continue}let dt=qF(_,W.quoting,k,re,`${be} quoting`,o),ne=`${b(M,dt.schema)}.${b(Be,dt.identifier)}`;if(r.push({member:c,output:ne,file:k,line:re}),W.columns===void 0||W.columns===null)continue;if(!Array.isArray(W.columns)){o.push({file:k,line:re,message:`${be}: columns is not a list; its columns were not read`});continue}let ye=re;for(let ge of W.columns){if(!du(ge))continue;let oe=qy(ge.name),Se=KF(R,oe,ye);if(ye=Se,oe===void 0||ff(oe)){o.push({file:k,line:Se,message:`${be}: column ${JSON.stringify(ge.name)} is a Jinja template or not a name, which chant does not render; it was not read`});continue}let Ne=ge.quote===!0;r.push({member:c,output:`${ne}.${b(oe,Ne)}`,anchor:ne,file:k,line:Se})}}}}return s}function qy(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}function Kte(e,t,n,i,r){let o=du(e.config)?e.config:{},s=e.enabled??o.enabled;return s==null||s===!0?!0:(s===!1||r.push({file:t,line:n,message:`${i}: enabled is ${JSON.stringify(s)}, which chant does not render; it was not read`}),!1)}function qF(e,t,n,i,r,o){if(t==null)return e;if(!du(t))return o.push({file:n,line:i,message:`${r} is not a mapping; the quoting above it applies`}),e;let s={...e};for(let a of["schema","identifier"]){let c=t[a];c!==void 0&&(typeof c=="boolean"?s[a]=c:o.push({file:n,line:i,message:`${r}.${a} is ${JSON.stringify(c)}, not true or false; the quoting above it applies`}))}return s}function SDe(e,t){if(t!==""&&e.stat(t)!=="dir")return[];let n=[],i=r=>{for(let o of e.list(r)??[]){let s=qe(r,o.name);o.type==="dir"?Bi(o.name)||i(s):/\.ya?ml$/.test(o.name)&&n.push(s)}};return i(t),n}function Jte(e){return e.replace(/\r\n/g,`
290
+ `))}`,newest:o}}catch{return}}function wDe(e){let t=lS(lS(e.identity)),n="";try{n=String(JSON.parse(WF(Sr(t,"package.json"),"utf-8")).version??"")}catch{}let i=e.identity.split(Wte).includes("node_modules"),r="";return!i&&QIe(Sr(t,"src"))&&(r=VF(Sr(t,"src"))?.value??`unstamped:${Date.now()}`),`${e.identity}\0${n}\0${r}`}function bDe(e){let t="";try{t=String(JSON.parse(WF(Sr(e.packageDir,"package.json"),"utf-8")).version??"")}catch{}return JSON.stringify([e.lexicon,e.config,e.packageDir,t])}function vDe(e=process.env){let t=Object.keys(e).filter(n=>!pDe.some(i=>typeof i=="string"?i===n:i.test(n))).sort();return Hy(t.map(n=>`${n}=${e[n]??""}`).join("\0"))}function kDe(e){return Hy(JSON.stringify([UF,e.member,e.dir,e.stamp,e.toolchain,e.argv,e.env]))}function xDe(e,t=process.env){let n=t[Bte]||Sr(t.XDG_CACHE_HOME||Sr(sDe(),".cache"),"chant"),i=zF(e);try{i=tDe(i)}catch{}return Sr(n,"workspace-graph",Hy(i).slice(0,16))}function zte(e,t=process.env){let n=xDe(e,t),i=r=>Sr(n,`${r}.json`);return{dir:n,get(r){try{let o=JSON.parse(WF(i(r),"utf-8"));if(o.format!==UF||o.key!==r||typeof o.stdout!="string")return;let s=new Date;return iDe(i(r),s,s),o}catch{return}},put(r){try{eDe(n,{recursive:!0});let o=Sr(n,`.${r.key}.${process.pid}.${XIe(4).toString("hex")}.tmp`);oDe(o,JSON.stringify(r)),nDe(o,i(r.key)),$De(n)}catch{}}}}function $De(e){let t=Gte(e).filter(i=>i.endsWith(".json")&&!i.startsWith(".")).map(i=>{try{let r=BF(Sr(e,i));return{path:Sr(e,i),mtime:r.mtimeMs,size:r.size}}catch{return}}).filter(i=>i!==void 0).sort((i,r)=>r.mtime-i.mtime),n=0;t.forEach((i,r)=>{n+=i.size,(r>=cDe||n>lDe)&&rDe(i.path,{force:!0})})}function Ute(e,t,n,i,r=o=>FF("graph",o,t)){let o=Date.now(),s=vDe(),a=[],c=new Map,l=new Map;for(let u of e.groups){let d=wDe(u.toolchain);for(let p of u.units){if(p.group)continue;let f=r(p);if(!gDe(f))continue;let g=p.reader?bDe(p.reader):"",h=p.dir==="."?e.workspace.root:Sr(e.workspace.root,...p.dir.split("/")),w=i?{commit:i,dir:p.dir}:void 0,b=VF(h,p.exclude,w);if(!b)continue;c.set(p.id,b.value);let k=kDe({member:p.member,dir:p.dir,stamp:b.value,toolchain:`${d}\0${g}`,argv:f,env:s}),$=n.get(k);$?a.push({unit:p,toolchain:u.toolchain,chant:$.chant,mode:"member-run",id:p.id,member:p.member,dir:p.dir,exclude:p.exclude,exitCode:0,stdout:$.stdout,stderr:""}):l.set(p.id,{key:k,stamp:b,abs:h,exclude:p.exclude,...w?{at:w}:{},member:p.member})}}return{hits:a,stamps:c,pending:l,started:o}}function uS(e,t){if(t.size===0)return e;let n=e.groups.map(i=>({...i,units:i.units.filter(r=>!t.has(r.id))})).filter(i=>i.units.length>0);return{...e,groups:n}}function Vte(e,t,n){for(let i of t){let r=e.pending.get(i.id);if(!r||i.exitCode!==0||"reason"in pf(i.stdout)||!r.at&&r.stamp.newest>e.started-uDe)continue;let o=VF(r.abs,r.exclude,r.at);!o||o.value!==r.stamp.value||n.put({format:UF,key:r.key,member:r.member,stamp:r.stamp.value,chant:i.chant,stdout:i.stdout})}}var UF,Bte,cDe,lDe,uDe,dDe,pDe,fDe,mDe,Hte=v(()=>{"use strict";Fy();Vy();UF=1,Bte="CHANT_CACHE_DIR",cDe=512,lDe=128*1024*1024,uDe=2e3,dDe=["--live","--overlay","--traffic"],pDe=["_","PWD","OLDPWD","SHLVL","COLUMNS","LINES","WINDOWID",/^TERM/,/^ITERM_/,/^TMUX/,/^SSH_/,/^VSCODE_/,/^npm_/,/^VITEST/,/^__/,Bte],fDe=new Set(["node_modules","dist",".git"]),mDe=[Sr("node_modules",".package-lock.json"),"package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lock","bun.lockb"]});import{posix as qte}from"node:path";function Yte(e){let{dir:t,tree:n,fields:i}=e,r=[],o=[],s={reader:"dbt-project",links:r,gaps:o,producerField:"sqlMember"},a=qe(t,HF),c=typeof i?.sqlMember=="string"&&i.sqlMember!==""?i.sqlMember:null,l=i?.dialect==="clickhouse"?"clickhouse":"postgres",u;try{u=ry(n.read(a))}catch(k){return o.push({file:a,line:k instanceof su?k.line:1,message:`${HF} could not be read (${k.message}), so no source was read`}),s}if(!du(u))return o.push({file:a,line:1,message:`${HF} is not a mapping, so no source was read`}),s;let d=Jte(n.read(a)),p=u["model-paths"]!==void 0?"model-paths":u["source-paths"]!==void 0?"source-paths":null,f=p?u[p]:RDe,g=[];if(!Array.isArray(f))return o.push({file:a,line:Ky(d,p??""),message:`${p} is not a list, so no source was read`}),s;for(let k of f){if(typeof k!="string"||ff(k)){o.push({file:a,line:Ky(d,p??""),message:`${p} entry ${JSON.stringify(k)} is not a plain path; its sources were not read`});continue}let $=qte.normalize(qe(t,k));if($.startsWith("../")||$===".."||qte.isAbsolute(k)){o.push({file:a,line:Ky(d,p??""),message:`${p} entry ${k} lies outside the workspace; its sources were not read`});continue}g.push($==="."?"":$)}let h=qF({schema:!0,identifier:!0},u.quoting,a,Ky(d,"quoting"),"dbt_project.yml quoting",o),w=new Set;for(let k of g)for(let $ of SDe(n,k))w.add($);let b=(k,$)=>l==="postgres"&&!$?k.toLowerCase():k;for(let k of[...w].sort()){let $,x;try{$=n.read(k),x=ry($)}catch(A){o.push({file:k,line:A instanceof su?A.line:1,message:`the file could not be read as YAML (${A.message}); any sources in it were not read`});continue}if(!du(x)||x.sources===void 0||x.sources===null)continue;let R=Jte($),P=Ky(R,"sources");if(!Array.isArray(x.sources)){o.push({file:k,line:P,message:"sources is not a list; its sources were not read"});continue}let I=P;for(let A of x.sources){if(!du(A))continue;let B=qy(A.name),C=KF(R,B,I);if(I=C,B===void 0){o.push({file:k,line:C,message:"a source has no name; its tables were not read"});continue}let q=`source ${B}`;if(ff(B)){o.push({file:k,line:C,message:`${q}: its name is a Jinja template, which chant does not render; its tables were not read`});continue}if(Kte(A,k,C,q,o)!==!0)continue;let M=A.schema===void 0||A.schema===null?B:qy(A.schema);if(M===void 0||ff(M)){o.push({file:k,line:Zte(R,"schema",C),message:`${q}: schema ${JSON.stringify(A.schema)} is a Jinja template or not a name; chant reads names as declared and never renders them for a target, so its tables were not read`});continue}let _=qF(h,A.quoting,k,C,`${q} quoting`,o);if(A.tables===void 0||A.tables===null)continue;if(!Array.isArray(A.tables)){o.push({file:k,line:C,message:`${q}: tables is not a list; its tables were not read`});continue}let T=C;for(let W of A.tables){if(!du(W))continue;let ke=qy(W.name),re=KF(R,ke,T);if(T=re,ke===void 0){o.push({file:k,line:re,message:`${q}: a table has no name; it was not read`});continue}let be=`${q} table ${ke}`;if(ff(ke)){o.push({file:k,line:re,message:`${be}: its name is a Jinja template, which chant does not render; it was not read`});continue}if(Kte(W,k,re,be,o)!==!0)continue;let Be=W.identifier===void 0||W.identifier===null?ke:qy(W.identifier);if(Be===void 0||ff(Be)){o.push({file:k,line:Zte(R,"identifier",re),message:`${be}: identifier ${JSON.stringify(W.identifier)} is a Jinja template or not a name, which chant does not render; it was not read`});continue}let dt=qF(_,W.quoting,k,re,`${be} quoting`,o),ne=`${b(M,dt.schema)}.${b(Be,dt.identifier)}`;if(r.push({member:c,output:ne,file:k,line:re}),W.columns===void 0||W.columns===null)continue;if(!Array.isArray(W.columns)){o.push({file:k,line:re,message:`${be}: columns is not a list; its columns were not read`});continue}let ye=re;for(let ge of W.columns){if(!du(ge))continue;let oe=qy(ge.name),Se=KF(R,oe,ye);if(ye=Se,oe===void 0||ff(oe)){o.push({file:k,line:Se,message:`${be}: column ${JSON.stringify(ge.name)} is a Jinja template or not a name, which chant does not render; it was not read`});continue}let Ne=ge.quote===!0;r.push({member:c,output:`${ne}.${b(oe,Ne)}`,anchor:ne,file:k,line:Se})}}}}return s}function qy(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}function Kte(e,t,n,i,r){let o=du(e.config)?e.config:{},s=e.enabled??o.enabled;return s==null||s===!0?!0:(s===!1||r.push({file:t,line:n,message:`${i}: enabled is ${JSON.stringify(s)}, which chant does not render; it was not read`}),!1)}function qF(e,t,n,i,r,o){if(t==null)return e;if(!du(t))return o.push({file:n,line:i,message:`${r} is not a mapping; the quoting above it applies`}),e;let s={...e};for(let a of["schema","identifier"]){let c=t[a];c!==void 0&&(typeof c=="boolean"?s[a]=c:o.push({file:n,line:i,message:`${r}.${a} is ${JSON.stringify(c)}, not true or false; the quoting above it applies`}))}return s}function SDe(e,t){if(t!==""&&e.stat(t)!=="dir")return[];let n=[],i=r=>{for(let o of e.list(r)??[]){let s=qe(r,o.name);o.type==="dir"?Bi(o.name)||i(s):/\.ya?ml$/.test(o.name)&&n.push(s)}};return i(t),n}function Jte(e){return e.replace(/\r\n/g,`
291
291
  `).split(`
292
292
  `)}function dS(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ky(e,t){let n=new RegExp(`^${dS(t)}\\s*:`),i=e.findIndex(r=>n.test(r));return i<0?1:i+1}function KF(e,t,n){return t===void 0?n:EDe(e,"name",t,n)}function Zte(e,t,n){let i=new RegExp(`^\\s*(?:-\\s+)?${dS(t)}\\s*:`);for(let r=Math.max(n,0);r<e.length;r++)if(i.test(e[r]))return r+1;return n}function EDe(e,t,n,i){let r=new RegExp(`^\\s*(?:-\\s+)?${dS(t)}\\s*:\\s*(["']?)${dS(n)}\\1\\s*(?:#.*)?$`);for(let o=Math.max(i,0);o<e.length;o++)if(r.test(e[o]))return o+1;return i}var HF,RDe,ff,du,Xte=v(()=>{"use strict";iy();on();HF="dbt_project.yml",RDe=["models"],ff=e=>/\{\{|\{%/.test(e),du=e=>e!==null&&typeof e=="object"&&!Array.isArray(e)});function pS(e,t,n){let i=new Map;for(let r of e.members){let o=n.get(r.kind);if(!o?.reader)continue;let s=r.dir==="."?"":r.dir;if(t.stat(s)!=="dir")continue;let{fields:a}=vI(o,r.fields);try{i.set(r.name,ODe[o.reader]({member:r,dir:s,fields:a,tree:t}))}catch(c){i.set(r.name,{reader:o.reader,links:[],gaps:[{file:s||".",line:1,message:`the ${o.reader} reader failed: ${c.message}`}]})}}return i}var ODe,JF=v(()=>{"use strict";qi();Xte();ODe={"dbt-project":Yte}});import{mkdirSync as ADe,mkdtempSync as PDe,realpathSync as CDe,rmSync as _De,symlinkSync as TDe,writeFileSync as IDe}from"node:fs";import{tmpdir as DDe}from"node:os";import{join as Jy}from"node:path";function jDe(e,t){let n=e;for(let i=0;i<t.split("/").length;i++)n=Jy(n,"..");return n}function ZF(e){try{return CDe(e)}catch{return e}}function NDe(e,t){let n=e.reader,i=uk(n.lexicon),r=ba(i,t);return r?ZF(r)!==ZF(n.packageDir)?{message:`kind ${e.kind} comes from ${n.packageDir}, and the ${i} found from ${t} is ${ZF(r)}; install the pinned package where the workspace resolves it`}:{modules:jDe(r,i)}:{message:`kind ${e.kind} is read by the ${n.lexicon} lexicon, and ${i} is not installed in a node_modules at or above ${t}; install it there to read this member`}}function Qte(e,t){let n=[],i,r=()=>{i&&_De(i,{recursive:!0,force:!0}),i=void 0};try{for(let o of e.groups)o.units=o.units.filter(s=>{if(!s.reader)return!0;let a=NDe(s,t);if("message"in a)return n.push({name:s.member,dir:s.dir,kind:s.kind,reason:{code:"command-failed",message:a.message}}),!1;i??=PDe(Jy(DDe(),"chant-ws-reader-"));let c=Jy(i,s.id);ADe(c,{recursive:!0});let l=n4(s.reader.config,{member:s.member,dir:s.abs,workspace:t});return IDe(Jy(c,"chant.config.json"),`${JSON.stringify({lexicons:[s.reader.lexicon],[s.reader.lexicon]:l},null,2)}
293
293
  `),TDe(a.modules,Jy(c,"node_modules"),"dir"),s.abs=c,!0});e.groups=e.groups.filter(o=>o.units.length>0)}catch(o){throw r(),o}return e.unreadable.push(...n),{failed:n,cleanup:r}}var ene=v(()=>{"use strict";qi()});var rne={};_e(rne,{foldNested:()=>GDe,nestedArgv:()=>tne,readNested:()=>FDe,readNestedDocument:()=>nne});import{spawn as LDe}from"node:child_process";function tne(e,t,n){return["workspace","graph",e,...n?["--at",n]:[],...t.env?["--env",t.env]:[],...t.live?["--live"]:[],...t.overlay?["--overlay"]:[],...t.traffic!==void 0?["--traffic",String(t.traffic)]:[],...t.noCache?["--no-cache"]:[]]}function MDe(e,t,n){let[i,...r]=e;return new Promise(o=>{let s=LDe(i,[...r,...t],{cwd:n,stdio:["ignore","pipe","pipe"],env:process.env}),a=[],c=[];s.stdout.on("data",l=>a.push(l)),s.stderr.on("data",l=>c.push(l)),s.on("error",l=>o({exitCode:127,stdout:"",stderr:`could not start ${i}: ${l.message}
@@ -300,14 +300,14 @@ ${l.stderr}`}});let p=[];for(let f of s){let g=await jte(o.command,a.get(f.id),f
300
300
  `).filter(Boolean);return{envs:r.filter((s,a)=>o[a]!==void 0&&!o[a].endsWith(" missing")).sort(),reason:null}}catch(r){let o=(r instanceof Error?r.message:String(r)).split(`
301
301
  `)[0];return{envs:[],reason:{code:"environments-ledger-unreadable",message:`${mf}:${i||"."}: ${o}`}}}}});var _ne={};_e(_ne,{COMPOSITES_CONTRACT_VERSION:()=>One,COMPOSITES_ENVIRONMENT_REASON_CODES:()=>YDe,COMPOSITES_ERROR_CODES:()=>KDe,COMPOSITES_OUTPUT_SCHEMA_ID:()=>Ene,COMPOSITES_REASON_CODES:()=>JDe,COMPOSITES_RUNTIME_REASON_CODES:()=>ZDe,compositeInstances:()=>Ane,joinComponents:()=>Pne,runWorkspaceComposites:()=>tje,workspaceComposites:()=>Cne});function XDe(e,t,n,i,r){if(n.exitCode!==0){let a=n.stderr.trim().split(`
302
302
  `).slice(-5).join(`
303
- `);return{reason:{code:"command-failed",message:`chant graph --components exited ${n.exitCode}${a?`: ${a}`:""}`}}}let o=pf(n.stdout);if("reason"in o)return{reason:{...o.reason,message:`chant graph --components: ${o.reason.message}`}};let s=[];for(let a of o.ir.nodes){if(a.kind!=="Component")continue;let c=a.attrs??{},l=Array.isArray(c.composites)?c.composites.filter(d=>typeof d=="string"):null,u=a.sourceLoc?.file;s.push({id:`${e}/${a.id}`,name:a.id,member:e,archetype:typeof c.archetype=="string"?c.archetype:null,composites:l&&l.length>0?l:null,file:u?t==="."?u:`${t}/${u}`:null,runtimes:ane(a.id,i),environments:Rne(a.id,r,i?.default,QDe(c.environments),i?.lexicons??[],r?.reasons??[])})}return{components:s}}function QDe(e){if(!Array.isArray(e))return[];let t=n=>typeof n=="string"&&n.length>0?n:void 0;return e.filter(n=>n!==null&&typeof n=="object"&&typeof n.name=="string").map(n=>({name:n.name,runtime:t(n.runtime),url:t(n.url),domain:t(n.domain),lifecycle:t(n.lifecycle)}))}function Ane(e){let t=new Map;for(let n of e.nodes){if(!n.compositeInstance)continue;let i=t.get(n.compositeInstance)??{member:n.member,kinds:new Set,lexicons:new Set,nodes:[]};n.compositeParent&&i.kinds.add(n.compositeParent),i.lexicons.add(n.lexicon),i.nodes.push(n.id),t.set(n.compositeInstance,i)}return[...t.entries()].sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>({id:n,member:i.member,instance:n.slice(i.member.length+1),kinds:[...i.kinds].sort(),lexicons:[...i.lexicons].sort(),nodes:i.nodes.sort(),components:[]}))}function Pne(e,t,n){let i=new Set;for(let o of n)"consumer"in o&&"producer"in o&&o.status==="resolved"&&i.add(`${o.consumer}\0${o.producer}`);let r=(o,s)=>o.member===s.member?"member":i.has(`${o.member}\0${s.member}`)?"link":"unlinked";return e.map(o=>{let s=[];for(let a of t){if(a.composites){let l=o.kinds.find(u=>a.composites.includes(u));l&&s.push({component:a.id,by:"composites",against:"kind",value:l,label:"exact",via:r(a,o)});continue}let c;for(let l of o.kinds){let u=Eh(a.name,l);u&&(!c||u==="exact"&&c.label!=="exact")&&(c={by:"name",against:"kind",value:l,label:u})}if(!c){let l=Eh(a.name,o.instance);l&&(c={by:"name",against:"instance",value:o.instance,label:l})}c&&s.push({component:a.id,...c,via:r(a,o)})}return s.sort((a,c)=>a.component.localeCompare(c.component)),{...o,components:s}})}function eje(e,t,n,i){let r=e.reason??t,o=e.status==="composed"?t?"failed":"read":e.status;return{name:e.name,dir:e.dir,kind:e.kind,status:o,reason:r,chant:e.chant,runtimeReasons:n?.reasons??[],environmentReasons:i?.reasons??[]}}async function Cne(e){let t={$schema:Ene,contract:One,chant:en()},n=new Map,{loadPlugin:i,readLedgerEnvironments:r=xne,...o}=e,{doc:s,failed:a,components:c}=await fS({...o,...o.args?{args:{...o.args,live:!1,overlay:!1,traffic:void 0}}:{},components:!0,inTree:async(b,k)=>{n=await cne(b,k,i)}});if("error"in s)return{doc:{...t,error:{...s.error,code:s.error.code}},failed:!0};let l=new Map((c??[]).map(b=>[b.unit.member,b])),u=[],d=[],p=!1;for(let b of s.members){let k=b.status==="composed"?l.get(b.name):void 0,$=n.get(b.name),x=$?$ne($,r(b,e.cwd)):void 0,R=null;if(k){let P=XDe(b.name,b.dir,k,$,x);"reason"in P?(R=P.reason,p=!0):d.push(...P.components)}u.push(eje(b,R,$,x))}d.sort((b,k)=>b.id.localeCompare(k.id));let f=Pne(Ane(s),d,s.links),g=u.filter(b=>b.status==="read"),h=[];if(!u.some(b=>b.kind==="chant"&&b.status!=="skipped"))h.push({code:"composites-no-chant-member",message:"no member of kind chant was read, so nothing declares a composite or a component"});else if(g.length>0){let b=g.map(k=>k.name).join(", ");f.length===0&&h.push({code:"composites-none-declared",message:`the members read (${b}) declare no composite instance`}),d.length===0&&h.push({code:"composites-no-component",message:`the members read (${b}) declare no component in a *.component.ts file`})}let w=f.filter(b=>b.components.length>0).length;return{doc:{...t,at:s.at,workspace:s.workspace,members:u,composites:f,components:d,reasons:h,summary:{composites:f.length,withComponent:w,withoutComponent:f.length-w,components:d.length}},failed:a||p}}async function tje(e,t){let{args:n}=e,{doc:i,failed:r}=await Cne({cwd:t,at:n.at,members:n.members,args:n,onStderr:o=>process.stderr.write(o)});if(zy(i,n.output),"error"in i){let o=i.error.location;console.error(we({message:`${i.error.code}: ${o?`${o.file}:${o.line}:${o.column}: `:""}${i.error.message}`}))}return r?1:0}var Ene,One,KDe,JDe,ZDe,YDe,Tne=v(()=>{"use strict";ur();NN();Fy();nG();Vy();Tt();Sne();XF();Ene="https://intentius.io/chant/schemas/workspace/composites/v1/composites.schema.json",One=1,KDe=yi,JDe=["composites-no-chant-member","composites-none-declared","composites-no-component"],ZDe=sne,YDe=kne});async function Ine(e){let t={$schema:rje,contract:nje,chant:en()};try{return await oje(e,t)}catch(n){if(n instanceof pn||n instanceof xe||n instanceof Xe)return{doc:{...t,error:{code:n.code,message:n.message}},failed:!0};throw n}}async function oje(e,t){let n=qt(e.cwd,e.at),i=n.top;if(!i)throw new pn("not-a-git-repository","the intent walk reads git history, and this directory is not in a git repository");let r=_t(n.tree,"",{rootChant:!0}),o=e.kinds??yr(r).map(U=>Ri(U,n.rootOnDisk)),s=await hS({cwd:e.cwd,region:"",at:e.at,kinds:o},i),a=n.root==="."?"":n.root,c=U=>U.records.workspaceRoot==="."?"":U.records.workspaceRoot,l=U=>a===""?U:U.startsWith(`${a}/`)?U.slice(a.length+1):U===a?".":U,u=e.record.indexOf("/"),[d,p]=u>0?[e.record.slice(0,u),e.record.slice(u+1)]:[null,e.record],f=s.filter(U=>U.records&&!U.records.loaded.kind.work),g=f.filter(U=>d===null||U.records.loaded.kind.name===d).flatMap(U=>U.records.views.filter(ke=>ke.id===p).map(ke=>({kind:U,view:ke})))[0];if(!g){let U=f.map(ke=>ke.records.loaded.kind.name);throw new pn("intent-record-unknown",`no record of ${U.length>0?`the decision kinds read (${U.join(", ")})`:"a decision kind: none was read"} has the id ${e.record}`)}let h=g.kind.records.loaded.kind,w=g.view,b=n.at??(xn(i,["rev-parse","--verify","--quiet","HEAD^{commit}"])?.trim()||null),k=xn(i,["rev-parse","--is-shallow-repository"])?.trim()==="true",$=[];k&&$.push({code:"intent-history-shallow",message:"this is a shallow clone, so the history stops at its boundary and the oldest commit listed may stand for many"});let x=[],R=[],P=[],I=new Map,A=h.constrains?.field?w.data?.[h.constrains.field]:void 0;for(let U of Array.isArray(A)?A:[])if(typeof U=="string")if(U.startsWith("path:")){let ke=U.slice(5);if(!Jn(ke)){x.push({entry:U,granularity:"path",path:null,exists:null,walked:!1});continue}let We=qe(c(g.kind),ke),$t=n.tree.stat(l(We));if(x.push({entry:U,granularity:"path",path:l(We),exists:$t!==void 0,walked:b!==null}),R.push({entry:U,full:We}),!b)continue;for(let ht of mS(i,b,We,$t==="file"?"file":"dir",null))(I.get(ht.sha)??I.set(ht.sha,[]).get(ht.sha)).push(U)}else if(U.startsWith("member:")){let ke=U.slice(7),We=r.members.find(Mt=>Mt.name===ke);if(x.push({entry:U,granularity:"member",path:We?We.dir:null,exists:!!We,walked:!!We&&b!==null}),!We||(P.push({entry:U,name:ke}),!b))continue;let $t=qe(a,We.dir),ht=r.members.filter(Mt=>Mt.name!==We.name&&Mt.dir!==We.dir&&(We.dir==="."||Mt.dir.startsWith(`${We.dir}/`))).map(Mt=>`:(exclude)${qe(a,Mt.dir)}`),Mn=xn(i,["log","--format=%H",b,"--",$t===""?".":$t,...ht]);for(let Mt of(Mn??"").split(`
304
- `).map(nn=>nn.trim()).filter(Boolean))(I.get(Mt)??I.set(Mt,[]).get(Mt)).push(U)}else x.push({entry:U,granularity:/^[^/\s]+\/[^/\s]+#[0-9]+$/.test(U)?"issue":"contract",path:null,exists:null,walked:!1});let B=new Map;for(let U of f)for(let ke of U.records.views)ke.id!==null&&B.set(`${U.records.loaded.kind.name}/${ke.id}`,{kind:U,view:ke});let C=(U,ke)=>{let We=b?hf(i,b,ke):null,$t=ke.supersededBy?B.get(`${U.records.loaded.kind.name}/${ke.supersededBy}`):void 0,ht=b&&$t?hf(i,b,$t.view):null;return{from:We,until:ht,fromSet:We&&b?mo(i,We,b):new Set,untilSet:ht&&b?mo(i,ht,b):null}},q=(U,ke)=>U.fromSet.has(ke)&&!U.untilSet?.has(ke),L=C(g.kind,w),M=[...I.keys()].filter(U=>q(L,U)),_=Ec(i,M),T=e.followSquash?Ch(i,[..._.values()],{fetchMissing:!0}):new Map;for(let U of T.values())U.problem&&$.push({code:"squash-unfollowed",message:`${U.sha.slice(0,8)} squashes pull request #${U.pullRequest}, and ${U.problem}, so its original commits are not followed`});let W=Ec(i,[...new Set([...T.values()].flatMap(U=>U.commits))]),ve=U=>(T.get(U)?.commits??[]).map(ke=>W.get(ke)).filter(ke=>ke!==void 0),re=(M.length>0?xn(i,["rev-list","--no-walk=sorted","--stdin"],`${M.join(`
303
+ `);return{reason:{code:"command-failed",message:`chant graph --components exited ${n.exitCode}${a?`: ${a}`:""}`}}}let o=pf(n.stdout);if("reason"in o)return{reason:{...o.reason,message:`chant graph --components: ${o.reason.message}`}};let s=[];for(let a of o.ir.nodes){if(a.kind!=="Component")continue;let c=a.attrs??{},l=Array.isArray(c.composites)?c.composites.filter(d=>typeof d=="string"):null,u=a.sourceLoc?.file;s.push({id:`${e}/${a.id}`,name:a.id,member:e,archetype:typeof c.archetype=="string"?c.archetype:null,composites:l&&l.length>0?l:null,file:u?t==="."?u:`${t}/${u}`:null,runtimes:ane(a.id,i),environments:Rne(a.id,r,i?.default,QDe(c.environments),i?.lexicons??[],r?.reasons??[])})}return{components:s}}function QDe(e){if(!Array.isArray(e))return[];let t=n=>typeof n=="string"&&n.length>0?n:void 0;return e.filter(n=>n!==null&&typeof n=="object"&&typeof n.name=="string").map(n=>({name:n.name,runtime:t(n.runtime),url:t(n.url),domain:t(n.domain),lifecycle:t(n.lifecycle)}))}function Ane(e){let t=new Map;for(let n of e.nodes){if(!n.compositeInstance)continue;let i=t.get(n.compositeInstance)??{member:n.member,kinds:new Set,lexicons:new Set,nodes:[]};n.compositeParent&&i.kinds.add(n.compositeParent),i.lexicons.add(n.lexicon),i.nodes.push(n.id),t.set(n.compositeInstance,i)}return[...t.entries()].sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>({id:n,member:i.member,instance:n.slice(i.member.length+1),kinds:[...i.kinds].sort(),lexicons:[...i.lexicons].sort(),nodes:i.nodes.sort(),components:[]}))}function Pne(e,t,n){let i=new Set;for(let o of n)"consumer"in o&&"producer"in o&&o.status==="resolved"&&i.add(`${o.consumer}\0${o.producer}`);let r=(o,s)=>o.member===s.member?"member":i.has(`${o.member}\0${s.member}`)?"link":"unlinked";return e.map(o=>{let s=[];for(let a of t){if(a.composites){let l=o.kinds.find(u=>a.composites.includes(u));l&&s.push({component:a.id,by:"composites",against:"kind",value:l,label:"exact",via:r(a,o)});continue}let c;for(let l of o.kinds){let u=Eh(a.name,l);u&&(!c||u==="exact"&&c.label!=="exact")&&(c={by:"name",against:"kind",value:l,label:u})}if(!c){let l=Eh(a.name,o.instance);l&&(c={by:"name",against:"instance",value:o.instance,label:l})}c&&s.push({component:a.id,...c,via:r(a,o)})}return s.sort((a,c)=>a.component.localeCompare(c.component)),{...o,components:s}})}function eje(e,t,n,i){let r=e.reason??t,o=e.status==="composed"?t?"failed":"read":e.status;return{name:e.name,dir:e.dir,kind:e.kind,status:o,reason:r,chant:e.chant,runtimeReasons:n?.reasons??[],environmentReasons:i?.reasons??[]}}async function Cne(e){let t={$schema:Ene,contract:One,chant:en()},n=new Map,{loadPlugin:i,readLedgerEnvironments:r=xne,...o}=e,{doc:s,failed:a,components:c}=await fS({...o,...o.args?{args:{...o.args,live:!1,overlay:!1,traffic:void 0}}:{},components:!0,inTree:async(b,k)=>{n=await cne(b,k,i)}});if("error"in s)return{doc:{...t,error:{...s.error,code:s.error.code}},failed:!0};let l=new Map((c??[]).map(b=>[b.unit.member,b])),u=[],d=[],p=!1;for(let b of s.members){let k=b.status==="composed"?l.get(b.name):void 0,$=n.get(b.name),x=$?$ne($,r(b,e.cwd)):void 0,R=null;if(k){let P=XDe(b.name,b.dir,k,$,x);"reason"in P?(R=P.reason,p=!0):d.push(...P.components)}u.push(eje(b,R,$,x))}d.sort((b,k)=>b.id.localeCompare(k.id));let f=Pne(Ane(s),d,s.links),g=u.filter(b=>b.status==="read"),h=[];if(!u.some(b=>b.kind==="chant"&&b.status!=="skipped"))h.push({code:"composites-no-chant-member",message:"no member of kind chant was read, so nothing declares a composite or a component"});else if(g.length>0){let b=g.map(k=>k.name).join(", ");f.length===0&&h.push({code:"composites-none-declared",message:`the members read (${b}) declare no composite instance`}),d.length===0&&h.push({code:"composites-no-component",message:`the members read (${b}) declare no component in a *.component.ts file`})}let w=f.filter(b=>b.components.length>0).length;return{doc:{...t,at:s.at,workspace:s.workspace,members:u,composites:f,components:d,reasons:h,summary:{composites:f.length,withComponent:w,withoutComponent:f.length-w,components:d.length}},failed:a||p}}async function tje(e,t){let{args:n}=e,{doc:i,failed:r}=await Cne({cwd:t,at:n.at,members:n.members,args:n,onStderr:o=>process.stderr.write(o)});if(zy(i,n.output),"error"in i){let o=i.error.location;console.error(we({message:`${i.error.code}: ${o?`${o.file}:${o.line}:${o.column}: `:""}${i.error.message}`}))}return r?1:0}var Ene,One,KDe,JDe,ZDe,YDe,Tne=v(()=>{"use strict";ur();NN();Fy();nG();Vy();Tt();Sne();XF();Ene="https://intentius.io/chant/schemas/workspace/composites/v1/composites.schema.json",One=1,KDe=yi,JDe=["composites-no-chant-member","composites-none-declared","composites-no-component"],ZDe=sne,YDe=kne});async function Ine(e){let t={$schema:rje,contract:nje,chant:en()};try{return await oje(e,t)}catch(n){if(n instanceof pn||n instanceof ve||n instanceof Xe)return{doc:{...t,error:{code:n.code,message:n.message}},failed:!0};throw n}}async function oje(e,t){let n=qt(e.cwd,e.at),i=n.top;if(!i)throw new pn("not-a-git-repository","the intent walk reads git history, and this directory is not in a git repository");let r=_t(n.tree,"",{rootChant:!0}),o=e.kinds??yr(r).map(U=>Ri(U,n.rootOnDisk)),s=await hS({cwd:e.cwd,region:"",at:e.at,kinds:o},i),a=n.root==="."?"":n.root,c=U=>U.records.workspaceRoot==="."?"":U.records.workspaceRoot,l=U=>a===""?U:U.startsWith(`${a}/`)?U.slice(a.length+1):U===a?".":U,u=e.record.indexOf("/"),[d,p]=u>0?[e.record.slice(0,u),e.record.slice(u+1)]:[null,e.record],f=s.filter(U=>U.records&&!U.records.loaded.kind.work),g=f.filter(U=>d===null||U.records.loaded.kind.name===d).flatMap(U=>U.records.views.filter(xe=>xe.id===p).map(xe=>({kind:U,view:xe})))[0];if(!g){let U=f.map(xe=>xe.records.loaded.kind.name);throw new pn("intent-record-unknown",`no record of ${U.length>0?`the decision kinds read (${U.join(", ")})`:"a decision kind: none was read"} has the id ${e.record}`)}let h=g.kind.records.loaded.kind,w=g.view,b=n.at??(xn(i,["rev-parse","--verify","--quiet","HEAD^{commit}"])?.trim()||null),k=xn(i,["rev-parse","--is-shallow-repository"])?.trim()==="true",$=[];k&&$.push({code:"intent-history-shallow",message:"this is a shallow clone, so the history stops at its boundary and the oldest commit listed may stand for many"});let x=[],R=[],P=[],I=new Map,A=h.constrains?.field?w.data?.[h.constrains.field]:void 0;for(let U of Array.isArray(A)?A:[])if(typeof U=="string")if(U.startsWith("path:")){let xe=U.slice(5);if(!Jn(xe)){x.push({entry:U,granularity:"path",path:null,exists:null,walked:!1});continue}let We=qe(c(g.kind),xe),$t=n.tree.stat(l(We));if(x.push({entry:U,granularity:"path",path:l(We),exists:$t!==void 0,walked:b!==null}),R.push({entry:U,full:We}),!b)continue;for(let ht of mS(i,b,We,$t==="file"?"file":"dir",null))(I.get(ht.sha)??I.set(ht.sha,[]).get(ht.sha)).push(U)}else if(U.startsWith("member:")){let xe=U.slice(7),We=r.members.find(Mt=>Mt.name===xe);if(x.push({entry:U,granularity:"member",path:We?We.dir:null,exists:!!We,walked:!!We&&b!==null}),!We||(P.push({entry:U,name:xe}),!b))continue;let $t=qe(a,We.dir),ht=r.members.filter(Mt=>Mt.name!==We.name&&Mt.dir!==We.dir&&(We.dir==="."||Mt.dir.startsWith(`${We.dir}/`))).map(Mt=>`:(exclude)${qe(a,Mt.dir)}`),Mn=xn(i,["log","--format=%H",b,"--",$t===""?".":$t,...ht]);for(let Mt of(Mn??"").split(`
304
+ `).map(nn=>nn.trim()).filter(Boolean))(I.get(Mt)??I.set(Mt,[]).get(Mt)).push(U)}else x.push({entry:U,granularity:/^[^/\s]+\/[^/\s]+#[0-9]+$/.test(U)?"issue":"contract",path:null,exists:null,walked:!1});let B=new Map;for(let U of f)for(let xe of U.records.views)xe.id!==null&&B.set(`${U.records.loaded.kind.name}/${xe.id}`,{kind:U,view:xe});let C=(U,xe)=>{let We=b?hf(i,b,xe):null,$t=xe.supersededBy?B.get(`${U.records.loaded.kind.name}/${xe.supersededBy}`):void 0,ht=b&&$t?hf(i,b,$t.view):null;return{from:We,until:ht,fromSet:We&&b?mo(i,We,b):new Set,untilSet:ht&&b?mo(i,ht,b):null}},q=(U,xe)=>U.fromSet.has(xe)&&!U.untilSet?.has(xe),L=C(g.kind,w),M=[...I.keys()].filter(U=>q(L,U)),_=Ec(i,M),T=e.followSquash?Ch(i,[..._.values()],{fetchMissing:!0}):new Map;for(let U of T.values())U.problem&&$.push({code:"squash-unfollowed",message:`${U.sha.slice(0,8)} squashes pull request #${U.pullRequest}, and ${U.problem}, so its original commits are not followed`});let W=Ec(i,[...new Set([...T.values()].flatMap(U=>U.commits))]),ke=U=>(T.get(U)?.commits??[]).map(xe=>W.get(xe)).filter(xe=>xe!==void 0),re=(M.length>0?xn(i,["rev-list","--no-walk=sorted","--stdin"],`${M.join(`
305
305
  `)}
306
306
  `):"")?.split(`
307
- `).map(U=>U.trim()).filter(Boolean)??M;M.sort((U,ke)=>re.indexOf(U)-re.indexOf(ke));let be=U=>R.some(ke=>jo(ke.full,U))||P.some(ke=>Fr(l(U),r.members)===ke.name),Be=new Map;if(M.length>0){let U=xn(i,["log","--no-walk=unsorted","--stdin","--format=%x00%H","--name-only","--no-renames","--diff-merges=first-parent"],`${M.join(`
307
+ `).map(U=>U.trim()).filter(Boolean)??M;M.sort((U,xe)=>re.indexOf(U)-re.indexOf(xe));let be=U=>R.some(xe=>jo(xe.full,U))||P.some(xe=>Fr(l(U),r.members)===xe.name),Be=new Map;if(M.length>0){let U=xn(i,["log","--no-walk=unsorted","--stdin","--format=%x00%H","--name-only","--no-renames","--diff-merges=first-parent"],`${M.join(`
308
308
  `)}
309
- `)??"";for(let ke of U.split("\0")){if(!ke)continue;let[We,...$t]=ke.split(`
310
- `).map(ht=>ht.trim());Be.set(We,[...new Set($t.filter(ht=>ht!==""&&be(ht)))].map(l))}}let dt=(U,ke)=>{let We=U.records.loaded.kind.constrains?.field,$t=We?ke.data?.[We]:void 0;return(Array.isArray($t)?$t:[]).filter(ht=>typeof ht=="string"&&ht.startsWith("path:")&&Jn(ht.slice(5))).map(ht=>qe(c(U),ht.slice(5)))},ne=[...new Set([...Be.values()].flat())].map(U=>qe(a,U)),ye=[];for(let[,U]of B){if(U.view===w)continue;let ke=dt(U.kind,U.view);ke.some(We=>ne.some($t=>jo(We,$t)))&&ye.push({ref:{recordKind:U.kind.records.loaded.kind.name,record:U.view.id,state:U.view.state},paths:ke,window:C(U.kind,U.view)})}let ge=[];for(let U of s.filter(ke=>ke.records?.loaded.kind.work)){let ke=U.records.loaded.kind;for(let We of U.records.views){if(We.id===null||We.state!==null&&We.state!==ke.work.done&&(ke.closedStates??[]).includes(We.state))continue;let ht=Gr(We.data,ke.work.implements).includes(w.id),Mn=dt(U,We);if(!ht&&!Mn.some(Fn=>ne.some(lr=>jo(Fn,lr))))continue;let Mt=b?Zy(i,b,We.path):null,nn=b&&ke.stateField?gS(i,b,We.path,ke.stateField,ke.closedStates??[]):null,fn=nn&&b?mo(i,nn,b):null;nn&&fn.delete(nn),ge.push({ref:{recordKind:ke.name,record:We.id,state:We.state},paths:Mn,implementsRecord:ht,window:{fromSet:Mt&&b?mo(i,Mt,b):new Set,untilSet:fn}})}}let oe=U=>Jn(U)&&n.tree.stat(U)==="file"?n.tree.read(U):void 0,Se=U=>{let ke=U==="."?"":U.replace(/\/+$/,"");if(!(ke!==""&&(!Jn(ke)||n.tree.stat(ke)!=="dir")))return n.tree.list(ke)?.map(We=>`${qe(ke,We.name)}${We.type==="dir"?"/":""}`).sort()},Ne=new Set,te=x.filter(U=>U.granularity==="contract").map(U=>U.entry),Ve=[],z=lf(i,[..._.values(),...W.values()]),$e=new Map(s.filter(U=>U.records).map(U=>[U.records.loaded.kind.name,U])),Ie=s.filter(U=>U.records?.loaded.kind.work),et=await r$(i,n.rootOnDisk,[...new Set([...M,...W.keys()])].map(U=>({sha:U,run:z.get(U)?.joins.run??null})));i$(et.refs,T);let ct=(U,ke)=>{let We=U.records.views.find($t=>$t.id===ke);return We?Gr(We.data,U.records.loaded.kind.work.implements).includes(w.id):void 0};for(let U of M){let ke=_.get(U);if(!ke)continue;let We=null,$t=!1,ht=z.get(U).joins,Mn=ve(U);for(let y of[ht,...Mn.map(N=>z.get(N.sha).joins)]){for(let K of y.records){let Q=$e.get(K.kind);!Q||!Q.records.views.some(H=>H.id===K.id)||(K.node=`record:${K.kind}/${K.id}`,(Q.records.loaded.kind.work?ct(Q,K.id):K.kind===h.name&&K.id===w.id)&&($t=!0))}let N=y.lease?.item;if(N){let K=Ie.filter(Q=>Q.records.views.some(H=>H.id===N));K.length===1&&ct(K[0],N)&&($t=!0)}}let Mt=[ke,...Mn];for(let y of s)if(y.joins)for(let N of Mt){let K;try{K=await ax(y.joins,N,{read:oe,list:Se,at:n.at},y.name)}catch(H){let S=`${y.display}: commitJoins failed for ${N.sha.slice(0,8)}: ${H instanceof Error?H.message:String(H)}`;Ne.has(S)||$.push({code:"intent-plugin-failed",message:S}),Ne.add(S);continue}if(!K.unit)continue;We??=K.unit.id,[...fp(K.unit),...fp(K.contract)].some(H=>H===w.id||H===`${h.name}/${w.id}`)&&($t=!0),K.contract&&te.includes(K.contract.id)&&($t=!0)}let nn=T.get(U),fn=(Be.get(U)??[]).map(y=>qe(a,y)),Fn=y=>y.some(N=>fn.some(K=>jo(N,K))),lr=ge.filter(y=>q(y.window,U)&&(y.implementsRecord||Fn(y.paths))).map(y=>y.ref),Xn=ye.filter(y=>q(y.window,U)&&Fn(y.paths)).map(y=>y.ref),Zs=ke.subject.match(/\(#([0-9]+)\)\s*$/);Ve.push({sha:U,subject:ke.subject,author:ke.author,date:ke.date,trailers:ke.trailers,pullRequest:Zs?Number(Zs[1]):null,unit:We,joins:ht,runs:et.refs.get(U)??[],...nn?{squash:{pullRequest:nn.pullRequest,forge:nn.forge,ref:nn.ref,head:nn.head,fetched:nn.fetched,followed:nn.followed,commits:Mn.map(y=>({sha:y.sha,subject:y.subject,author:y.author,date:y.date,trailers:y.trailers,joins:z.get(y.sha).joins}))}}:{},entries:I.get(U),files:Be.get(U)??[],bucket:$t?"own":lr.length>0?"worked":Xn.length>0?"within-other":"unexplained",workedBy:lr,alsoWithin:Xn})}let Vt=U=>Ve.filter(ke=>ke.bucket===U).length;return{doc:{...t,at:n.at,workspace:{name:r.name,root:n.root},record:{id:`record:${h.name}/${w.id}`,recordKind:h.name,record:w.id,path:w.path,title:ije(w.data?.title),state:w.state,supersededBy:w.supersededBy,decidedIn:w.decidedIn??null,constrains:x},history:{rev:b,shallow:k},window:{from:L.from,until:L.until},kinds:s.map(U=>({file:U.display,name:U.name,records:U.records?.loaded.kind.name??null,joins:U.joins?.form??null})),commits:Ve,counts:{commits:Ve.length,own:Vt("own"),worked:Vt("worked"),withinOther:Vt("within-other"),unexplained:Vt("unexplained"),outsideWindow:I.size-M.length},reasons:$},failed:$.some(U=>U.code==="intent-plugin-failed")}}var nje,rje,ije,Dne=v(()=>{"use strict";Tt();cc();Lg();Ty();No();un();HN();t$();BR();on();Wr();Yd();nje=1,rje="https://intentius.io/chant/schemas/workspace/intent-record/v1/intent-record.schema.json",ije=e=>typeof e=="string"?e:null});var Une={};_e(Une,{IN_WINDOW_QUESTION:()=>Fne,formatIntent:()=>Bne,formatIntentRecord:()=>zne,runWorkspaceIntent:()=>fje,traceLines:()=>Wne,whyLines:()=>Gne});import{resolve as Lne}from"node:path";function Yy(e,t,n){return e.edges.filter(i=>i.from===t&&i.kind===n)}function Pc(e,t){return e.nodes.filter(n=>n.kind===t)}function sje(e,t){let n=e.edges.filter(r=>r.kind==="within"&&r.to===t.id),i=[];for(let r of n){let o=e.nodes.find(d=>d.kind==="commit"&&d.id===r.from);if(!o)continue;let s=Yy(e,o.id,"produced-by").map(d=>e.nodes.find(p=>p.id===d.to)).map(d=>d&&"ref"in d?d.ref:void 0).filter(Boolean),a=(o.joins?.records??[]).filter(d=>d.node!==null).map(d=>`${d.kind}:${d.id}`),c=o.joins?.lease?.item;c&&!a.some(d=>d.endsWith(`:${c}`))&&a.push(`lease on ${c}`);let l=s.length>0?`unit ${s.join(", ")}`:a.length>0?`carries ${a.join(", ")}`:"no unit",u=r.state==="decided"?"decided ":"within ";i.push(` ${u} ${an(o.sha)} ${o.subject}; ${l}${r.state==="decided"?`, ${t.record}'s own work`:`, in ${t.record}'s window and not its work`}`)}return n.some(r=>r.state==="decided-by-window")&&i.push(` ask ${Fne}`),i}function aje(e){let t=e.constrains.length>0?e.constrains.map(s=>`${s.entry} (${s.granularity})`).join(", "):"through supersession only",n=e.decided_by?`, decided by ${e.decided_by}${e.decided_on?` on ${e.decided_on}`:""}`:"",i=e.decidedIn?` in ${an(e.decidedIn.sha)}`:"",r=`${e.reviews.agree} agree, ${e.reviews.dissent} dissent, ${e.reviews.abstain} abstain`,o=e.supersededBy?`, superseded by ${e.supersededBy}`:"";return`decision ${e.record} ${e.state??"stateless"}${o}: ${e.title??e.path}; constrains ${t}${n}${i}; ${r}; ${e.provenance.level}${e.valid?"":`; invalid: ${e.reasons.map(s=>s.code).join(", ")}`}`}function cje(e,t){let n=t.constrains.length>0?t.constrains.map(c=>`${c.entry} (${c.granularity})`).join(", "):"through a link only",i=t.implements.length>0?`; implements ${t.implements.map(c=>`${c.id} (${c.state??"unknown"})`).join(", ")}`:"",r=t.ready?"; ready":t.blockedBy.length>0?`; blocked by ${t.blockedBy.map(c=>`${c.id} (${c.state??"unknown"})`).join(", ")}`:"",o=t.owner?`, owned by ${t.owner}`:"",s=t.source?`; from ${t.source.finding} on ${t.source.region}`:"",a=[`work ${t.record} ${t.state??"stateless"}${o}: ${t.title??t.path}; constrains ${n}${i}${r}${s}`];for(let c of e.edges.filter(l=>l.kind==="within"&&l.to===t.id)){let l=e.nodes.find(u=>u.kind==="commit"&&u.id===c.from);l&&a.push(` worked ${an(l.sha)} ${l.subject}; in ${t.record}'s window`)}for(let c of t.warnings)a.push(` warning ${c.code}: ${c.message}`);return a}function lje(e,t){let n=e.edges.filter(i=>i.kind==="pins"&&i.to===t.id).map(i=>`${i.from.slice(i.from.indexOf("/")+1)} at ${an(i.pinnedSha256)} (${i.pinState})`);return`artifact ${t.path} ${t.pinState}; pinned by ${n.join(", ")}; now ${an(t.currentSha256)}`}function uje(e){if(!e)return[];let t=[];e.agent&&t.push(` agent ${e.agent}`),e.lease&&t.push(` lease ${e.lease.token}${e.lease.item?` on ${e.lease.item}`:", no lease history names it"}`);for(let n of e.records)t.push(` record ${n.kind}:${n.id}${n.node?"":", in no kind read"}`);return e.applied&&t.push(` applied by ${e.applied.by}${e.applied.at?` at ${e.applied.at}`:""}${e.applied.commit?`, ${an(e.applied.commit)}`:""}`),t}function dje(e,t){let n=t.lines&&t.lines.length>0?`, lines ${t.lines.map(r=>r.start===r.end?`${r.start}`:`${r.start}-${r.end}`).join(", ")}`:"",i=[`commit ${an(t.sha)} ${t.date.slice(0,10)} ${t.author.name}: ${t.subject}${n}; ${t.signature.level}`];for(let r of Yy(e,t.id,"produced-by")){let o=e.nodes.find(s=>s.id===r.to);i.push(` unit ${o&&"ref"in o?o.ref:r.to}`);for(let s of Yy(e,r.to,"serves"))i.push(` contract ${s.to.slice(9)}`);for(let s of Yy(e,r.to,"cites-evidence"))i.push(` evidence ${s.to.slice(9)}`)}if(i.push(...uje(t.joins)),t.squash){let r=t.squash;i.push(` squash #${r.pullRequest}${r.followed?`: ${r.commits.length} original ${r.commits.length===1?"commit":"commits"} from ${r.ref}${r.fetched?", fetched":""}`:", not followed"}`);for(let o of r.commits){let s=[...o.joins.records.map(a=>`${a.kind}:${a.id}`),...o.joins.lease?[`lease ${o.joins.lease.token}`]:[],...o.joins.run?[`run ${o.joins.run}`]:[]];i.push(` original ${an(o.sha)} ${o.subject}; ${o.signature.level}${s.length>0?`; ${s.join(", ")}`:""}`)}}for(let r of Yy(e,t.id,"made-by")){let o=e.nodes.find(c=>c.kind==="run"&&c.id===r.to);if(!o)continue;let s=o.recorded?`${[o.harness?.name,o.model].filter(Boolean).join("/")||"no model recorded"}${o.by?` for ${o.by}`:""}${o.cost?`, ${o.cost.amount} ${o.cost.currency}`:", unpriced"}`:"not in the run ledger",a=r.kind!=="made-by"?"":r.joinedBy.includes("patch-id")?`; joined by content${r.recordedAs?`, as ${an(r.recordedAs)}`:""}`:r.joinedBy.length===1&&r.joinedBy[0]==="squash"?`; through the squash, by ${(r.via??[]).map(an).join(", ")}`:"";i.push(` run ${o.run}: ${s}${a}`)}return i}function Gne(e,t){let n=[],i=o=>{let s=e.nodes.find(a=>a.id===o);return s&&(s.kind==="decision"||s.kind==="work")?s.record:o},r=o=>{let s=e.nodes.find(c=>c.kind==="run"&&c.id===o);if(!s)return o;let a=[s.harness?.name,s.model].filter(Boolean).join("/");return`${s.run}${a?` (${a})`:s.recorded?"":" (not in the run ledger)"}${s.unit?` on ${s.unit}`:""}`};n.push(`why ${t.explained?"explained":"unexplained"}${t.lines?`, lines ${yS(t.lines)}`:""}`);for(let o of t.decisions)n.push(` decision ${i(o.decision)} ${o.relevance}${o.lines>0?`, ${o.lines} ${o.lines===1?"line":"lines"}`:""}${o.current?"":", superseded"}${o.closed?", closed":""}`);for(let o of t.blame){let s=o.runs.length>0?`; ${o.runs.map(r).join(", ")}${o.narrowedBy?" (by its hunks)":""}${o.joinedBy?.includes("patch-id")?" (joined by content)":""}${o.via&&o.via.length>0?` (squashed from ${o.via.map(an).join(", ")})`:""}`:o.sha?"; no run":"";n.push(` lines ${yS(o)} ${o.sha?an(o.sha):"uncommitted"}${s}`)}for(let o of t.gaps)n.push(` gap ${o.code}: ${o.message}${o.lines?` (lines ${o.lines.map(yS).join(", ")})`:""}`);return n}function Wne(e){let t=[],n=i=>e.releases.find(r=>r.releaseDigest===i)?.label??i.slice(0,24);for(let i of e.commits){let r=[];i.work&&i.work.state!=="unlinked"&&r.push(i.work.state==="linked"?`work ${i.work.items.map(o=>`${o.id} (${o.source.field})`).join(", ")||"by a lease not checked"}`:`work ${i.work.state}`),i.windowMatches.length>0&&r.push(`in the window of ${i.windowMatches.map(o=>o.id).join(", ")}`),i.tag.state!=="none"&&r.push(i.tag.state);for(let o of i.releases)r.push(`${o.link==="cut-from"?"released as":"shipped in"} ${n(o.release)}`);for(let o of i.deploys)r.push(`${o.env} since ${e.deploys.find(s=>s.id===o.deploy)?.timestamp??"?"}`);r.length>0&&t.push(`trace ${an(i.sha)} ${r.join("; ")}`)}for(let i of e.releases){let r=i.cuts[0];t.push(`release ${i.label??i.releaseDigest.slice(0,24)} from ${an(i.commit)}, ${i.tag.state}${r?`; cut by ${r.actor} at ${r.timestamp}${r.signed?", signed":""}`:""}`);for(let o of i.gates)t.push(` gate ${Nne(o)}`);for(let o of i.deploys){let s=e.deploys.find(a=>a.id===o);s&&t.push(` deploy ${s.env} ${s.component} at ${s.timestamp} by ${s.actor}${s.admittedBy?`, admitted by ${s.admittedBy.op}/${s.admittedBy.gate} (${s.admittedBy.resolvedBy})`:""}`)}}for(let i of e.deploys.filter(r=>r.release===null))t.push(`deploy ${i.env} ${i.component} at ${i.timestamp} by ${i.actor} from ${an(i.gitSha)}, no release${i.admittedBy?`; admitted by ${Nne(i.admittedBy)}`:""}${i.plan?`; plan ${i.plan.document.digest.slice(0,24)}`:""}`);for(let i of e.reasons)t.push(`reason ${i.code}: ${i.message}`);return t}function Bne(e){let t=[],n=e.nodes.find(s=>s.id===e.region);if(n?.kind==="region"){let s=n.lines?`:${n.lines.start}${n.lines.end===n.lines.start?"":`-${n.lines.end}`}`:"",a=e.at?`at ${an(e.at)}`:"in the working tree",c=n.symbol?`#${n.symbol.name} (${n.symbol.kind} ${n.symbol.qualified}, lines ${n.lines?yS(n.lines):"none"})`:s;n.commit?t.push(`region commit ${an(n.commit)} (member ${n.member??"none"}) ${e.at?`at ${an(e.at)}`:"in the working tree"}`):t.push(`region ${n.path}${c} (${n.type}, member ${n.member??"none"}${n.generated?", generated":""}) ${a}${n.node?`, from node ${n.node}`:""}`)}let i=Pc(e,"file");i.length>0&&t.push(`files ${i.length} under the region, ${i.filter(s=>s.generated).length} generated`);for(let s of Pc(e,"decision"))t.push(aje(s),...sje(e,s));for(let s of Pc(e,"work"))t.push(...cje(e,s));for(let s of Pc(e,"artifact"))t.push(lje(e,s));for(let s of Pc(e,"commit"))t.push(...dje(e,s));for(let s of Pc(e,"link")){let a=s.row;t.push(`link ${a.consumer} reads ${"producer"in a?`${a.producer} ${a.output}`:a.input} (${a.status})`)}for(let s of Pc(e,"finding")){let a=s.addressedBy&&s.addressedBy.length>0?`; addressed by ${s.addressedBy.map(c=>`${c.id} (${c.state??"unknown"})`).join(", ")}`:"";t.push(`finding ${s.code}: ${s.message}${a}`)}for(let s of e.reasons)t.push(`reason ${s.code}: ${s.message}`);e.why&&t.push(...Gne(e,e.why)),e.trace&&t.push(...Wne(e.trace));let r=e.kinds.length===0?"; no --kind, so no decisions were read":"",o=Pc(e,"work").length;return t.push(`${e.summary.commits} commits, ${e.summary.decisions} decisions, ${o>0?`${o} work ${o===1?"item":"items"}, `:""}${e.summary.artifacts} artifacts, ${e.summary.findings} findings${r}`),t.join(`
309
+ `)??"";for(let xe of U.split("\0")){if(!xe)continue;let[We,...$t]=xe.split(`
310
+ `).map(ht=>ht.trim());Be.set(We,[...new Set($t.filter(ht=>ht!==""&&be(ht)))].map(l))}}let dt=(U,xe)=>{let We=U.records.loaded.kind.constrains?.field,$t=We?xe.data?.[We]:void 0;return(Array.isArray($t)?$t:[]).filter(ht=>typeof ht=="string"&&ht.startsWith("path:")&&Jn(ht.slice(5))).map(ht=>qe(c(U),ht.slice(5)))},ne=[...new Set([...Be.values()].flat())].map(U=>qe(a,U)),ye=[];for(let[,U]of B){if(U.view===w)continue;let xe=dt(U.kind,U.view);xe.some(We=>ne.some($t=>jo(We,$t)))&&ye.push({ref:{recordKind:U.kind.records.loaded.kind.name,record:U.view.id,state:U.view.state},paths:xe,window:C(U.kind,U.view)})}let ge=[];for(let U of s.filter(xe=>xe.records?.loaded.kind.work)){let xe=U.records.loaded.kind;for(let We of U.records.views){if(We.id===null||We.state!==null&&We.state!==xe.work.done&&(xe.closedStates??[]).includes(We.state))continue;let ht=Gr(We.data,xe.work.implements).includes(w.id),Mn=dt(U,We);if(!ht&&!Mn.some(Fn=>ne.some(lr=>jo(Fn,lr))))continue;let Mt=b?Zy(i,b,We.path):null,nn=b&&xe.stateField?gS(i,b,We.path,xe.stateField,xe.closedStates??[]):null,fn=nn&&b?mo(i,nn,b):null;nn&&fn.delete(nn),ge.push({ref:{recordKind:xe.name,record:We.id,state:We.state},paths:Mn,implementsRecord:ht,window:{fromSet:Mt&&b?mo(i,Mt,b):new Set,untilSet:fn}})}}let oe=U=>Jn(U)&&n.tree.stat(U)==="file"?n.tree.read(U):void 0,Se=U=>{let xe=U==="."?"":U.replace(/\/+$/,"");if(!(xe!==""&&(!Jn(xe)||n.tree.stat(xe)!=="dir")))return n.tree.list(xe)?.map(We=>`${qe(xe,We.name)}${We.type==="dir"?"/":""}`).sort()},Ne=new Set,te=x.filter(U=>U.granularity==="contract").map(U=>U.entry),Ve=[],z=lf(i,[..._.values(),...W.values()]),$e=new Map(s.filter(U=>U.records).map(U=>[U.records.loaded.kind.name,U])),Ie=s.filter(U=>U.records?.loaded.kind.work),et=await r$(i,n.rootOnDisk,[...new Set([...M,...W.keys()])].map(U=>({sha:U,run:z.get(U)?.joins.run??null})));i$(et.refs,T);let ct=(U,xe)=>{let We=U.records.views.find($t=>$t.id===xe);return We?Gr(We.data,U.records.loaded.kind.work.implements).includes(w.id):void 0};for(let U of M){let xe=_.get(U);if(!xe)continue;let We=null,$t=!1,ht=z.get(U).joins,Mn=ke(U);for(let y of[ht,...Mn.map(N=>z.get(N.sha).joins)]){for(let K of y.records){let Q=$e.get(K.kind);!Q||!Q.records.views.some(H=>H.id===K.id)||(K.node=`record:${K.kind}/${K.id}`,(Q.records.loaded.kind.work?ct(Q,K.id):K.kind===h.name&&K.id===w.id)&&($t=!0))}let N=y.lease?.item;if(N){let K=Ie.filter(Q=>Q.records.views.some(H=>H.id===N));K.length===1&&ct(K[0],N)&&($t=!0)}}let Mt=[xe,...Mn];for(let y of s)if(y.joins)for(let N of Mt){let K;try{K=await ax(y.joins,N,{read:oe,list:Se,at:n.at},y.name)}catch(H){let S=`${y.display}: commitJoins failed for ${N.sha.slice(0,8)}: ${H instanceof Error?H.message:String(H)}`;Ne.has(S)||$.push({code:"intent-plugin-failed",message:S}),Ne.add(S);continue}if(!K.unit)continue;We??=K.unit.id,[...fp(K.unit),...fp(K.contract)].some(H=>H===w.id||H===`${h.name}/${w.id}`)&&($t=!0),K.contract&&te.includes(K.contract.id)&&($t=!0)}let nn=T.get(U),fn=(Be.get(U)??[]).map(y=>qe(a,y)),Fn=y=>y.some(N=>fn.some(K=>jo(N,K))),lr=ge.filter(y=>q(y.window,U)&&(y.implementsRecord||Fn(y.paths))).map(y=>y.ref),Xn=ye.filter(y=>q(y.window,U)&&Fn(y.paths)).map(y=>y.ref),Zs=xe.subject.match(/\(#([0-9]+)\)\s*$/);Ve.push({sha:U,subject:xe.subject,author:xe.author,date:xe.date,trailers:xe.trailers,pullRequest:Zs?Number(Zs[1]):null,unit:We,joins:ht,runs:et.refs.get(U)??[],...nn?{squash:{pullRequest:nn.pullRequest,forge:nn.forge,ref:nn.ref,head:nn.head,fetched:nn.fetched,followed:nn.followed,commits:Mn.map(y=>({sha:y.sha,subject:y.subject,author:y.author,date:y.date,trailers:y.trailers,joins:z.get(y.sha).joins}))}}:{},entries:I.get(U),files:Be.get(U)??[],bucket:$t?"own":lr.length>0?"worked":Xn.length>0?"within-other":"unexplained",workedBy:lr,alsoWithin:Xn})}let Vt=U=>Ve.filter(xe=>xe.bucket===U).length;return{doc:{...t,at:n.at,workspace:{name:r.name,root:n.root},record:{id:`record:${h.name}/${w.id}`,recordKind:h.name,record:w.id,path:w.path,title:ije(w.data?.title),state:w.state,supersededBy:w.supersededBy,decidedIn:w.decidedIn??null,constrains:x},history:{rev:b,shallow:k},window:{from:L.from,until:L.until},kinds:s.map(U=>({file:U.display,name:U.name,records:U.records?.loaded.kind.name??null,joins:U.joins?.form??null})),commits:Ve,counts:{commits:Ve.length,own:Vt("own"),worked:Vt("worked"),withinOther:Vt("within-other"),unexplained:Vt("unexplained"),outsideWindow:I.size-M.length},reasons:$},failed:$.some(U=>U.code==="intent-plugin-failed")}}var nje,rje,ije,Dne=v(()=>{"use strict";Tt();cc();Lg();Ty();No();un();HN();t$();BR();on();Wr();Yd();nje=1,rje="https://intentius.io/chant/schemas/workspace/intent-record/v1/intent-record.schema.json",ije=e=>typeof e=="string"?e:null});var Une={};_e(Une,{IN_WINDOW_QUESTION:()=>Fne,formatIntent:()=>Bne,formatIntentRecord:()=>zne,runWorkspaceIntent:()=>fje,traceLines:()=>Wne,whyLines:()=>Gne});import{resolve as Lne}from"node:path";function Yy(e,t,n){return e.edges.filter(i=>i.from===t&&i.kind===n)}function Pc(e,t){return e.nodes.filter(n=>n.kind===t)}function sje(e,t){let n=e.edges.filter(r=>r.kind==="within"&&r.to===t.id),i=[];for(let r of n){let o=e.nodes.find(d=>d.kind==="commit"&&d.id===r.from);if(!o)continue;let s=Yy(e,o.id,"produced-by").map(d=>e.nodes.find(p=>p.id===d.to)).map(d=>d&&"ref"in d?d.ref:void 0).filter(Boolean),a=(o.joins?.records??[]).filter(d=>d.node!==null).map(d=>`${d.kind}:${d.id}`),c=o.joins?.lease?.item;c&&!a.some(d=>d.endsWith(`:${c}`))&&a.push(`lease on ${c}`);let l=s.length>0?`unit ${s.join(", ")}`:a.length>0?`carries ${a.join(", ")}`:"no unit",u=r.state==="decided"?"decided ":"within ";i.push(` ${u} ${an(o.sha)} ${o.subject}; ${l}${r.state==="decided"?`, ${t.record}'s own work`:`, in ${t.record}'s window and not its work`}`)}return n.some(r=>r.state==="decided-by-window")&&i.push(` ask ${Fne}`),i}function aje(e){let t=e.constrains.length>0?e.constrains.map(s=>`${s.entry} (${s.granularity})`).join(", "):"through supersession only",n=e.decided_by?`, decided by ${e.decided_by}${e.decided_on?` on ${e.decided_on}`:""}`:"",i=e.decidedIn?` in ${an(e.decidedIn.sha)}`:"",r=`${e.reviews.agree} agree, ${e.reviews.dissent} dissent, ${e.reviews.abstain} abstain`,o=e.supersededBy?`, superseded by ${e.supersededBy}`:"";return`decision ${e.record} ${e.state??"stateless"}${o}: ${e.title??e.path}; constrains ${t}${n}${i}; ${r}; ${e.provenance.level}${e.valid?"":`; invalid: ${e.reasons.map(s=>s.code).join(", ")}`}`}function cje(e,t){let n=t.constrains.length>0?t.constrains.map(c=>`${c.entry} (${c.granularity})`).join(", "):"through a link only",i=t.implements.length>0?`; implements ${t.implements.map(c=>`${c.id} (${c.state??"unknown"})`).join(", ")}`:"",r=t.ready?"; ready":t.blockedBy.length>0?`; blocked by ${t.blockedBy.map(c=>`${c.id} (${c.state??"unknown"})`).join(", ")}`:"",o=t.owner?`, owned by ${t.owner}`:"",s=t.source?`; from ${t.source.finding} on ${t.source.region}`:"",a=[`work ${t.record} ${t.state??"stateless"}${o}: ${t.title??t.path}; constrains ${n}${i}${r}${s}`];for(let c of e.edges.filter(l=>l.kind==="within"&&l.to===t.id)){let l=e.nodes.find(u=>u.kind==="commit"&&u.id===c.from);l&&a.push(` worked ${an(l.sha)} ${l.subject}; in ${t.record}'s window`)}for(let c of t.warnings)a.push(` warning ${c.code}: ${c.message}`);return a}function lje(e,t){let n=e.edges.filter(i=>i.kind==="pins"&&i.to===t.id).map(i=>`${i.from.slice(i.from.indexOf("/")+1)} at ${an(i.pinnedSha256)} (${i.pinState})`);return`artifact ${t.path} ${t.pinState}; pinned by ${n.join(", ")}; now ${an(t.currentSha256)}`}function uje(e){if(!e)return[];let t=[];e.agent&&t.push(` agent ${e.agent}`),e.lease&&t.push(` lease ${e.lease.token}${e.lease.item?` on ${e.lease.item}`:", no lease history names it"}`);for(let n of e.records)t.push(` record ${n.kind}:${n.id}${n.node?"":", in no kind read"}`);return e.applied&&t.push(` applied by ${e.applied.by}${e.applied.at?` at ${e.applied.at}`:""}${e.applied.commit?`, ${an(e.applied.commit)}`:""}`),t}function dje(e,t){let n=t.lines&&t.lines.length>0?`, lines ${t.lines.map(r=>r.start===r.end?`${r.start}`:`${r.start}-${r.end}`).join(", ")}`:"",i=[`commit ${an(t.sha)} ${t.date.slice(0,10)} ${t.author.name}: ${t.subject}${n}; ${t.signature.level}`];for(let r of Yy(e,t.id,"produced-by")){let o=e.nodes.find(s=>s.id===r.to);i.push(` unit ${o&&"ref"in o?o.ref:r.to}`);for(let s of Yy(e,r.to,"serves"))i.push(` contract ${s.to.slice(9)}`);for(let s of Yy(e,r.to,"cites-evidence"))i.push(` evidence ${s.to.slice(9)}`)}if(i.push(...uje(t.joins)),t.squash){let r=t.squash;i.push(` squash #${r.pullRequest}${r.followed?`: ${r.commits.length} original ${r.commits.length===1?"commit":"commits"} from ${r.ref}${r.fetched?", fetched":""}`:", not followed"}`);for(let o of r.commits){let s=[...o.joins.records.map(a=>`${a.kind}:${a.id}`),...o.joins.lease?[`lease ${o.joins.lease.token}`]:[],...o.joins.run?[`run ${o.joins.run}`]:[]];i.push(` original ${an(o.sha)} ${o.subject}; ${o.signature.level}${s.length>0?`; ${s.join(", ")}`:""}`)}}for(let r of Yy(e,t.id,"made-by")){let o=e.nodes.find(c=>c.kind==="run"&&c.id===r.to);if(!o)continue;let s=o.recorded?`${[o.harness?.name,o.model].filter(Boolean).join("/")||"no model recorded"}${o.by?` for ${o.by}`:""}${o.cost?`, ${o.cost.amount} ${o.cost.currency}`:", unpriced"}`:"not in the run ledger",a=r.kind!=="made-by"?"":r.joinedBy.includes("patch-id")?`; joined by content${r.recordedAs?`, as ${an(r.recordedAs)}`:""}`:r.joinedBy.length===1&&r.joinedBy[0]==="squash"?`; through the squash, by ${(r.via??[]).map(an).join(", ")}`:"";i.push(` run ${o.run}: ${s}${a}`)}return i}function Gne(e,t){let n=[],i=o=>{let s=e.nodes.find(a=>a.id===o);return s&&(s.kind==="decision"||s.kind==="work")?s.record:o},r=o=>{let s=e.nodes.find(c=>c.kind==="run"&&c.id===o);if(!s)return o;let a=[s.harness?.name,s.model].filter(Boolean).join("/");return`${s.run}${a?` (${a})`:s.recorded?"":" (not in the run ledger)"}${s.unit?` on ${s.unit}`:""}`};n.push(`why ${t.explained?"explained":"unexplained"}${t.lines?`, lines ${yS(t.lines)}`:""}`);for(let o of t.decisions)n.push(` decision ${i(o.decision)} ${o.relevance}${o.lines>0?`, ${o.lines} ${o.lines===1?"line":"lines"}`:""}${o.current?"":", superseded"}${o.closed?", closed":""}`);for(let o of t.blame){let s=o.runs.length>0?`; ${o.runs.map(r).join(", ")}${o.narrowedBy?" (by its hunks)":""}${o.joinedBy?.includes("patch-id")?" (joined by content)":""}${o.via&&o.via.length>0?` (squashed from ${o.via.map(an).join(", ")})`:""}`:o.sha?"; no run":"";n.push(` lines ${yS(o)} ${o.sha?an(o.sha):"uncommitted"}${s}`)}for(let o of t.gaps)n.push(` gap ${o.code}: ${o.message}${o.lines?` (lines ${o.lines.map(yS).join(", ")})`:""}`);return n}function Wne(e){let t=[],n=i=>e.releases.find(r=>r.releaseDigest===i)?.label??i.slice(0,24);for(let i of e.commits){let r=[];i.work&&i.work.state!=="unlinked"&&r.push(i.work.state==="linked"?`work ${i.work.items.map(o=>`${o.id} (${o.source.field})`).join(", ")||"by a lease not checked"}`:`work ${i.work.state}`),i.windowMatches.length>0&&r.push(`in the window of ${i.windowMatches.map(o=>o.id).join(", ")}`),i.tag.state!=="none"&&r.push(i.tag.state);for(let o of i.releases)r.push(`${o.link==="cut-from"?"released as":"shipped in"} ${n(o.release)}`);for(let o of i.deploys)r.push(`${o.env} since ${e.deploys.find(s=>s.id===o.deploy)?.timestamp??"?"}`);r.length>0&&t.push(`trace ${an(i.sha)} ${r.join("; ")}`)}for(let i of e.releases){let r=i.cuts[0];t.push(`release ${i.label??i.releaseDigest.slice(0,24)} from ${an(i.commit)}, ${i.tag.state}${r?`; cut by ${r.actor} at ${r.timestamp}${r.signed?", signed":""}`:""}`);for(let o of i.gates)t.push(` gate ${Nne(o)}`);for(let o of i.deploys){let s=e.deploys.find(a=>a.id===o);s&&t.push(` deploy ${s.env} ${s.component} at ${s.timestamp} by ${s.actor}${s.admittedBy?`, admitted by ${s.admittedBy.op}/${s.admittedBy.gate} (${s.admittedBy.resolvedBy})`:""}`)}}for(let i of e.deploys.filter(r=>r.release===null))t.push(`deploy ${i.env} ${i.component} at ${i.timestamp} by ${i.actor} from ${an(i.gitSha)}, no release${i.admittedBy?`; admitted by ${Nne(i.admittedBy)}`:""}${i.plan?`; plan ${i.plan.document.digest.slice(0,24)}`:""}`);for(let i of e.reasons)t.push(`reason ${i.code}: ${i.message}`);return t}function Bne(e){let t=[],n=e.nodes.find(s=>s.id===e.region);if(n?.kind==="region"){let s=n.lines?`:${n.lines.start}${n.lines.end===n.lines.start?"":`-${n.lines.end}`}`:"",a=e.at?`at ${an(e.at)}`:"in the working tree",c=n.symbol?`#${n.symbol.name} (${n.symbol.kind} ${n.symbol.qualified}, lines ${n.lines?yS(n.lines):"none"})`:s;n.commit?t.push(`region commit ${an(n.commit)} (member ${n.member??"none"}) ${e.at?`at ${an(e.at)}`:"in the working tree"}`):t.push(`region ${n.path}${c} (${n.type}, member ${n.member??"none"}${n.generated?", generated":""}) ${a}${n.node?`, from node ${n.node}`:""}`)}let i=Pc(e,"file");i.length>0&&t.push(`files ${i.length} under the region, ${i.filter(s=>s.generated).length} generated`);for(let s of Pc(e,"decision"))t.push(aje(s),...sje(e,s));for(let s of Pc(e,"work"))t.push(...cje(e,s));for(let s of Pc(e,"artifact"))t.push(lje(e,s));for(let s of Pc(e,"commit"))t.push(...dje(e,s));for(let s of Pc(e,"link")){let a=s.row;t.push(`link ${a.consumer} reads ${"producer"in a?`${a.producer} ${a.output}`:a.input} (${a.status})`)}for(let s of Pc(e,"finding")){let a=s.addressedBy&&s.addressedBy.length>0?`; addressed by ${s.addressedBy.map(c=>`${c.id} (${c.state??"unknown"})`).join(", ")}`:"";t.push(`finding ${s.code}: ${s.message}${a}`)}for(let s of e.reasons)t.push(`reason ${s.code}: ${s.message}`);e.why&&t.push(...Gne(e,e.why)),e.trace&&t.push(...Wne(e.trace));let r=e.kinds.length===0?"; no --kind, so no decisions were read":"",o=Pc(e,"work").length;return t.push(`${e.summary.commits} commits, ${e.summary.decisions} decisions, ${o>0?`${o} work ${o===1?"item":"items"}, `:""}${e.summary.artifacts} artifacts, ${e.summary.findings} findings${r}`),t.join(`
311
311
  `)}function zne(e){let t=e.record,n=[`record ${t.record} ${t.state??"stateless"}${t.supersededBy?`, superseded by ${t.supersededBy}`:""}: ${t.title??t.path}`];n.push(`window ${e.window.from?`from ${an(e.window.from)}`:"no history"}${e.window.until?` until ${an(e.window.until)}`:""}${t.decidedIn?`; decided in ${an(t.decidedIn.sha)} ${t.decidedIn.date.slice(0,10)}: ${t.decidedIn.subject}`:"; not decided in the history read"}`);for(let r of t.constrains)n.push(`entry ${r.entry}${r.walked?"":r.exists===!1?" (not in the tree read)":" (not walked)"}`);for(let r of e.commits){let o=r.bucket==="own"?r.unit!==null?`unit ${r.unit}`:`carries ${[...(r.joins?.records??[]).filter(c=>c.node!==null).map(c=>`${c.kind}:${c.id}`),...r.joins?.lease?.item?[`lease on ${r.joins.lease.item}`]:[]].join(", ")}`:r.bucket==="worked"?`worked by ${r.workedBy.map(c=>c.record).join(", ")}`:r.bucket==="within-other"?`within ${r.alsoWithin.map(c=>c.record).join(", ")}`:"nothing else accounts for it",s=(r.runs??[]).map(c=>`run ${c.id}${c.model?` (${c.model})`:""}${c.joinedBy?.includes("squash")&&!c.joinedBy.some(l=>l!=="squash")?" through the squash":""}`).join(", "),a=r.squash?`; squash of #${r.squash.pullRequest}${r.squash.followed?`, ${r.squash.commits.length} original ${r.squash.commits.length===1?"commit":"commits"}`:", not followed"}`:"";n.push(`${r.bucket.padEnd(12)} ${an(r.sha)} ${r.date.slice(0,10)} ${r.subject}; ${o}${s?`; ${s}`:""}${a}; ${r.files.join(", ")||r.entries.join(", ")}`)}for(let r of e.reasons)n.push(`reason ${r.code}: ${r.message}`);let i=e.counts;return n.push(`${i.commits} commits in the window: ${i.own} own, ${i.worked} worked, ${i.withinOther} within another record's window, ${i.unexplained} unexplained; ${i.outsideWindow} outside it`),n.join(`
312
312
  `)}async function pje(e,t,n){let{args:i}=e,{doc:r,failed:o}=await Ine({cwd:t,record:i.record,at:i.at,kinds:n?.map(s=>Lne(s)),followSquash:i.followSquash});return i.json&&console.log(JSON.stringify(r,null,2)),"error"in r?(console.error(we({message:`${r.error.code}: ${r.error.message}`,hint:Mne})),1):(i.json||console.log(zne(r)),o?1:0)}async function fje(e,t){let{args:n}=e;if(n.record!==void 0)return n.intent?(console.error(we({message:"--record walks a record, so --intent takes no region with it",hint:Mne})),1):pje(e,t,n.kinds??(n.kind!==void 0?[n.kind]:void 0));if(!n.intent)return console.error(we({message:"--intent needs a region: a path, path:line, path:start-end, path#symbol, a graph node id or a commit sha",hint:jne})),1;let i=n.kinds??(n.kind!==void 0?[n.kind]:void 0),{doc:r,failed:o}=await rG({cwd:t,region:n.intent,at:n.at,kinds:i?.map(s=>Lne(s)),followSquash:n.followSquash});return n.json&&console.log(JSON.stringify(r,null,2)),"error"in r?(console.error(we({message:`${r.error.code}: ${r.error.message}`,hint:jne})),1):(n.json||console.log(Bne(r)),o?1:0)}var jne,Mne,an,Fne,yS,Nne,Vne=v(()=>{"use strict";ur();Dne();Ty();jne="chant workspace graph --intent <path[:start-end]|path#symbol|member/node|sha> [--at <rev>] [--kind <kind file>...] [--follow-squash] [--json]",Mne="chant workspace graph --intent --record <id> [--at <rev>] [--kind <kind file>...] [--follow-squash] [--json]";an=e=>e?e.slice(0,8):"none",Fne="is this drift, a superseding decision nobody wrote down, or the decision being wrong?";yS=e=>e.start===e.end?`${e.start}`:`${e.start}-${e.end}`;Nne=e=>`${e.op}/${e.gate}${e.environment?` ${e.environment}`:""}: ${e.empty?"passed over an empty change set":`${e.resolvedBy}${e.relayedBy?` relayed by ${e.relayedBy}`:""}`}${e.channel?` on ${e.channel}`:""} at ${e.at}${e.planDigest?`, plan ${e.planDigest.slice(0,24)}${e.changeSet?" (change set stored)":""}`:""}${e.sealed?", sealed":""}`});var Qne={};_e(Qne,{GRAPH_CONTRACT_VERSION:()=>wS,GRAPH_ERROR_CODES:()=>yje,GRAPH_OUTPUT_SCHEMA_ID:()=>bS,componentGraphArgv:()=>Zne,exportRevision:()=>Yne,planGraph:()=>Xne,runWorkspaceGraph:()=>vje,workspaceGraph:()=>fS});import{execFileSync as Hne}from"node:child_process";import{existsSync as pu,mkdirSync as mje,mkdtempSync as gje,rmSync as Jne,symlinkSync as qne}from"node:fs";import{tmpdir as hje}from"node:os";import{dirname as Xy,join as cs,resolve as Kne}from"node:path";function Zne(e){return["graph",".","--components","--format","ir",...e.env?["--env",e.env]:[]]}function Yne(e,t){let{top:n,at:i,root:r,rootOnDisk:o}=e;if(!n||!i)throw new Error("exportRevision needs a revision");let s=gje(cs(hje(),"chant-ws-at-")),a=cs(s,"root"),c=cs(s,"tree.tar");Hne("git",["archive","--format=tar","-o",c,r==="."?i:`${i}:${r}`],{cwd:n,stdio:["ignore","ignore","pipe"]}),mje(a,{recursive:!0}),Hne("tar",["-xf",c,"-C",a],{stdio:["ignore","ignore","pipe"]}),Jne(c,{force:!0});let l=new Set([""]);for(let u of t){if(u===".")continue;let d=u.split("/");for(let p=1;p<=d.length;p++)l.add(d.slice(0,p).join("/"))}for(let u of l){let d=cs(o,...u.split("/"),"node_modules"),p=cs(a,...u.split("/"),"node_modules");pu(d)&&pu(Xy(p))&&!pu(p)&&qne(d,p,"dir")}if(!pu(cs(a,"node_modules")))for(let u=Xy(o);;u=Xy(u)){if(pu(cs(u,"node_modules"))){qne(cs(u,"node_modules"),cs(a,"node_modules"),"dir");break}if(Xy(u)===u)break}return a}function wje(e,t,n,i,r=!1){let o=(l,u)=>(r&&(l.live=!0,u.finishedAt&&(l.readAt=u.finishedAt)),l),s=new Map(t.map(l=>[l.id,l])),a=[],c=e.unreadable.length>0;for(let l of i){if(n?.length&&!n.includes(l.name))continue;let u=s.get(l.name),d=e.skipped.find(g=>g.name===l.name)??e.unreadable.find(g=>g.name===l.name);if(!u){let g=e.unreadable.some(h=>h.name===l.name)?"failed":"skipped";a.push({member:Uy(l.name,l.dir,l.kind,g,d?.reason??null,null)});continue}if(u.exitCode!==0){c=!0;let g=u.stderr.trim().split(`
313
313
  `).slice(-5).join(`
@@ -316,9 +316,9 @@ ${l.stderr}`}});let p=[];for(let f of s){let g=await jte(o.command,a.get(f.id),f
316
316
  `);for(let R of h)R.stderr.trim()&&e.onStderr&&e.onStderr(R.stderr.endsWith(`
317
317
  `)?R.stderr:`${R.stderr}
318
318
  `);let{inputs:w,failed:b}=wje(a,h,e.members,o.members,!!c.live);for(let{member:R}of w)R.status==="composed"&&(R.cached=d.has(R.name),R.stamp=u?.stamps.get(R.name)??null);let k=xte({name:o.name,root:r.root},w,{declaration:o,kinds:s,read:pS(o,r.tree,s)});for(let R of k.members)R.box=bte(o.members.find(P=>P.name===R.name)?.box??null,r.tree,o.members);let $=await bje(k,o.members,e,r.rootOnDisk,r.at),x=!1;if(e.kind!==void 0){let{readRecordsFor:R}=await Promise.resolve().then(()=>(Ei(),ere));try{let P=await R({kind:e.kind,cwd:e.cwd,at:e.at}),I=P.loaded.kind.name;k.records=P.result.records.map(A=>({kind:I,id:A.id,path:A.path,state:A.state,valid:A.valid,supersededBy:A.supersededBy,remediatedBy:A.remediatedBy})),k.links.push(...V6(I,P.result.records,P.loaded.kind.constrains?.field,r.tree,o.members))}catch(P){if(!(P instanceof Xe))throw P;x=!0,e.onStderr?.(`${we({message:`--kind ${e.kind}: ${P.code}: ${P.message}`,hint:Cc})}
319
- `)}}return{doc:{...t,at:r.at,plantable:TF(o),...k},failed:b||x||$,...g?{components:g}:{}}}catch(r){if(!(r instanceof xe))throw r;return{doc:{...t,error:{code:r.code,message:r.message,location:r.location??null}},failed:!0}}finally{i?.cleanup(),n&&Jne(Xy(n),{recursive:!0,force:!0})}}async function bje(e,t,n,i,r){let o=t.filter(u=>u.kind==="workspace"&&(!n.members?.length||n.members.includes(u.name)));if(o.length===0)return!1;let{foldNested:s,readNested:a}=await Promise.resolve().then(()=>(ine(),rne)),c=await Promise.all(o.map(async u=>{let d=cs(i,...u.dir.split("/"));return pu(d)?{m:u,read:await a(d,n.args??{},r,bS,wS,n.reader)}:{m:u,read:null}})),l=!1;for(let{m:u,read:d}of c){let p=e.members.find(f=>f.name===u.name);if(p){if(!d){l=!0,p.status="failed",p.reason={code:"dir-missing",message:`the nested workspace's directory ${u.dir} does not exist`};continue}d.stderr.trim()&&n.onStderr&&n.onStderr(d.stderr.endsWith(`
319
+ `)}}return{doc:{...t,at:r.at,plantable:TF(o),...k},failed:b||x||$,...g?{components:g}:{}}}catch(r){if(!(r instanceof ve))throw r;return{doc:{...t,error:{code:r.code,message:r.message,location:r.location??null}},failed:!0}}finally{i?.cleanup(),n&&Jne(Xy(n),{recursive:!0,force:!0})}}async function bje(e,t,n,i,r){let o=t.filter(u=>u.kind==="workspace"&&(!n.members?.length||n.members.includes(u.name)));if(o.length===0)return!1;let{foldNested:s,readNested:a}=await Promise.resolve().then(()=>(ine(),rne)),c=await Promise.all(o.map(async u=>{let d=cs(i,...u.dir.split("/"));return pu(d)?{m:u,read:await a(d,n.args??{},r,bS,wS,n.reader)}:{m:u,read:null}})),l=!1;for(let{m:u,read:d}of c){let p=e.members.find(f=>f.name===u.name);if(p){if(!d){l=!0,p.status="failed",p.reason={code:"dir-missing",message:`the nested workspace's directory ${u.dir} does not exist`};continue}d.stderr.trim()&&n.onStderr&&n.onStderr(d.stderr.endsWith(`
320
320
  `)?d.stderr:`${d.stderr}
321
- `),p.chant=d.chant,d.ok?s(e,p,d.doc):(l=!0,p.status="failed",p.reason={code:d.code,message:d.message})}}return l}async function vje(e){let{args:t}=e,n=Kne(t.extraPositional??".");if(!pu(n))return console.error(we({message:`${n} does not exist`,hint:Cc})),1;let i=await cx(n,t.at);if(i!==void 0)return i;if(t.composites){if(t.intent!==void 0||t.kind!==void 0)return console.error(we({message:"--composites takes neither --intent nor --kind",hint:Cc})),1;if(!t.dryRun)return(await Promise.resolve().then(()=>(Tne(),_ne))).runWorkspaceComposites(e,n)}if(!t.composites&&t.intent===void 0){if((t.overlay||t.traffic!==void 0)&&!t.live)return console.error(we({message:"--overlay and --traffic act on a live read; add --live --env <env>",hint:Cc})),1;if(t.live&&t.at!==void 0)return zy({$schema:bS,contract:wS,chant:en(),error:{code:"live-at-revision",message:iG,location:null}},t.output),console.error(we({message:`live-at-revision: ${iG}`,hint:Cc})),1;if(t.live&&!t.env)return console.error(we({message:"--live needs an environment, as each member's chant graph --live does: --live --env <env>",hint:Cc})),1}if(t.intent!==void 0)return(await Promise.resolve().then(()=>(Vne(),Une))).runWorkspaceIntent(e,n);if(t.dryRun){let s;try{s=Xne({cwd:n,at:t.at,members:t.members})}catch(a){if(!(a instanceof xe))throw a;return console.error(we({message:`${a.code}: ${a.describe()}`,hint:Cc})),1}return console.log(t.json?JSON.stringify(Fte(s),null,2):Mte(s)),0}let{doc:r,failed:o}=await fS({cwd:n,at:t.at,members:t.members,args:t,...t.noCache?{noCache:!0}:{},...t.kind!==void 0?{kind:Kne(t.kind)}:{},onStderr:s=>process.stderr.write(s)});if(zy(r,t.output),"error"in r){let s=r.error.location;console.error(we({message:`${r.error.code}: ${s?`${s.file}:${s.line}:${s.column}: `:""}${r.error.message}`,hint:Cc}))}return o?1:0}var wS,bS,yje,iG,Cc,nG=v(()=>{"use strict";ur();IF();Fy();Hte();Tt();Vy();qi();JF();ene();No();un();on();Wr();wS=1,bS="https://intentius.io/chant/schemas/workspace/graph/v1/graph.schema.json",yje=[...yi,"live-at-revision"],iG="--live reads the account as it stands now, and --at reads the source at a revision; chant workspace graph takes one of them",Cc="chant workspace graph [dir] [--at <rev>] [--member <name>] [--kind <kind file>] [-o <file>] [--env <env>] [--live [--overlay] [--traffic <level>]] [--no-cache] [--dry-run] | chant workspace graph --composites [--at <rev>] [--member <name>] [-o <file>] | chant workspace graph --intent <path[:start-end]|path#symbol|member/node|sha> [--at <rev>] [--kind <kind file>...] [--follow-squash] [--json]"});var rre={};_e(rre,{attributeEntry:()=>oG,commitFiles:()=>nre,readOverlap:()=>Eje,trailerCommits:()=>tre});import{execFileSync as kje}from"node:child_process";import{dirname as xje}from"node:path";function sG(e,t,n){return kje("git",["-c","core.quotepath=off",...t],{cwd:e,encoding:"utf-8",stdio:[n===void 0?"ignore":"pipe","pipe","ignore"],maxBuffer:512*1024*1024,...n!==void 0?{input:n}:{}})}async function Rje(e,t,n){let i=new Map,r=new Map;for(let o of yr(e)){let s=Ri(o,t),a=await Ht(s,t);if(!a.kind.work)continue;let c=await Ht(a.kind.work.decisions,xje(a.file)),l=new Set(c.kind.closedStates??[]),u=await ii({kind:s,cwd:t}),d=new Map((u.result.decisions??[]).map(f=>[f.id,f])),p=i.get(a.kind.name)??new Set;for(let f of u.result.records){if(f.id===null||(p.add(f.id),f.supersededBy!==null))continue;let g=f.implements??[],h=g.length>0&&g.every(b=>zk(d.get(b.id),l)),w=`${a.kind.name}:${f.id}`;!h&&!r.has(w)&&r.set(w,{path:f.path,state:f.state})}i.set(a.kind.name,p)}return i.size===0?null:{index:{kinds:i,ledger:zR(n)},inFlight:r}}function tre(e){let t;try{t=sG(e,["log","--no-merges",`--format=%H%x1f%(trailers:key=${mp},key=${Fg},valueonly,separator=%x1e)%x1d`,"--exclude=chant/*","--branches","--exclude=*/chant/*","--remotes","HEAD","--"])}catch{return[]}let n=[];for(let i of t.split("")){let[r,o]=i.trim().split("");r&&o&&o.trim()!==""&&n.push(r)}return n}function nre(e,t){let n=new Map;if(t.length===0)return n;let i=sG(e,["log","--no-walk=unsorted","--stdin","--no-renames","--name-only","--format=%x1e%H"],`${t.join(`
321
+ `),p.chant=d.chant,d.ok?s(e,p,d.doc):(l=!0,p.status="failed",p.reason={code:d.code,message:d.message})}}return l}async function vje(e){let{args:t}=e,n=Kne(t.extraPositional??".");if(!pu(n))return console.error(we({message:`${n} does not exist`,hint:Cc})),1;let i=await cx(n,t.at);if(i!==void 0)return i;if(t.composites){if(t.intent!==void 0||t.kind!==void 0)return console.error(we({message:"--composites takes neither --intent nor --kind",hint:Cc})),1;if(!t.dryRun)return(await Promise.resolve().then(()=>(Tne(),_ne))).runWorkspaceComposites(e,n)}if(!t.composites&&t.intent===void 0){if((t.overlay||t.traffic!==void 0)&&!t.live)return console.error(we({message:"--overlay and --traffic act on a live read; add --live --env <env>",hint:Cc})),1;if(t.live&&t.at!==void 0)return zy({$schema:bS,contract:wS,chant:en(),error:{code:"live-at-revision",message:iG,location:null}},t.output),console.error(we({message:`live-at-revision: ${iG}`,hint:Cc})),1;if(t.live&&!t.env)return console.error(we({message:"--live needs an environment, as each member's chant graph --live does: --live --env <env>",hint:Cc})),1}if(t.intent!==void 0)return(await Promise.resolve().then(()=>(Vne(),Une))).runWorkspaceIntent(e,n);if(t.dryRun){let s;try{s=Xne({cwd:n,at:t.at,members:t.members})}catch(a){if(!(a instanceof ve))throw a;return console.error(we({message:`${a.code}: ${a.describe()}`,hint:Cc})),1}return console.log(t.json?JSON.stringify(Fte(s),null,2):Mte(s)),0}let{doc:r,failed:o}=await fS({cwd:n,at:t.at,members:t.members,args:t,...t.noCache?{noCache:!0}:{},...t.kind!==void 0?{kind:Kne(t.kind)}:{},onStderr:s=>process.stderr.write(s)});if(zy(r,t.output),"error"in r){let s=r.error.location;console.error(we({message:`${r.error.code}: ${s?`${s.file}:${s.line}:${s.column}: `:""}${r.error.message}`,hint:Cc}))}return o?1:0}var wS,bS,yje,iG,Cc,nG=v(()=>{"use strict";ur();IF();Fy();Hte();Tt();Vy();qi();JF();ene();No();un();on();Wr();wS=1,bS="https://intentius.io/chant/schemas/workspace/graph/v1/graph.schema.json",yje=[...yi,"live-at-revision"],iG="--live reads the account as it stands now, and --at reads the source at a revision; chant workspace graph takes one of them",Cc="chant workspace graph [dir] [--at <rev>] [--member <name>] [--kind <kind file>] [-o <file>] [--env <env>] [--live [--overlay] [--traffic <level>]] [--no-cache] [--dry-run] | chant workspace graph --composites [--at <rev>] [--member <name>] [-o <file>] | chant workspace graph --intent <path[:start-end]|path#symbol|member/node|sha> [--at <rev>] [--kind <kind file>...] [--follow-squash] [--json]"});var rre={};_e(rre,{attributeEntry:()=>oG,commitFiles:()=>nre,readOverlap:()=>Eje,trailerCommits:()=>tre});import{execFileSync as kje}from"node:child_process";import{dirname as xje}from"node:path";function sG(e,t,n){return kje("git",["-c","core.quotepath=off",...t],{cwd:e,encoding:"utf-8",stdio:[n===void 0?"ignore":"pipe","pipe","ignore"],maxBuffer:512*1024*1024,...n!==void 0?{input:n}:{}})}async function Rje(e,t,n){let i=new Map,r=new Map;for(let o of yr(e)){let s=Ri(o,t),a=await Ht(s,t);if(!a.kind.work)continue;let c=await Ht(a.kind.work.decisions,xje(a.file)),l=new Set(c.kind.closedStates??[]),u=await ii({kind:s,cwd:t}),d=new Map((u.result.decisions??[]).map(f=>[f.id,f])),p=i.get(a.kind.name)??new Set;for(let f of u.result.records){if(f.id===null||(p.add(f.id),f.supersededBy!==null))continue;let g=f.implements??[],h=g.length>0&&g.every(b=>zk(d.get(b.id),l)),w=`${a.kind.name}:${f.id}`;!h&&!r.has(w)&&r.set(w,{path:f.path,state:f.state})}i.set(a.kind.name,p)}return i.size===0?null:{index:{kinds:i,ledger:zR(n)},inFlight:r}}function tre(e){let t;try{t=sG(e,["log","--no-merges",`--format=%H%x1f%(trailers:key=${mp},key=${Fg},valueonly,separator=%x1e)%x1d`,"--exclude=chant/*","--branches","--exclude=*/chant/*","--remotes","HEAD","--"])}catch{return[]}let n=[];for(let i of t.split("")){let[r,o]=i.trim().split("");r&&o&&o.trim()!==""&&n.push(r)}return n}function nre(e,t){let n=new Map;if(t.length===0)return n;let i=sG(e,["log","--no-walk=unsorted","--stdin","--no-renames","--name-only","--format=%x1e%H"],`${t.join(`
322
322
  `)}
323
323
  `);for(let r of i.split("")){let o=r.split(`
324
324
  `).map(s=>s.trim()).filter(Boolean);o.length!==0&&n.set(o[0],o.slice(1))}return n}function Sje(e,t){try{return new Set(sG(e,["rev-list",t,"--"]).split(`
@@ -332,23 +332,23 @@ ${l.stderr}`}});let p=[];for(let f of s){let g=await jte(o.command,a.get(f.id),f
332
332
  `),f={};for(let g of(l??"").split("")){let h=g.indexOf(":");if(h<=0)continue;let w=g.slice(0,h).trim();(f[w]??=[]).push(g.slice(h+1).trim())}n.set(o.trim(),{sha:o.trim(),subject:p<0?d:d.slice(0,p),body:p<0?"":d.slice(p+1).replace(/^\n+/,""),author:{name:s,email:a},date:c,trailers:f})}return n}function Zy(e,t,n){return xn(e,["log","--diff-filter=A","-1","--format=%H",t,"--",n])?.trim()||null}function gS(e,t,n,i,r){let o=xn(e,["log","--format=%H",t,"--",n]),s=null;for(let a of(o??"").split(`
333
333
  `).map(c=>c.trim()).filter(Boolean)){let c=xn(e,["show",`${a}:${n}`]),l=c===void 0?void 0:Ss(c),u=l?.ok?l.value[i]:void 0;if(typeof u!="string"||!r.includes(u))break;s=a}return s}function hre(e,t,n){let i=xn(e,["diff-tree","--no-commit-id","-r","--name-only","--root","-m","--first-parent","-z",t])??"",r=new Set;for(let o of i.split("\0"))o&&(n===""?r.add(o):o.startsWith(`${n}/`)&&r.add(o.slice(n.length+1)));return[...r].sort()}function hf(e,t,n){return n.decidedIn?.sha??Zy(e,t,n.path)}function Uje(e,t){let n=`${e}\0${t}`;if(cG?.key===n)return cG.children;let i=xn(e,["rev-list","--parents",t]);if(i===void 0)return;let r=new Map;for(let o of i.split(`
334
334
  `)){let[s,...a]=o.trim().split(" ");if(s)for(let c of a){let l=r.get(c);l?l.push(s):r.set(c,[s])}}return cG={key:n,children:r},r}function mo(e,t,n){let i=new Set([t]),r=uG.test(t)&&uG.test(n)?Uje(e,n):void 0;if(r){let s=[t];for(;s.length>0;)for(let a of r.get(s.pop())??[])i.has(a)||(i.add(a),s.push(a));return i}let o=xn(e,["rev-list","--ancestry-path",`${t}..${n}`]);for(let s of(o??"").split(`
335
- `))s.trim()&&i.add(s.trim());return i}function Vje(e){let n=xn(e,["config","--get","remote.origin.url"])?.trim()?.match(/[:/]([^/:]+)\/([^/]+?)(?:\.git)?\/?$/);return n?`${n[1]}/${n[2]}`.toLowerCase():null}function Qy(e){try{return Nje(e)}catch{return e}}function pG(e){let t=e.match(/^(.+?):(\d+)(?:-(\d+))?$/);if(!t)return{path:e,lines:null};let n=Number(t[2]),i=t[3]===void 0?n:Number(t[3]);return n<1||i<n?{error:`${e}: a line range is start-end with 1 <= start <= end`}:{path:t[1],lines:{start:n,end:i}}}function Hje(e,t,n){return n!==void 0?`region:${e}#${n}`:`region:${e}${t?`:${t.start}${t.end===t.start?"":`-${t.end}`}`:""}`}function qje(e,t){let n=[],i=r=>{for(let o of(e.list(r)??[]).sort((s,a)=>s.name.localeCompare(a.name))){let s=qe(r,o.name);o.type==="dir"?Bi(o.name)||i(s):n.push(s)}};return i(t==="."?"":t),n}function mu(e){return typeof e=="string"?e:null}function lre(e){let t=e?.source;if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t;return typeof n.finding!="string"||typeof n.region!="string"?null:{finding:n.finding,region:n.region,...typeof n.decision=="string"?{decision:n.decision}:{},...typeof n.artifact=="string"?{artifact:n.artifact}:{}}}function Kje(e){let t={agree:0,dissent:0,abstain:0,openConcerns:0},n=e?.reviews;if(!Array.isArray(n))return t;for(let i of n){if(i===null||typeof i!="object")continue;let r=i;r.verdict==="agree"?t.agree++:r.verdict==="abstain"?t.abstain++:r.verdict==="dissent"&&(t.dissent++,r.addressed_by==null&&r.withdrawn_on==null&&t.openConcerns++)}return t}async function Yje(e,t,n,i){let{workspaceGraph:r}=await Promise.resolve().then(()=>(nG(),Qne)),{doc:o}=await r({cwd:e,at:t,members:[n]});if("error"in o)return null;let s=o.nodes.find(a=>a.id===i);return s?s.sourceLoc?{file:s.sourceLoc.file,line:s.sourceLoc.line??null}:{file:".",line:null}:null}async function hS(e,t){let n=[];for(let i of e.kinds??[]){let r=dG(e.cwd,i),o=yre(dre(t,Qy(r))),s;try{s=await LD(r)}catch(l){throw new pn("kind-unreadable",`kind file ${i} could not be loaded: ${l instanceof Error?l.message:String(l)}`)}let a=nZ(s);if(typeof a=="string")throw new pn("kind-invalid",`kind file ${i} has a commitJoins export that can't be read: ${a}`);let c={file:r,display:o,name:a?.name??Lje(r).replace(/(?:\.kind)?\.[cm]?[jt]s$/,""),...a?{joins:a}:{}};if(s.recordKind!==void 0){let l=await ew({kind:r,at:e.at,cwd:e.cwd,workGaps:!1});if("error"in l)throw new pn(l.error.code,l.error.message);try{c.records={loaded:await Ht(r),views:l.records,workspaceRoot:l.workspaceRoot},c.name=a?.name??c.records.loaded.kind.name}catch(u){throw u instanceof Xe?new pn(u.code,u.message):u}}else if(!a)throw new pn("kind-invalid",`kind file ${i} exports neither recordKind nor commitJoins`);n.push(c)}return n}async function Qje(e,t,n){let i=pG(e.region);if("error"in i)throw new pn("intent-region-invalid",i.error);let r=l=>{let u=yre(dre(Qy(t.rootOnDisk),dG(Qy(e.cwd),l))),d=u===""?".":u;return d==="."||Jn(d)&&!d.startsWith("../")&&t.tree.stat(d)!==void 0?d:void 0},o=r(i.path);if(o!==void 0)return{path:o,lines:i.lines,node:null,symbol:null};let s=i.lines?-1:e.region.lastIndexOf("#");if(s>0){let l=e.region.slice(s+1),u=r(e.region.slice(0,s));if(u!==void 0&&l!==""){if(u==="."||t.tree.stat(u)!=="file")throw new pn("intent-region-invalid",`${u} is a directory, and a symbol needs a file`);let d=[],p="";if(!eF(u)){let g=Fr(u,n.members),h=g?n.members.find(w=>w.name===g):void 0;if(h&&h.kind==="chant"){let w=await dee(Py(t.rootOnDisk,h.dir),e.loadLexicon);d=w.resolvers,w.problems.length>0&&(p=`; member ${h.name}: ${w.problems.join("; ")}`)}}let f=tF(u,t.tree.read(u),l,d);if(!f.ok)throw new pn(f.reason==="unsupported"?"intent-symbol-unsupported":f.reason==="ambiguous"?"intent-symbol-ambiguous":"intent-symbol-unknown",`${f.message}${f.reason==="unsupported"?p:""}${t.tree.label}`);return{path:u,lines:f.declaration.lines,node:null,symbol:{name:l,qualified:f.declaration.qualified,kind:f.declaration.kind}}}}let a=e.region.indexOf("/"),c=a>0?n.members.find(l=>l.name===e.region.slice(0,a)):void 0;if(c&&!i.lines){let l=await(e.resolveNode??Yje)(e.cwd,e.at,c.name,e.region);if(l){let u=qe(c.dir,l.file);return{path:u===""?".":u,lines:l.line?{start:l.line,end:l.line}:null,node:e.region,symbol:null}}}if(Xje.test(e.region)&&t.top){let l=xn(t.top,["rev-parse","--verify","--quiet",`${e.region}^{commit}`])?.trim();if(l)return{path:".",lines:null,node:null,symbol:null,commit:l}}throw new pn("intent-region-invalid",`${e.region} is not a path in the workspace${t.tree.label}, a path#symbol, a graph node id or a commit`)}async function eNe(e,t,n,i,r){if(e.length===0||r!==null)return;let o;try{let{readOverlap:s}=await Promise.resolve().then(()=>(ire(),rre));o=await s({declaration:t,root:n,top:i,changeSets:[]})}catch{return}if(o!==null)for(let s of e){let a=`${s.recordKind}:${s.record}`;s.overlaps=o.pairs.filter(c=>c.items.includes(a)&&c.files.length>0).map(c=>({with:c.items[0]===a?c.items[1]:c.items[0],files:c.files}))}}async function rG(e){let t={$schema:fre,contract:pre,chant:en()};try{return await tNe(e,t)}catch(n){if(n instanceof pn||n instanceof xe||n instanceof Xe)return{doc:{...t,error:{code:n.code,message:n.message}},failed:!0};throw n}}async function tNe(e,t){let n=qt(e.cwd,e.at),i=n.top;if(!i)throw new pn("not-a-git-repository","the intent graph reads git history, and this directory is not in a git repository");let r=_t(n.tree,"",{rootChant:!0}),o=await Qje(e,n,r),s=o.commit?"commit":o.path==="."?"dir":n.tree.stat(o.path);if(!s)throw new pn("intent-region-invalid",`${o.path} does not exist${n.tree.label}`);if(o.lines){if(s!=="file")throw new pn("intent-region-invalid",`${o.path} is a directory, and a line range needs a file`);let E=n.tree.read(o.path).replace(/\n$/,"").split(`
335
+ `))s.trim()&&i.add(s.trim());return i}function Vje(e){let n=xn(e,["config","--get","remote.origin.url"])?.trim()?.match(/[:/]([^/:]+)\/([^/]+?)(?:\.git)?\/?$/);return n?`${n[1]}/${n[2]}`.toLowerCase():null}function Qy(e){try{return Nje(e)}catch{return e}}function pG(e){let t=e.match(/^(.+?):(\d+)(?:-(\d+))?$/);if(!t)return{path:e,lines:null};let n=Number(t[2]),i=t[3]===void 0?n:Number(t[3]);return n<1||i<n?{error:`${e}: a line range is start-end with 1 <= start <= end`}:{path:t[1],lines:{start:n,end:i}}}function Hje(e,t,n){return n!==void 0?`region:${e}#${n}`:`region:${e}${t?`:${t.start}${t.end===t.start?"":`-${t.end}`}`:""}`}function qje(e,t){let n=[],i=r=>{for(let o of(e.list(r)??[]).sort((s,a)=>s.name.localeCompare(a.name))){let s=qe(r,o.name);o.type==="dir"?Bi(o.name)||i(s):n.push(s)}};return i(t==="."?"":t),n}function mu(e){return typeof e=="string"?e:null}function lre(e){let t=e?.source;if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t;return typeof n.finding!="string"||typeof n.region!="string"?null:{finding:n.finding,region:n.region,...typeof n.decision=="string"?{decision:n.decision}:{},...typeof n.artifact=="string"?{artifact:n.artifact}:{}}}function Kje(e){let t={agree:0,dissent:0,abstain:0,openConcerns:0},n=e?.reviews;if(!Array.isArray(n))return t;for(let i of n){if(i===null||typeof i!="object")continue;let r=i;r.verdict==="agree"?t.agree++:r.verdict==="abstain"?t.abstain++:r.verdict==="dissent"&&(t.dissent++,r.addressed_by==null&&r.withdrawn_on==null&&t.openConcerns++)}return t}async function Yje(e,t,n,i){let{workspaceGraph:r}=await Promise.resolve().then(()=>(nG(),Qne)),{doc:o}=await r({cwd:e,at:t,members:[n]});if("error"in o)return null;let s=o.nodes.find(a=>a.id===i);return s?s.sourceLoc?{file:s.sourceLoc.file,line:s.sourceLoc.line??null}:{file:".",line:null}:null}async function hS(e,t){let n=[];for(let i of e.kinds??[]){let r=dG(e.cwd,i),o=yre(dre(t,Qy(r))),s;try{s=await LD(r)}catch(l){throw new pn("kind-unreadable",`kind file ${i} could not be loaded: ${l instanceof Error?l.message:String(l)}`)}let a=nZ(s);if(typeof a=="string")throw new pn("kind-invalid",`kind file ${i} has a commitJoins export that can't be read: ${a}`);let c={file:r,display:o,name:a?.name??Lje(r).replace(/(?:\.kind)?\.[cm]?[jt]s$/,""),...a?{joins:a}:{}};if(s.recordKind!==void 0){let l=await ew({kind:r,at:e.at,cwd:e.cwd,workGaps:!1});if("error"in l)throw new pn(l.error.code,l.error.message);try{c.records={loaded:await Ht(r),views:l.records,workspaceRoot:l.workspaceRoot},c.name=a?.name??c.records.loaded.kind.name}catch(u){throw u instanceof Xe?new pn(u.code,u.message):u}}else if(!a)throw new pn("kind-invalid",`kind file ${i} exports neither recordKind nor commitJoins`);n.push(c)}return n}async function Qje(e,t,n){let i=pG(e.region);if("error"in i)throw new pn("intent-region-invalid",i.error);let r=l=>{let u=yre(dre(Qy(t.rootOnDisk),dG(Qy(e.cwd),l))),d=u===""?".":u;return d==="."||Jn(d)&&!d.startsWith("../")&&t.tree.stat(d)!==void 0?d:void 0},o=r(i.path);if(o!==void 0)return{path:o,lines:i.lines,node:null,symbol:null};let s=i.lines?-1:e.region.lastIndexOf("#");if(s>0){let l=e.region.slice(s+1),u=r(e.region.slice(0,s));if(u!==void 0&&l!==""){if(u==="."||t.tree.stat(u)!=="file")throw new pn("intent-region-invalid",`${u} is a directory, and a symbol needs a file`);let d=[],p="";if(!eF(u)){let g=Fr(u,n.members),h=g?n.members.find(w=>w.name===g):void 0;if(h&&h.kind==="chant"){let w=await dee(Py(t.rootOnDisk,h.dir),e.loadLexicon);d=w.resolvers,w.problems.length>0&&(p=`; member ${h.name}: ${w.problems.join("; ")}`)}}let f=tF(u,t.tree.read(u),l,d);if(!f.ok)throw new pn(f.reason==="unsupported"?"intent-symbol-unsupported":f.reason==="ambiguous"?"intent-symbol-ambiguous":"intent-symbol-unknown",`${f.message}${f.reason==="unsupported"?p:""}${t.tree.label}`);return{path:u,lines:f.declaration.lines,node:null,symbol:{name:l,qualified:f.declaration.qualified,kind:f.declaration.kind}}}}let a=e.region.indexOf("/"),c=a>0?n.members.find(l=>l.name===e.region.slice(0,a)):void 0;if(c&&!i.lines){let l=await(e.resolveNode??Yje)(e.cwd,e.at,c.name,e.region);if(l){let u=qe(c.dir,l.file);return{path:u===""?".":u,lines:l.line?{start:l.line,end:l.line}:null,node:e.region,symbol:null}}}if(Xje.test(e.region)&&t.top){let l=xn(t.top,["rev-parse","--verify","--quiet",`${e.region}^{commit}`])?.trim();if(l)return{path:".",lines:null,node:null,symbol:null,commit:l}}throw new pn("intent-region-invalid",`${e.region} is not a path in the workspace${t.tree.label}, a path#symbol, a graph node id or a commit`)}async function eNe(e,t,n,i,r){if(e.length===0||r!==null)return;let o;try{let{readOverlap:s}=await Promise.resolve().then(()=>(ire(),rre));o=await s({declaration:t,root:n,top:i,changeSets:[]})}catch{return}if(o!==null)for(let s of e){let a=`${s.recordKind}:${s.record}`;s.overlaps=o.pairs.filter(c=>c.items.includes(a)&&c.files.length>0).map(c=>({with:c.items[0]===a?c.items[1]:c.items[0],files:c.files}))}}async function rG(e){let t={$schema:fre,contract:pre,chant:en()};try{return await tNe(e,t)}catch(n){if(n instanceof pn||n instanceof ve||n instanceof Xe)return{doc:{...t,error:{code:n.code,message:n.message}},failed:!0};throw n}}async function tNe(e,t){let n=qt(e.cwd,e.at),i=n.top;if(!i)throw new pn("not-a-git-repository","the intent graph reads git history, and this directory is not in a git repository");let r=_t(n.tree,"",{rootChant:!0}),o=await Qje(e,n,r),s=o.commit?"commit":o.path==="."?"dir":n.tree.stat(o.path);if(!s)throw new pn("intent-region-invalid",`${o.path} does not exist${n.tree.label}`);if(o.lines){if(s!=="file")throw new pn("intent-region-invalid",`${o.path} is a directory, and a line range needs a file`);let E=n.tree.read(o.path).replace(/\n$/,"").split(`
336
336
  `).length;if(o.lines.end>E)throw new pn("intent-region-invalid",`${o.path} has ${E} lines${n.tree.label}, so ${o.lines.start}-${o.lines.end} is not in it`)}let a=e.kinds??yr(r).map(E=>Ri(E,n.rootOnDisk)),c=await hS({...e,kinds:a},i),l=new Map,u=[],d=[],p=[],f=E=>(l.has(E.id)||l.set(E.id,E),l.get(E.id)),g=(E,O,D)=>{p.push({id:`finding:${E}:${p.filter(Y=>Y.code===E).length+1}`,kind:"finding",code:E,message:O,concerns:D})},h=n.root==="."?"":n.root,w=o.commit?hre(i,o.commit,h):[],b=[...new Set(w.map(E=>Fr(E,r.members)).filter(E=>E!==null))],k=o.commit?b.length===1?b[0]:null:o.path==="."?r.members.find(E=>E.dir===".")?.name??null:Fr(o.path,r.members),$=o.commit?b:k?[k]:[],x=o.commit?`region:commit:${o.commit}`:Hje(o.path,o.lines,o.symbol?.name),R=o.commit?`commit ${o.commit.slice(0,8)}`:o.path;f({id:x,kind:"region",path:o.path,lines:o.lines,member:k,at:n.at,type:s,generated:s==="file"?PN(r,o.path):null,node:o.node,symbol:o.symbol,...o.commit?{commit:o.commit}:{}});let P=s==="dir"?qje(n.tree,o.path):[];for(let E of P)f({id:`file:${E}`,kind:"file",path:E,member:Fr(E,r.members),generated:PN(r,E)});let I=E=>{let O=r.members.find(D=>D.name===E);return f({id:`member:${E}`,kind:"member",name:E,dir:O?.dir??"",memberKind:O?.kind??""})};k&&I(k);let A=n.at??(xn(i,["rev-parse","--verify","--quiet","HEAD^{commit}"])?.trim()||null),B=xn(i,["rev-parse","--is-shallow-repository"])?.trim()==="true";B&&d.push({code:"intent-history-shallow",message:"this is a shallow clone, so the history stops at its boundary and the oldest commit listed may stand for many"});let C=qe(h,o.path),q=o.commit?[{sha:o.commit,lines:null}]:A&&s!=="commit"?mS(i,A,C,s,o.lines):[],L=s==="file"?o.lines??{start:1,end:Math.max(1,n.tree.read(o.path).replace(/\n$/,"").split(`
337
- `).length)}:null,M=L===null?[]:(A?gre(i,n.at,C,o.lines):void 0)??(n.at===null?Array.from({length:L.end-L.start+1},(E,O)=>({line:L.start+O,sha:null,origPath:C,origLine:L.start+O})):[]);for(let E of new Set(M.map(O=>O.sha).filter(O=>O!==null)))q.some(O=>O.sha===E)||q.push({sha:E,lines:null});let _=Ec(i,q.map(E=>E.sha)),T=e.followSquash?Ch(i,[..._.values()],{fetchMissing:!0}):new Map;for(let E of T.values())E.problem&&d.push({code:"squash-unfollowed",message:`${E.sha.slice(0,8)} squashes pull request #${E.pullRequest}, and ${E.problem}, so its original commits are not followed`});let W=Ec(i,[...new Set([...T.values()].flatMap(E=>E.commits))]),ve=E=>(T.get(E)?.commits??[]).map(O=>W.get(O)).filter(O=>O!==void 0),re=$i(i,ti(i)),be=re.active?await jg():[],Be=E=>{if(!(!Jn(E)||n.tree.stat(E)!=="file"))return n.tree.read(E)},dt=E=>{let O=E==="."?"":E.replace(/\/+$/,"");return O!==""&&(!Jn(O)||n.tree.stat(O)!=="dir")?void 0:n.tree.list(O)?.map(Y=>`${qe(O,Y.name)}${Y.type==="dir"?"/":""}`).sort()},ne=new Map,ye=lf(i,[..._.values(),...W.values()]),ge=[],oe=E=>{if(!re.active)return{level:"unattested",reason:re.problems.length?re.problems.join("; "):`no signers file (${re.signersPath}) at base; attestation is off`};let O=Ng(i,re,E,be);return{level:O.level,reason:O.reason,...O.principal?{principal:O.principal}:{}}},Se=new Set;for(let E of q){let O=_.get(E.sha);if(!O)continue;let D=oe(O.sha),Y=O.subject.match(/\(#([0-9]+)\)\s*$/),ue=`commit:${O.sha}`,V=T.get(O.sha),De=V?{pullRequest:V.pullRequest,forge:V.forge,ref:V.ref,head:V.head,fetched:V.fetched,followed:V.followed,commits:ve(O.sha).map(kt=>({sha:kt.sha,subject:kt.subject,author:kt.author,date:kt.date,trailers:kt.trailers,signature:oe(kt.sha),joins:ye.get(kt.sha).joins}))}:void 0;f({id:ue,kind:"commit",sha:O.sha,subject:O.subject,author:O.author,date:O.date,trailers:O.trailers,pullRequest:Y?Number(Y[1]):null,signature:D,lines:E.lines,state:null,joins:ye.get(O.sha).joins,...De?{squash:De}:{}}),u.push({kind:"touched-by",from:x,to:ue,lines:E.lines});let Ae={contracts:[],authorship:[],decisions:[],carries:[]};ne.set(O.sha,Ae);let lt=kt=>{u.some(Er=>Er.kind===kt.kind&&Er.from===kt.from&&Er.to===kt.to)||u.push(kt)},rn=[O,...ve(O.sha)];for(let kt of c)if(kt.joins)for(let Er of rn){let kf=Er!==O,Gn;try{Gn=await ax(kt.joins,Er,{read:Be,list:dt,at:n.at},kt.name)}catch(Vr){let bo=`${kt.display}: commitJoins failed for ${Er.sha.slice(0,8)}: ${Vr instanceof Error?Vr.message:String(Vr)}`;Se.has(bo)||d.push({code:"intent-plugin-failed",message:bo}),Se.add(bo);continue}let wu=(Vr,bo)=>{let{id:Ys,...de}=bo;return f({id:`${Vr}:${Ys}`,kind:Vr,ref:Ys,plugin:kt.display,data:de}).id},ji=Gn.unit?wu("unit",Gn.unit):void 0,Nc=Gn.contract?wu("contract",Gn.contract):void 0;ji&&(kf?Ae.unit??=ji:Ae.unit=ji,lt({kind:"produced-by",from:ue,to:ji}),Nc&&lt({kind:"serves",from:ji,to:Nc})),Nc&&Ae.contracts.push(Gn.contract.id),ji&&Ae.decisions.push(...fp(Gn.unit),...fp(Gn.contract));for(let Vr of Gn.findings??[])ge.push({commit:ue,plugin:kt.display,finding:Vr});let Lc=Gn.evidence===void 0?[]:Array.isArray(Gn.evidence)?Gn.evidence:[Gn.evidence];for(let Vr of Lc)lt({kind:"cites-evidence",from:ji??Nc??ue,to:wu("evidence",Vr)});kf||Ae.authorship.push(...Gn.authorship??[])}}let Ne=await r$(i,n.rootOnDisk,[...new Set([...q.map(E=>E.sha),...W.keys()])].map(E=>({sha:E,run:ye.get(E)?.joins.run??null})));i$(Ne.refs,T);for(let E of q)if(l.has(`commit:${E.sha}`))for(let O of Ne.refs.get(E.sha)??[]){let D=Ne.runs.get(O.id),Y=f({id:`run:${O.id}`,kind:"run",run:O.id,recorded:D!==void 0,state:D?.state??null,harness:D?.harness??null,model:D?.model??null,provider:D?.provider??null,by:D?.by??null,agent:D?.agent??null,unit:D?.unit?.id??null,startedAt:D?.startedAt??null,endedAt:D?.endedAt??null,outcome:D?.outcome??null,usage:D?.usage??null,cost:D?.cost??null,transcript:D?.transcript??null,instruction:D?.instruction??null,lease:D?.lease??null});u.push({kind:"made-by",from:`commit:${E.sha}`,to:Y.id,joinedBy:O.joinedBy,...O.recordedAs?{recordedAs:O.recordedAs}:{},...O.via?{via:O.via}:{}})}for(let E of Ne.conflicts){if(!l.has(`commit:${E.sha}`))continue;let O=E.content.map(D=>`${D.run} (${D.sha.slice(0,8)})`).join(", ");g("intent-commit-join-conflict",`${E.sha.slice(0,8)} joins ${E.joined.join(", ")} by its trailer or the run's record, and has the patch-id of a commit ${O} recorded; it is not joined to ${E.content.length===1?"that run":"those runs"}`,[`commit:${E.sha}`,...E.joined.map(D=>`run:${D}`)])}let te=o.path==="."?h:C,Ve=Vje(i),z=new Set;for(let E of _.values())for(let O of E.subject.matchAll(/#([0-9]+)/g))z.add(O[1]);let $e=new Set([...ne.values()].flatMap(E=>E.contracts)),Ie=[],et=new Map,ct=(E,O)=>`record:${E.records.loaded.kind.name}/${O}`,Vt=(E,O)=>{let D=E.records.loaded.kind,Y=FD(D,O.data);return f({id:ct(E,O.id),kind:"decision",recordKind:D.name,record:O.id,path:O.path,title:mu(O.data?.title),state:O.state,closed:O.state!==null&&(D.closedStates??[]).includes(O.state),valid:O.valid,reasons:O.reasons,provenance:{level:O.provenance.level,commit:O.provenance.commit,reason:O.provenance.reason},decided_by:mu(O.data?.decided_by),decided_on:mu(O.data?.decided_on),decidedIn:O.decidedIn??null,reviews:Kje(O.data),supersededBy:O.supersededBy,supersedes:Y,constrains:[]})},U=E=>P.filter(O=>jo(E,qe(h,O))),ke=(E,O)=>{let D=E.records.loaded.kind.constrains?.field,Y=E.records.workspaceRoot==="."?"":E.records.workspaceRoot,ue=D?O.data?.[D]:void 0,V=[];if(!Array.isArray(ue))return V;for(let De of ue)if(typeof De=="string")if(De.startsWith("path:")){let Ae=De.slice(5);if(!Jn(Ae))continue;let lt=qe(Y,Ae);if(s==="commit")w.some(rn=>jo(lt,qe(h,rn)))&&V.push({entry:De,granularity:"path",to:x});else if(te!==""&&jo(lt,te))V.push({entry:De,granularity:"path",to:x});else if(s==="dir"&&lt!==te&&(te===""||lt.startsWith(`${te}/`)))for(let rn of U(lt))V.push({entry:De,granularity:"path",to:`file:${rn}`})}else if(De.startsWith("member:"))$.includes(De.slice(7))&&V.push({entry:De,granularity:"member",to:x});else{let Ae=De.match(Zje);Ae&&Ve!==null&&Ae[1].toLowerCase()===Ve&&z.has(Ae[2])?V.push({entry:De,granularity:"issue",to:x}):$e.has(De)&&V.push({entry:De,granularity:"contract",to:`contract:${De}`})}return V};for(let E of c)if(!(!E.records||E.records.loaded.kind.work))for(let O of E.records.views){if(O.id===null)continue;et.set(`${E.records.loaded.kind.name}/${O.id}`,{view:O,kind:E});let D=ke(E,O);if(D.length===0)continue;let Y=Vt(E,O);for(let ue of D)u.push({kind:"constrains",from:Y.id,to:ue.to,granularity:ue.granularity,entry:ue.entry}),(ue.to===x||ue.granularity==="contract")&&Y.constrains.push({entry:ue.entry,granularity:ue.granularity});Y.constrains.length>0&&Ie.push({view:O,kind:E,node:Y})}let We=[...l.values()].filter(E=>E.kind==="decision");for(;We.length>0;){let E=We.shift(),O=[];E.supersededBy&&O.push(`${E.recordKind}/${E.supersededBy}`);for(let[D,{view:Y}]of et)D.startsWith(`${E.recordKind}/`)&&Y.supersededBy===E.record&&O.push(D);for(let D of O){let Y=et.get(D);if(!Y)continue;let ue=ct(Y.kind,Y.view.id);l.has(ue)||We.push(Vt(Y.kind,Y.view))}}let $t=[...l.values()].filter(E=>E.kind==="decision");for(let E of $t)if(E.supersededBy){let O=`record:${E.recordKind}/${E.supersededBy}`;l.has(O)&&u.push({kind:"supersedes",from:O,to:E.id})}let ht=new Map;for(let E of $t){let O=et.get(`${E.recordKind}/${E.record}`),D=O.kind.records.loaded.kind;for(let ue of O.view.assets){let V=ht.get(ue.path)??[];V.push({decision:E,state:ue.state,sha256:ue.sha256,actual:ue.actual}),ht.set(ue.path,V)}let Y=D.pins?O.view.data?.[D.pins.field]:void 0;if(Array.isArray(Y))for(let ue of Y){if(ue===null||typeof ue!="object"||Array.isArray(ue))continue;let V=ue,De=typeof V.sha256=="string"&&Jje.test(V.sha256);if(Jn(V.path)){if(De)continue;let lt=ht.get(V.path)??[];lt.push({decision:E,state:"unpinned",sha256:null,actual:null}),ht.set(V.path,lt),g("intent-evidence-unpinned",`${E.record} names ${V.path} as evidence with no sha256, so a later edit can't be told from what was decided on`,[E.id,`artifact:${V.path}`]);continue}if(typeof V.url!="string")continue;let Ae=f({id:`evidence:${V.url}`,kind:"evidence",ref:V.url,plugin:null,data:{title:mu(V.title),url:V.url,path:null,as_of:mu(V.as_of),sha256:De?V.sha256:null}});u.push({kind:"cites-evidence",from:E.id,to:Ae.id}),De||g("intent-evidence-unpinned",`${E.record} cites ${V.url} with no hash, so what the page said when it was decided can't be checked`,[E.id,Ae.id])}}for(let[E,O]of ht){let D=`artifact:${E}`,ue=[...O.filter(V=>V.decision.supersededBy===null&&V.state!=="unpinned")].sort((V,De)=>ure.indexOf(V.state)-ure.indexOf(De.state))[0];f({id:D,kind:"artifact",path:E,anchor:null,pinnedSha256:ue?.sha256??null,currentSha256:O.find(V=>V.state!=="unpinned")?.actual??null,pinState:ue?.state??"unpinned"});for(let V of O)if(u.push({kind:"pins",from:V.decision.id,to:D,pinnedSha256:V.sha256,pinState:V.state}),V.state==="drifted"&&g("intent-pin-drifted",`${E} changed after ${V.decision.record} pinned it: sha256 ${V.sha256?.slice(0,12)} is pinned, the file hashes to ${V.actual?.slice(0,12)}`,[V.decision.id,D]),V.state==="missing"&&g("intent-pin-missing",`${V.decision.record} pins ${E}, which does not exist${n.tree.label}`,[V.decision.id,D]),V.state==="stale"&&V.decision.supersededBy===null&&V.decision.constrains.length>0){let De=O.find(Ae=>Ae.decision.supersededBy===V.decision.record&&Ae.decision.recordKind===V.decision.recordKind&&Ae.sha256===V.sha256);g("intent-pin-stale",`${E} is pinned by ${V.decision.record} at sha256 ${V.sha256?.slice(0,12)}, the hash ${De?De.decision.record:"the record it supersedes"} pinned, and it has not changed since: the decision moved on and the artifact did not`,[V.decision.id,D,...De?[De.decision.id]:[]])}!ue&&O.some(V=>V.state!=="unpinned")&&g("intent-artifact-unpinned",`${E} was pinned by ${[...new Set(O.map(V=>V.decision.record))].join(", ")}, and no current decision pins it`,[D,...new Set(O.map(V=>V.decision.id))])}for(let E of $t){let O=et.get(`${E.recordKind}/${E.record}`),D=O.kind.records.loaded.kind.constrains?.field,Y=D?O.view.data?.[D]:void 0;if(!Array.isArray(Y))continue;let ue=O.kind.records.workspaceRoot==="."?"":O.kind.records.workspaceRoot;for(let V of Y){if(typeof V!="string"||!V.startsWith("path:"))continue;let De=V.slice(5);if(!Jn(De))continue;let Ae=qe(ue,De),lt=h===""?Ae:Ae.startsWith(`${h}/`)?Ae.slice(h.length+1):void 0;lt!==void 0&&n.tree.stat(lt)===void 0&&g("intent-constraint-lost",`${E.record} constrains ${De}, which does not exist${n.tree.label}`,[E.id])}}let Mn=new Map;if(A)for(let E of Ie){let O=hf(i,A,E.view),D=E.view.supersededBy?et.get(`${E.node.recordKind}/${E.view.supersededBy}`):void 0,Y=D?hf(i,A,D.view):null;Mn.set(E.node.id,{from:O?mo(i,O,A):new Set,until:Y?mo(i,Y,A):null})}let Mt=c.filter(E=>E.records?.loaded.kind.work),nn=Mt.length>0,fn=[],Fn=new Map;for(let E of Mt)for(let O of E.records.views){if(O.id===null)continue;let D={view:O,kind:E};fn.push(D);let Y=`${E.records.loaded.kind.name}/${O.id}`;Fn.has(Y)||Fn.set(Y,D)}let lr=E=>E.kind.records.loaded.kind.work,Xn=E=>{if(E.node)return E.node;let O=E.kind.records.loaded.kind,D=E.view;return E.node=f({id:`record:${O.name}/${D.id}`,kind:"work",recordKind:O.name,record:D.id,path:D.path,title:mu(D.data?.title),state:D.state,closed:D.state!==null&&(O.closedStates??[]).includes(D.state),valid:D.valid,reasons:D.reasons,provenance:{level:D.provenance.level,commit:D.provenance.commit,reason:D.provenance.reason},owner:mu(D.data?.owner),ready:D.ready??!1,blockedBy:D.blockedBy??[],implements:D.implements??[],needs:Gr(D.data,O.work.needs),source:lre(D.data),supersededBy:D.supersededBy,constrains:[],warnings:D.warnings.filter(Y=>OD.includes(Y.code))}),E.node},Zs=E=>{let O=Qy(dG(Mje(E.records.loaded.file),E.records.loaded.kind.work.decisions));return c.find(D=>D.records&&!D.records.loaded.kind.work&&Qy(D.records.loaded.file)===O)},y=E=>{let O=Zs(E.kind);return O?Gr(E.view.data,lr(E).implements).map(D=>et.get(`${O.records.loaded.kind.name}/${D}`)).filter(D=>D!==void 0).map(D=>ct(D.kind,D.view.id)):[]},N=E=>fn.filter(O=>{let D=O.kind.records.loaded.kind;return!(O.view.state!==null&&O.view.state!==D.work.done&&(D.closedStates??[]).includes(O.view.state))&&y(O).includes(E.id)}),K=[];for(let E of fn){let O=ke(E.kind,E.view);if(O.length===0)continue;let D=Xn(E);for(let Y of O)u.push({kind:"constrains",from:D.id,to:Y.to,granularity:Y.granularity,entry:Y.entry}),(Y.to===x||Y.granularity==="contract")&&D.constrains.push({entry:Y.entry,granularity:Y.granularity});D.constrains.length>0&&K.push(E)}let Q=new Map;if(A)for(let E of K){let O=E.kind.records.loaded.kind,D=Zy(i,A,E.view.path),Y=O.stateField?gS(i,A,E.view.path,O.stateField,O.closedStates??[]):null,ue=Y?mo(i,Y,A):null;Y&&ue.delete(Y),Q.set(E.node.id,{from:D?mo(i,D,A):new Set,until:ue})}let H=(E,O)=>{let D=Q.get(E.node.id);return!!D&&D.from.has(O)&&!D.until?.has(O)},S=new Map(c.filter(E=>E.records).map(E=>[E.records.loaded.kind.name,E])),G=E=>{let O=[],D=Y=>{O.some(ue=>ue.node===Y.node)||O.push(Y)};if(E.unit){let ue=(E.unit.kind?Mt.filter(V=>V.records.loaded.kind.name===E.unit.kind):Mt).map(V=>Fn.get(`${V.records.loaded.kind.name}/${E.unit.id}`)).filter(V=>V!==void 0);ue.length===1&&D({node:Xn(ue[0]).id,work:ue[0]})}for(let Y of E.records){let ue=S.get(Y.kind);if(!ue)continue;if(ue.records.loaded.kind.work){let De=Fn.get(`${Y.kind}/${Y.id}`);De&&D({node:Xn(De).id,work:De});continue}let V=et.get(`${Y.kind}/${Y.id}`);V&&D({node:Vt(V.kind,V.view).id,decision:`${Y.kind}/${Y.id}`})}return O};for(let E of q){let O=l.get(`commit:${E.sha}`),D=ne.get(E.sha);if(!O||!D)continue;let Y=V=>{D.carries.includes(V)||(D.carries.push(V),u.push({kind:"carries",from:O.id,to:V}))},ue=V=>{let De=Xn(V);return Y(De.id),D.decisions.push(...y(V).map(Ae=>Ae.slice(7))),De.id};for(let V of[O.joins,...(O.squash?.commits??[]).map(De=>De.joins)]){for(let Ae of V.records){let lt=S.get(Ae.kind);if(!lt)continue;if(lt.records.loaded.kind.work){let kt=Fn.get(`${Ae.kind}/${Ae.id}`);kt&&(Ae.node=ue(kt));continue}let rn=et.get(`${Ae.kind}/${Ae.id}`);rn&&(Ae.node=Vt(rn.kind,rn.view).id,Y(Ae.node),D.decisions.push(`${Ae.kind}/${Ae.id}`))}let De=V.lease?.item;if(De){let Ae=Mt.map(lt=>Fn.get(`${lt.records.loaded.kind.name}/${De}`)).filter(lt=>lt!==void 0);Ae.length===1&&ue(Ae[0])}}for(let V of Ne.refs.get(E.sha)??[]){let De=Ne.runs.get(V.id);if(De)for(let Ae of G(De))Ae.work?ue(Ae.work):Ae.decision&&(Y(Ae.node),D.decisions.push(Ae.decision))}}for(let E of[...l.values()]){if(E.kind!=="run")continue;let O=Ne.runs.get(E.run);if(O)for(let D of G(O))u.push({kind:"worked-on",from:E.id,to:D.node})}for(let E of fn.filter(O=>O.node)){for(let O of y(E)){let D=et.get(O.slice(7));u.push({kind:"implements",from:E.node.id,to:Vt(D.kind,D.view).id})}for(let O of Gr(E.view.data,lr(E).needs)){let D=Fn.get(`${E.kind.records.loaded.kind.name}/${O}`);D&&u.push({kind:"needs",from:E.node.id,to:Xn(D).id})}}let J=(E,O)=>Ie.filter(D=>{if(!D.node.constrains.some(ue=>O.includes(ue.granularity)))return!1;let Y=Mn.get(D.node.id);return!!Y&&Y.from.has(E)&&!Y.until?.has(E)}),ie=c.some(E=>E.records),se=(E,O)=>(!!E.unit||E.carries.length>0)&&(E.decisions.some(D=>D===O.record||D===`${O.recordKind}/${O.record}`)||O.constrains.some(D=>D.granularity==="contract"&&E.contracts.includes(D.entry)));for(let E of q){let O=l.get(`commit:${E.sha}`);if(!O)continue;let D=ne.get(E.sha);if(ie){let ue=J(E.sha,["path"]);for(let V of ue)u.push({kind:"within",from:O.id,to:V.node.id,state:se(D,V.node)?"decided":"decided-by-window"});O.state=ue.length===0?"undecided":ue.some(V=>se(D,V.node))?"decided":"decided-by-window"}for(let ue of K)ue.node.constrains.some(V=>V.granularity==="path")&&H(ue,E.sha)&&u.push({kind:"within",from:O.id,to:ue.node.id,state:"worked"});ie&&O.state==="undecided"&&g("intent-commit-undecided",`${E.sha.slice(0,8)} changed the region when no decision constrained ${R} by path`,[O.id,x]),ie&&!D.unit&&D.carries.length===0&&O.pullRequest===null&&J(E.sha,["path","member","contract","issue"]).length===0&&g("intent-commit-bare",`${E.sha.slice(0,8)} names no unit, no record, no pull request and no decision`,[O.id]);let Y=[...new Set(D.authorship)].filter(ue=>ZD(O.trailers,ue));Y.length>0&&O.signature.level!=="attested"&&g("intent-trailer-unverified",`${E.sha.slice(0,8)} carries ${Y.join(", ")}, and the commit is ${O.signature.level}, so nothing vouches for the trailer`,[O.id])}if(ie){let E=Ie.filter(D=>D.node.supersededBy===null);Ie.length===0?g("intent-region-unconstrained",`no decision constrains ${R}`,[x]):E.length===0?g("intent-decision-superseded-live",`every decision constraining ${R} is superseded: ${Ie.map(D=>`${D.node.record} by ${D.node.supersededBy}`).join(", ")}`,[x,...Ie.map(D=>D.node.id)]):E.every(D=>!D.node.closed)&&g("intent-decision-provisional",`the decisions constraining ${R} are ${[...new Set(E.map(D=>D.node.state??"stateless"))].join(" or ")}, and none is in a closed state`,[x,...E.map(D=>D.node.id)]);for(let D of E){let Y=D.view.quorum?.openConcerns??[];if(Y.length===0)continue;let ue=[...new Set(Y.map(V=>V.principal))];p.push({id:`finding:intent-decision-contested:${p.filter(V=>V.code==="intent-decision-contested").length+1}`,kind:"finding",code:"intent-decision-contested",message:`${D.node.record} constrains ${R} and has ${Y.length} open ${Y.length===1?"concern":"concerns"}, from ${Y.map(V=>V.reviewer).join(", ")}: a dissent neither addressed nor withdrawn`,concerns:[D.node.id,x],openConcerns:{count:Y.length,principals:ue}})}let O=new Set(Ie.flatMap(D=>D.node.constrains.map(Y=>Y.granularity)));Ie.length>0&&!O.has("path")&&O.has("member")&&g("intent-constraint-coarse",`${R} is constrained only through its member, ${$.join(", ")}`,[x,...Ie.map(D=>D.node.id)])}if(nn){for(let E of Ie){if(E.node.supersededBy!==null||!kl(E.kind.records.loaded.kind,E.node.state)||N(E.node).length>0)continue;let O=Mn.get(E.node.id);O&&q.some(D=>O.from.has(D.sha)&&!O.until?.has(D.sha))||g("intent-decision-unimplemented",`${E.node.record} is ${E.node.state} and constrains ${R}, and no work item that is not dropped implements it, and no commit changed the region in its window`,[E.node.id,x])}for(let E of K){let O=E.node;if(O.blockedBy.length===0)continue;let D=q.filter(V=>H(E,V.sha));if(D.length===0)continue;let Y=O.blockedBy.map(V=>`${V.id} (${V.state??"unknown"})`).join(", "),ue=O.blockedBy.map(V=>Fn.get(`${O.recordKind}/${V.id}`)).filter(V=>V!==void 0).map(V=>Xn(V).id);g("intent-work-blocked",`${O.record} has ${D.length} ${D.length===1?"commit":"commits"} in its window while it waits on ${Y}`,[O.id,...D.map(V=>`commit:${V.sha}`),...ue])}for(let E of[...l.values()].filter(O=>O.kind==="decision")){let O=u.filter(Y=>Y.kind==="within"&&Y.to===E.id&&Y.state==="decided").map(Y=>Y.from);if(O.length===0)continue;let D=N(E);D.length===0||D.some(Y=>Y.view.state===lr(Y).done)||g("intent-work-open-decided-code",`${O.length} ${O.length===1?"commit":"commits"} in ${R} ${O.length===1?"is":"are"} ${E.record}'s own work, and ${D.map(Y=>`${Y.view.id} is ${Y.view.state??"stateless"}`).join(", ")}: the code says done and the queue says not`,[E.id,...O,...D.map(Y=>Xn(Y).id)])}}if(k){let E=[];try{let O=_a(r,n.tree),D=Pa(r.pins,n.rootOnDisk).registry,{gatherLexiconOutputs:Y}=await Promise.resolve().then(()=>(are(),sre)),ue=await Y(n.rootOnDisk,r,n.at?Rn(n.rootOnDisk):n.tree,O,D,{atRevision:n.at!==null,...e.loadLexicon?{load:e.loadLexicon}:{}});E=MN(r,i3(r,n.tree,O,D,ue)).filter(V=>V.origin==="declared")}catch(O){if(!(O instanceof xe))throw O}E.forEach((O,D)=>{let Y="producer"in O?O.producer:null;if(O.consumer!==k&&Y!==k)return;let{pointer:ue,...V}=O;f({id:`link:${D+1}`,kind:"link",row:V}),I(O.consumer),Y&&r.members.some(De=>De.name===Y)&&(I(Y),u.push({kind:"links",from:`member:${O.consumer}`,to:`member:${Y}`}))})}p.sort((E,O)=>lG.indexOf(E.code)-lG.indexOf(O.code));let ce=E=>{if(l.has(E))return E;for(let O of["commit","unit","contract","evidence","artifact","file","member"])if(l.has(`${O}:${E}`))return`${O}:${E}`;for(let O of l.values())if(O.kind==="decision"&&(E===O.record||E===`${O.recordKind}/${O.record}`)||O.kind==="commit"&&/^[0-9a-f]{7,}$/.test(E)&&O.sha.startsWith(E))return O.id};for(let{commit:E,plugin:O,finding:D}of ge){let Y=D.code,ue=D.refs??[],V=[...new Set([E,...ue.map(ce).filter(De=>De!==void 0)])];p.push({id:`finding:${Y}:${p.filter(De=>De.code===Y).length+1}`,kind:"finding",code:Y,message:D.message,concerns:V,plugin:O,refs:ue})}if(nn){let E=new Set(["intent-pin-drifted","intent-pin-missing","intent-pin-stale"]),O=(D,Y)=>{let ue=lre(D.view.data);if(ue===null||ue.finding!==Y)return!1;let V=pG(ue.region);if("error"in V)return!1;let De=D.kind.records.workspaceRoot==="."?"":D.kind.records.workspaceRoot,Ae=qe(De,V.path),lt=(rn,kt)=>rn===kt||rn===""||kt.startsWith(`${rn}/`);return s==="commit"?w.some(rn=>lt(Ae,qe(h,rn))||lt(qe(h,rn),Ae)):!lt(Ae,te)&&!lt(te,Ae)?!1:Ae===te&&V.lines&&o.lines?V.lines.start<=o.lines.end&&o.lines.start<=V.lines.end:!0};for(let D of p){let Y=[];for(let ue of fn){let V=O(ue,D.code),De=(E.has(D.code)||ox(D.code))&&y(ue).some(Ae=>D.concerns.includes(Ae));if((V||De)&&Y.push(ue),V&&ue.view.state===lr(ue).done){let Ae=Xn(ue);Ae.warnings.some(lt=>lt.code==="work-done-gap-open")||Ae.warnings.push({code:"work-done-gap-open",message:`${Ae.record} is ${ue.view.state}, and ${D.code}, the gap it came from, still fires on ${R}`})}}D.addressed=Y.length>0,D.addressedBy=Y.map(ue=>({id:ue.view.id,state:ue.view.state}));for(let ue of Y)u.push({kind:"addressed-by",from:D.id,to:Xn(ue).id})}}let ee=[...l.values()].filter(E=>E.kind==="work");if(ee.length>0){let E=new Map(ee.map(O=>[`${O.recordKind}:${O.record}`,O]));for(let O of c){let D=O.records?.loaded.kind;if(D?.session)for(let Y of O.records.views){if(Y.id===null||!Y.data)continue;let ue=new Map,V=(Ae,lt)=>{if(Array.isArray(Ae))for(let rn of Ae){let kt=typeof rn=="string"?E.get(rn):void 0;if(!kt)continue;let Er=ue.get(kt)??[];lt!==null&&!Er.includes(lt)&&Er.push(lt),ue.set(kt,Er)}};V(Y.data.follow_ups,null),(Array.isArray(Y.data.comments)?Y.data.comments:[]).forEach((Ae,lt)=>V(Ae?.follow_ups,lt+1));for(let[Ae,lt]of ue)(Ae.reviews??=[]).push({id:`record:${D.name}/${Y.id}`,recordKind:D.name,record:Y.id,path:Y.path,state:Y.state,comments:lt.sort((rn,kt)=>rn-kt)})}}}for(let E of p)l.set(E.id,E);await eNe([...l.values()].filter(E=>E.kind==="work"),r,n.rootOnDisk,i,n.at);let he=jc(),Oe=[...l.values()],Ge=new Map,ze=new Map;for(let E of fn){let O=E.kind.records.loaded.kind.name;(Ge.get(O)??Ge.set(O,new Set).get(O)).add(E.view.id),E.node&&ze.set(`${O}:${E.view.id}`,E.node.id)}for(let E of Mt)Ge.has(E.records.loaded.kind.name)||Ge.set(E.records.loaded.kind.name,new Set);let He=new Map;for(let E of u){if(E.kind!=="within"||E.state!=="worked")continue;let O=l.get(E.to);if(!O)continue;let D=E.from.slice(7);(He.get(D)??He.set(D,[]).get(D)).push({id:`${O.recordKind}:${O.record}`,node:O.id,path:O.path})}let nt=new Map,wo=await mte({top:i,commits:Oe.filter(E=>E.kind==="commit").map(E=>({id:E.id,sha:E.sha,trailers:E.trailers,joins:E.joins})),work:nn?{index:{kinds:Ge},nodes:ze}:null,windows:He,ledgers:($.length>0?$:r.members.map(E=>E.name)).map(E=>{let O=r.members.find(D=>D.name===E).dir;return{member:E,cwd:Py(n.rootOnDisk,O),within:O==="."?null:`_members/${E}/`}}).concat($.length>0?[]:[{member:null,cwd:n.rootOnDisk,within:null}]),green:r.ci?.green??null,contains:(E,O)=>{if(O===E)return!0;if(!A||!uG.test(O))return!1;let D=nt.get(E);return D||nt.set(E,D=mo(i,E,A)),D.has(O)}});return{doc:{...t,at:n.at,workspace:{name:r.name,root:n.root},region:x,history:{rev:A,follows:o.commit?"commit":o.lines?"line-range":s==="file"?"file":"directory",shallow:B},kinds:c.map(E=>({file:E.display,name:E.name,records:E.records?.loaded.kind.name??null,joins:E.joins?.form??null})),nodes:Oe,edges:u,reasons:d,summary:{commits:Oe.filter(E=>E.kind==="commit").length,decisions:Oe.filter(E=>E.kind==="decision").length,artifacts:Oe.filter(E=>E.kind==="artifact").length,findings:p.length},why:he,trace:wo},failed:d.some(E=>E.code==="intent-plugin-failed")};function jc(){let E=(de,Pe)=>Ne.runs.get(de)?.commits.find(Rt=>Rt.sha===Pe)?.hunks??null,O=(de,Pe)=>(Ne.refs.get(Pe)??[]).find(Rt=>Rt.id===de)?.joinedBy??[],D=(de,Pe)=>{let Rt=new Set(de.flatMap(Et=>Pe.flatMap(Hr=>O(Et,Hr))));return b3.filter(Et=>Rt.has(Et))},Y=new Map,ue=(de,Pe,Rt)=>{let Et=T.get(de);if(!Et?.followed||!Et.head)return{squash:!1,origin:void 0};let Hr=`${de}\0${Pe}`;return Y.has(Hr)||Y.set(Hr,s3(i,de,Et.head,Pe,new Set(Et.commits))),{squash:!0,origin:Y.get(Hr)?.get(Rt)}},V=M.map(de=>{if(de.sha===null)return{line:de.line,sha:null,runs:[],narrowedBy:null,via:void 0};let Pe=de.sha,{squash:Rt,origin:Et}=ue(Pe,de.origPath,de.origLine),Hr=Rt?Et?[Et]:[]:void 0,Mc=(Ne.refs.get(Pe)??[]).filter(Jt=>!Et||Jt.joinedBy.some(ds=>ds!=="squash")||(Jt.via??[]).includes(Et)).map(Jt=>Jt.id),Wn=Mc.filter(Jt=>E(Jt,Pe)!==null);if(Wn.length===0)return{line:de.line,sha:Pe,runs:Mc,narrowedBy:null,via:Hr};let dw=Wn.filter(Jt=>E(Jt,Pe).some(ds=>ds.path===de.origPath&&ds.start<=de.origLine&&de.origLine<=ds.end));return{line:de.line,sha:Pe,runs:dw.length>0?dw:Mc.filter(Jt=>!Wn.includes(Jt)),narrowedBy:"hunks",via:Hr}}),De=[];for(let de of V){let Pe=De[De.length-1],Rt=de.via;if(Pe&&Pe.end===de.line-1&&Pe.sha===de.sha&&Pe.narrowedBy===de.narrowedBy&&Pe.runs.join("\0")===de.runs.map(Et=>`run:${Et}`).join("\0")&&Pe.via?.join("\0")===Rt?.join("\0")){Pe.end=de.line;continue}De.push({start:de.line,end:de.line,commit:de.sha?`commit:${de.sha}`:null,sha:de.sha,runs:de.runs.map(Et=>`run:${Et}`),narrowedBy:de.narrowedBy,joinedBy:de.sha?D(de.runs,[de.sha]):[],...Rt?{via:Rt}:{}})}let Ae=de=>{let Pe=[];for(let Rt of de){let Et=Pe[Pe.length-1];Et&&Et.end===Rt-1?Et.end=Rt:Pe.push({start:Rt,end:Rt})}return Pe},lt=[...l.values()].filter(de=>de.kind==="decision"),rn=de=>V.filter(Pe=>Pe.sha!==null&&se(ne.get(Pe.sha)??{contracts:[],authorship:[],decisions:[],carries:[]},de)).length,kt=["carried","path","contract","issue","member","related"],Er=lt.map(de=>{let Pe=rn(de),Rt=Pe>0||L===null&&q.some(Wn=>se(ne.get(Wn.sha)??{contracts:[],authorship:[],decisions:[],carries:[]},de)),Et=new Set(de.constrains.map(Wn=>Wn.granularity)),Hr=Rt?"carried":["path","contract","issue","member"].find(Wn=>Et.has(Wn))??"related",Mc=Math.max(0,...de.constrains.filter(Wn=>Wn.granularity==="path").map(Wn=>Wn.entry.length));return{d:de,entry:{decision:de.id,relevance:Hr,current:de.supersededBy===null,closed:de.closed,lines:Pe},specificity:Mc}});Er.sort((de,Pe)=>Number(Pe.entry.current)-Number(de.entry.current)||kt.indexOf(de.entry.relevance)-kt.indexOf(Pe.entry.relevance)||Pe.entry.lines-de.entry.lines||Number(Pe.entry.closed)-Number(de.entry.closed)||Pe.specificity-de.specificity||(Pe.d.decidedIn?.date??"").localeCompare(de.d.decidedIn?.date??"")||de.d.id.localeCompare(Pe.d.id));let kf=Er.map(de=>de.entry),Gn=[...l.values()].filter(de=>de.kind==="run"),wu=(de,Pe,Rt)=>{let Et=Ne.runs.get(de.run),Hr=u.filter(Jt=>Jt.kind==="worked-on"&&Jt.from===de.id).map(Jt=>l.get(Jt.to)),Mc=Et?.unit?Hr.find(Jt=>Jt?.kind==="work"&&Jt.record===Et.unit.id):void 0,Wn=new Set;for(let Jt of Hr)if(Jt?.kind==="decision"&&Wn.add(Jt.id),Jt?.kind==="work")for(let ds of u)ds.kind==="implements"&&ds.from===Jt.id&&Wn.add(ds.to);let dw=Rt.map(Jt=>Jt.slice(7));return{run:de.id,lines:Pe,commits:Rt,unit:Et?.unit?{id:Et.unit.id,kind:Et.unit.kind,node:Mc?.id??null}:null,decisions:[...Wn],joinedBy:D([de.run],dw)}},ji;if(L!==null){let de=new Map;for(let Pe of V)for(let Rt of Pe.runs){let Et=de.get(Rt)??de.set(Rt,{lines:0,commits:new Set}).get(Rt);Et.lines++,Et.commits.add(`commit:${Pe.sha}`)}ji=[...de].map(([Pe,Rt])=>({n:l.get(`run:${Pe}`),t:Rt})).filter(Pe=>Pe.n!==void 0).sort((Pe,Rt)=>Rt.t.lines-Pe.t.lines||(Rt.n.startedAt??"").localeCompare(Pe.n.startedAt??"")||Pe.n.run.localeCompare(Rt.n.run)).map(Pe=>wu(Pe.n,Pe.t.lines,[...Pe.t.commits]))}else ji=Gn.sort((de,Pe)=>(Pe.startedAt??"").localeCompare(de.startedAt??"")||de.run.localeCompare(Pe.run)).map(de=>wu(de,0,u.filter(Pe=>Pe.kind==="made-by"&&Pe.to===de.id).map(Pe=>Pe.from)));let Nc=kf.some(de=>de.current&&de.relevance!=="related"),Lc=[];Nc||Lc.push({code:"intent-why-no-decision",message:ie?`no current decision governs ${R}, and none is carried out by what made its lines`:`no record kind was read, so no decision can account for ${R}`});let Vr=V.filter(de=>de.sha!==null);(L!==null?Vr.length>0&&Vr.every(de=>de.runs.length===0):q.length>0&&Gn.length===0)&&Lc.push({code:"intent-why-no-run",message:`no agent run is joined to the commits that made ${L!==null?"the current lines of ":""}${R}`});let bo=V.filter(de=>de.sha===null).map(de=>de.line);bo.length>0&&Lc.push({code:"intent-why-uncommitted",message:`${bo.length} ${bo.length===1?"line is":"lines are"} not committed yet`,lines:Ae(bo)});let Ys=V.filter(de=>de.runs.length>1).map(de=>de.line);return Ys.length>0&&Lc.push({code:"intent-why-run-ambiguous",message:`${Ys.length} ${Ys.length===1?"line comes":"lines come"} from a commit several runs made, and no run's recorded hunks say which wrote ${Ys.length===1?"it":"them"}`,lines:Ae(Ys)}),{lines:L,blame:De,decisions:kf,runs:ji,explained:Nc,gaps:Lc}}}var pre,fre,lG,Fje,Gje,Wje,pn,zje,uG,cG,yre,Jje,Zje,ure,Xje,Ty=v(()=>{"use strict";Tt();cc();CN();Lg();qi();Dp();UN();No();un();Ei();KD();HN();t$();Q1();fee();BR();gte();on();lp();Pl();Wr();Yd();pre=1,fre="https://intentius.io/chant/schemas/workspace/intent/v1/intent.schema.json",lG=["intent-commit-undecided","intent-commit-bare","intent-pin-drifted","intent-pin-missing","intent-pin-stale","intent-artifact-unpinned","intent-decision-superseded-live","intent-decision-provisional","intent-decision-contested","intent-constraint-coarse","intent-constraint-lost","intent-evidence-unpinned","intent-trailer-unverified","intent-region-unconstrained","intent-decision-unimplemented","intent-work-blocked","intent-work-open-decided-code","intent-commit-join-conflict"],Fje=["intent-history-shallow","intent-plugin-failed","squash-unfollowed"],Gje=[...yi,"kind-unreadable","kind-invalid","schema-unreadable","schema-id-mismatch","schema-invalid","location-missing","intent-region-invalid","intent-record-unknown","intent-symbol-unsupported","intent-symbol-unknown","intent-symbol-ambiguous"],Wje=["intent-why-no-decision","intent-why-no-run","intent-why-uncommitted","intent-why-run-ambiguous"],pn=class extends Error{constructor(n,i){super(i);this.code=n;this.name="IntentError"}};zje=/^0+$/;uG=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;yre=e=>cre==="/"?e:e.split(cre).join("/");Jje=/^[0-9a-f]{64}$/,Zje=/^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#([0-9]+)$/,ure=["missing","drifted","stale","pinned"];Xje=/^[0-9a-fA-F]{7,64}$/});var gG={};_e(gG,{RECORDS_SINCE_ERROR_CODES:()=>iNe,RECORDS_SINCE_OUTPUT_SCHEMA_ID:()=>fG,RECORDS_SINCE_REASON_CODES:()=>oNe,SINCE_CHANGE_KINDS:()=>mG,compareRecords:()=>kre,formatSince:()=>dNe,queryRecordsSince:()=>aNe});import{realpathSync as nNe}from"node:fs";import{relative as rNe}from"node:path";async function aNe(e){let t=(n,i)=>({$schema:fG,contract:Ks,error:{code:n,message:i}});try{let n=await lNe(e),i=uNe(e.cwd,n?n.since:e.since,n?.session.id),r=n?n.at??void 0:e.at,o=await ii({kind:e.kind,at:r,cwd:e.cwd}),s;try{s=(await ii({kind:e.kind,at:i,cwd:e.cwd})).result.records}catch(l){if(!(l instanceof Xe)||l.code!=="location-missing")throw l;s=[]}let a=kre(o.loaded.kind,s,o.result.records),c=Object.fromEntries(mG.map(l=>[l,a.filter(u=>u.change===l).length]));return{$schema:fG,contract:Ks,kind:cNe(o.loaded,o.root),since:i,at:o.at,...n?{session:n.session}:{},changes:a,summary:c}}catch(n){if(n instanceof yf||n instanceof Xe)return t(n.code,n.message);throw n}}function cNe(e,t){return{name:e.kind.name,schema:e.kind.schema.id,file:rNe(t,e.file).split("\\").join("/")}}async function lNe(e){let t=cr(Yn(e.cwd));if(!t||!Y5.test(e.since))return null;let n=await ah(e.cwd,[e.kind]);for(let i of n){let r;try{r=(await ii({kind:i.file,cwd:e.cwd})).result.records}catch(p){if(p instanceof Xe)continue;throw p}let o=r.find(p=>p.id===e.since);if(!o)continue;let s=i.kind.session,a=p=>p!==void 0&&typeof o.data?.[p]=="string"?o.data[p]:null,c=o.state!==null&&(i.kind.closedStates??[]).includes(o.state),l={id:o.id,path:o.path,state:o.state,sinceFrom:"opened-rev",atFrom:"working-tree",reasons:[]},u=a(s.openedRev);if(u===null&&(u=Nx(t,o.path,["--diff-filter=A"])[0]??null,l.sinceFrom="history",u===null))throw new yf("since-rev-unknown",`session ${o.id} (${o.path}) names no commit it opened at${s.openedRev?` in ${s.openedRev}`:""}, and no commit added its file`);let d=null;if(e.at!==void 0)d=e.at,l.atFrom="at";else if(c){let p=a(s.closedRev);p!==null&&/^[0-9a-f]{40,64}$/.test(p)?(d=Nx(t,o.path,[`${p}..HEAD`]).slice(-1)[0]??null,l.atFrom=d===null?"working-tree":"close-commit"):(d=Nx(t,o.path,["-1"])[0]??null,l.atFrom=d===null?"working-tree":"history")}else l.reasons.push({code:"since-session-open",message:`session ${o.id} is ${o.state??"not closed"}, so it has no closing revision, and the comparison runs to the working tree`});return{since:u,at:d,session:l}}try{return Ol(t,e.since),null}catch(i){if(!(i instanceof Xe))throw i}if(n.length===0)return null;throw new yf("since-session-unknown",`--since ${e.since} names no commit, and no ${[...new Set(n.map(i=>i.kind.name))].join(" or ")} record has that id`)}function uNe(e,t,n){let i=e;try{i=nNe(e)}catch{}let r=cr(i);if(!r)throw new Xe("not-a-git-repository","--since reads git objects, and this directory is not in a git repository");try{return Ol(r,t)}catch(o){throw o instanceof Xe&&o.code==="revision-unknown"?new yf("since-rev-unknown",n?`session ${n} names ${t}, which is no commit in this repository`:`--since ${t} names no commit in this repository`):o}}function bre(e){let t=new Map;for(let n of e)n.id!==null&&!t.has(n.id)&&t.set(n.id,n);return t}function vre(e,t){let n=e.session?e.session.verdicts:e.reviews?.field??sNe,i=t.data?.[n];if(!Array.isArray(i))return[];let r=s=>typeof s=="string"?s:void 0,o=[];return i.forEach((s,a)=>{if(s===null||typeof s!="object"||Array.isArray(s))return;let c=s,l=r(e.session?c.principal:c.reviewer)??null,u=r(c.verdict)??null,d=r(c.record),p=r(c.session);o.push({key:JSON.stringify([l,u,r(c.on)??null,p??null,d??null]),index:a,principal:l,verdict:u,...d!==void 0?{record:d}:{},...p!==void 0?{session:p}:{}})}),o}function kre(e,t,n){let i=bre(t),r=bre(n),o=[...new Set([...i.keys(),...r.keys()])].sort(),s={new:[],removed:[],state:[],verdict:[],supersession:[],pin:[]};for(let a of o){let c=i.get(a),l=r.get(a);if(!c&&l&&s.new.push({change:"new",id:a,path:l.path,state:l.state}),c&&!l&&s.removed.push({change:"removed",id:a,path:c.path,state:c.state}),!l)continue;c&&c.state!==l.state&&s.state.push({change:"state",id:a,from:c.state,to:l.state});let u=new Map;for(let d of c?vre(e,c):[])u.set(d.key,(u.get(d.key)??0)+1);for(let d of vre(e,l)){let p=u.get(d.key)??0;if(p>0){u.set(d.key,p-1);continue}s.verdict.push({change:"verdict",id:a,principal:d.principal,verdict:d.verdict,index:d.index,...d.record!==void 0?{record:d.record}:{},...d.session!==void 0?{session:d.session}:{}})}if(l.supersededBy!==null&&(!c||c.supersededBy!==l.supersededBy)&&s.supersession.push({change:"supersession",id:l.supersededBy,supersedes:a}),c&&e.pins){let d=new Map(Rg(c.data,e.pins.field).map(f=>[f.path,f.sha256])),p=new Map(Rg(l.data,e.pins.field).map(f=>[f.path,f.sha256]));for(let f of[...new Set([...d.keys(),...p.keys()])].sort()){let g=d.get(f)??null,h=p.get(f)??null;g!==h&&s.pin.push({change:"pin",id:a,path:f,from:g,to:h})}}}return s.supersession.sort((a,c)=>a.id<c.id?-1:a.id>c.id?1:0),mG.flatMap(a=>s[a])}function dNe(e){let t=e.changes.map(i=>{switch(i.change){case"new":return`${i.id} new, ${i.state??"no state"} (${i.path})`;case"removed":return`${i.id} removed, was ${i.state??"no state"} (${i.path})`;case"state":return`${i.id} state ${i.from??"none"} to ${i.to??"none"}`;case"verdict":return`${i.id} verdict ${i.verdict??"-"} by ${i.principal??"-"}${i.record?` on ${i.record}`:""}${i.session?` in ${i.session}`:""}`;case"supersession":return`${i.id} supersedes ${i.supersedes}`;case"pin":return`${i.id} pin ${i.path} ${i.from?i.from.slice(0,12):"none"} to ${i.to?i.to.slice(0,12):"none"}`}}),n=e.summary;if(e.session){let i=e.session;t.unshift(`session ${i.id} (${i.state??"no state"}): opened at ${e.since.slice(0,8)} (${i.sinceFrom}), compared to ${e.at?`${e.at.slice(0,8)} (${i.atFrom})`:"the working tree"}`)}return t.push(`${e.changes.length} changes since ${e.since.slice(0,8)}${e.at?` to ${e.at.slice(0,8)}`:" to the working tree"}: ${n.new} new, ${n.removed} removed, ${n.state} state, ${n.verdict} verdicts, ${n.supersession} supersessions, ${n.pin} pins`),t.join(`
338
- `)}var fG,iNe,oNe,mG,sNe,yf,hG=v(()=>{"use strict";No();Qi();un();Ei();Lx();fG="https://intentius.io/chant/schemas/workspace/records-since/v1/records-since.schema.json",iNe=[...SJ,"since-rev-unknown","since-session-unknown"],oNe=["since-session-open"],mG=["new","removed","state","verdict","supersession","pin"],sNe="reviews",yf=class extends Error{constructor(n,i){super(i);this.code=n}}});var ere={};_e(ere,{AGENT_ROLE:()=>xS,EXIT_BELOW_REQUIRED:()=>wG,RECORDS_CONTRACT_VERSION:()=>Ks,RECORDS_OUTPUT_SCHEMA_ID:()=>rw,belowRequired:()=>bG,declaredKindFiles:()=>Si,pinFile:()=>$re,pinRoot:()=>Bx,queryDeclaredRecords:()=>$S,queryRecords:()=>ew,quorumOptionsFor:()=>gh,quorumShortfall:()=>Wx,readRecordsFor:()=>ii,realpathOr:()=>Yn,runWorkspaceRecords:()=>kNe,runWorkspaceUnknown:()=>SNe,specOf:()=>xre});import{execFileSync as pNe}from"node:child_process";import{readFileSync as fNe,realpathSync as mNe}from"node:fs";import{dirname as nw,join as yG,relative as wf,resolve as kS,sep as tw}from"node:path";function gNe(e){try{return fNe(e,"utf-8")}catch{return null}}function xre(e){let t={kinds:[],records:[]};for(let n of e)if(!("error"in n||!n.kind.spec)){t.kinds.push(n.declared);for(let i of n.records)t.records.push({kind:n.kind.name,id:i.id,path:i.path,state:i.state,valid:i.valid,digest:i.digest,assets:i.assets})}return t}function Si(e,t){let n;try{n=qt(e,t)}catch(i){if(i instanceof xe&&i.code==="declaration-missing")return[];throw i}return yr(_t(n.tree)).map(i=>({declared:i,file:Ri(i,n.rootOnDisk)}))}async function $S(e,t){let n=[];for(let i of e){let r=await ew({...t,kind:i.file});n.push({...r,declared:{member:i.declared.member,path:i.declared.path,name:i.declared.name}})}return{$schema:rw,contract:Ks,kinds:n,...t.current&&!t.uncommitted?{spec:xre(n)}:{}}}function hNe(e){try{let t=_t(e).quorum;if(t!==null)return{need:t,needFrom:"declaration"}}catch{}return{need:AJ,needFrom:"default"}}async function gh(e,t,n){if(!e.kind.reviews)return;let{checkVerdictSeal:i}=await Promise.resolve().then(()=>(Op(),Ep));return{...hNe(t),agents:new Set((n.roles[xS]??[]).map(An)),attestation:n.active,verifySeal:r=>i(n,r)}}function Wx(e){let t=e.notCounted.length>0?` (not counted: ${e.notCounted.map(n=>`${n.reviewer}, ${n.reason.code}`).join("; ")})`:"";return`its quorum needs ${e.need} agreeing verdicts that count, and it has ${e.agreed}${t}`}function Bx(e,t){let n=tr(nw(e));if(!n)return".";let i=wf(t,Yn(n.dir)).split(tw).join("/");return i===""||i.startsWith("..")?".":i}function yNe(e,t,n){let i=r=>{try{return pNe("git",r,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).split(`
339
- `).filter(Boolean).map(Number)}catch{return[]}};return{fileChanged:r=>i(["log","-1","--format=%ct",t,"--",n==="."?r:`${n}/${r}`])[0]??null,recorded:r=>i(["log","--diff-filter=A","--format=%ct",t,"--",r])[0]??null}}async function ii(e){let t=Yn(e.cwd),n=cr(t),i=n??t,r=await Ht(e.kind,t),o=Bx(r.file,i),s=null,a=ip(i),c=Rn(o==="."?i:yG(i,...o.split("/")));if(e.at!==void 0){if(!n)throw new Xe("not-a-git-repository","--at reads git objects, and this directory is not in a git repository");s=Ol(n,e.at),a=xi(n,s),c=cd(n,s,o==="."?"":o)}s===null&&e.overlay&&(a=await e.overlay(a,{loaded:r,root:i}));let l=n?yNe(n,s??"HEAD",o):void 0,u=await Hk(r,i,a),d=await Mo(r,{root:i,source:a,current:!!e.current,assets:c,workspaceRoot:o,...l?{history:l}:{},...u?{subjects:u}:{}});return{loaded:r,root:i,top:n,at:s,workspaceRoot:o,tree:c,result:d}}async function ew(e){if(e.uncommitted&&e.at!==void 0)throw new Error("--uncommitted reads the working tree and takes no --at");try{let t,{loaded:n,root:i,top:r,at:o,workspaceRoot:s,tree:a,result:c}=await ii({...e,overlay:async($,{loaded:x,root:R})=>{if(!x.kind.answers)return $;let{readLedgerAnswers:P,refreshLedger:I,withLedgerAnswers:A}=await Promise.resolve().then(()=>(wh(),vN));e.fetchLedger&&await I(x.file);let B=await P({file:x.file,name:x.kind.name,dirRel:wf(R,x.dir).split(tw).join("/")||"."});return t=new Map([...B.byPath.values()].map(C=>[C.path,C.ledger])),A($,B)}}),l=r?ti(r,e.base):{commit:null,from:null},u=r?$i(r,l):$i(i,l),d=u.active?await jg():[],p=tZ({repo:r,policy:u,at:o,paths:c.records.map($=>$.path),attestors:d,...u.active?{revisit:await wNe(a,s,u,d)}:{}}),f=n.kind.reviews?await Promise.resolve().then(()=>(Op(),Ep)):void 0,g=await gh(n,a,u),h=[];for(let $ of c.records){let x=p.get($.path),R=x.returned?Xk(u,x.returned.id):u,P=x.returned?await gh(n,a,R):g,I=P?Kk(n.kind,$,P):null,A=n.kind.reviews?.ratified;I&&!I.met&&A!==void 0&&$.state===A&&$.warnings.push({code:"record-ratified-below-quorum",message:`${$.id??$.path} is ${A}, and ${Wx(I)}`}),h.push({...$,provenance:x,...P?{quorum:I}:{},...f?bNe(n.kind,$,R,f.checkRecordSeal):{}})}if(t)for(let $ of h)$.ledger=t.get($.path)??null;if(n.kind.approval&&!n.kind.work&&r){let $=W5(r,o??"HEAD",h.map(x=>x.path),n.kind);for(let x of h)x.decidedIn=$.get(x.path)??null}if(n.kind.work&&e.workGaps!==!1&&r&&await vNe(n,h,{root:i,workspaceRoot:s,at:e.at}),n.kind.work&&o===null&&r){let{activeWorkLeases:$}=await Promise.resolve().then(()=>(Bl(),F9)),x=await $(n.file);for(let R of h)R.id!==null&&(R.lease=x.get(R.id)??null)}if(n.kind.work?.answers){let[{workAnswers:$},{readLedgerAnswers:x,withLedgerAnswers:R}]=await Promise.all([Promise.resolve().then(()=>(Yd(),AD)),Promise.resolve().then(()=>(wh(),vN))]),P=await ii({kind:kS(nw(n.file),n.kind.work.answers),cwd:e.cwd,...e.at!==void 0?{at:e.at}:{},overlay:async(I,{loaded:A,root:B})=>R(I,await x({file:A.file,name:A.kind.name,dirRel:wf(B,A.dir).split(tw).join("/")||"."}))}).catch(I=>{if(!(I instanceof Xe))throw I});if(P){let I=$(P.result.records,h.flatMap(A=>A.id!==null?[A.id]:[]));for(let A of h)A.id!==null&&(A.answers=I.get(A.id)??[])}}let w,b=h,k=c.summary;if(o===null&&r){let{head:$,...x}=tN(r,e.base),R=wf(i,n.dir).split(tw).join("/")||".",P=h.filter(C=>!C.ledger),{states:I,deleted:A}=V5(r,$,R,h.map(C=>C.path),new RegExp(n.kind.location.match));for(let C of P)C.worktree=I.get(C.path)??"new";let B=Tx(r);for(let C of P)C.lastWrite=B(C.path,gNe(yG(r,...C.path.split("/"))));w={branch:x.branch,head:$,base:x.base,baseFrom:x.baseFrom,deleted:A},e.uncommitted&&(b=P.filter(C=>C.worktree!=="committed"),k={...k,total:b.length,valid:b.filter(C=>C.valid).length,invalid:b.filter(C=>!C.valid).length})}else if(e.uncommitted&&!r)throw new Xe("not-a-git-repository","--uncommitted compares the working tree with HEAD, and this directory is not in a git repository");return{$schema:rw,contract:Ks,kind:{name:n.kind.name,schema:n.kind.schema.id,file:wf(i,n.file).split("\\").join("/"),format:n.kind.format,spec:n.kind.spec===!0},at:o,workspaceRoot:s,current:!!e.current,uncommitted:!!e.uncommitted,...w?{checkout:w}:{},trust:{base:l.commit,baseFrom:l.from,active:u.active,signersPath:u.signersPath,problems:u.problems},records:b,summary:k,...c.decisions?{decisions:c.decisions}:{}}}catch(t){if(!(t instanceof Xe))throw t;return{$schema:rw,contract:Ks,error:{code:t.code,message:t.message}}}}async function wNe(e,t,n,i){let{readReturns:r,returnedProvenance:o}=await Promise.resolve().then(()=>(X9(),Y9)),{returns:s}=r(e);if(s.length===0)return;let a=t==="."?"":`${t}/`;return(c,l)=>{if(!c.startsWith(a))return;let u=c.slice(a.length),d=s.filter(f=>f.paths[u]!==void 0);if(d.length===0||e.stat(u)!=="file")return;let p=Buffer.from(e.bytes?e.bytes(u):e.read(u));for(let f of d){let g=o(n,i,f,u,p,l);if(g)return g}}}function bNe(e,t,n,i){if(t.data===null)return{};let r=e.reviews.decider,o=typeof t.data[r]=="string"&&t.data[r].trim()!==""?t.data[r]:null,{attested:s,...a}=i(n,{record:t.id,digest:t.digest,author:o,authorField:r,state:t.state,seal:t.data[wn]});return n.active&&o!==null&&s!==!0&&t.warnings.push({code:"record-unattested",message:`an attestation policy is active at base, and ${a.message}`}),{attested:s,attestation:a}}async function vNe(e,t,n){let i=e.kind.work,r=new Map;for(let u of t){if(u.id===null||u.state!==i.done)continue;let d=u.data?.source;if(d===null||typeof d!="object"||Array.isArray(d))continue;let{finding:p,region:f}=d;typeof p!="string"||typeof f!="string"||r.set(f,[...r.get(f)??[],u])}if(r.size===0)return;let o=n.workspaceRoot==="."?n.root:yG(n.root,...n.workspaceRoot.split("/")),s;try{s=Si(o,n.at).map(u=>u.file)}catch(u){if(u instanceof xe)return;throw u}let a=[],c=new Set;for(let u of[...s,kS(nw(e.file),i.decisions),e.file]){let d=Yn(u);c.has(d)||(c.add(d),a.push(u))}let{intentGraph:l}=await Promise.resolve().then(()=>(Ty(),wre));for(let[u,d]of r){let{doc:p}=await l({cwd:o,region:u,at:n.at,kinds:a});if(!("error"in p))for(let f of d){let g=p.nodes.find(w=>w.kind==="work"&&w.id===`record:${e.kind.name}/${f.id}`),h=g?.kind==="work"?g.warnings.find(w=>w.code==="work-done-gap-open"):void 0;h&&!f.warnings.some(w=>w.code===h.code)&&f.warnings.push(h)}}}function $re(e,t,n){let i=Yn(kS(t,e)),r=n===void 0?nw(i):nw(kS(t,n)),o=n===void 0?tr(t)??tr(r):tr(r),s=cr(r),a=Yn(o?o.dir:s||t),c=wf(a,i).split(tw).join("/");if(c.startsWith("..")||!Jn(c))return{error:`${e} is not a file path inside the workspace at ${a}`};let l=$D(Rn(a),c);return l===void 0?{error:`${e} is not a file`}:{path:c,sha256:l}}async function kNe(e){let{args:t}=e;if(t.extraPositional==="new"||t.extraPositional==="amend"||t.extraPositional==="review"||t.extraPositional==="close")return(await Promise.resolve().then(()=>(dh(),$9))).runRecordsWrite(e);if(t.extraPositional==="pin"){if(!t.extraPositional2)return console.error(we({message:"pin needs the path of a file",hint:Ur})),1;let r=$re(t.extraPositional2,process.cwd(),t.kind);return"error"in r?(console.error(we({message:r.error,hint:Ur})),1):(console.log(JSON.stringify(r,null,2)),0)}if(t.extraPositional)return console.error(we({message:`chant workspace records takes no argument but pin, new, amend, review or close (got ${t.extraPositional})`,hint:Ur})),1;let n=RNe(t);if(n)return console.error(we({message:n,hint:Ur})),1;if(!t.kind)return xNe(t);if(t.require!==void 0&&t.require!=="attested")return console.error(we({message:`--require takes one level, attested, not ${JSON.stringify(t.require)}`,hint:Ur})),1;if(t.since!==void 0){if(t.current||t.require!==void 0||t.base!==void 0)return console.error(we({message:"--since compares two revisions and takes no --current, --require or --base",hint:Ur})),1;let{formatSince:r,queryRecordsSince:o}=await Promise.resolve().then(()=>(hG(),gG)),s=await o({kind:t.kind,since:t.since,at:t.at,cwd:process.cwd()});return t.json?console.log(JSON.stringify(s,null,2)):"error"in s?console.error(we({message:`${s.error.code}: ${s.error.message}`,hint:Ur})):console.log(r(s)),"error"in s?1:0}let i=await ew({kind:t.kind,current:t.current,uncommitted:t.uncommitted,at:t.at,base:t.base,cwd:process.cwd(),fetchLedger:!0});if(t.json?console.log(JSON.stringify(i,null,2)):"error"in i?console.error(we({message:`${i.error.code}: ${i.error.message}`,hint:Ur})):console.log(Rre(i.records,i.summary,i.at,i.checkout)),"error"in i)return 1;if(t.require){let r=bG(i.records,t.require);if(r.length>0)return console.error(we({message:`${r.length} of ${i.records.length} records are not ${t.require}: ${r.slice(0,5).map(o=>`${o.path} (${o.provenance.level})`).join(", ")}${r.length>5?", ...":""}`,hint:i.trust.active?"run with --json to see each record's reason":`there is no signers file (${i.trust.signersPath}) at base`})),wG}return 0}async function xNe(e){if(e.require!==void 0&&e.require!=="attested")return console.error(we({message:`--require takes one level, attested, not ${JSON.stringify(e.require)}`,hint:Ur})),1;let t;try{t=Si(process.cwd(),e.at)}catch(i){if(!(i instanceof xe))throw i;let r=`${i.describe()}; without --kind, the declaration names the record kinds`;return e.json&&(i.code==="not-a-git-repository"||i.code==="revision-unknown")?console.log(JSON.stringify({$schema:rw,contract:Ks,error:{code:i.code,message:r}},null,2)):console.error(we({message:`${i.code}: ${r}`,hint:Ur})),1}if(t.length===0)return console.error(we({message:"--kind <kind file> is required",hint:Ur})),1;if(e.since!==void 0)return $Ne(t,e);let n=await $S(t,{current:e.current,uncommitted:e.uncommitted,at:e.at,base:e.base,cwd:process.cwd(),fetchLedger:!0});e.json&&console.log(JSON.stringify(n,null,2));for(let i of e.json?[]:n.kinds){if("error"in i){console.error(we({message:`${i.declared.path}: ${i.error.code}: ${i.error.message}`,hint:Ur}));continue}console.log(`${i.declared.name??i.kind.name} (${i.declared.path})`),console.log(Rre(i.records,i.summary,i.at,i.checkout))}if(n.kinds.some(i=>"error"in i))return 1;if(e.require){let i=n.kinds.filter(s=>!("error"in s)),r=i.flatMap(s=>s.records),o=bG(r,e.require);if(o.length>0){let s=i.find(a=>!a.trust.active);return console.error(we({message:`${o.length} of ${r.length} records are not ${e.require}: ${o.slice(0,5).map(a=>`${a.path} (${a.provenance.level})`).join(", ")}${o.length>5?", ...":""}`,hint:s?`there is no signers file (${s.trust.signersPath}) at base`:"run with --json to see each record's reason"})),wG}}return 0}async function $Ne(e,t){if(t.current||t.require!==void 0||t.base!==void 0)return console.error(we({message:"--since compares two revisions and takes no --current, --require or --base",hint:Ur})),1;let{formatSince:n,queryRecordsSince:i,RECORDS_SINCE_OUTPUT_SCHEMA_ID:r}=await Promise.resolve().then(()=>(hG(),gG)),o=[];for(let s of e){let a=await i({kind:s.file,since:t.since,at:t.at,cwd:process.cwd()});o.push({...a,declared:{member:s.declared.member,path:s.declared.path,name:s.declared.name}})}t.json&&console.log(JSON.stringify({$schema:r,contract:Ks,kinds:o},null,2));for(let s of t.json?[]:o){if("error"in s){console.error(we({message:`${s.declared.path}: ${s.error.code}: ${s.error.message}`,hint:Ur}));continue}console.log(`${s.declared.name??s.kind.name} (${s.declared.path})`),console.log(n(s))}return o.some(s=>"error"in s)?1:0}function Yn(e){try{return mNe(e)}catch{return e}}function bG(e,t){return e.filter(n=>n.provenance.level!==t)}function RNe(e){if(e.uncommitted){if(e.at!==void 0)return"--uncommitted reads the working tree against HEAD, and takes no --at";if(e.since!==void 0)return"--uncommitted takes no --since: --since compares two revisions"}}function Rre(e,t,n,i){let r=[],o=Math.max(2,...e.map(a=>(a.id??"-").length)),s=Math.max(5,...e.map(a=>(a.state??"-").length));for(let a of e){let c=typeof a.data?.title=="string"?a.data.title:a.path,l=a.valid?"":" INVALID",u=a.supersededBy?` superseded by ${a.supersededBy}`:"",d=a.remediatedBy.length>0?` remediated by ${a.remediatedBy.join(", ")}`:"",p=a.provenance.level==="attested"?` attested by ${a.provenance.principal}`:"",f=a.attested===!0?` sealed by ${(a.data?.[wn]).signer}`:"",g=a.worktree==="new"||a.worktree==="modified"?` (${a.worktree}, uncommitted)`:"",h=a.ledger?` (held on ${a.ledger})`:"";if(r.push(`${(a.id??"-").padEnd(o)} ${(a.state??"-").padEnd(s)} ${c}${u}${d}${p}${f}${g}${h}${l}`),a.ready!==void 0){let b=(a.blockedBy??[]).map(R=>`${R.id} (${R.state??"unknown"})`).join(", "),k=(a.implements??[]).map(R=>`${R.id} (${R.state??"unknown"})`).join(", "),$=a.lease?`held by ${a.lease.holder} until ${a.lease.expiresAt}`:"",x=[a.ready?"ready":b?`blocked by ${b}`:"",k?`implements ${k}`:"",$].filter(Boolean).join("; ");x&&r.push(`${" ".repeat(o+2)}${x}`)}for(let b of a.reasons)r.push(`${" ".repeat(o+2)}${b.code}: ${b.message} (${a.path})`);for(let b of a.warnings)r.push(`${" ".repeat(o+2)}warning ${b.code}: ${b.message} (${a.path})`);let w=a.quorum;if(w&&w.counted.length+w.notCounted.length>0){let b=w.metWithObjections?"met with objections":w.met?"met":"not met",k=w.openConcerns.length>0?`, ${w.openConcerns.length} open ${w.openConcerns.length===1?"concern":"concerns"}`:"";r.push(`${" ".repeat(o+2)}quorum ${w.agreed} of ${w.need} agreed, ${b}; ${w.notCounted.length} not counted${k}`)}}for(let a of i?.deleted??[])r.push(`${"-".padEnd(o)} ${"-".padEnd(s)} ${a} (deleted, uncommitted)`);if(r.push(`${t.total} records${n?` at ${n.slice(0,8)}`:""}: ${t.valid} valid, ${t.invalid} invalid, ${t.superseded} superseded`),i){let a=i.branch??"a detached HEAD",c=i.head?` at ${i.head.slice(0,8)}`:" with no commits",l=i.base?`, forked from ${i.base.slice(0,8)} of ${i.baseFrom}`:"";r.push(`working tree on ${a}${c}${l}`)}return r.join(`
340
- `)}async function SNe(e){let t=e.args.path&&e.args.path!=="."?e.args.path:"";return console.error(we({message:t?`Unknown workspace subcommand: ${t}`:"chant workspace needs a subcommand",hint:'Workspace subcommands: adopt-lineage, audit, build, check, evidence, graph, hash-index, init, lineage, lint, ls, pin, records, signers, status, upgrade, verify, versions, work. Run "chant --help" for their options.'})),1}var Ks,rw,Ur,wG,xS,Ei=v(()=>{"use strict";ur();Mi();No();B5();Qi();Tt();cc();Wr();un();nN();oh();on();lp();Pl();Go();Ks=1,rw="https://intentius.io/chant/schemas/workspace/records/v1/records.schema.json",Ur="chant workspace records [--kind <kind file>] [--current] [--uncommitted | --at <rev>] [--base <rev>] [--require attested] [--json] | chant workspace records [--kind <kind file>] --since <rev|session id> [--at <rev>] [--json] | chant workspace records pin <path> [--kind <kind file>] | chant workspace records new|amend|review|close (#2670, #2693)",wG=2,xS="agent"});var OG={};_e(OG,{POINTS_WRITE_CONTRACT_VERSION:()=>go,POINTS_WRITE_ERROR_CODES:()=>ONe,POINTS_WRITE_SCHEMA_ID:()=>ho,PointsWriteError:()=>wt,STEWARD_HARNESS:()=>vG,answerFields:()=>bf,answerKindFiles:()=>kG,answerPoint:()=>RG,askPoint:()=>xG,askedByOf:()=>SS,questionView:()=>gu,reasonFields:()=>OS,retractAnswer:()=>SG,tallyQuorum:()=>Ore,withdrawQuestion:()=>EG});import{writeFileSync as ENe}from"node:fs";function ANe(e){if(!Array.isArray(e.retractions))return[];let t=i=>typeof i=="string"?i:null,n=i=>Array.isArray(i)?i.filter(r=>typeof r=="string"):[];return e.retractions.filter(i=>i!==null&&typeof i=="object"&&!Array.isArray(i)).map(i=>({answer:typeof i.answer=="string"||typeof i.answer=="boolean"?i.answer:null,decider:i.decider!==null&&typeof i.decider=="object"&&!Array.isArray(i.decider)?i.decider:{},answeredBy:n(i.answered_by),answeredOn:t(i.answered_on),answerNote:t(i.answer_note),answerRelayedBy:t(i.answer_relayed_by),by:n(i.by),on:t(i.on),note:t(i.note)}))}function PNe(e){let t=e.withdrawn;if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t;return{by:Array.isArray(n.by)?n.by.filter(i=>typeof i=="string"):[],on:typeof n.on=="string"?n.on:null,note:typeof n.note=="string"?n.note:null}}function SS(e){let t=e.source;if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t;if(n.harness!==vG)return null;let i=n.client,r=i&&typeof i.name=="string"?i.name:null;if(r===null)return null;let o=n.session,s=typeof o=="string"?o:o&&typeof o=="object"&&typeof o.id=="string"?o.id:null;return{steward:r,run:s}}function gu(e,t,n=null){let i=e.data;if(i===null||e.id===null)return null;let r=f=>typeof f=="string"?f:null,o=f=>typeof f=="number"?f:null,s=["escalated","proposed","answered"].find(f=>f===e.state)??"escalated",a=i.decider!==null&&typeof i.decider=="object"&&!Array.isArray(i.decider)?i.decider:{},c=Array.isArray(i.escalations)?i.escalations:[],l=typeof i.answer=="string"||typeof i.answer=="boolean"?i.answer:null,u=null;if(a.kind==="model")u={answer:l,confidence:o(i.confidence),threshold:o(i.threshold),model:r(a.model),backend:r(a.backend),observed:!0,reason:r(i.reason)};else{let f=[...c].reverse().find(g=>g.kind==="model"&&g.answer!==void 0&&g.answer!==null);f&&(u={answer:f.answer??null,confidence:f.confidence??null,threshold:f.threshold??null,model:f.model??null,backend:f.backend??null,observed:!1,reason:typeof f.model_reason=="string"?f.model_reason:null})}let d=Array.isArray(i.constrains)?i.constrains.filter(f=>typeof f=="string"):[],p=PNe(i);return{id:e.id,path:e.path,point:r(i.point)??"",title:r(i.title)??"",subject:d[0]??null,state:s,open:s!=="answered"&&p===null,questionType:r(i.question_type)??"",candidates:Array.isArray(i.candidates)?i.candidates:[],inputs:i.inputs!==null&&typeof i.inputs=="object"&&!Array.isArray(i.inputs)?i.inputs:{},inputsHash:r(i.inputs_hash)??"",pointVersion:r(i.point_version)??"",current:t?za(t)===i.point_version:null,answer:l,decider:a,probabilities:i.probabilities!==null&&typeof i.probabilities=="object"?i.probabilities:null,confidence:o(i.confidence),threshold:o(i.threshold),reason:a.kind==="model"?r(i.reason):null,model:u,escalations:c,answeredBy:Array.isArray(i.answered_by)?i.answered_by.filter(f=>typeof f=="string"):[],askedOn:r(i.asked_on),answeredOn:r(i.answered_on),note:r(i.note),relayedBy:r(i.relayed_by),retractions:ANe(i),withdrawn:p,asked:ep(i)??null,askedBy:SS(i),ledger:n,valid:e.valid,warnings:e.warnings}}function Tc(e,t){if(t instanceof wt||t instanceof Ee||t instanceof Xe||t instanceof As||t instanceof sc)return{$schema:ho,contract:go,verb:e,error:{code:t.code,message:t.message}};if(t instanceof xe)return{$schema:ho,contract:go,verb:e,error:{code:"points-undeclared",message:`the declaration can't be read: ${t.code}: ${t.message}`}};throw t}async function kG(e,t){if(t!==void 0)return[Cp(t,e)];let n=[];for(let i of Si(e))try{(await Ht(i.file)).kind.answers&&n.push(i.file)}catch(r){if(!(r instanceof Xe))throw r}return n}async function Sre(e,t){let n=await Ts(e,t);if(!n.loaded.kind.answers)throw new wt("points-undeclared",`the ${n.loaded.kind.name} kind has no answers block, so it holds no answers to decision points`);let i=np(n.loaded,n.root),r=rp(n.source,i);if("error"in r)throw new wt("points-invalid",r.error);return{o:n,points:r.points,pointsFile:i}}function iw(e,t,n,i,r){let o=n==="withdrawn"?"withdrawn":n==="escalated"?"open for people":n==="proposed"?`${_c(i,e.question.type)}, proposed`:_c(i,e.question.type);return`${r?r.question:e.title}${t?` (${t})`:""}: ${o}`}function ow(e,t,n){let i=Qd(e,n),r=s=>i.type==="score"?"":i.criteria?.[String(s)]??"",o=Fo(i).map(s=>`- ${_c(s,i.type)}${r(s)?`: ${r(s)}`:""}`);return["",`# ${t}`,"",i.instructions.trim(),"",...o,""].join(`
341
- `)}async function CNe(e,t,n){if(e.length===0)throw new wt("points-undeclared","no record kind with an answers block is declared: name one with --kind, or declare one in chant.workspace.json");let i=[];for(let r of e){let o=await Sre(r,n),s=Rl(o.points,t);if(s)return{...o,point:s};i.push(...Object.keys(o.points))}throw new wt("point-unknown",`no points file declares ${JSON.stringify(t)}${i.length?` (the points are ${i.join(", ")})`:""}`)}function _Ne(e,t,n,i){if(!t.adhoc){if(n!==void 0)throw new wt("point-candidates-invalid",`${e} declares its candidates, so the ask gives none: --candidates is for an ad-hoc point`);return}if(n===void 0)throw new wt("point-candidates-invalid",`${e} is an ad-hoc point, so each ask gives the question and its candidates: --candidates <file|-|json>`);let r=ID(t,n);if("problems"in r)throw new wt("point-candidates-invalid",`the candidates for ${e}, a ${t.question.type} question: ${r.problems.join("; ")}`);if(!bf(i.schema).asked)throw new wt("answer-field-unsupported",`the ${i.kind.name} kind's schema has no asked field, so an ad-hoc question's text and candidates can't be kept: copy point-answer.schema.json from @intentius/chant anew`);return r.asked}function TNe(e,t,n){if(n===null||typeof n!="object"||Array.isArray(n))throw new wt("point-inputs-invalid",`the inputs to ${e} must be a JSON object`);let i=Object.keys(t.inputs),r=Object.keys(n).filter(o=>!i.includes(o));if(r.length>0)throw new wt("point-inputs-invalid",`${e} reads ${i.join(", ")}, and the inputs also give ${r.join(", ")}`);return n}async function sw(e,t,n,i,r,o,s){let a=await Gx(e,t,n,i,s.source),c=s.ledger.byPath.get(n);if(s.onLedger){if(o)return{warnings:a,ledger:c?.ledger??null};try{let{ledger:l}=await bN(s.ledger,n,i,s.message,c?.sha??null);return{warnings:a,ledger:l}}catch(l){throw l instanceof Ot?new wt("record-id-taken",`${n} was written on chant/lifecycle by another ask or answer at the same time: ask again to read it`):l}}if(!o)try{ENe(Jo(e,n),i,r?{flag:"wx"}:void 0),Cs(e.root,[{path:n,text:i}],s.who)}catch(l){throw l.code==="EEXIST"?new wt("record-id-taken",`${n} was written by another ask at the same time: ask again to read it`):l}return{warnings:a,ledger:null}}async function Ere(e){let t=await hh({file:e.loaded.file,name:e.loaded.kind.name,dirRel:e.dirRel}),n=yh(e.source,t);return{ledger:t,source:n,before:await ro(e,n)}}function aw(e,t){let n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0));return pc(n,Tp(n,{properties:e.loaded.schema.properties}))}function OS(e){let t=(i,r)=>i!==null&&typeof i=="object"&&Object.prototype.hasOwnProperty.call(i,r),n=e.definitions??e.$defs;return{top:t(e.properties,"reason"),escalation:t(n?.escalation?.properties,"model_reason")}}function INe(e,t){return t.escalation?e:e.map(({model_reason:n,...i})=>i)}function DNe(e,t){let n=e.escalations.length>0?INe(e.escalations,t):void 0;if(e.status==="proposed"){let i=t.top?e.reason:void 0;return{state:"proposed",answer:e.answer,decider:e.decider,probabilities:e.probabilities,confidence:e.confidence,threshold:e.threshold,reason:i,escalations:n}}return e.status==="answered"?{state:"answered",answer:e.answer,decider:e.decider,escalations:n}:{state:"escalated",decider:e.decider,escalations:n}}async function xG(e){try{return await no(e.cwd,{verb:"points ask",by:e.steward?.name??null},e.dryRun,()=>jNe(e))}catch(t){return Tc("ask",t)}}async function jNe(e){try{let t=e.steward?void 0:Ho(),n=e.steward??(t?{name:t.steward,...t.run?{run:t.run}:{}}:void 0),i=e.store!==void 0?e.store==="ledger":n!==void 0,r=await kG(e.cwd,e.kind),{o,point:s}=await CNe(r,e.point,e.cwd),a=TNe(e.point,s,e.inputs),c=_Ne(e.point,s,e.candidates,o.loaded),l=za(s),u=TD(e.point,l,a,c),d=DD(e.point,u);i&&!e.dryRun&&await zx(o.loaded.file);let{ledger:p,source:f,before:g}=await Ere(o),h=g.find(be=>be.id===d),w=be=>p.byPath.get(be.path)?.ledger??null,b=(be,Be)=>({$schema:ho,contract:go,verb:"ask",kind:o.view,id:d,path:be.path,reused:Be.reused,written:Be.written,dryRun:!!e.dryRun,question:gu(be,s,Be.ledger!==void 0?Be.ledger:w(be)),...Be.text!==void 0?{text:Be.text}:{}}),k=async be=>{let{withdrawn:Be,...dt}=be.data,ne=Array.isArray(dt.constrains)&&typeof dt.constrains[0]=="string"?dt.constrains[0]:void 0,ye=iw(s,ne,String(dt.state),dt.answer,c),ge=aw(o,{...dt,title:ye}),oe=Is(ge,ow(s,ye,c)),Se=`Decision point ${e.point}: asked again${ne?` (${ne})`:""}`,Ne=await sw(o,g,be.path,oe,!1,!!e.dryRun,{source:f,ledger:p,onLedger:i||p.byPath.has(be.path),message:Se,who:{verb:"points ask",by:n?.name??null}});return b({...be,data:ge,valid:!0,reasons:[],warnings:Ne.warnings},{reused:!1,written:!e.dryRun,ledger:Ne.ledger,...e.dryRun?{text:oe}:{}})},$=h!==void 0&&h.data!==null&&h.data.withdrawn!==void 0;if(h&&h.data!==null&&!$&&(h.state==="answered"||h.state==="proposed"))return b(h,{reused:!0,written:!1});if(h&&h.data!==null&&Array.isArray(h.data.retractions)&&h.data.retractions.length>0)return $?k(h):b(h,{reused:!0,written:!1});let x;try{x=await jD(e.point,{...s,question:Qd(s,c)},a,e.ask)}catch(be){throw be instanceof Xd?new wt("point-decider-failed",be.message):be}if(h&&h.data!==null&&!$&&x.status==="escalated")return b(h,{reused:!0,written:!1});let R=e.on??ES(),P=x.status,I=x.status==="escalated"?void 0:x.answer,A=iw(s,e.subject,P,I,c),B=x.status==="proposed"?x.decider.model:void 0,C=n?{name:n.name}:e.client,q={via:e.via??"cli",...n?{harness:vG}:{},...C?{client:C}:{},...B?{model:B}:{},...n?.run?{session:{id:n.run}}:{}},L=aw(o,{id:d,title:A,point:e.point,point_version:l,question_type:s.question.type,candidates:Fo(Qd(s,c)),asked:c,inputs:a,inputs_hash:u,constrains:e.subject!==void 0?[e.subject]:h?.data?.constrains,...DNe(x,OS(o.loaded.schema)),asked_on:R,answered_on:P==="answered"?R:void 0,source:q}),M=h?h.path:o.dirRel==="."?`${d}.md`:`${o.dirRel}/${d}.md`,_=Is(L,ow(s,A,c)),T=i||p.byPath.has(M),W=`Decision point ${e.point}: ${P}${e.subject?` (${e.subject})`:""}${n?`, asked by ${n.name}`:""}`,ve=await sw(o,g,M,_,!h,!!e.dryRun,{source:f,ledger:p,onLedger:T,message:W,who:{verb:"points ask",by:n?.name??null}}),re={...h??NNe(M),id:d,path:M,state:P,data:L,valid:!0,reasons:[],warnings:ve.warnings};return b(re,{reused:!1,written:!e.dryRun,ledger:ve.ledger,...e.dryRun?{text:_}:{}})}catch(t){return Tc("ask",t)}}function NNe(e){return{id:null,path:e,state:null,valid:!0,reasons:[],supersededBy:null,remediatedBy:[],data:null,assets:[],warnings:[],digest:""}}function bf(e){let t=e.properties,n=i=>t!=null&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,i);return{note:n("note"),retractions:n("retractions"),relayedBy:n("relayed_by"),asked:n("asked"),withdrawn:n("withdrawn")}}function LNe(e){if(!cr(e))return eo(null);try{return $i(e,ti(e))}catch{return eo(null)}}function Ore(e,t,n,i){let r=u=>new Set((n.roles[u]??[]).map(An)),o=r(xS),s=i!==void 0?An(i):void 0,a=[],c=new Set,l=[];for(let u of e){let d=An(u);if(!(d===""||c.has(d))){if(c.add(d),s!==void 0&&d===s){l.push({name:u,why:"is the steward that asked"});continue}if(o.has(d)){l.push({name:u,why:"holds the agent role"});continue}if(t.roles&&!t.roles.some(p=>r(p).has(d))){l.push({name:u,why:`holds none of the roles ${t.roles.join(", ")}`});continue}a.push(u)}}return{counted:a,left:l,met:a.length>=t.count}}function Are(e,t){let n=Ho();if(n)throw new wt("answer-in-steward-turn",`this is the steward ${n.steward}'s turn, and a steward never ${t} a decision point: a person ${t==="answers"?"answers":"retracts the answer to"} ${e} through hud or \`chant workspace points ${t==="answers"?"answer":"retract"}\` at a shell`)}async function $G(e,t,n){let i=await kG(e,t);if(i.length===0)throw new wt("points-undeclared","no record kind with an answers block is declared: name one with --kind, or declare one in chant.workspace.json");for(let r of i){let o=await Sre(r,e);await zx(o.o.loaded.file);let s=await Ere(o.o),a=s.before.find(c=>c.id===n);if(a&&a.data!==null)return{opened:o,before:s.before,read:s,target:a}}throw new wt("record-not-found",`no answer record has id ${n}`)}function Cre(e,t,n,i,r,o,s){let a=di(s),c=a?{counted:[],left:t.map(l=>({name:l,why:`was named over ${Pre(s)}, where an answer is an agent's`})),met:!1}:Ore(t,n,LNe(i),r);if(!c.met){let l=c.counted.length,u=c.left.length?`; not counted: ${c.left.map(p=>`${p.name}, who ${p.why}`).join("; ")}`:"",d=a?`: a person ${o==="answer"?"answers":"retracts it"} at a shell with \`chant workspace points ${o}\`, or through hud`:"";throw new wt("quorum-not-met",`${e} needs ${n.count} ${n.count===1?"person":"people"}${n.roles?` holding ${n.roles.join(" or ")}`:""} to ${o==="answer"?"answer":"retract an answer"}, and ${l} ${l===1?"counts":"count"}${l?` (${c.counted.join(", ")})`:""}${u}${d}`)}return c}function MNe(e){let t=[];for(let n of Array.isArray(e.constrains)?e.constrains:[]){if(typeof n!="string"||!n.startsWith("gate:"))continue;let i=n.slice(5),r=i.lastIndexOf("@"),o=r>0?i.slice(0,r):i,s=o.indexOf("/");s>0&&s<o.length-1&&t.push({op:o.slice(0,s),gate:o.slice(s+1)})}return t}async function _re(e,t,n,i,r){if(!di(i))return;let o=MNe(t);if(o.length===0)return;let{isNeverOverMcpGateOp:s}=await Promise.resolve().then(()=>(Yr(),TV)),{readGateLedger:a}=await Promise.resolve().then(()=>(Mr(),UI)),c;for(let{op:l,gate:u}of o){let d=s(l);if(!d){let{pending:p}=await a(l,{cwd:n}).catch(()=>({pending:[]}));d=p.some(f=>f.gate===u&&f.neverOverMcp===!0)}if(!d){if(c===void 0){let{discoverOps:p}=await Promise.resolve().then(()=>(qo(),qj));c=await p({cwd:n}).then(f=>f.ops).catch(()=>new Map)}d=!!c.get(l)?.config.neverOverMcp}if(d)throw new wt("answer-never-over-mcp",`${e} constrains gate "${u}" on "${l}", which is never resolved over ${Pre(i)}, so its question is not ${r==="answers"?"answered":"retracted"} there either: a person ${r==="answers"?"answers":"retracts the answer to"} it at a shell with \`chant workspace points ${r==="answers"?"answer":"retract"} ${e}\`, or through hud`)}}async function RG(e){try{return await no(e.cwd,{verb:"points answer",by:(e.by??[]).join(", ")||null},e.dryRun,()=>FNe(e))}catch(t){return Tc("answer",t)}}async function FNe(e){try{Are(e.id,"answers"),zo(to(e.cwd),e.by,"--by");let t=RS(e.relayedBy);t!==void 0&&zo(to(e.cwd),[t],"--relayed-by");let n=await $G(e.cwd,e.kind,e.id),{opened:i,before:r,target:o}=n,s=n.read.ledger,{o:a}=i,c=o.data;if(o.state==="answered")throw new wt("record-closed",`${e.id} is answered, and an answer never changes in place: retract it with \`points retract ${e.id}\` and answer again, ask again with other inputs, or change the point, which asks the question anew`);if(c.withdrawn!==void 0)throw new wt("record-closed",`${e.id} was withdrawn, so nobody answers it: ask it again with \`points ask\`, which opens it again, when it applies again`);let l=RS(e.note);if(l!==void 0&&!bf(a.loaded.schema).note)throw new wt("answer-field-unsupported",`the ${a.loaded.kind.name} kind's schema has no note field, so ${e.id} can't keep the note: copy point-answer.schema.json from @intentius/chant anew`);if(t!==void 0&&!bf(a.loaded.schema).relayedBy)throw new wt("answer-field-unsupported",`the ${a.loaded.kind.name} kind's schema has no relayed_by field, so ${e.id} can't record who relayed the answer: copy point-answer.schema.json from @intentius/chant anew`);let u=String(c.point),d=Rl(i.points,u);if(!d)throw new wt("point-unknown",`${e.id} answers ${u}, which ${i.pointsFile} no longer declares`);let p=ep(c),f=p?Fo(Qd(d,p)):Array.isArray(c.candidates)?c.candidates:Fo(d.question),g=String(c.question_type),h=g==="noul"&&typeof e.answer=="string"?{true:!0,yes:!0,false:!1,no:!1}[e.answer.toLowerCase()]:e.answer;if(h===void 0||!f.includes(h))throw new wt("answer-not-candidate",`${e.id} takes one of ${f.map(T=>JSON.stringify(T)).join(", ")}, not ${JSON.stringify(e.answer)}`);let w=e.origin??bs();await _re(e.id,c,a.root,w,"answers");let b=tp(d),k=Cre(u,e.by,b,a.root,SS(c)?.steward,"answer",w),$=e.on??ES(),x=c.decider,R=o.state==="proposed"&&x.kind==="model"&&c.answer===h,P=Array.isArray(c.escalations)?[...c.escalations]:[],I;R?I={...c,state:"answered",answered_by:k.counted,answered_on:$,note:l,relayed_by:t}:(o.state==="proposed"&&x.kind==="model"&&P.push({kind:"model",backend:String(x.backend),model:String(x.model),answer:c.answer,...c.probabilities?{probabilities:c.probabilities}:{},...typeof c.confidence=="number"?{confidence:c.confidence}:{},...typeof c.threshold=="number"?{threshold:c.threshold}:{},reason:`proposed ${_c(c.answer,g)}, and people answered ${_c(h,g)}`,...typeof c.reason=="string"&&OS(a.loaded.schema).escalation?{model_reason:c.reason}:{}}),I={...Object.fromEntries(Object.entries(c).filter(([W])=>W!=="probabilities"&&W!=="confidence"&&W!=="threshold"&&W!=="reason")),state:"answered",answer:h,decider:{kind:"quorum",count:b.count,...b.roles?{roles:b.roles}:{},by:k.counted},escalations:P.length>0?P:void 0,answered_by:k.counted,answered_on:$,note:l,relayed_by:t});let A=Array.isArray(c.constrains)&&typeof c.constrains[0]=="string"?c.constrains[0]:void 0;I.title=iw(d,A,"answered",h,p);let B=aw(a,I),C=Is(B,ow(d,String(I.title),p)),q=s.byPath.has(o.path),L=`Decision point ${u}: answered ${_c(h,g)} by ${k.counted.join(", ")}${t?`, relayed by ${t}`:""}`,M=await sw(a,r,o.path,C,!1,!!e.dryRun,{source:n.read.source,ledger:s,onLedger:q,message:L,who:{verb:"points answer",by:k.counted.join(", ")}}),_={...o,state:"answered",data:B,valid:!0,reasons:[],warnings:M.warnings};return{$schema:ho,contract:go,verb:"answer",kind:a.view,id:e.id,path:o.path,reused:!1,written:!e.dryRun,dryRun:!!e.dryRun,question:gu(_,d,q?M.ledger??s.byPath.get(o.path)?.ledger??null:null),...e.dryRun?{text:C}:{}}}catch(t){return Tc("answer",t)}}async function SG(e){try{return await no(e.cwd,{verb:"points retract",by:(e.by??[]).join(", ")||null},e.dryRun,()=>GNe(e))}catch(t){return Tc("retract",t)}}async function GNe(e){try{Are(e.id,"retracts"),zo(to(e.cwd),e.by,"--by");let t=await $G(e.cwd,e.kind,e.id),{opened:n,before:i,target:r}=t,o=t.read.ledger,{o:s}=n,a=r.data;if(r.state!=="answered")throw new wt("answer-not-answered",`${e.id} is ${r.state??"not answered"}, so there is no answer to retract: answer it with \`points answer ${e.id}\``);if(!bf(s.loaded.schema).retractions)throw new wt("answer-field-unsupported",`the ${s.loaded.kind.name} kind's schema has no retractions field, so ${e.id} can't keep the answer it would retract: copy point-answer.schema.json from @intentius/chant anew`);let c=String(a.point),l=Rl(n.points,c);if(!l)throw new wt("point-unknown",`${e.id} answers ${c}, which ${n.pointsFile} no longer declares, so no quorum can take the answer back: ask the point as it is declared now`);let u=e.origin??bs();await _re(e.id,a,s.root,u,"retracts");let d=tp(l),p=Cre(c,e.by,d,s.root,SS(a)?.steward,"retract",u),f=e.on??ES(),g=String(a.question_type),h=a.decider!==null&&typeof a.decider=="object"&&!Array.isArray(a.decider)?a.decider:{kind:"quorum"},w=a.answer,b=RS(e.note),k={answer:w,decider:h,answered_by:Array.isArray(a.answered_by)&&a.answered_by.length>0?a.answered_by:void 0,answered_on:typeof a.answered_on=="string"?a.answered_on:void 0,answer_note:typeof a.note=="string"?a.note:void 0,answer_relayed_by:typeof a.relayed_by=="string"?a.relayed_by:void 0,by:p.counted,on:f,note:b},$=Array.isArray(a.escalations)?[...a.escalations]:[];h.kind==="model"&&$.push({kind:"model",backend:String(h.backend),model:String(h.model),answer:w,...a.probabilities?{probabilities:a.probabilities}:{},...typeof a.confidence=="number"?{confidence:a.confidence}:{},...typeof a.threshold=="number"?{threshold:a.threshold}:{},reason:`proposed ${_c(w,g)}, which people confirmed and then retracted`,...typeof a.reason=="string"&&OS(s.loaded.schema).escalation?{model_reason:a.reason}:{}});let x=new Set(["answer","answered_by","answered_on","note","relayed_by","probabilities","confidence","threshold","reason"]),R=Object.fromEntries(Object.entries(a).filter(([W])=>!x.has(W))),P=Array.isArray(a.retractions)?a.retractions:[],I=Array.isArray(a.constrains)&&typeof a.constrains[0]=="string"?a.constrains[0]:void 0,A=ep(a),B=iw(l,I,"escalated",void 0,A),C=aw(s,{...R,title:B,state:"escalated",decider:{kind:"quorum",count:d.count,...d.roles?{roles:d.roles}:{}},escalations:$.length>0?$:void 0,retractions:[...P,Object.fromEntries(Object.entries(k).filter(([,W])=>W!==void 0))]}),q=Is(C,ow(l,B,A)),L=o.byPath.has(r.path),M=`Decision point ${c}: ${_c(w,g)} retracted by ${p.counted.join(", ")}`,_=await sw(s,i,r.path,q,!1,!!e.dryRun,{source:t.read.source,ledger:o,onLedger:L,message:M,who:{verb:"points retract",by:p.counted.join(", ")}}),T={...r,state:"escalated",data:C,valid:!0,reasons:[],warnings:_.warnings};return{$schema:ho,contract:go,verb:"retract",kind:s.view,id:e.id,path:r.path,reused:!1,written:!e.dryRun,dryRun:!!e.dryRun,question:gu(T,l,L?_.ledger??o.byPath.get(r.path)?.ledger??null:null),...e.dryRun?{text:q}:{}}}catch(t){return Tc("retract",t)}}async function EG(e){try{return await no(e.cwd,{verb:"points withdraw",by:(e.by??[]).join(", ")||null},e.dryRun,()=>WNe(e))}catch(t){return Tc("withdraw",t)}}async function WNe(e){try{let t=[...new Set((e.by??[]).map(P=>P.trim()).filter(P=>P!==""))];if(t.length===0)throw new wt("write-usage-invalid","--by <name> is required: who withdraws the question");zo(to(e.cwd),t,"--by");let n=await $G(e.cwd,e.kind,e.id),{opened:i,before:r,target:o}=n,s=n.read.ledger,{o:a}=i,c=o.data;if(o.state==="answered")throw new wt("record-closed",`${e.id} is answered, so it is not withdrawn: people take the answer back with \`points retract ${e.id}\``);if(c.withdrawn!==void 0)throw new wt("record-closed",`${e.id} is withdrawn already`);if(!bf(a.loaded.schema).withdrawn)throw new wt("answer-field-unsupported",`the ${a.loaded.kind.name} kind's schema has no withdrawn field, so ${e.id} can't record that it no longer applies: copy point-answer.schema.json from @intentius/chant anew`);let l=String(c.point),u=Rl(i.points,l);if(!u)throw new wt("point-unknown",`${e.id} asks ${l}, which ${i.pointsFile} no longer declares`);let d=e.on??ES(),p=RS(e.note),f=Array.isArray(c.constrains)&&typeof c.constrains[0]=="string"?c.constrains[0]:void 0,g=ep(c),h=iw(u,f,"withdrawn",void 0,g),w=aw(a,{...c,title:h,withdrawn:Object.fromEntries(Object.entries({by:t,on:d,note:p}).filter(([,P])=>P!==void 0))}),b=Is(w,ow(u,h,g)),k=s.byPath.has(o.path),$=`Decision point ${l}: withdrawn by ${t.join(", ")}${f?` (${f})`:""}`,x=await sw(a,r,o.path,b,!1,!!e.dryRun,{source:n.read.source,ledger:s,onLedger:k,message:$,who:{verb:"points withdraw",by:t.join(", ")}}),R={...o,data:w,valid:!0,reasons:[],warnings:x.warnings};return{$schema:ho,contract:go,verb:"withdraw",kind:a.view,id:e.id,path:o.path,reused:!1,written:!e.dryRun,dryRun:!!e.dryRun,question:gu(R,u,k?x.ledger??s.byPath.get(o.path)?.ledger??null:null),...e.dryRun?{text:b}:{}}}catch(t){return Tc("withdraw",t)}}var go,ho,ONe,wt,vG,ES,_c,RS,Pre,AS=v(()=>{"use strict";oh();Qi();un();Ei();dh();Ag();Tt();Pl();Go();Ei();jl();Tl();Bo();Pt();wh();el();go=1,ho="https://intentius.io/chant/schemas/workspace/points-write/v1/points-write.schema.json",ONe=[...lc,"write-usage-invalid","write-input-invalid","points-undeclared","points-invalid","point-unknown","point-inputs-invalid","point-decider-failed","answer-not-candidate","quorum-not-met","record-not-found","record-closed","record-id-taken","answer-in-steward-turn","answer-never-over-mcp","principal-unidentified","answer-not-answered","answer-field-unsupported","point-candidates-invalid",...ac,...Ua],wt=class extends Error{constructor(n,i){super(i);this.code=n;this.name="PointsWriteError"}};vG="chant-steward";ES=()=>new Date().toISOString().slice(0,10),_c=(e,t)=>t==="noul"?e?"yes":"no":String(e);RS=e=>{let t=e?.trim();return t||void 0};Pre=e=>e==="acp"?"ACP":"MCP"});function cf(e){return!!e&&typeof e=="object"&&e[Dre]===!0&&"question"in e}async function BNe(e,t){if(e.capabilities!==void 0)return{capabilities:e.capabilities,vault:e.vault??null};let{discoverStewards:n}=await Promise.resolve().then(()=>(qo(),qj)),i=(await n({cwd:t})).stewards.get(e.steward)?.declaration;return{capabilities:i?.capabilities??[],vault:i?.vault??null}}async function FR(e,t){let n=t.capability??KQ,i={capability:n,broker:t.broker??null},r=t.turn===void 0?Ho():t.turn;if(!r)return a=>e(a,i);let{capabilities:o,vault:s}=await BNe(r,t.cwd);if(!o.includes(n)){let a=s!==null?`the steward ${r.steward} holds the vault ${s} and names no brokered capabilities, and a steward's model call goes through the broker`:`the steward ${r.steward} does not name the brokered capability ${n}`+(o.length?` (it names ${o.join(", ")})`:"")+", and a steward holds no credential of its own";return async()=>{throw new Error(a)}}return a=>e(a,i)}async function z1(e){let t=e.turn===void 0?Ho():e.turn,n=e.ask?await FR(e.ask,{capability:e.capability,broker:e.broker,turn:t,cwd:e.cwd}):void 0,{askPoint:i}=await Promise.resolve().then(()=>(AS(),OG)),r=await i({cwd:e.cwd,point:e.point,inputs:e.inputs,...e.subject!==void 0?{subject:e.subject}:{},...e.kind!==void 0?{kind:e.kind}:{},...n?{ask:n}:{},...e.on!==void 0?{on:e.on}:{},...e.store!==void 0?{store:e.store}:{},...t?{steward:{name:t.steward,...t.run?{run:t.run}:{}}}:{}});if("error"in r)throw new Error(`decision point ${e.point}: ${r.error.code}: ${r.error.message}`);let o=r.question;if(o.state==="answered"&&o.answer!==null)return{answer:o.answer,question:o};throw new MR({id:o.id,point:o.point,state:o.state==="proposed"?"proposed":"escalated",path:o.path,subject:o.subject,steward:o.askedBy?.steward??null})}var KQ,Dre,Tre,Ire,MR,Ey=v(()=>{"use strict";jl();KQ="inference",Dre=Symbol.for("chant.op.PointWait"),MR=class extends(Ire=Error,Tre=Dre,Ire){constructor(n){super(`waiting on decision point ${n.point} (${n.id}, ${n.state}): a person answers it through hud or \`chant workspace points answer ${n.id}\``);this.question=n;this[Tre]=!0;this.name="PointWait"}}});function AG(e,t,n){return async(i,r,o)=>{let s=`${zNe(e)}${r}`,a=await n(s,{method:i,headers:{...t,...o!==void 0?{"Content-Type":"application/json"}:{}},...o!==void 0?{body:JSON.stringify(o)}:{}}),c=await a.text();if(!a.ok)throw new tc(i,s,a.status,c);if(!c)return null;try{return JSON.parse(c)}catch{return c}}}async function PG(e,t){let n=t.fetch??globalThis.fetch,i=e.url?{url:e.url}:{},r=g=>({status:"skipped",forge:e.forge,reason:g,...i}),o=g=>({status:"would-resume",forge:e.forge,how:`would ${g}`,...i});if(e.forge==="github"){let g=AG(e.api,{Authorization:`Bearer ${t.token}`,Accept:"application/vnd.github+json"},n),h=`/repos/${e.repo}/actions/runs/${e.run}`,w=await g("GET",h);if(!Js(w))throw new Error(`GET ${h} returned no run`);if(w.status!=="completed")return r(`run ${e.run} is ${String(w.status)}, not finished`);let b=typeof w.run_attempt=="number"?w.run_attempt:void 0;return e.attempt!==void 0&&b!==void 0&&b>e.attempt?r(`run ${e.run} was already re-run (attempt ${b}; attempt ${e.attempt} waited)`):w.conclusion==="success"?r(`run ${e.run} succeeded`):t.dryRun?o(`re-run the failed jobs of run ${e.run}`):(await g("POST",`${h}/rerun-failed-jobs`,{}),{status:"resumed",forge:"github",how:`re-ran the failed jobs of run ${e.run}`,...i})}if(e.forge==="gitlab"){let g=AG(e.api,{"PRIVATE-TOKEN":t.token},n),h=`/projects/${encodeURIComponent(decodeURIComponent(e.repo))}`,w=await g("GET",`${h}/jobs/${e.job}`);if(!Js(w))throw new Error(`GET ${h}/jobs/${e.job} returned no job`);let b=String(w.status);if(b==="success")return r(`job ${e.job} succeeded`);if(!["failed","canceled","skipped"].includes(b))return r(`job ${e.job} is ${b}, not finished`);let k=e.jobName??(typeof w.name=="string"?w.name:void 0);if(k){let R=await g("GET",`${h}/pipelines/${e.run}/jobs?per_page=100`),P=Array.isArray(R)?R.find(I=>Js(I)&&I.name===k):void 0;if(Js(P)&&String(P.id)!==String(e.job))return r(`job ${e.job} (${k}) was already retried as job ${String(P.id)}`)}if(t.dryRun)return o(`retry job ${e.job}`);let $=await g("POST",`${h}/jobs/${e.job}/retry`),x=Js($)&&$.id!==void 0?` as job ${String($.id)}`:"";return{status:"resumed",forge:"gitlab",how:`retried job ${e.job}${x}`,...i}}let s=AG(e.api,{Authorization:`token ${t.token}`,Accept:"application/json"},n),a=`/repos/${e.repo}`,c=await s("GET",`${a}/actions/runs/${e.run}`);if(!Js(c))throw new Error(`GET ${a}/actions/runs/${e.run} returned no run`);let l=String(c.status);if(l==="success")return r(`run ${e.run} succeeded`);if(["waiting","running","blocked","unknown"].includes(l))return r(`run ${e.run} is ${l}, not finished`);let u=await s("GET",`${a}/actions/runs?workflow_id=${encodeURIComponent(e.workflow)}&limit=50`),d=Js(u)&&Array.isArray(u.workflow_runs)?u.workflow_runs:Array.isArray(u)?u:[],p=t.since?Math.floor(new Date(t.since).getTime()/1e3)*1e3:void 0,f=d.find(g=>Js(g)&&Number(g.id)>Number(e.run)&&(g.prettyref===void 0||g.prettyref===e.ref)&&(p===void 0||typeof g.created=="string"&&new Date(g.created).getTime()>=p));return Js(f)?r(`run ${String(f.id)} of ${e.workflow} started after the approval`):t.dryRun?o(`dispatch ${e.workflow} on ${e.ref}`):(await s("POST",`${a}/actions/workflows/${encodeURIComponent(e.workflow)}/dispatches`,{ref:e.ref}),{status:"resumed",forge:"forgejo",how:`dispatched ${e.workflow} on ${e.ref}`,...i})}function CG(e,t=process.env){return t.CHANT_FORGE_TOKEN?t.CHANT_FORGE_TOKEN:e==="gitlab"?t.GITLAB_TOKEN:t.GITHUB_TOKEN??t.GH_TOKEN}var zNe,Js,jre=v(()=>{"use strict";Ej();Ga();zNe=e=>e.replace(/\/+$/,""),Js=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function _G(e,t,n=[t]){let i=t.environment,r=e.filter(o=>i===void 0||o.environment===i);if(t.approval){let o=Ya(r,t.gate,t.timestamp,t.planDigest,t.approval,Qa(n,t));return o.permit?o.permit:o.counted.length>=o.need?o.counted[o.counted.length-1]:void 0}return Qr(r,t.gate,t.timestamp,t.planDigest).resolution}var Nre=v(()=>{"use strict";Mr();Uo();jre()});var jG={};_e(jG,{readAppliedGateFile:()=>Mre,resumeAfterAnswer:()=>HNe,resumeAfterApproval:()=>VNe,resumeCandidate:()=>TG,resumeOpGates:()=>PS,resumeStanding:()=>UNe,resumeWaitingGates:()=>Fre,runResumeCommand:()=>DG,workspaceQuestions:()=>Lre});async function Lre(e){let{workspacePoints:t}=await Promise.resolve().then(()=>(cw(),_S)),n=await t({cwd:e}).catch(()=>{});return!n||!("questions"in n)?new Map:new Map(n.questions.map(i=>[i.id,{id:i.id,state:i.state,answer:i.answer,answeredBy:i.answeredBy,answeredOn:i.answeredOn}]))}async function UNe(e,t,n={},i=[e]){let[r]=LR({op:e.op,pending:[e],resolutions:t,applied:n.applied??[],now:e.timestamp,...n.questions?{questions:n.questions}:{},answering:(o,s)=>_G(o,s,i)});return TG(r,n)}async function TG(e,t={}){let n={op:e.op,gate:e.gate,...e.environment!==void 0?{environment:e.environment}:{},source:e.source,status:"not-approved",reason:e.reason,resumable:e.resumable,message:e.message,...e.planDigest!==void 0?{planDigest:e.planDigest}:{},...e.approvedBy!==void 0?{approvedBy:e.approvedBy}:{},...e.approvedAt!==void 0?{approvedAt:e.approvedAt}:{},...e.run?.url?{url:e.run.url}:{},...e.run?{run:e.run}:{},...e.spent?{spent:e.spent}:{},...e.stopped?{stopped:{...e.stopped}}:{}};if(e.reason==="spent")return{...n,status:"spent"};if(!e.resumable)return n;if(!e.run)return{...n,status:"no-job",message:"its pending fact names no CI job (it was recorded outside CI); run it again by hand"};let i=e.source==="stopped",r=CG(e.run.forge,t.env??process.env);if(t.dryRun&&!i)return{...n,status:"would-resume",message:`would resume ${e.run.forge} run ${e.run.run}; ${e.message}`};if(!r){let o=`${e.run.forge==="gitlab"?"GITLAB_TOKEN":"GITHUB_TOKEN"}`;return{...n,...i?{resumable:!1}:{},status:"no-token",message:i?`${e.message}; whether run ${e.run.run} is gone needs a token to read ${e.run.forge} with: set CHANT_FORGE_TOKEN (or ${o})`:`no token to call ${e.run.forge} with: set CHANT_FORGE_TOKEN (or ${o})`}}try{let o=i?e.stopped.appliedAt:e.approvedAt,s=await PG(e.run,{token:r,...o?{since:o}:{},...t.fetch?{fetch:t.fetch}:{},...t.dryRun?{dryRun:!0}:{}}),a=s.status==="skipped"?s.reason:s.how;if(!i)return{...n,status:s.status,message:a};let c=s.status!=="skipped";return{...n,status:s.status,resumable:c,message:c?`the apply that began at ${e.stopped.appliedAt} stopped and its run is gone: ${a}`:`the apply that began at ${e.stopped.appliedAt} is left alone: ${a}`,stopped:{...e.stopped,runGone:c}}}catch(o){return{...n,status:"failed",message:o instanceof Error?o.message:String(o)}}}async function Mre(e){let{dir:t,file:n}=yl(e),i=await At(t,n);return i?z4(i):{applied:[],finished:[]}}async function PS(e,t,n={}){let i=await Kn(e),r=n.applied?{applied:n.applied,finished:n.finished??[]}:await Mre(e),o=n.now??new Date().toISOString(),s=n.questions??(i.pending.some(l=>l.answer)?await Lre(process.cwd()):void 0),a=LR({op:e,pending:i.pending,resolutions:i.resolutions,applied:r.applied,finished:r.finished,now:o,...t!==void 0?{gate:t}:{},...s?{questions:s}:{},answering:_G}),c=[];for(let l of a)c.push(await TG(l,n));return c}function IG(e){let t=`${e.op} / ${e.gate}${e.environment!==void 0?` (${e.environment})`:""}`,n=e.approvedBy?`, approved by ${e.approvedBy}`:"",i=e.url?` ${e.url}`:"";e.status==="resumed"?console.error(xf(`${t}${n}: ${e.message}${i}`)):e.status==="would-resume"?console.error(Qn(`${t}${n}: ${e.message}${i}`)):e.status==="failed"||e.status==="no-token"?console.error(we({message:`${t}${n}: not resumed: ${e.message}`,hint:"GitHub needs actions: write; GitLab a token with the api scope and the Developer role; Forgejo a token with write:repository."})):console.error(Qn(`${t}${n}: not resumed: ${e.message}${i}`))}async function VNe(e,t,n,i){if(!i)return console.error(si({message:"Not resuming: the approval did not reach the remote, so the resumed job would not see it.",hint:"Push chant/lifecycle, then run `chant run resume --op "+e+"`."})),1;let r=(await PS(e,t)).filter(o=>n===void 0||o.environment===n);if(r.length===0)return console.error(Qn(`No pending fact for ${e} / ${t} is waiting, so there is nothing to resume.`)),0;for(let o of r)IG(o);return r.some(o=>o.status==="failed"||o.status==="no-token")?1:0}async function HNe(e,t=process.cwd()){let n=hx(e.subject);if(!n)return console.error(Qn(`Question ${e.id} names no gate in its subject, so there is nothing to resume.`)),0;if(e.ledger===null)return console.error(si({message:`Not resuming: the answer to ${e.id} is in the working tree, and the resumed job would not see it.`,hint:`Commit and push it, then run \`chant run resume --op ${n.op}\`.`})),1;if((await Ta({cwd:t})).status!=="pushed")return console.error(si({message:"Not resuming: the answer did not reach the remote, so the resumed job would not see it.",hint:`Push chant/lifecycle, then run \`chant run resume --op ${n.op}\`.`})),1;let i=(await PS(n.op,n.gate)).filter(r=>r.environment===void 0);if(i.length===0)return console.error(Qn(`No pending fact for ${n.op} / ${n.gate} is waiting, so there is nothing to resume.`)),0;for(let r of i)IG(r);return i.some(r=>r.status==="failed"||r.status==="no-token")?1:0}async function Fre(e={}){let{op:t,gate:n,...i}=e,r=t?[t]:(await Zi(Ak)).filter(s=>s.endsWith(".jsonl")).map(s=>s.slice(0,-6)),o=[];for(let s of r)o.push(...await PS(s,n,i));return o}async function DG(e){try{await Lr()}catch(i){return console.error(we({message:`Cannot read the gate ledgers: ${i instanceof Error?i.message:String(i)}`})),1}let t=e.args.dryRun===!0,n=await Fre({...e.args.op?{op:e.args.op}:{},...e.args.gate?{gate:e.args.gate}:{},dryRun:t});if(e.args.json)console.log(JSON.stringify({dryRun:t,reports:n},null,2));else{for(let o of n.filter(s=>s.status!=="not-approved"))IG(o);let i=n.filter(o=>o.status==="not-approved").length,r=t?`${n.filter(o=>o.resumable).length} would resume`:`${n.filter(o=>o.status==="resumed").length} resumed`;console.error(Qn(`${r}, ${i} still waiting for an approval or a passing answer.`))}return n.some(i=>i.status==="failed"||!t&&i.status==="no-token")?1:0}var CS=v(()=>{"use strict";Mr();Ma();Pt();Ps();Nre();M1();ur()});var _S={};_e(_S,{POINTS_CONTRACT_VERSION:()=>Bre,POINTS_ERROR_CODES:()=>ZNe,POINTS_OUTPUT_SCHEMA_ID:()=>zre,POINTS_SOURCE_REASON_CODES:()=>YNe,formatPoints:()=>Ure,readQuestionStates:()=>XNe,responseAsk:()=>Vre,runWorkspacePoints:()=>MG,workspacePoints:()=>LG});import{readFileSync as qNe}from"node:fs";import{relative as KNe,resolve as Wre,sep as JNe}from"node:path";async function LG(e){let t={$schema:zre,contract:Bre,chant:en()},n,i;try{n=qt(e.cwd,e.at),i=_t(n.tree)}catch(l){if(!(l instanceof xe))throw l;return{...t,error:{code:l.code,message:l.message,location:l.location??null}}}let r=e.kind!==void 0?[{shown:e.kind,file:Wre(e.cwd,e.kind),given:!0}]:yr(i).map(l=>({shown:l.path,file:Ri(l,n.rootOnDisk),given:!1})),o=[],s=[],a=[];for(let l of r)try{let u=await Ht(l.file);if(!u.kind.answers){l.given&&o.push({kind:l.shown,points:null,reason:{code:"kind-invalid",message:`the ${u.kind.name} kind has no answers block, so it holds no answers to decision points`}});continue}let d,p=await ii({kind:l.file,cwd:e.cwd,at:e.at,overlay:async(b,{loaded:k,root:$})=>(d=await hh({file:k.file,name:k.kind.name,dirRel:KNe($,k.dir).split(JNe).join("/")||"."}),yh(b,d))}),f=p.at!==null&&p.top?xi(p.top,p.at):ip(p.root),g=np(p.loaded,p.root),h=rp(f,g),w="points"in h?h.points:{};o.push({kind:l.shown,points:g,reason:"error"in h?{code:"points-invalid",message:h.error}:null});for(let[b,k]of Object.entries(w))s.push({name:b,title:k.title,kind:l.shown,file:g,version:za(k),questionType:k.question.type,instructions:k.question.instructions,candidates:k.adhoc?[]:Fo(k.question),criteria:k.question.criteria??(k.question.type==="score"?[]:{}),adhoc:!!k.adhoc,inputs:Object.entries(k.inputs).map(([$,x])=>({name:$,output:$l($),description:x})),deciders:k.deciders,quorum:tp(k)});for(let b of p.result.records){let k=gu(b,typeof b.data?.point=="string"?w[b.data.point]:void 0,d?.byPath.get(b.path)?.ledger??null);k&&(!e.open||k.open)&&a.push(k)}}catch(u){if(!(u instanceof Xe))throw u;o.push({kind:l.shown,points:null,reason:{code:u.code,message:u.message}})}let c=l=>a.filter(u=>u.state===l).length;return{...t,at:n.at,workspace:{name:i.name,root:n.root},open:!!e.open,sources:o,points:s,questions:a,summary:{points:s.length,questions:a.length,open:a.filter(l=>l.open).length,escalated:c("escalated"),proposed:c("proposed"),answered:c("answered"),withdrawn:a.filter(l=>l.withdrawn!==null).length}}}async function XNe(e){try{let t=await LG({cwd:e});return!("questions"in t)||t.sources.some(n=>n.reason!==null)?null:new Map(t.questions.map(n=>[n.id,n.state]))}catch{return null}}function Ure(e){let t=[];for(let i of e.sources)i.reason&&t.push(`${i.kind}: ${i.reason.code}: ${i.reason.message}`);for(let i of e.points)t.push(`${i.name} ${i.questionType}${i.adhoc?", ad hoc":""} ${i.title} (${i.deciders.map(r=>r.kind).join(", ")})`);e.points.length===0&&t.push("no decision points are declared"),t.push("");for(let i of e.questions){let r=i.model&&i.state!=="answered"?` model ${JSON.stringify(i.model.answer)} at ${i.model.confidence??"?"}${i.model.observed?"":`, below ${i.model.threshold??"?"}`}`:"";t.push(`${i.id} ${i.withdrawn?"withdrawn":i.state} ${i.title}${r}`)}let n=e.summary.questions;return t.push(e.open?`${n} open ${n===1?"question":"questions"}`:`${n} ${n===1?"question":"questions"}, ${e.summary.open} open`),t.join(`
337
+ `).length)}:null,M=L===null?[]:(A?gre(i,n.at,C,o.lines):void 0)??(n.at===null?Array.from({length:L.end-L.start+1},(E,O)=>({line:L.start+O,sha:null,origPath:C,origLine:L.start+O})):[]);for(let E of new Set(M.map(O=>O.sha).filter(O=>O!==null)))q.some(O=>O.sha===E)||q.push({sha:E,lines:null});let _=Ec(i,q.map(E=>E.sha)),T=e.followSquash?Ch(i,[..._.values()],{fetchMissing:!0}):new Map;for(let E of T.values())E.problem&&d.push({code:"squash-unfollowed",message:`${E.sha.slice(0,8)} squashes pull request #${E.pullRequest}, and ${E.problem}, so its original commits are not followed`});let W=Ec(i,[...new Set([...T.values()].flatMap(E=>E.commits))]),ke=E=>(T.get(E)?.commits??[]).map(O=>W.get(O)).filter(O=>O!==void 0),re=$i(i,ti(i)),be=re.active?await jg():[],Be=E=>{if(!(!Jn(E)||n.tree.stat(E)!=="file"))return n.tree.read(E)},dt=E=>{let O=E==="."?"":E.replace(/\/+$/,"");return O!==""&&(!Jn(O)||n.tree.stat(O)!=="dir")?void 0:n.tree.list(O)?.map(Y=>`${qe(O,Y.name)}${Y.type==="dir"?"/":""}`).sort()},ne=new Map,ye=lf(i,[..._.values(),...W.values()]),ge=[],oe=E=>{if(!re.active)return{level:"unattested",reason:re.problems.length?re.problems.join("; "):`no signers file (${re.signersPath}) at base; attestation is off`};let O=Ng(i,re,E,be);return{level:O.level,reason:O.reason,...O.principal?{principal:O.principal}:{}}},Se=new Set;for(let E of q){let O=_.get(E.sha);if(!O)continue;let D=oe(O.sha),Y=O.subject.match(/\(#([0-9]+)\)\s*$/),ue=`commit:${O.sha}`,V=T.get(O.sha),De=V?{pullRequest:V.pullRequest,forge:V.forge,ref:V.ref,head:V.head,fetched:V.fetched,followed:V.followed,commits:ke(O.sha).map(kt=>({sha:kt.sha,subject:kt.subject,author:kt.author,date:kt.date,trailers:kt.trailers,signature:oe(kt.sha),joins:ye.get(kt.sha).joins}))}:void 0;f({id:ue,kind:"commit",sha:O.sha,subject:O.subject,author:O.author,date:O.date,trailers:O.trailers,pullRequest:Y?Number(Y[1]):null,signature:D,lines:E.lines,state:null,joins:ye.get(O.sha).joins,...De?{squash:De}:{}}),u.push({kind:"touched-by",from:x,to:ue,lines:E.lines});let Ae={contracts:[],authorship:[],decisions:[],carries:[]};ne.set(O.sha,Ae);let lt=kt=>{u.some(Er=>Er.kind===kt.kind&&Er.from===kt.from&&Er.to===kt.to)||u.push(kt)},rn=[O,...ke(O.sha)];for(let kt of c)if(kt.joins)for(let Er of rn){let kf=Er!==O,Gn;try{Gn=await ax(kt.joins,Er,{read:Be,list:dt,at:n.at},kt.name)}catch(Vr){let bo=`${kt.display}: commitJoins failed for ${Er.sha.slice(0,8)}: ${Vr instanceof Error?Vr.message:String(Vr)}`;Se.has(bo)||d.push({code:"intent-plugin-failed",message:bo}),Se.add(bo);continue}let wu=(Vr,bo)=>{let{id:Ys,...de}=bo;return f({id:`${Vr}:${Ys}`,kind:Vr,ref:Ys,plugin:kt.display,data:de}).id},ji=Gn.unit?wu("unit",Gn.unit):void 0,Nc=Gn.contract?wu("contract",Gn.contract):void 0;ji&&(kf?Ae.unit??=ji:Ae.unit=ji,lt({kind:"produced-by",from:ue,to:ji}),Nc&&lt({kind:"serves",from:ji,to:Nc})),Nc&&Ae.contracts.push(Gn.contract.id),ji&&Ae.decisions.push(...fp(Gn.unit),...fp(Gn.contract));for(let Vr of Gn.findings??[])ge.push({commit:ue,plugin:kt.display,finding:Vr});let Lc=Gn.evidence===void 0?[]:Array.isArray(Gn.evidence)?Gn.evidence:[Gn.evidence];for(let Vr of Lc)lt({kind:"cites-evidence",from:ji??Nc??ue,to:wu("evidence",Vr)});kf||Ae.authorship.push(...Gn.authorship??[])}}let Ne=await r$(i,n.rootOnDisk,[...new Set([...q.map(E=>E.sha),...W.keys()])].map(E=>({sha:E,run:ye.get(E)?.joins.run??null})));i$(Ne.refs,T);for(let E of q)if(l.has(`commit:${E.sha}`))for(let O of Ne.refs.get(E.sha)??[]){let D=Ne.runs.get(O.id),Y=f({id:`run:${O.id}`,kind:"run",run:O.id,recorded:D!==void 0,state:D?.state??null,harness:D?.harness??null,model:D?.model??null,provider:D?.provider??null,by:D?.by??null,agent:D?.agent??null,unit:D?.unit?.id??null,startedAt:D?.startedAt??null,endedAt:D?.endedAt??null,outcome:D?.outcome??null,usage:D?.usage??null,cost:D?.cost??null,transcript:D?.transcript??null,instruction:D?.instruction??null,lease:D?.lease??null});u.push({kind:"made-by",from:`commit:${E.sha}`,to:Y.id,joinedBy:O.joinedBy,...O.recordedAs?{recordedAs:O.recordedAs}:{},...O.via?{via:O.via}:{}})}for(let E of Ne.conflicts){if(!l.has(`commit:${E.sha}`))continue;let O=E.content.map(D=>`${D.run} (${D.sha.slice(0,8)})`).join(", ");g("intent-commit-join-conflict",`${E.sha.slice(0,8)} joins ${E.joined.join(", ")} by its trailer or the run's record, and has the patch-id of a commit ${O} recorded; it is not joined to ${E.content.length===1?"that run":"those runs"}`,[`commit:${E.sha}`,...E.joined.map(D=>`run:${D}`)])}let te=o.path==="."?h:C,Ve=Vje(i),z=new Set;for(let E of _.values())for(let O of E.subject.matchAll(/#([0-9]+)/g))z.add(O[1]);let $e=new Set([...ne.values()].flatMap(E=>E.contracts)),Ie=[],et=new Map,ct=(E,O)=>`record:${E.records.loaded.kind.name}/${O}`,Vt=(E,O)=>{let D=E.records.loaded.kind,Y=FD(D,O.data);return f({id:ct(E,O.id),kind:"decision",recordKind:D.name,record:O.id,path:O.path,title:mu(O.data?.title),state:O.state,closed:O.state!==null&&(D.closedStates??[]).includes(O.state),valid:O.valid,reasons:O.reasons,provenance:{level:O.provenance.level,commit:O.provenance.commit,reason:O.provenance.reason},decided_by:mu(O.data?.decided_by),decided_on:mu(O.data?.decided_on),decidedIn:O.decidedIn??null,reviews:Kje(O.data),supersededBy:O.supersededBy,supersedes:Y,constrains:[]})},U=E=>P.filter(O=>jo(E,qe(h,O))),xe=(E,O)=>{let D=E.records.loaded.kind.constrains?.field,Y=E.records.workspaceRoot==="."?"":E.records.workspaceRoot,ue=D?O.data?.[D]:void 0,V=[];if(!Array.isArray(ue))return V;for(let De of ue)if(typeof De=="string")if(De.startsWith("path:")){let Ae=De.slice(5);if(!Jn(Ae))continue;let lt=qe(Y,Ae);if(s==="commit")w.some(rn=>jo(lt,qe(h,rn)))&&V.push({entry:De,granularity:"path",to:x});else if(te!==""&&jo(lt,te))V.push({entry:De,granularity:"path",to:x});else if(s==="dir"&&lt!==te&&(te===""||lt.startsWith(`${te}/`)))for(let rn of U(lt))V.push({entry:De,granularity:"path",to:`file:${rn}`})}else if(De.startsWith("member:"))$.includes(De.slice(7))&&V.push({entry:De,granularity:"member",to:x});else{let Ae=De.match(Zje);Ae&&Ve!==null&&Ae[1].toLowerCase()===Ve&&z.has(Ae[2])?V.push({entry:De,granularity:"issue",to:x}):$e.has(De)&&V.push({entry:De,granularity:"contract",to:`contract:${De}`})}return V};for(let E of c)if(!(!E.records||E.records.loaded.kind.work))for(let O of E.records.views){if(O.id===null)continue;et.set(`${E.records.loaded.kind.name}/${O.id}`,{view:O,kind:E});let D=xe(E,O);if(D.length===0)continue;let Y=Vt(E,O);for(let ue of D)u.push({kind:"constrains",from:Y.id,to:ue.to,granularity:ue.granularity,entry:ue.entry}),(ue.to===x||ue.granularity==="contract")&&Y.constrains.push({entry:ue.entry,granularity:ue.granularity});Y.constrains.length>0&&Ie.push({view:O,kind:E,node:Y})}let We=[...l.values()].filter(E=>E.kind==="decision");for(;We.length>0;){let E=We.shift(),O=[];E.supersededBy&&O.push(`${E.recordKind}/${E.supersededBy}`);for(let[D,{view:Y}]of et)D.startsWith(`${E.recordKind}/`)&&Y.supersededBy===E.record&&O.push(D);for(let D of O){let Y=et.get(D);if(!Y)continue;let ue=ct(Y.kind,Y.view.id);l.has(ue)||We.push(Vt(Y.kind,Y.view))}}let $t=[...l.values()].filter(E=>E.kind==="decision");for(let E of $t)if(E.supersededBy){let O=`record:${E.recordKind}/${E.supersededBy}`;l.has(O)&&u.push({kind:"supersedes",from:O,to:E.id})}let ht=new Map;for(let E of $t){let O=et.get(`${E.recordKind}/${E.record}`),D=O.kind.records.loaded.kind;for(let ue of O.view.assets){let V=ht.get(ue.path)??[];V.push({decision:E,state:ue.state,sha256:ue.sha256,actual:ue.actual}),ht.set(ue.path,V)}let Y=D.pins?O.view.data?.[D.pins.field]:void 0;if(Array.isArray(Y))for(let ue of Y){if(ue===null||typeof ue!="object"||Array.isArray(ue))continue;let V=ue,De=typeof V.sha256=="string"&&Jje.test(V.sha256);if(Jn(V.path)){if(De)continue;let lt=ht.get(V.path)??[];lt.push({decision:E,state:"unpinned",sha256:null,actual:null}),ht.set(V.path,lt),g("intent-evidence-unpinned",`${E.record} names ${V.path} as evidence with no sha256, so a later edit can't be told from what was decided on`,[E.id,`artifact:${V.path}`]);continue}if(typeof V.url!="string")continue;let Ae=f({id:`evidence:${V.url}`,kind:"evidence",ref:V.url,plugin:null,data:{title:mu(V.title),url:V.url,path:null,as_of:mu(V.as_of),sha256:De?V.sha256:null}});u.push({kind:"cites-evidence",from:E.id,to:Ae.id}),De||g("intent-evidence-unpinned",`${E.record} cites ${V.url} with no hash, so what the page said when it was decided can't be checked`,[E.id,Ae.id])}}for(let[E,O]of ht){let D=`artifact:${E}`,ue=[...O.filter(V=>V.decision.supersededBy===null&&V.state!=="unpinned")].sort((V,De)=>ure.indexOf(V.state)-ure.indexOf(De.state))[0];f({id:D,kind:"artifact",path:E,anchor:null,pinnedSha256:ue?.sha256??null,currentSha256:O.find(V=>V.state!=="unpinned")?.actual??null,pinState:ue?.state??"unpinned"});for(let V of O)if(u.push({kind:"pins",from:V.decision.id,to:D,pinnedSha256:V.sha256,pinState:V.state}),V.state==="drifted"&&g("intent-pin-drifted",`${E} changed after ${V.decision.record} pinned it: sha256 ${V.sha256?.slice(0,12)} is pinned, the file hashes to ${V.actual?.slice(0,12)}`,[V.decision.id,D]),V.state==="missing"&&g("intent-pin-missing",`${V.decision.record} pins ${E}, which does not exist${n.tree.label}`,[V.decision.id,D]),V.state==="stale"&&V.decision.supersededBy===null&&V.decision.constrains.length>0){let De=O.find(Ae=>Ae.decision.supersededBy===V.decision.record&&Ae.decision.recordKind===V.decision.recordKind&&Ae.sha256===V.sha256);g("intent-pin-stale",`${E} is pinned by ${V.decision.record} at sha256 ${V.sha256?.slice(0,12)}, the hash ${De?De.decision.record:"the record it supersedes"} pinned, and it has not changed since: the decision moved on and the artifact did not`,[V.decision.id,D,...De?[De.decision.id]:[]])}!ue&&O.some(V=>V.state!=="unpinned")&&g("intent-artifact-unpinned",`${E} was pinned by ${[...new Set(O.map(V=>V.decision.record))].join(", ")}, and no current decision pins it`,[D,...new Set(O.map(V=>V.decision.id))])}for(let E of $t){let O=et.get(`${E.recordKind}/${E.record}`),D=O.kind.records.loaded.kind.constrains?.field,Y=D?O.view.data?.[D]:void 0;if(!Array.isArray(Y))continue;let ue=O.kind.records.workspaceRoot==="."?"":O.kind.records.workspaceRoot;for(let V of Y){if(typeof V!="string"||!V.startsWith("path:"))continue;let De=V.slice(5);if(!Jn(De))continue;let Ae=qe(ue,De),lt=h===""?Ae:Ae.startsWith(`${h}/`)?Ae.slice(h.length+1):void 0;lt!==void 0&&n.tree.stat(lt)===void 0&&g("intent-constraint-lost",`${E.record} constrains ${De}, which does not exist${n.tree.label}`,[E.id])}}let Mn=new Map;if(A)for(let E of Ie){let O=hf(i,A,E.view),D=E.view.supersededBy?et.get(`${E.node.recordKind}/${E.view.supersededBy}`):void 0,Y=D?hf(i,A,D.view):null;Mn.set(E.node.id,{from:O?mo(i,O,A):new Set,until:Y?mo(i,Y,A):null})}let Mt=c.filter(E=>E.records?.loaded.kind.work),nn=Mt.length>0,fn=[],Fn=new Map;for(let E of Mt)for(let O of E.records.views){if(O.id===null)continue;let D={view:O,kind:E};fn.push(D);let Y=`${E.records.loaded.kind.name}/${O.id}`;Fn.has(Y)||Fn.set(Y,D)}let lr=E=>E.kind.records.loaded.kind.work,Xn=E=>{if(E.node)return E.node;let O=E.kind.records.loaded.kind,D=E.view;return E.node=f({id:`record:${O.name}/${D.id}`,kind:"work",recordKind:O.name,record:D.id,path:D.path,title:mu(D.data?.title),state:D.state,closed:D.state!==null&&(O.closedStates??[]).includes(D.state),valid:D.valid,reasons:D.reasons,provenance:{level:D.provenance.level,commit:D.provenance.commit,reason:D.provenance.reason},owner:mu(D.data?.owner),ready:D.ready??!1,blockedBy:D.blockedBy??[],implements:D.implements??[],needs:Gr(D.data,O.work.needs),source:lre(D.data),supersededBy:D.supersededBy,constrains:[],warnings:D.warnings.filter(Y=>OD.includes(Y.code))}),E.node},Zs=E=>{let O=Qy(dG(Mje(E.records.loaded.file),E.records.loaded.kind.work.decisions));return c.find(D=>D.records&&!D.records.loaded.kind.work&&Qy(D.records.loaded.file)===O)},y=E=>{let O=Zs(E.kind);return O?Gr(E.view.data,lr(E).implements).map(D=>et.get(`${O.records.loaded.kind.name}/${D}`)).filter(D=>D!==void 0).map(D=>ct(D.kind,D.view.id)):[]},N=E=>fn.filter(O=>{let D=O.kind.records.loaded.kind;return!(O.view.state!==null&&O.view.state!==D.work.done&&(D.closedStates??[]).includes(O.view.state))&&y(O).includes(E.id)}),K=[];for(let E of fn){let O=xe(E.kind,E.view);if(O.length===0)continue;let D=Xn(E);for(let Y of O)u.push({kind:"constrains",from:D.id,to:Y.to,granularity:Y.granularity,entry:Y.entry}),(Y.to===x||Y.granularity==="contract")&&D.constrains.push({entry:Y.entry,granularity:Y.granularity});D.constrains.length>0&&K.push(E)}let Q=new Map;if(A)for(let E of K){let O=E.kind.records.loaded.kind,D=Zy(i,A,E.view.path),Y=O.stateField?gS(i,A,E.view.path,O.stateField,O.closedStates??[]):null,ue=Y?mo(i,Y,A):null;Y&&ue.delete(Y),Q.set(E.node.id,{from:D?mo(i,D,A):new Set,until:ue})}let H=(E,O)=>{let D=Q.get(E.node.id);return!!D&&D.from.has(O)&&!D.until?.has(O)},S=new Map(c.filter(E=>E.records).map(E=>[E.records.loaded.kind.name,E])),G=E=>{let O=[],D=Y=>{O.some(ue=>ue.node===Y.node)||O.push(Y)};if(E.unit){let ue=(E.unit.kind?Mt.filter(V=>V.records.loaded.kind.name===E.unit.kind):Mt).map(V=>Fn.get(`${V.records.loaded.kind.name}/${E.unit.id}`)).filter(V=>V!==void 0);ue.length===1&&D({node:Xn(ue[0]).id,work:ue[0]})}for(let Y of E.records){let ue=S.get(Y.kind);if(!ue)continue;if(ue.records.loaded.kind.work){let De=Fn.get(`${Y.kind}/${Y.id}`);De&&D({node:Xn(De).id,work:De});continue}let V=et.get(`${Y.kind}/${Y.id}`);V&&D({node:Vt(V.kind,V.view).id,decision:`${Y.kind}/${Y.id}`})}return O};for(let E of q){let O=l.get(`commit:${E.sha}`),D=ne.get(E.sha);if(!O||!D)continue;let Y=V=>{D.carries.includes(V)||(D.carries.push(V),u.push({kind:"carries",from:O.id,to:V}))},ue=V=>{let De=Xn(V);return Y(De.id),D.decisions.push(...y(V).map(Ae=>Ae.slice(7))),De.id};for(let V of[O.joins,...(O.squash?.commits??[]).map(De=>De.joins)]){for(let Ae of V.records){let lt=S.get(Ae.kind);if(!lt)continue;if(lt.records.loaded.kind.work){let kt=Fn.get(`${Ae.kind}/${Ae.id}`);kt&&(Ae.node=ue(kt));continue}let rn=et.get(`${Ae.kind}/${Ae.id}`);rn&&(Ae.node=Vt(rn.kind,rn.view).id,Y(Ae.node),D.decisions.push(`${Ae.kind}/${Ae.id}`))}let De=V.lease?.item;if(De){let Ae=Mt.map(lt=>Fn.get(`${lt.records.loaded.kind.name}/${De}`)).filter(lt=>lt!==void 0);Ae.length===1&&ue(Ae[0])}}for(let V of Ne.refs.get(E.sha)??[]){let De=Ne.runs.get(V.id);if(De)for(let Ae of G(De))Ae.work?ue(Ae.work):Ae.decision&&(Y(Ae.node),D.decisions.push(Ae.decision))}}for(let E of[...l.values()]){if(E.kind!=="run")continue;let O=Ne.runs.get(E.run);if(O)for(let D of G(O))u.push({kind:"worked-on",from:E.id,to:D.node})}for(let E of fn.filter(O=>O.node)){for(let O of y(E)){let D=et.get(O.slice(7));u.push({kind:"implements",from:E.node.id,to:Vt(D.kind,D.view).id})}for(let O of Gr(E.view.data,lr(E).needs)){let D=Fn.get(`${E.kind.records.loaded.kind.name}/${O}`);D&&u.push({kind:"needs",from:E.node.id,to:Xn(D).id})}}let J=(E,O)=>Ie.filter(D=>{if(!D.node.constrains.some(ue=>O.includes(ue.granularity)))return!1;let Y=Mn.get(D.node.id);return!!Y&&Y.from.has(E)&&!Y.until?.has(E)}),ie=c.some(E=>E.records),se=(E,O)=>(!!E.unit||E.carries.length>0)&&(E.decisions.some(D=>D===O.record||D===`${O.recordKind}/${O.record}`)||O.constrains.some(D=>D.granularity==="contract"&&E.contracts.includes(D.entry)));for(let E of q){let O=l.get(`commit:${E.sha}`);if(!O)continue;let D=ne.get(E.sha);if(ie){let ue=J(E.sha,["path"]);for(let V of ue)u.push({kind:"within",from:O.id,to:V.node.id,state:se(D,V.node)?"decided":"decided-by-window"});O.state=ue.length===0?"undecided":ue.some(V=>se(D,V.node))?"decided":"decided-by-window"}for(let ue of K)ue.node.constrains.some(V=>V.granularity==="path")&&H(ue,E.sha)&&u.push({kind:"within",from:O.id,to:ue.node.id,state:"worked"});ie&&O.state==="undecided"&&g("intent-commit-undecided",`${E.sha.slice(0,8)} changed the region when no decision constrained ${R} by path`,[O.id,x]),ie&&!D.unit&&D.carries.length===0&&O.pullRequest===null&&J(E.sha,["path","member","contract","issue"]).length===0&&g("intent-commit-bare",`${E.sha.slice(0,8)} names no unit, no record, no pull request and no decision`,[O.id]);let Y=[...new Set(D.authorship)].filter(ue=>ZD(O.trailers,ue));Y.length>0&&O.signature.level!=="attested"&&g("intent-trailer-unverified",`${E.sha.slice(0,8)} carries ${Y.join(", ")}, and the commit is ${O.signature.level}, so nothing vouches for the trailer`,[O.id])}if(ie){let E=Ie.filter(D=>D.node.supersededBy===null);Ie.length===0?g("intent-region-unconstrained",`no decision constrains ${R}`,[x]):E.length===0?g("intent-decision-superseded-live",`every decision constraining ${R} is superseded: ${Ie.map(D=>`${D.node.record} by ${D.node.supersededBy}`).join(", ")}`,[x,...Ie.map(D=>D.node.id)]):E.every(D=>!D.node.closed)&&g("intent-decision-provisional",`the decisions constraining ${R} are ${[...new Set(E.map(D=>D.node.state??"stateless"))].join(" or ")}, and none is in a closed state`,[x,...E.map(D=>D.node.id)]);for(let D of E){let Y=D.view.quorum?.openConcerns??[];if(Y.length===0)continue;let ue=[...new Set(Y.map(V=>V.principal))];p.push({id:`finding:intent-decision-contested:${p.filter(V=>V.code==="intent-decision-contested").length+1}`,kind:"finding",code:"intent-decision-contested",message:`${D.node.record} constrains ${R} and has ${Y.length} open ${Y.length===1?"concern":"concerns"}, from ${Y.map(V=>V.reviewer).join(", ")}: a dissent neither addressed nor withdrawn`,concerns:[D.node.id,x],openConcerns:{count:Y.length,principals:ue}})}let O=new Set(Ie.flatMap(D=>D.node.constrains.map(Y=>Y.granularity)));Ie.length>0&&!O.has("path")&&O.has("member")&&g("intent-constraint-coarse",`${R} is constrained only through its member, ${$.join(", ")}`,[x,...Ie.map(D=>D.node.id)])}if(nn){for(let E of Ie){if(E.node.supersededBy!==null||!kl(E.kind.records.loaded.kind,E.node.state)||N(E.node).length>0)continue;let O=Mn.get(E.node.id);O&&q.some(D=>O.from.has(D.sha)&&!O.until?.has(D.sha))||g("intent-decision-unimplemented",`${E.node.record} is ${E.node.state} and constrains ${R}, and no work item that is not dropped implements it, and no commit changed the region in its window`,[E.node.id,x])}for(let E of K){let O=E.node;if(O.blockedBy.length===0)continue;let D=q.filter(V=>H(E,V.sha));if(D.length===0)continue;let Y=O.blockedBy.map(V=>`${V.id} (${V.state??"unknown"})`).join(", "),ue=O.blockedBy.map(V=>Fn.get(`${O.recordKind}/${V.id}`)).filter(V=>V!==void 0).map(V=>Xn(V).id);g("intent-work-blocked",`${O.record} has ${D.length} ${D.length===1?"commit":"commits"} in its window while it waits on ${Y}`,[O.id,...D.map(V=>`commit:${V.sha}`),...ue])}for(let E of[...l.values()].filter(O=>O.kind==="decision")){let O=u.filter(Y=>Y.kind==="within"&&Y.to===E.id&&Y.state==="decided").map(Y=>Y.from);if(O.length===0)continue;let D=N(E);D.length===0||D.some(Y=>Y.view.state===lr(Y).done)||g("intent-work-open-decided-code",`${O.length} ${O.length===1?"commit":"commits"} in ${R} ${O.length===1?"is":"are"} ${E.record}'s own work, and ${D.map(Y=>`${Y.view.id} is ${Y.view.state??"stateless"}`).join(", ")}: the code says done and the queue says not`,[E.id,...O,...D.map(Y=>Xn(Y).id)])}}if(k){let E=[];try{let O=_a(r,n.tree),D=Pa(r.pins,n.rootOnDisk).registry,{gatherLexiconOutputs:Y}=await Promise.resolve().then(()=>(are(),sre)),ue=await Y(n.rootOnDisk,r,n.at?Rn(n.rootOnDisk):n.tree,O,D,{atRevision:n.at!==null,...e.loadLexicon?{load:e.loadLexicon}:{}});E=MN(r,i3(r,n.tree,O,D,ue)).filter(V=>V.origin==="declared")}catch(O){if(!(O instanceof ve))throw O}E.forEach((O,D)=>{let Y="producer"in O?O.producer:null;if(O.consumer!==k&&Y!==k)return;let{pointer:ue,...V}=O;f({id:`link:${D+1}`,kind:"link",row:V}),I(O.consumer),Y&&r.members.some(De=>De.name===Y)&&(I(Y),u.push({kind:"links",from:`member:${O.consumer}`,to:`member:${Y}`}))})}p.sort((E,O)=>lG.indexOf(E.code)-lG.indexOf(O.code));let ce=E=>{if(l.has(E))return E;for(let O of["commit","unit","contract","evidence","artifact","file","member"])if(l.has(`${O}:${E}`))return`${O}:${E}`;for(let O of l.values())if(O.kind==="decision"&&(E===O.record||E===`${O.recordKind}/${O.record}`)||O.kind==="commit"&&/^[0-9a-f]{7,}$/.test(E)&&O.sha.startsWith(E))return O.id};for(let{commit:E,plugin:O,finding:D}of ge){let Y=D.code,ue=D.refs??[],V=[...new Set([E,...ue.map(ce).filter(De=>De!==void 0)])];p.push({id:`finding:${Y}:${p.filter(De=>De.code===Y).length+1}`,kind:"finding",code:Y,message:D.message,concerns:V,plugin:O,refs:ue})}if(nn){let E=new Set(["intent-pin-drifted","intent-pin-missing","intent-pin-stale"]),O=(D,Y)=>{let ue=lre(D.view.data);if(ue===null||ue.finding!==Y)return!1;let V=pG(ue.region);if("error"in V)return!1;let De=D.kind.records.workspaceRoot==="."?"":D.kind.records.workspaceRoot,Ae=qe(De,V.path),lt=(rn,kt)=>rn===kt||rn===""||kt.startsWith(`${rn}/`);return s==="commit"?w.some(rn=>lt(Ae,qe(h,rn))||lt(qe(h,rn),Ae)):!lt(Ae,te)&&!lt(te,Ae)?!1:Ae===te&&V.lines&&o.lines?V.lines.start<=o.lines.end&&o.lines.start<=V.lines.end:!0};for(let D of p){let Y=[];for(let ue of fn){let V=O(ue,D.code),De=(E.has(D.code)||ox(D.code))&&y(ue).some(Ae=>D.concerns.includes(Ae));if((V||De)&&Y.push(ue),V&&ue.view.state===lr(ue).done){let Ae=Xn(ue);Ae.warnings.some(lt=>lt.code==="work-done-gap-open")||Ae.warnings.push({code:"work-done-gap-open",message:`${Ae.record} is ${ue.view.state}, and ${D.code}, the gap it came from, still fires on ${R}`})}}D.addressed=Y.length>0,D.addressedBy=Y.map(ue=>({id:ue.view.id,state:ue.view.state}));for(let ue of Y)u.push({kind:"addressed-by",from:D.id,to:Xn(ue).id})}}let ee=[...l.values()].filter(E=>E.kind==="work");if(ee.length>0){let E=new Map(ee.map(O=>[`${O.recordKind}:${O.record}`,O]));for(let O of c){let D=O.records?.loaded.kind;if(D?.session)for(let Y of O.records.views){if(Y.id===null||!Y.data)continue;let ue=new Map,V=(Ae,lt)=>{if(Array.isArray(Ae))for(let rn of Ae){let kt=typeof rn=="string"?E.get(rn):void 0;if(!kt)continue;let Er=ue.get(kt)??[];lt!==null&&!Er.includes(lt)&&Er.push(lt),ue.set(kt,Er)}};V(Y.data.follow_ups,null),(Array.isArray(Y.data.comments)?Y.data.comments:[]).forEach((Ae,lt)=>V(Ae?.follow_ups,lt+1));for(let[Ae,lt]of ue)(Ae.reviews??=[]).push({id:`record:${D.name}/${Y.id}`,recordKind:D.name,record:Y.id,path:Y.path,state:Y.state,comments:lt.sort((rn,kt)=>rn-kt)})}}}for(let E of p)l.set(E.id,E);await eNe([...l.values()].filter(E=>E.kind==="work"),r,n.rootOnDisk,i,n.at);let he=jc(),Oe=[...l.values()],Ge=new Map,ze=new Map;for(let E of fn){let O=E.kind.records.loaded.kind.name;(Ge.get(O)??Ge.set(O,new Set).get(O)).add(E.view.id),E.node&&ze.set(`${O}:${E.view.id}`,E.node.id)}for(let E of Mt)Ge.has(E.records.loaded.kind.name)||Ge.set(E.records.loaded.kind.name,new Set);let He=new Map;for(let E of u){if(E.kind!=="within"||E.state!=="worked")continue;let O=l.get(E.to);if(!O)continue;let D=E.from.slice(7);(He.get(D)??He.set(D,[]).get(D)).push({id:`${O.recordKind}:${O.record}`,node:O.id,path:O.path})}let nt=new Map,wo=await mte({top:i,commits:Oe.filter(E=>E.kind==="commit").map(E=>({id:E.id,sha:E.sha,trailers:E.trailers,joins:E.joins})),work:nn?{index:{kinds:Ge},nodes:ze}:null,windows:He,ledgers:($.length>0?$:r.members.map(E=>E.name)).map(E=>{let O=r.members.find(D=>D.name===E).dir;return{member:E,cwd:Py(n.rootOnDisk,O),within:O==="."?null:`_members/${E}/`}}).concat($.length>0?[]:[{member:null,cwd:n.rootOnDisk,within:null}]),green:r.ci?.green??null,contains:(E,O)=>{if(O===E)return!0;if(!A||!uG.test(O))return!1;let D=nt.get(E);return D||nt.set(E,D=mo(i,E,A)),D.has(O)}});return{doc:{...t,at:n.at,workspace:{name:r.name,root:n.root},region:x,history:{rev:A,follows:o.commit?"commit":o.lines?"line-range":s==="file"?"file":"directory",shallow:B},kinds:c.map(E=>({file:E.display,name:E.name,records:E.records?.loaded.kind.name??null,joins:E.joins?.form??null})),nodes:Oe,edges:u,reasons:d,summary:{commits:Oe.filter(E=>E.kind==="commit").length,decisions:Oe.filter(E=>E.kind==="decision").length,artifacts:Oe.filter(E=>E.kind==="artifact").length,findings:p.length},why:he,trace:wo},failed:d.some(E=>E.code==="intent-plugin-failed")};function jc(){let E=(de,Pe)=>Ne.runs.get(de)?.commits.find(Rt=>Rt.sha===Pe)?.hunks??null,O=(de,Pe)=>(Ne.refs.get(Pe)??[]).find(Rt=>Rt.id===de)?.joinedBy??[],D=(de,Pe)=>{let Rt=new Set(de.flatMap(Et=>Pe.flatMap(Hr=>O(Et,Hr))));return b3.filter(Et=>Rt.has(Et))},Y=new Map,ue=(de,Pe,Rt)=>{let Et=T.get(de);if(!Et?.followed||!Et.head)return{squash:!1,origin:void 0};let Hr=`${de}\0${Pe}`;return Y.has(Hr)||Y.set(Hr,s3(i,de,Et.head,Pe,new Set(Et.commits))),{squash:!0,origin:Y.get(Hr)?.get(Rt)}},V=M.map(de=>{if(de.sha===null)return{line:de.line,sha:null,runs:[],narrowedBy:null,via:void 0};let Pe=de.sha,{squash:Rt,origin:Et}=ue(Pe,de.origPath,de.origLine),Hr=Rt?Et?[Et]:[]:void 0,Mc=(Ne.refs.get(Pe)??[]).filter(Jt=>!Et||Jt.joinedBy.some(ds=>ds!=="squash")||(Jt.via??[]).includes(Et)).map(Jt=>Jt.id),Wn=Mc.filter(Jt=>E(Jt,Pe)!==null);if(Wn.length===0)return{line:de.line,sha:Pe,runs:Mc,narrowedBy:null,via:Hr};let dw=Wn.filter(Jt=>E(Jt,Pe).some(ds=>ds.path===de.origPath&&ds.start<=de.origLine&&de.origLine<=ds.end));return{line:de.line,sha:Pe,runs:dw.length>0?dw:Mc.filter(Jt=>!Wn.includes(Jt)),narrowedBy:"hunks",via:Hr}}),De=[];for(let de of V){let Pe=De[De.length-1],Rt=de.via;if(Pe&&Pe.end===de.line-1&&Pe.sha===de.sha&&Pe.narrowedBy===de.narrowedBy&&Pe.runs.join("\0")===de.runs.map(Et=>`run:${Et}`).join("\0")&&Pe.via?.join("\0")===Rt?.join("\0")){Pe.end=de.line;continue}De.push({start:de.line,end:de.line,commit:de.sha?`commit:${de.sha}`:null,sha:de.sha,runs:de.runs.map(Et=>`run:${Et}`),narrowedBy:de.narrowedBy,joinedBy:de.sha?D(de.runs,[de.sha]):[],...Rt?{via:Rt}:{}})}let Ae=de=>{let Pe=[];for(let Rt of de){let Et=Pe[Pe.length-1];Et&&Et.end===Rt-1?Et.end=Rt:Pe.push({start:Rt,end:Rt})}return Pe},lt=[...l.values()].filter(de=>de.kind==="decision"),rn=de=>V.filter(Pe=>Pe.sha!==null&&se(ne.get(Pe.sha)??{contracts:[],authorship:[],decisions:[],carries:[]},de)).length,kt=["carried","path","contract","issue","member","related"],Er=lt.map(de=>{let Pe=rn(de),Rt=Pe>0||L===null&&q.some(Wn=>se(ne.get(Wn.sha)??{contracts:[],authorship:[],decisions:[],carries:[]},de)),Et=new Set(de.constrains.map(Wn=>Wn.granularity)),Hr=Rt?"carried":["path","contract","issue","member"].find(Wn=>Et.has(Wn))??"related",Mc=Math.max(0,...de.constrains.filter(Wn=>Wn.granularity==="path").map(Wn=>Wn.entry.length));return{d:de,entry:{decision:de.id,relevance:Hr,current:de.supersededBy===null,closed:de.closed,lines:Pe},specificity:Mc}});Er.sort((de,Pe)=>Number(Pe.entry.current)-Number(de.entry.current)||kt.indexOf(de.entry.relevance)-kt.indexOf(Pe.entry.relevance)||Pe.entry.lines-de.entry.lines||Number(Pe.entry.closed)-Number(de.entry.closed)||Pe.specificity-de.specificity||(Pe.d.decidedIn?.date??"").localeCompare(de.d.decidedIn?.date??"")||de.d.id.localeCompare(Pe.d.id));let kf=Er.map(de=>de.entry),Gn=[...l.values()].filter(de=>de.kind==="run"),wu=(de,Pe,Rt)=>{let Et=Ne.runs.get(de.run),Hr=u.filter(Jt=>Jt.kind==="worked-on"&&Jt.from===de.id).map(Jt=>l.get(Jt.to)),Mc=Et?.unit?Hr.find(Jt=>Jt?.kind==="work"&&Jt.record===Et.unit.id):void 0,Wn=new Set;for(let Jt of Hr)if(Jt?.kind==="decision"&&Wn.add(Jt.id),Jt?.kind==="work")for(let ds of u)ds.kind==="implements"&&ds.from===Jt.id&&Wn.add(ds.to);let dw=Rt.map(Jt=>Jt.slice(7));return{run:de.id,lines:Pe,commits:Rt,unit:Et?.unit?{id:Et.unit.id,kind:Et.unit.kind,node:Mc?.id??null}:null,decisions:[...Wn],joinedBy:D([de.run],dw)}},ji;if(L!==null){let de=new Map;for(let Pe of V)for(let Rt of Pe.runs){let Et=de.get(Rt)??de.set(Rt,{lines:0,commits:new Set}).get(Rt);Et.lines++,Et.commits.add(`commit:${Pe.sha}`)}ji=[...de].map(([Pe,Rt])=>({n:l.get(`run:${Pe}`),t:Rt})).filter(Pe=>Pe.n!==void 0).sort((Pe,Rt)=>Rt.t.lines-Pe.t.lines||(Rt.n.startedAt??"").localeCompare(Pe.n.startedAt??"")||Pe.n.run.localeCompare(Rt.n.run)).map(Pe=>wu(Pe.n,Pe.t.lines,[...Pe.t.commits]))}else ji=Gn.sort((de,Pe)=>(Pe.startedAt??"").localeCompare(de.startedAt??"")||de.run.localeCompare(Pe.run)).map(de=>wu(de,0,u.filter(Pe=>Pe.kind==="made-by"&&Pe.to===de.id).map(Pe=>Pe.from)));let Nc=kf.some(de=>de.current&&de.relevance!=="related"),Lc=[];Nc||Lc.push({code:"intent-why-no-decision",message:ie?`no current decision governs ${R}, and none is carried out by what made its lines`:`no record kind was read, so no decision can account for ${R}`});let Vr=V.filter(de=>de.sha!==null);(L!==null?Vr.length>0&&Vr.every(de=>de.runs.length===0):q.length>0&&Gn.length===0)&&Lc.push({code:"intent-why-no-run",message:`no agent run is joined to the commits that made ${L!==null?"the current lines of ":""}${R}`});let bo=V.filter(de=>de.sha===null).map(de=>de.line);bo.length>0&&Lc.push({code:"intent-why-uncommitted",message:`${bo.length} ${bo.length===1?"line is":"lines are"} not committed yet`,lines:Ae(bo)});let Ys=V.filter(de=>de.runs.length>1).map(de=>de.line);return Ys.length>0&&Lc.push({code:"intent-why-run-ambiguous",message:`${Ys.length} ${Ys.length===1?"line comes":"lines come"} from a commit several runs made, and no run's recorded hunks say which wrote ${Ys.length===1?"it":"them"}`,lines:Ae(Ys)}),{lines:L,blame:De,decisions:kf,runs:ji,explained:Nc,gaps:Lc}}}var pre,fre,lG,Fje,Gje,Wje,pn,zje,uG,cG,yre,Jje,Zje,ure,Xje,Ty=v(()=>{"use strict";Tt();cc();CN();Lg();qi();Dp();UN();No();un();Ei();KD();HN();t$();Q1();fee();BR();gte();on();lp();Pl();Wr();Yd();pre=1,fre="https://intentius.io/chant/schemas/workspace/intent/v1/intent.schema.json",lG=["intent-commit-undecided","intent-commit-bare","intent-pin-drifted","intent-pin-missing","intent-pin-stale","intent-artifact-unpinned","intent-decision-superseded-live","intent-decision-provisional","intent-decision-contested","intent-constraint-coarse","intent-constraint-lost","intent-evidence-unpinned","intent-trailer-unverified","intent-region-unconstrained","intent-decision-unimplemented","intent-work-blocked","intent-work-open-decided-code","intent-commit-join-conflict"],Fje=["intent-history-shallow","intent-plugin-failed","squash-unfollowed"],Gje=[...yi,"kind-unreadable","kind-invalid","schema-unreadable","schema-id-mismatch","schema-invalid","location-missing","intent-region-invalid","intent-record-unknown","intent-symbol-unsupported","intent-symbol-unknown","intent-symbol-ambiguous"],Wje=["intent-why-no-decision","intent-why-no-run","intent-why-uncommitted","intent-why-run-ambiguous"],pn=class extends Error{constructor(n,i){super(i);this.code=n;this.name="IntentError"}};zje=/^0+$/;uG=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;yre=e=>cre==="/"?e:e.split(cre).join("/");Jje=/^[0-9a-f]{64}$/,Zje=/^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#([0-9]+)$/,ure=["missing","drifted","stale","pinned"];Xje=/^[0-9a-fA-F]{7,64}$/});var gG={};_e(gG,{RECORDS_SINCE_ERROR_CODES:()=>iNe,RECORDS_SINCE_OUTPUT_SCHEMA_ID:()=>fG,RECORDS_SINCE_REASON_CODES:()=>oNe,SINCE_CHANGE_KINDS:()=>mG,compareRecords:()=>kre,formatSince:()=>dNe,queryRecordsSince:()=>aNe});import{realpathSync as nNe}from"node:fs";import{relative as rNe}from"node:path";async function aNe(e){let t=(n,i)=>({$schema:fG,contract:Ks,error:{code:n,message:i}});try{let n=await lNe(e),i=uNe(e.cwd,n?n.since:e.since,n?.session.id),r=n?n.at??void 0:e.at,o=await ii({kind:e.kind,at:r,cwd:e.cwd}),s;try{s=(await ii({kind:e.kind,at:i,cwd:e.cwd})).result.records}catch(l){if(!(l instanceof Xe)||l.code!=="location-missing")throw l;s=[]}let a=kre(o.loaded.kind,s,o.result.records),c=Object.fromEntries(mG.map(l=>[l,a.filter(u=>u.change===l).length]));return{$schema:fG,contract:Ks,kind:cNe(o.loaded,o.root),since:i,at:o.at,...n?{session:n.session}:{},changes:a,summary:c}}catch(n){if(n instanceof yf||n instanceof Xe)return t(n.code,n.message);throw n}}function cNe(e,t){return{name:e.kind.name,schema:e.kind.schema.id,file:rNe(t,e.file).split("\\").join("/")}}async function lNe(e){let t=cr(Yn(e.cwd));if(!t||!Y5.test(e.since))return null;let n=await ah(e.cwd,[e.kind]);for(let i of n){let r;try{r=(await ii({kind:i.file,cwd:e.cwd})).result.records}catch(p){if(p instanceof Xe)continue;throw p}let o=r.find(p=>p.id===e.since);if(!o)continue;let s=i.kind.session,a=p=>p!==void 0&&typeof o.data?.[p]=="string"?o.data[p]:null,c=o.state!==null&&(i.kind.closedStates??[]).includes(o.state),l={id:o.id,path:o.path,state:o.state,sinceFrom:"opened-rev",atFrom:"working-tree",reasons:[]},u=a(s.openedRev);if(u===null&&(u=Nx(t,o.path,["--diff-filter=A"])[0]??null,l.sinceFrom="history",u===null))throw new yf("since-rev-unknown",`session ${o.id} (${o.path}) names no commit it opened at${s.openedRev?` in ${s.openedRev}`:""}, and no commit added its file`);let d=null;if(e.at!==void 0)d=e.at,l.atFrom="at";else if(c){let p=a(s.closedRev);p!==null&&/^[0-9a-f]{40,64}$/.test(p)?(d=Nx(t,o.path,[`${p}..HEAD`]).slice(-1)[0]??null,l.atFrom=d===null?"working-tree":"close-commit"):(d=Nx(t,o.path,["-1"])[0]??null,l.atFrom=d===null?"working-tree":"history")}else l.reasons.push({code:"since-session-open",message:`session ${o.id} is ${o.state??"not closed"}, so it has no closing revision, and the comparison runs to the working tree`});return{since:u,at:d,session:l}}try{return Ol(t,e.since),null}catch(i){if(!(i instanceof Xe))throw i}if(n.length===0)return null;throw new yf("since-session-unknown",`--since ${e.since} names no commit, and no ${[...new Set(n.map(i=>i.kind.name))].join(" or ")} record has that id`)}function uNe(e,t,n){let i=e;try{i=nNe(e)}catch{}let r=cr(i);if(!r)throw new Xe("not-a-git-repository","--since reads git objects, and this directory is not in a git repository");try{return Ol(r,t)}catch(o){throw o instanceof Xe&&o.code==="revision-unknown"?new yf("since-rev-unknown",n?`session ${n} names ${t}, which is no commit in this repository`:`--since ${t} names no commit in this repository`):o}}function bre(e){let t=new Map;for(let n of e)n.id!==null&&!t.has(n.id)&&t.set(n.id,n);return t}function vre(e,t){let n=e.session?e.session.verdicts:e.reviews?.field??sNe,i=t.data?.[n];if(!Array.isArray(i))return[];let r=s=>typeof s=="string"?s:void 0,o=[];return i.forEach((s,a)=>{if(s===null||typeof s!="object"||Array.isArray(s))return;let c=s,l=r(e.session?c.principal:c.reviewer)??null,u=r(c.verdict)??null,d=r(c.record),p=r(c.session);o.push({key:JSON.stringify([l,u,r(c.on)??null,p??null,d??null]),index:a,principal:l,verdict:u,...d!==void 0?{record:d}:{},...p!==void 0?{session:p}:{}})}),o}function kre(e,t,n){let i=bre(t),r=bre(n),o=[...new Set([...i.keys(),...r.keys()])].sort(),s={new:[],removed:[],state:[],verdict:[],supersession:[],pin:[]};for(let a of o){let c=i.get(a),l=r.get(a);if(!c&&l&&s.new.push({change:"new",id:a,path:l.path,state:l.state}),c&&!l&&s.removed.push({change:"removed",id:a,path:c.path,state:c.state}),!l)continue;c&&c.state!==l.state&&s.state.push({change:"state",id:a,from:c.state,to:l.state});let u=new Map;for(let d of c?vre(e,c):[])u.set(d.key,(u.get(d.key)??0)+1);for(let d of vre(e,l)){let p=u.get(d.key)??0;if(p>0){u.set(d.key,p-1);continue}s.verdict.push({change:"verdict",id:a,principal:d.principal,verdict:d.verdict,index:d.index,...d.record!==void 0?{record:d.record}:{},...d.session!==void 0?{session:d.session}:{}})}if(l.supersededBy!==null&&(!c||c.supersededBy!==l.supersededBy)&&s.supersession.push({change:"supersession",id:l.supersededBy,supersedes:a}),c&&e.pins){let d=new Map(Rg(c.data,e.pins.field).map(f=>[f.path,f.sha256])),p=new Map(Rg(l.data,e.pins.field).map(f=>[f.path,f.sha256]));for(let f of[...new Set([...d.keys(),...p.keys()])].sort()){let g=d.get(f)??null,h=p.get(f)??null;g!==h&&s.pin.push({change:"pin",id:a,path:f,from:g,to:h})}}}return s.supersession.sort((a,c)=>a.id<c.id?-1:a.id>c.id?1:0),mG.flatMap(a=>s[a])}function dNe(e){let t=e.changes.map(i=>{switch(i.change){case"new":return`${i.id} new, ${i.state??"no state"} (${i.path})`;case"removed":return`${i.id} removed, was ${i.state??"no state"} (${i.path})`;case"state":return`${i.id} state ${i.from??"none"} to ${i.to??"none"}`;case"verdict":return`${i.id} verdict ${i.verdict??"-"} by ${i.principal??"-"}${i.record?` on ${i.record}`:""}${i.session?` in ${i.session}`:""}`;case"supersession":return`${i.id} supersedes ${i.supersedes}`;case"pin":return`${i.id} pin ${i.path} ${i.from?i.from.slice(0,12):"none"} to ${i.to?i.to.slice(0,12):"none"}`}}),n=e.summary;if(e.session){let i=e.session;t.unshift(`session ${i.id} (${i.state??"no state"}): opened at ${e.since.slice(0,8)} (${i.sinceFrom}), compared to ${e.at?`${e.at.slice(0,8)} (${i.atFrom})`:"the working tree"}`)}return t.push(`${e.changes.length} changes since ${e.since.slice(0,8)}${e.at?` to ${e.at.slice(0,8)}`:" to the working tree"}: ${n.new} new, ${n.removed} removed, ${n.state} state, ${n.verdict} verdicts, ${n.supersession} supersessions, ${n.pin} pins`),t.join(`
338
+ `)}var fG,iNe,oNe,mG,sNe,yf,hG=v(()=>{"use strict";No();Qi();un();Ei();Lx();fG="https://intentius.io/chant/schemas/workspace/records-since/v1/records-since.schema.json",iNe=[...SJ,"since-rev-unknown","since-session-unknown"],oNe=["since-session-open"],mG=["new","removed","state","verdict","supersession","pin"],sNe="reviews",yf=class extends Error{constructor(n,i){super(i);this.code=n}}});var ere={};_e(ere,{AGENT_ROLE:()=>xS,EXIT_BELOW_REQUIRED:()=>wG,RECORDS_CONTRACT_VERSION:()=>Ks,RECORDS_OUTPUT_SCHEMA_ID:()=>rw,belowRequired:()=>bG,declaredKindFiles:()=>Si,pinFile:()=>$re,pinRoot:()=>Bx,queryDeclaredRecords:()=>$S,queryRecords:()=>ew,quorumOptionsFor:()=>gh,quorumShortfall:()=>Wx,readRecordsFor:()=>ii,realpathOr:()=>Yn,runWorkspaceRecords:()=>kNe,runWorkspaceUnknown:()=>SNe,specOf:()=>xre});import{execFileSync as pNe}from"node:child_process";import{readFileSync as fNe,realpathSync as mNe}from"node:fs";import{dirname as nw,join as yG,relative as wf,resolve as kS,sep as tw}from"node:path";function gNe(e){try{return fNe(e,"utf-8")}catch{return null}}function xre(e){let t={kinds:[],records:[]};for(let n of e)if(!("error"in n||!n.kind.spec)){t.kinds.push(n.declared);for(let i of n.records)t.records.push({kind:n.kind.name,id:i.id,path:i.path,state:i.state,valid:i.valid,digest:i.digest,assets:i.assets})}return t}function Si(e,t){let n;try{n=qt(e,t)}catch(i){if(i instanceof ve&&i.code==="declaration-missing")return[];throw i}return yr(_t(n.tree)).map(i=>({declared:i,file:Ri(i,n.rootOnDisk)}))}async function $S(e,t){let n=[];for(let i of e){let r=await ew({...t,kind:i.file});n.push({...r,declared:{member:i.declared.member,path:i.declared.path,name:i.declared.name}})}return{$schema:rw,contract:Ks,kinds:n,...t.current&&!t.uncommitted?{spec:xre(n)}:{}}}function hNe(e){try{let t=_t(e).quorum;if(t!==null)return{need:t,needFrom:"declaration"}}catch{}return{need:AJ,needFrom:"default"}}async function gh(e,t,n){if(!e.kind.reviews)return;let{checkVerdictSeal:i}=await Promise.resolve().then(()=>(Op(),Ep));return{...hNe(t),agents:new Set((n.roles[xS]??[]).map(An)),attestation:n.active,verifySeal:r=>i(n,r)}}function Wx(e){let t=e.notCounted.length>0?` (not counted: ${e.notCounted.map(n=>`${n.reviewer}, ${n.reason.code}`).join("; ")})`:"";return`its quorum needs ${e.need} agreeing verdicts that count, and it has ${e.agreed}${t}`}function Bx(e,t){let n=tr(nw(e));if(!n)return".";let i=wf(t,Yn(n.dir)).split(tw).join("/");return i===""||i.startsWith("..")?".":i}function yNe(e,t,n){let i=r=>{try{return pNe("git",r,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).split(`
339
+ `).filter(Boolean).map(Number)}catch{return[]}};return{fileChanged:r=>i(["log","-1","--format=%ct",t,"--",n==="."?r:`${n}/${r}`])[0]??null,recorded:r=>i(["log","--diff-filter=A","--format=%ct",t,"--",r])[0]??null}}async function ii(e){let t=Yn(e.cwd),n=cr(t),i=n??t,r=await Ht(e.kind,t),o=Bx(r.file,i),s=null,a=ip(i),c=Rn(o==="."?i:yG(i,...o.split("/")));if(e.at!==void 0){if(!n)throw new Xe("not-a-git-repository","--at reads git objects, and this directory is not in a git repository");s=Ol(n,e.at),a=xi(n,s),c=cd(n,s,o==="."?"":o)}s===null&&e.overlay&&(a=await e.overlay(a,{loaded:r,root:i}));let l=n?yNe(n,s??"HEAD",o):void 0,u=await Hk(r,i,a),d=await Mo(r,{root:i,source:a,current:!!e.current,assets:c,workspaceRoot:o,...l?{history:l}:{},...u?{subjects:u}:{}});return{loaded:r,root:i,top:n,at:s,workspaceRoot:o,tree:c,result:d}}async function ew(e){if(e.uncommitted&&e.at!==void 0)throw new Error("--uncommitted reads the working tree and takes no --at");try{let t,{loaded:n,root:i,top:r,at:o,workspaceRoot:s,tree:a,result:c}=await ii({...e,overlay:async($,{loaded:x,root:R})=>{if(!x.kind.answers)return $;let{readLedgerAnswers:P,refreshLedger:I,withLedgerAnswers:A}=await Promise.resolve().then(()=>(wh(),vN));e.fetchLedger&&await I(x.file);let B=await P({file:x.file,name:x.kind.name,dirRel:wf(R,x.dir).split(tw).join("/")||"."});return t=new Map([...B.byPath.values()].map(C=>[C.path,C.ledger])),A($,B)}}),l=r?ti(r,e.base):{commit:null,from:null},u=r?$i(r,l):$i(i,l),d=u.active?await jg():[],p=tZ({repo:r,policy:u,at:o,paths:c.records.map($=>$.path),attestors:d,...u.active?{revisit:await wNe(a,s,u,d)}:{}}),f=n.kind.reviews?await Promise.resolve().then(()=>(Op(),Ep)):void 0,g=await gh(n,a,u),h=[];for(let $ of c.records){let x=p.get($.path),R=x.returned?Xk(u,x.returned.id):u,P=x.returned?await gh(n,a,R):g,I=P?Kk(n.kind,$,P):null,A=n.kind.reviews?.ratified;I&&!I.met&&A!==void 0&&$.state===A&&$.warnings.push({code:"record-ratified-below-quorum",message:`${$.id??$.path} is ${A}, and ${Wx(I)}`}),h.push({...$,provenance:x,...P?{quorum:I}:{},...f?bNe(n.kind,$,R,f.checkRecordSeal):{}})}if(t)for(let $ of h)$.ledger=t.get($.path)??null;if(n.kind.approval&&!n.kind.work&&r){let $=W5(r,o??"HEAD",h.map(x=>x.path),n.kind);for(let x of h)x.decidedIn=$.get(x.path)??null}if(n.kind.work&&e.workGaps!==!1&&r&&await vNe(n,h,{root:i,workspaceRoot:s,at:e.at}),n.kind.work&&o===null&&r){let{activeWorkLeases:$}=await Promise.resolve().then(()=>(Bl(),F9)),x=await $(n.file);for(let R of h)R.id!==null&&(R.lease=x.get(R.id)??null)}if(n.kind.work?.answers){let[{workAnswers:$},{readLedgerAnswers:x,withLedgerAnswers:R}]=await Promise.all([Promise.resolve().then(()=>(Yd(),AD)),Promise.resolve().then(()=>(wh(),vN))]),P=await ii({kind:kS(nw(n.file),n.kind.work.answers),cwd:e.cwd,...e.at!==void 0?{at:e.at}:{},overlay:async(I,{loaded:A,root:B})=>R(I,await x({file:A.file,name:A.kind.name,dirRel:wf(B,A.dir).split(tw).join("/")||"."}))}).catch(I=>{if(!(I instanceof Xe))throw I});if(P){let I=$(P.result.records,h.flatMap(A=>A.id!==null?[A.id]:[]));for(let A of h)A.id!==null&&(A.answers=I.get(A.id)??[])}}let w,b=h,k=c.summary;if(o===null&&r){let{head:$,...x}=tN(r,e.base),R=wf(i,n.dir).split(tw).join("/")||".",P=h.filter(C=>!C.ledger),{states:I,deleted:A}=V5(r,$,R,h.map(C=>C.path),new RegExp(n.kind.location.match));for(let C of P)C.worktree=I.get(C.path)??"new";let B=Tx(r);for(let C of P)C.lastWrite=B(C.path,gNe(yG(r,...C.path.split("/"))));w={branch:x.branch,head:$,base:x.base,baseFrom:x.baseFrom,deleted:A},e.uncommitted&&(b=P.filter(C=>C.worktree!=="committed"),k={...k,total:b.length,valid:b.filter(C=>C.valid).length,invalid:b.filter(C=>!C.valid).length})}else if(e.uncommitted&&!r)throw new Xe("not-a-git-repository","--uncommitted compares the working tree with HEAD, and this directory is not in a git repository");return{$schema:rw,contract:Ks,kind:{name:n.kind.name,schema:n.kind.schema.id,file:wf(i,n.file).split("\\").join("/"),format:n.kind.format,spec:n.kind.spec===!0},at:o,workspaceRoot:s,current:!!e.current,uncommitted:!!e.uncommitted,...w?{checkout:w}:{},trust:{base:l.commit,baseFrom:l.from,active:u.active,signersPath:u.signersPath,problems:u.problems},records:b,summary:k,...c.decisions?{decisions:c.decisions}:{}}}catch(t){if(!(t instanceof Xe))throw t;return{$schema:rw,contract:Ks,error:{code:t.code,message:t.message}}}}async function wNe(e,t,n,i){let{readReturns:r,returnedProvenance:o}=await Promise.resolve().then(()=>(X9(),Y9)),{returns:s}=r(e);if(s.length===0)return;let a=t==="."?"":`${t}/`;return(c,l)=>{if(!c.startsWith(a))return;let u=c.slice(a.length),d=s.filter(f=>f.paths[u]!==void 0);if(d.length===0||e.stat(u)!=="file")return;let p=Buffer.from(e.bytes?e.bytes(u):e.read(u));for(let f of d){let g=o(n,i,f,u,p,l);if(g)return g}}}function bNe(e,t,n,i){if(t.data===null)return{};let r=e.reviews.decider,o=typeof t.data[r]=="string"&&t.data[r].trim()!==""?t.data[r]:null,{attested:s,...a}=i(n,{record:t.id,digest:t.digest,author:o,authorField:r,state:t.state,seal:t.data[wn]});return n.active&&o!==null&&s!==!0&&t.warnings.push({code:"record-unattested",message:`an attestation policy is active at base, and ${a.message}`}),{attested:s,attestation:a}}async function vNe(e,t,n){let i=e.kind.work,r=new Map;for(let u of t){if(u.id===null||u.state!==i.done)continue;let d=u.data?.source;if(d===null||typeof d!="object"||Array.isArray(d))continue;let{finding:p,region:f}=d;typeof p!="string"||typeof f!="string"||r.set(f,[...r.get(f)??[],u])}if(r.size===0)return;let o=n.workspaceRoot==="."?n.root:yG(n.root,...n.workspaceRoot.split("/")),s;try{s=Si(o,n.at).map(u=>u.file)}catch(u){if(u instanceof ve)return;throw u}let a=[],c=new Set;for(let u of[...s,kS(nw(e.file),i.decisions),e.file]){let d=Yn(u);c.has(d)||(c.add(d),a.push(u))}let{intentGraph:l}=await Promise.resolve().then(()=>(Ty(),wre));for(let[u,d]of r){let{doc:p}=await l({cwd:o,region:u,at:n.at,kinds:a});if(!("error"in p))for(let f of d){let g=p.nodes.find(w=>w.kind==="work"&&w.id===`record:${e.kind.name}/${f.id}`),h=g?.kind==="work"?g.warnings.find(w=>w.code==="work-done-gap-open"):void 0;h&&!f.warnings.some(w=>w.code===h.code)&&f.warnings.push(h)}}}function $re(e,t,n){let i=Yn(kS(t,e)),r=n===void 0?nw(i):nw(kS(t,n)),o=n===void 0?tr(t)??tr(r):tr(r),s=cr(r),a=Yn(o?o.dir:s||t),c=wf(a,i).split(tw).join("/");if(c.startsWith("..")||!Jn(c))return{error:`${e} is not a file path inside the workspace at ${a}`};let l=$D(Rn(a),c);return l===void 0?{error:`${e} is not a file`}:{path:c,sha256:l}}async function kNe(e){let{args:t}=e;if(t.extraPositional==="new"||t.extraPositional==="amend"||t.extraPositional==="review"||t.extraPositional==="close")return(await Promise.resolve().then(()=>(dh(),$9))).runRecordsWrite(e);if(t.extraPositional==="pin"){if(!t.extraPositional2)return console.error(we({message:"pin needs the path of a file",hint:Ur})),1;let r=$re(t.extraPositional2,process.cwd(),t.kind);return"error"in r?(console.error(we({message:r.error,hint:Ur})),1):(console.log(JSON.stringify(r,null,2)),0)}if(t.extraPositional)return console.error(we({message:`chant workspace records takes no argument but pin, new, amend, review or close (got ${t.extraPositional})`,hint:Ur})),1;let n=RNe(t);if(n)return console.error(we({message:n,hint:Ur})),1;if(!t.kind)return xNe(t);if(t.require!==void 0&&t.require!=="attested")return console.error(we({message:`--require takes one level, attested, not ${JSON.stringify(t.require)}`,hint:Ur})),1;if(t.since!==void 0){if(t.current||t.require!==void 0||t.base!==void 0)return console.error(we({message:"--since compares two revisions and takes no --current, --require or --base",hint:Ur})),1;let{formatSince:r,queryRecordsSince:o}=await Promise.resolve().then(()=>(hG(),gG)),s=await o({kind:t.kind,since:t.since,at:t.at,cwd:process.cwd()});return t.json?console.log(JSON.stringify(s,null,2)):"error"in s?console.error(we({message:`${s.error.code}: ${s.error.message}`,hint:Ur})):console.log(r(s)),"error"in s?1:0}let i=await ew({kind:t.kind,current:t.current,uncommitted:t.uncommitted,at:t.at,base:t.base,cwd:process.cwd(),fetchLedger:!0});if(t.json?console.log(JSON.stringify(i,null,2)):"error"in i?console.error(we({message:`${i.error.code}: ${i.error.message}`,hint:Ur})):console.log(Rre(i.records,i.summary,i.at,i.checkout)),"error"in i)return 1;if(t.require){let r=bG(i.records,t.require);if(r.length>0)return console.error(we({message:`${r.length} of ${i.records.length} records are not ${t.require}: ${r.slice(0,5).map(o=>`${o.path} (${o.provenance.level})`).join(", ")}${r.length>5?", ...":""}`,hint:i.trust.active?"run with --json to see each record's reason":`there is no signers file (${i.trust.signersPath}) at base`})),wG}return 0}async function xNe(e){if(e.require!==void 0&&e.require!=="attested")return console.error(we({message:`--require takes one level, attested, not ${JSON.stringify(e.require)}`,hint:Ur})),1;let t;try{t=Si(process.cwd(),e.at)}catch(i){if(!(i instanceof ve))throw i;let r=`${i.describe()}; without --kind, the declaration names the record kinds`;return e.json&&(i.code==="not-a-git-repository"||i.code==="revision-unknown")?console.log(JSON.stringify({$schema:rw,contract:Ks,error:{code:i.code,message:r}},null,2)):console.error(we({message:`${i.code}: ${r}`,hint:Ur})),1}if(t.length===0)return console.error(we({message:"--kind <kind file> is required",hint:Ur})),1;if(e.since!==void 0)return $Ne(t,e);let n=await $S(t,{current:e.current,uncommitted:e.uncommitted,at:e.at,base:e.base,cwd:process.cwd(),fetchLedger:!0});e.json&&console.log(JSON.stringify(n,null,2));for(let i of e.json?[]:n.kinds){if("error"in i){console.error(we({message:`${i.declared.path}: ${i.error.code}: ${i.error.message}`,hint:Ur}));continue}console.log(`${i.declared.name??i.kind.name} (${i.declared.path})`),console.log(Rre(i.records,i.summary,i.at,i.checkout))}if(n.kinds.some(i=>"error"in i))return 1;if(e.require){let i=n.kinds.filter(s=>!("error"in s)),r=i.flatMap(s=>s.records),o=bG(r,e.require);if(o.length>0){let s=i.find(a=>!a.trust.active);return console.error(we({message:`${o.length} of ${r.length} records are not ${e.require}: ${o.slice(0,5).map(a=>`${a.path} (${a.provenance.level})`).join(", ")}${o.length>5?", ...":""}`,hint:s?`there is no signers file (${s.trust.signersPath}) at base`:"run with --json to see each record's reason"})),wG}}return 0}async function $Ne(e,t){if(t.current||t.require!==void 0||t.base!==void 0)return console.error(we({message:"--since compares two revisions and takes no --current, --require or --base",hint:Ur})),1;let{formatSince:n,queryRecordsSince:i,RECORDS_SINCE_OUTPUT_SCHEMA_ID:r}=await Promise.resolve().then(()=>(hG(),gG)),o=[];for(let s of e){let a=await i({kind:s.file,since:t.since,at:t.at,cwd:process.cwd()});o.push({...a,declared:{member:s.declared.member,path:s.declared.path,name:s.declared.name}})}t.json&&console.log(JSON.stringify({$schema:r,contract:Ks,kinds:o},null,2));for(let s of t.json?[]:o){if("error"in s){console.error(we({message:`${s.declared.path}: ${s.error.code}: ${s.error.message}`,hint:Ur}));continue}console.log(`${s.declared.name??s.kind.name} (${s.declared.path})`),console.log(n(s))}return o.some(s=>"error"in s)?1:0}function Yn(e){try{return mNe(e)}catch{return e}}function bG(e,t){return e.filter(n=>n.provenance.level!==t)}function RNe(e){if(e.uncommitted){if(e.at!==void 0)return"--uncommitted reads the working tree against HEAD, and takes no --at";if(e.since!==void 0)return"--uncommitted takes no --since: --since compares two revisions"}}function Rre(e,t,n,i){let r=[],o=Math.max(2,...e.map(a=>(a.id??"-").length)),s=Math.max(5,...e.map(a=>(a.state??"-").length));for(let a of e){let c=typeof a.data?.title=="string"?a.data.title:a.path,l=a.valid?"":" INVALID",u=a.supersededBy?` superseded by ${a.supersededBy}`:"",d=a.remediatedBy.length>0?` remediated by ${a.remediatedBy.join(", ")}`:"",p=a.provenance.level==="attested"?` attested by ${a.provenance.principal}`:"",f=a.attested===!0?` sealed by ${(a.data?.[wn]).signer}`:"",g=a.worktree==="new"||a.worktree==="modified"?` (${a.worktree}, uncommitted)`:"",h=a.ledger?` (held on ${a.ledger})`:"";if(r.push(`${(a.id??"-").padEnd(o)} ${(a.state??"-").padEnd(s)} ${c}${u}${d}${p}${f}${g}${h}${l}`),a.ready!==void 0){let b=(a.blockedBy??[]).map(R=>`${R.id} (${R.state??"unknown"})`).join(", "),k=(a.implements??[]).map(R=>`${R.id} (${R.state??"unknown"})`).join(", "),$=a.lease?`held by ${a.lease.holder} until ${a.lease.expiresAt}`:"",x=[a.ready?"ready":b?`blocked by ${b}`:"",k?`implements ${k}`:"",$].filter(Boolean).join("; ");x&&r.push(`${" ".repeat(o+2)}${x}`)}for(let b of a.reasons)r.push(`${" ".repeat(o+2)}${b.code}: ${b.message} (${a.path})`);for(let b of a.warnings)r.push(`${" ".repeat(o+2)}warning ${b.code}: ${b.message} (${a.path})`);let w=a.quorum;if(w&&w.counted.length+w.notCounted.length>0){let b=w.metWithObjections?"met with objections":w.met?"met":"not met",k=w.openConcerns.length>0?`, ${w.openConcerns.length} open ${w.openConcerns.length===1?"concern":"concerns"}`:"";r.push(`${" ".repeat(o+2)}quorum ${w.agreed} of ${w.need} agreed, ${b}; ${w.notCounted.length} not counted${k}`)}}for(let a of i?.deleted??[])r.push(`${"-".padEnd(o)} ${"-".padEnd(s)} ${a} (deleted, uncommitted)`);if(r.push(`${t.total} records${n?` at ${n.slice(0,8)}`:""}: ${t.valid} valid, ${t.invalid} invalid, ${t.superseded} superseded`),i){let a=i.branch??"a detached HEAD",c=i.head?` at ${i.head.slice(0,8)}`:" with no commits",l=i.base?`, forked from ${i.base.slice(0,8)} of ${i.baseFrom}`:"";r.push(`working tree on ${a}${c}${l}`)}return r.join(`
340
+ `)}async function SNe(e){let t=e.args.path&&e.args.path!=="."?e.args.path:"";return console.error(we({message:t?`Unknown workspace subcommand: ${t}`:"chant workspace needs a subcommand",hint:'Workspace subcommands: adopt-lineage, audit, build, check, evidence, graph, hash-index, init, lineage, lint, ls, pin, records, signers, status, upgrade, verify, versions, work. Run "chant --help" for their options.'})),1}var Ks,rw,Ur,wG,xS,Ei=v(()=>{"use strict";ur();Mi();No();B5();Qi();Tt();cc();Wr();un();nN();oh();on();lp();Pl();Go();Ks=1,rw="https://intentius.io/chant/schemas/workspace/records/v1/records.schema.json",Ur="chant workspace records [--kind <kind file>] [--current] [--uncommitted | --at <rev>] [--base <rev>] [--require attested] [--json] | chant workspace records [--kind <kind file>] --since <rev|session id> [--at <rev>] [--json] | chant workspace records pin <path> [--kind <kind file>] | chant workspace records new|amend|review|close (#2670, #2693)",wG=2,xS="agent"});var OG={};_e(OG,{POINTS_WRITE_CONTRACT_VERSION:()=>go,POINTS_WRITE_ERROR_CODES:()=>ONe,POINTS_WRITE_SCHEMA_ID:()=>ho,PointsWriteError:()=>wt,STEWARD_HARNESS:()=>vG,answerFields:()=>bf,answerKindFiles:()=>kG,answerPoint:()=>RG,askPoint:()=>xG,askedByOf:()=>SS,questionView:()=>gu,reasonFields:()=>OS,retractAnswer:()=>SG,tallyQuorum:()=>Ore,withdrawQuestion:()=>EG});import{writeFileSync as ENe}from"node:fs";function ANe(e){if(!Array.isArray(e.retractions))return[];let t=i=>typeof i=="string"?i:null,n=i=>Array.isArray(i)?i.filter(r=>typeof r=="string"):[];return e.retractions.filter(i=>i!==null&&typeof i=="object"&&!Array.isArray(i)).map(i=>({answer:typeof i.answer=="string"||typeof i.answer=="boolean"?i.answer:null,decider:i.decider!==null&&typeof i.decider=="object"&&!Array.isArray(i.decider)?i.decider:{},answeredBy:n(i.answered_by),answeredOn:t(i.answered_on),answerNote:t(i.answer_note),answerRelayedBy:t(i.answer_relayed_by),by:n(i.by),on:t(i.on),note:t(i.note)}))}function PNe(e){let t=e.withdrawn;if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t;return{by:Array.isArray(n.by)?n.by.filter(i=>typeof i=="string"):[],on:typeof n.on=="string"?n.on:null,note:typeof n.note=="string"?n.note:null}}function SS(e){let t=e.source;if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t;if(n.harness!==vG)return null;let i=n.client,r=i&&typeof i.name=="string"?i.name:null;if(r===null)return null;let o=n.session,s=typeof o=="string"?o:o&&typeof o=="object"&&typeof o.id=="string"?o.id:null;return{steward:r,run:s}}function gu(e,t,n=null){let i=e.data;if(i===null||e.id===null)return null;let r=f=>typeof f=="string"?f:null,o=f=>typeof f=="number"?f:null,s=["escalated","proposed","answered"].find(f=>f===e.state)??"escalated",a=i.decider!==null&&typeof i.decider=="object"&&!Array.isArray(i.decider)?i.decider:{},c=Array.isArray(i.escalations)?i.escalations:[],l=typeof i.answer=="string"||typeof i.answer=="boolean"?i.answer:null,u=null;if(a.kind==="model")u={answer:l,confidence:o(i.confidence),threshold:o(i.threshold),model:r(a.model),backend:r(a.backend),observed:!0,reason:r(i.reason)};else{let f=[...c].reverse().find(g=>g.kind==="model"&&g.answer!==void 0&&g.answer!==null);f&&(u={answer:f.answer??null,confidence:f.confidence??null,threshold:f.threshold??null,model:f.model??null,backend:f.backend??null,observed:!1,reason:typeof f.model_reason=="string"?f.model_reason:null})}let d=Array.isArray(i.constrains)?i.constrains.filter(f=>typeof f=="string"):[],p=PNe(i);return{id:e.id,path:e.path,point:r(i.point)??"",title:r(i.title)??"",subject:d[0]??null,state:s,open:s!=="answered"&&p===null,questionType:r(i.question_type)??"",candidates:Array.isArray(i.candidates)?i.candidates:[],inputs:i.inputs!==null&&typeof i.inputs=="object"&&!Array.isArray(i.inputs)?i.inputs:{},inputsHash:r(i.inputs_hash)??"",pointVersion:r(i.point_version)??"",current:t?za(t)===i.point_version:null,answer:l,decider:a,probabilities:i.probabilities!==null&&typeof i.probabilities=="object"?i.probabilities:null,confidence:o(i.confidence),threshold:o(i.threshold),reason:a.kind==="model"?r(i.reason):null,model:u,escalations:c,answeredBy:Array.isArray(i.answered_by)?i.answered_by.filter(f=>typeof f=="string"):[],askedOn:r(i.asked_on),answeredOn:r(i.answered_on),note:r(i.note),relayedBy:r(i.relayed_by),retractions:ANe(i),withdrawn:p,asked:ep(i)??null,askedBy:SS(i),ledger:n,valid:e.valid,warnings:e.warnings}}function Tc(e,t){if(t instanceof wt||t instanceof Ee||t instanceof Xe||t instanceof As||t instanceof sc)return{$schema:ho,contract:go,verb:e,error:{code:t.code,message:t.message}};if(t instanceof ve)return{$schema:ho,contract:go,verb:e,error:{code:"points-undeclared",message:`the declaration can't be read: ${t.code}: ${t.message}`}};throw t}async function kG(e,t){if(t!==void 0)return[Cp(t,e)];let n=[];for(let i of Si(e))try{(await Ht(i.file)).kind.answers&&n.push(i.file)}catch(r){if(!(r instanceof Xe))throw r}return n}async function Sre(e,t){let n=await Ts(e,t);if(!n.loaded.kind.answers)throw new wt("points-undeclared",`the ${n.loaded.kind.name} kind has no answers block, so it holds no answers to decision points`);let i=np(n.loaded,n.root),r=rp(n.source,i);if("error"in r)throw new wt("points-invalid",r.error);return{o:n,points:r.points,pointsFile:i}}function iw(e,t,n,i,r){let o=n==="withdrawn"?"withdrawn":n==="escalated"?"open for people":n==="proposed"?`${_c(i,e.question.type)}, proposed`:_c(i,e.question.type);return`${r?r.question:e.title}${t?` (${t})`:""}: ${o}`}function ow(e,t,n){let i=Qd(e,n),r=s=>i.type==="score"?"":i.criteria?.[String(s)]??"",o=Fo(i).map(s=>`- ${_c(s,i.type)}${r(s)?`: ${r(s)}`:""}`);return["",`# ${t}`,"",i.instructions.trim(),"",...o,""].join(`
341
+ `)}async function CNe(e,t,n){if(e.length===0)throw new wt("points-undeclared","no record kind with an answers block is declared: name one with --kind, or declare one in chant.workspace.json");let i=[];for(let r of e){let o=await Sre(r,n),s=Rl(o.points,t);if(s)return{...o,point:s};i.push(...Object.keys(o.points))}throw new wt("point-unknown",`no points file declares ${JSON.stringify(t)}${i.length?` (the points are ${i.join(", ")})`:""}`)}function _Ne(e,t,n,i){if(!t.adhoc){if(n!==void 0)throw new wt("point-candidates-invalid",`${e} declares its candidates, so the ask gives none: --candidates is for an ad-hoc point`);return}if(n===void 0)throw new wt("point-candidates-invalid",`${e} is an ad-hoc point, so each ask gives the question and its candidates: --candidates <file|-|json>`);let r=ID(t,n);if("problems"in r)throw new wt("point-candidates-invalid",`the candidates for ${e}, a ${t.question.type} question: ${r.problems.join("; ")}`);if(!bf(i.schema).asked)throw new wt("answer-field-unsupported",`the ${i.kind.name} kind's schema has no asked field, so an ad-hoc question's text and candidates can't be kept: copy point-answer.schema.json from @intentius/chant anew`);return r.asked}function TNe(e,t,n){if(n===null||typeof n!="object"||Array.isArray(n))throw new wt("point-inputs-invalid",`the inputs to ${e} must be a JSON object`);let i=Object.keys(t.inputs),r=Object.keys(n).filter(o=>!i.includes(o));if(r.length>0)throw new wt("point-inputs-invalid",`${e} reads ${i.join(", ")}, and the inputs also give ${r.join(", ")}`);return n}async function sw(e,t,n,i,r,o,s){let a=await Gx(e,t,n,i,s.source),c=s.ledger.byPath.get(n);if(s.onLedger){if(o)return{warnings:a,ledger:c?.ledger??null};try{let{ledger:l}=await bN(s.ledger,n,i,s.message,c?.sha??null);return{warnings:a,ledger:l}}catch(l){throw l instanceof Ot?new wt("record-id-taken",`${n} was written on chant/lifecycle by another ask or answer at the same time: ask again to read it`):l}}if(!o)try{ENe(Jo(e,n),i,r?{flag:"wx"}:void 0),Cs(e.root,[{path:n,text:i}],s.who)}catch(l){throw l.code==="EEXIST"?new wt("record-id-taken",`${n} was written by another ask at the same time: ask again to read it`):l}return{warnings:a,ledger:null}}async function Ere(e){let t=await hh({file:e.loaded.file,name:e.loaded.kind.name,dirRel:e.dirRel}),n=yh(e.source,t);return{ledger:t,source:n,before:await ro(e,n)}}function aw(e,t){let n=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0));return pc(n,Tp(n,{properties:e.loaded.schema.properties}))}function OS(e){let t=(i,r)=>i!==null&&typeof i=="object"&&Object.prototype.hasOwnProperty.call(i,r),n=e.definitions??e.$defs;return{top:t(e.properties,"reason"),escalation:t(n?.escalation?.properties,"model_reason")}}function INe(e,t){return t.escalation?e:e.map(({model_reason:n,...i})=>i)}function DNe(e,t){let n=e.escalations.length>0?INe(e.escalations,t):void 0;if(e.status==="proposed"){let i=t.top?e.reason:void 0;return{state:"proposed",answer:e.answer,decider:e.decider,probabilities:e.probabilities,confidence:e.confidence,threshold:e.threshold,reason:i,escalations:n}}return e.status==="answered"?{state:"answered",answer:e.answer,decider:e.decider,escalations:n}:{state:"escalated",decider:e.decider,escalations:n}}async function xG(e){try{return await no(e.cwd,{verb:"points ask",by:e.steward?.name??null},e.dryRun,()=>jNe(e))}catch(t){return Tc("ask",t)}}async function jNe(e){try{let t=e.steward?void 0:Ho(),n=e.steward??(t?{name:t.steward,...t.run?{run:t.run}:{}}:void 0),i=e.store!==void 0?e.store==="ledger":n!==void 0,r=await kG(e.cwd,e.kind),{o,point:s}=await CNe(r,e.point,e.cwd),a=TNe(e.point,s,e.inputs),c=_Ne(e.point,s,e.candidates,o.loaded),l=za(s),u=TD(e.point,l,a,c),d=DD(e.point,u);i&&!e.dryRun&&await zx(o.loaded.file);let{ledger:p,source:f,before:g}=await Ere(o),h=g.find(be=>be.id===d),w=be=>p.byPath.get(be.path)?.ledger??null,b=(be,Be)=>({$schema:ho,contract:go,verb:"ask",kind:o.view,id:d,path:be.path,reused:Be.reused,written:Be.written,dryRun:!!e.dryRun,question:gu(be,s,Be.ledger!==void 0?Be.ledger:w(be)),...Be.text!==void 0?{text:Be.text}:{}}),k=async be=>{let{withdrawn:Be,...dt}=be.data,ne=Array.isArray(dt.constrains)&&typeof dt.constrains[0]=="string"?dt.constrains[0]:void 0,ye=iw(s,ne,String(dt.state),dt.answer,c),ge=aw(o,{...dt,title:ye}),oe=Is(ge,ow(s,ye,c)),Se=`Decision point ${e.point}: asked again${ne?` (${ne})`:""}`,Ne=await sw(o,g,be.path,oe,!1,!!e.dryRun,{source:f,ledger:p,onLedger:i||p.byPath.has(be.path),message:Se,who:{verb:"points ask",by:n?.name??null}});return b({...be,data:ge,valid:!0,reasons:[],warnings:Ne.warnings},{reused:!1,written:!e.dryRun,ledger:Ne.ledger,...e.dryRun?{text:oe}:{}})},$=h!==void 0&&h.data!==null&&h.data.withdrawn!==void 0;if(h&&h.data!==null&&!$&&(h.state==="answered"||h.state==="proposed"))return b(h,{reused:!0,written:!1});if(h&&h.data!==null&&Array.isArray(h.data.retractions)&&h.data.retractions.length>0)return $?k(h):b(h,{reused:!0,written:!1});let x;try{x=await jD(e.point,{...s,question:Qd(s,c)},a,e.ask)}catch(be){throw be instanceof Xd?new wt("point-decider-failed",be.message):be}if(h&&h.data!==null&&!$&&x.status==="escalated")return b(h,{reused:!0,written:!1});let R=e.on??ES(),P=x.status,I=x.status==="escalated"?void 0:x.answer,A=iw(s,e.subject,P,I,c),B=x.status==="proposed"?x.decider.model:void 0,C=n?{name:n.name}:e.client,q={via:e.via??"cli",...n?{harness:vG}:{},...C?{client:C}:{},...B?{model:B}:{},...n?.run?{session:{id:n.run}}:{}},L=aw(o,{id:d,title:A,point:e.point,point_version:l,question_type:s.question.type,candidates:Fo(Qd(s,c)),asked:c,inputs:a,inputs_hash:u,constrains:e.subject!==void 0?[e.subject]:h?.data?.constrains,...DNe(x,OS(o.loaded.schema)),asked_on:R,answered_on:P==="answered"?R:void 0,source:q}),M=h?h.path:o.dirRel==="."?`${d}.md`:`${o.dirRel}/${d}.md`,_=Is(L,ow(s,A,c)),T=i||p.byPath.has(M),W=`Decision point ${e.point}: ${P}${e.subject?` (${e.subject})`:""}${n?`, asked by ${n.name}`:""}`,ke=await sw(o,g,M,_,!h,!!e.dryRun,{source:f,ledger:p,onLedger:T,message:W,who:{verb:"points ask",by:n?.name??null}}),re={...h??NNe(M),id:d,path:M,state:P,data:L,valid:!0,reasons:[],warnings:ke.warnings};return b(re,{reused:!1,written:!e.dryRun,ledger:ke.ledger,...e.dryRun?{text:_}:{}})}catch(t){return Tc("ask",t)}}function NNe(e){return{id:null,path:e,state:null,valid:!0,reasons:[],supersededBy:null,remediatedBy:[],data:null,assets:[],warnings:[],digest:""}}function bf(e){let t=e.properties,n=i=>t!=null&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,i);return{note:n("note"),retractions:n("retractions"),relayedBy:n("relayed_by"),asked:n("asked"),withdrawn:n("withdrawn")}}function LNe(e){if(!cr(e))return eo(null);try{return $i(e,ti(e))}catch{return eo(null)}}function Ore(e,t,n,i){let r=u=>new Set((n.roles[u]??[]).map(An)),o=r(xS),s=i!==void 0?An(i):void 0,a=[],c=new Set,l=[];for(let u of e){let d=An(u);if(!(d===""||c.has(d))){if(c.add(d),s!==void 0&&d===s){l.push({name:u,why:"is the steward that asked"});continue}if(o.has(d)){l.push({name:u,why:"holds the agent role"});continue}if(t.roles&&!t.roles.some(p=>r(p).has(d))){l.push({name:u,why:`holds none of the roles ${t.roles.join(", ")}`});continue}a.push(u)}}return{counted:a,left:l,met:a.length>=t.count}}function Are(e,t){let n=Ho();if(n)throw new wt("answer-in-steward-turn",`this is the steward ${n.steward}'s turn, and a steward never ${t} a decision point: a person ${t==="answers"?"answers":"retracts the answer to"} ${e} through hud or \`chant workspace points ${t==="answers"?"answer":"retract"}\` at a shell`)}async function $G(e,t,n){let i=await kG(e,t);if(i.length===0)throw new wt("points-undeclared","no record kind with an answers block is declared: name one with --kind, or declare one in chant.workspace.json");for(let r of i){let o=await Sre(r,e);await zx(o.o.loaded.file);let s=await Ere(o.o),a=s.before.find(c=>c.id===n);if(a&&a.data!==null)return{opened:o,before:s.before,read:s,target:a}}throw new wt("record-not-found",`no answer record has id ${n}`)}function Cre(e,t,n,i,r,o,s){let a=di(s),c=a?{counted:[],left:t.map(l=>({name:l,why:`was named over ${Pre(s)}, where an answer is an agent's`})),met:!1}:Ore(t,n,LNe(i),r);if(!c.met){let l=c.counted.length,u=c.left.length?`; not counted: ${c.left.map(p=>`${p.name}, who ${p.why}`).join("; ")}`:"",d=a?`: a person ${o==="answer"?"answers":"retracts it"} at a shell with \`chant workspace points ${o}\`, or through hud`:"";throw new wt("quorum-not-met",`${e} needs ${n.count} ${n.count===1?"person":"people"}${n.roles?` holding ${n.roles.join(" or ")}`:""} to ${o==="answer"?"answer":"retract an answer"}, and ${l} ${l===1?"counts":"count"}${l?` (${c.counted.join(", ")})`:""}${u}${d}`)}return c}function MNe(e){let t=[];for(let n of Array.isArray(e.constrains)?e.constrains:[]){if(typeof n!="string"||!n.startsWith("gate:"))continue;let i=n.slice(5),r=i.lastIndexOf("@"),o=r>0?i.slice(0,r):i,s=o.indexOf("/");s>0&&s<o.length-1&&t.push({op:o.slice(0,s),gate:o.slice(s+1)})}return t}async function _re(e,t,n,i,r){if(!di(i))return;let o=MNe(t);if(o.length===0)return;let{isNeverOverMcpGateOp:s}=await Promise.resolve().then(()=>(Yr(),TV)),{readGateLedger:a}=await Promise.resolve().then(()=>(Mr(),UI)),c;for(let{op:l,gate:u}of o){let d=s(l);if(!d){let{pending:p}=await a(l,{cwd:n}).catch(()=>({pending:[]}));d=p.some(f=>f.gate===u&&f.neverOverMcp===!0)}if(!d){if(c===void 0){let{discoverOps:p}=await Promise.resolve().then(()=>(qo(),qj));c=await p({cwd:n}).then(f=>f.ops).catch(()=>new Map)}d=!!c.get(l)?.config.neverOverMcp}if(d)throw new wt("answer-never-over-mcp",`${e} constrains gate "${u}" on "${l}", which is never resolved over ${Pre(i)}, so its question is not ${r==="answers"?"answered":"retracted"} there either: a person ${r==="answers"?"answers":"retracts the answer to"} it at a shell with \`chant workspace points ${r==="answers"?"answer":"retract"} ${e}\`, or through hud`)}}async function RG(e){try{return await no(e.cwd,{verb:"points answer",by:(e.by??[]).join(", ")||null},e.dryRun,()=>FNe(e))}catch(t){return Tc("answer",t)}}async function FNe(e){try{Are(e.id,"answers"),zo(to(e.cwd),e.by,"--by");let t=RS(e.relayedBy);t!==void 0&&zo(to(e.cwd),[t],"--relayed-by");let n=await $G(e.cwd,e.kind,e.id),{opened:i,before:r,target:o}=n,s=n.read.ledger,{o:a}=i,c=o.data;if(o.state==="answered")throw new wt("record-closed",`${e.id} is answered, and an answer never changes in place: retract it with \`points retract ${e.id}\` and answer again, ask again with other inputs, or change the point, which asks the question anew`);if(c.withdrawn!==void 0)throw new wt("record-closed",`${e.id} was withdrawn, so nobody answers it: ask it again with \`points ask\`, which opens it again, when it applies again`);let l=RS(e.note);if(l!==void 0&&!bf(a.loaded.schema).note)throw new wt("answer-field-unsupported",`the ${a.loaded.kind.name} kind's schema has no note field, so ${e.id} can't keep the note: copy point-answer.schema.json from @intentius/chant anew`);if(t!==void 0&&!bf(a.loaded.schema).relayedBy)throw new wt("answer-field-unsupported",`the ${a.loaded.kind.name} kind's schema has no relayed_by field, so ${e.id} can't record who relayed the answer: copy point-answer.schema.json from @intentius/chant anew`);let u=String(c.point),d=Rl(i.points,u);if(!d)throw new wt("point-unknown",`${e.id} answers ${u}, which ${i.pointsFile} no longer declares`);let p=ep(c),f=p?Fo(Qd(d,p)):Array.isArray(c.candidates)?c.candidates:Fo(d.question),g=String(c.question_type),h=g==="noul"&&typeof e.answer=="string"?{true:!0,yes:!0,false:!1,no:!1}[e.answer.toLowerCase()]:e.answer;if(h===void 0||!f.includes(h))throw new wt("answer-not-candidate",`${e.id} takes one of ${f.map(T=>JSON.stringify(T)).join(", ")}, not ${JSON.stringify(e.answer)}`);let w=e.origin??bs();await _re(e.id,c,a.root,w,"answers");let b=tp(d),k=Cre(u,e.by,b,a.root,SS(c)?.steward,"answer",w),$=e.on??ES(),x=c.decider,R=o.state==="proposed"&&x.kind==="model"&&c.answer===h,P=Array.isArray(c.escalations)?[...c.escalations]:[],I;R?I={...c,state:"answered",answered_by:k.counted,answered_on:$,note:l,relayed_by:t}:(o.state==="proposed"&&x.kind==="model"&&P.push({kind:"model",backend:String(x.backend),model:String(x.model),answer:c.answer,...c.probabilities?{probabilities:c.probabilities}:{},...typeof c.confidence=="number"?{confidence:c.confidence}:{},...typeof c.threshold=="number"?{threshold:c.threshold}:{},reason:`proposed ${_c(c.answer,g)}, and people answered ${_c(h,g)}`,...typeof c.reason=="string"&&OS(a.loaded.schema).escalation?{model_reason:c.reason}:{}}),I={...Object.fromEntries(Object.entries(c).filter(([W])=>W!=="probabilities"&&W!=="confidence"&&W!=="threshold"&&W!=="reason")),state:"answered",answer:h,decider:{kind:"quorum",count:b.count,...b.roles?{roles:b.roles}:{},by:k.counted},escalations:P.length>0?P:void 0,answered_by:k.counted,answered_on:$,note:l,relayed_by:t});let A=Array.isArray(c.constrains)&&typeof c.constrains[0]=="string"?c.constrains[0]:void 0;I.title=iw(d,A,"answered",h,p);let B=aw(a,I),C=Is(B,ow(d,String(I.title),p)),q=s.byPath.has(o.path),L=`Decision point ${u}: answered ${_c(h,g)} by ${k.counted.join(", ")}${t?`, relayed by ${t}`:""}`,M=await sw(a,r,o.path,C,!1,!!e.dryRun,{source:n.read.source,ledger:s,onLedger:q,message:L,who:{verb:"points answer",by:k.counted.join(", ")}}),_={...o,state:"answered",data:B,valid:!0,reasons:[],warnings:M.warnings};return{$schema:ho,contract:go,verb:"answer",kind:a.view,id:e.id,path:o.path,reused:!1,written:!e.dryRun,dryRun:!!e.dryRun,question:gu(_,d,q?M.ledger??s.byPath.get(o.path)?.ledger??null:null),...e.dryRun?{text:C}:{}}}catch(t){return Tc("answer",t)}}async function SG(e){try{return await no(e.cwd,{verb:"points retract",by:(e.by??[]).join(", ")||null},e.dryRun,()=>GNe(e))}catch(t){return Tc("retract",t)}}async function GNe(e){try{Are(e.id,"retracts"),zo(to(e.cwd),e.by,"--by");let t=await $G(e.cwd,e.kind,e.id),{opened:n,before:i,target:r}=t,o=t.read.ledger,{o:s}=n,a=r.data;if(r.state!=="answered")throw new wt("answer-not-answered",`${e.id} is ${r.state??"not answered"}, so there is no answer to retract: answer it with \`points answer ${e.id}\``);if(!bf(s.loaded.schema).retractions)throw new wt("answer-field-unsupported",`the ${s.loaded.kind.name} kind's schema has no retractions field, so ${e.id} can't keep the answer it would retract: copy point-answer.schema.json from @intentius/chant anew`);let c=String(a.point),l=Rl(n.points,c);if(!l)throw new wt("point-unknown",`${e.id} answers ${c}, which ${n.pointsFile} no longer declares, so no quorum can take the answer back: ask the point as it is declared now`);let u=e.origin??bs();await _re(e.id,a,s.root,u,"retracts");let d=tp(l),p=Cre(c,e.by,d,s.root,SS(a)?.steward,"retract",u),f=e.on??ES(),g=String(a.question_type),h=a.decider!==null&&typeof a.decider=="object"&&!Array.isArray(a.decider)?a.decider:{kind:"quorum"},w=a.answer,b=RS(e.note),k={answer:w,decider:h,answered_by:Array.isArray(a.answered_by)&&a.answered_by.length>0?a.answered_by:void 0,answered_on:typeof a.answered_on=="string"?a.answered_on:void 0,answer_note:typeof a.note=="string"?a.note:void 0,answer_relayed_by:typeof a.relayed_by=="string"?a.relayed_by:void 0,by:p.counted,on:f,note:b},$=Array.isArray(a.escalations)?[...a.escalations]:[];h.kind==="model"&&$.push({kind:"model",backend:String(h.backend),model:String(h.model),answer:w,...a.probabilities?{probabilities:a.probabilities}:{},...typeof a.confidence=="number"?{confidence:a.confidence}:{},...typeof a.threshold=="number"?{threshold:a.threshold}:{},reason:`proposed ${_c(w,g)}, which people confirmed and then retracted`,...typeof a.reason=="string"&&OS(s.loaded.schema).escalation?{model_reason:a.reason}:{}});let x=new Set(["answer","answered_by","answered_on","note","relayed_by","probabilities","confidence","threshold","reason"]),R=Object.fromEntries(Object.entries(a).filter(([W])=>!x.has(W))),P=Array.isArray(a.retractions)?a.retractions:[],I=Array.isArray(a.constrains)&&typeof a.constrains[0]=="string"?a.constrains[0]:void 0,A=ep(a),B=iw(l,I,"escalated",void 0,A),C=aw(s,{...R,title:B,state:"escalated",decider:{kind:"quorum",count:d.count,...d.roles?{roles:d.roles}:{}},escalations:$.length>0?$:void 0,retractions:[...P,Object.fromEntries(Object.entries(k).filter(([,W])=>W!==void 0))]}),q=Is(C,ow(l,B,A)),L=o.byPath.has(r.path),M=`Decision point ${c}: ${_c(w,g)} retracted by ${p.counted.join(", ")}`,_=await sw(s,i,r.path,q,!1,!!e.dryRun,{source:t.read.source,ledger:o,onLedger:L,message:M,who:{verb:"points retract",by:p.counted.join(", ")}}),T={...r,state:"escalated",data:C,valid:!0,reasons:[],warnings:_.warnings};return{$schema:ho,contract:go,verb:"retract",kind:s.view,id:e.id,path:r.path,reused:!1,written:!e.dryRun,dryRun:!!e.dryRun,question:gu(T,l,L?_.ledger??o.byPath.get(r.path)?.ledger??null:null),...e.dryRun?{text:q}:{}}}catch(t){return Tc("retract",t)}}async function EG(e){try{return await no(e.cwd,{verb:"points withdraw",by:(e.by??[]).join(", ")||null},e.dryRun,()=>WNe(e))}catch(t){return Tc("withdraw",t)}}async function WNe(e){try{let t=[...new Set((e.by??[]).map(P=>P.trim()).filter(P=>P!==""))];if(t.length===0)throw new wt("write-usage-invalid","--by <name> is required: who withdraws the question");zo(to(e.cwd),t,"--by");let n=await $G(e.cwd,e.kind,e.id),{opened:i,before:r,target:o}=n,s=n.read.ledger,{o:a}=i,c=o.data;if(o.state==="answered")throw new wt("record-closed",`${e.id} is answered, so it is not withdrawn: people take the answer back with \`points retract ${e.id}\``);if(c.withdrawn!==void 0)throw new wt("record-closed",`${e.id} is withdrawn already`);if(!bf(a.loaded.schema).withdrawn)throw new wt("answer-field-unsupported",`the ${a.loaded.kind.name} kind's schema has no withdrawn field, so ${e.id} can't record that it no longer applies: copy point-answer.schema.json from @intentius/chant anew`);let l=String(c.point),u=Rl(i.points,l);if(!u)throw new wt("point-unknown",`${e.id} asks ${l}, which ${i.pointsFile} no longer declares`);let d=e.on??ES(),p=RS(e.note),f=Array.isArray(c.constrains)&&typeof c.constrains[0]=="string"?c.constrains[0]:void 0,g=ep(c),h=iw(u,f,"withdrawn",void 0,g),w=aw(a,{...c,title:h,withdrawn:Object.fromEntries(Object.entries({by:t,on:d,note:p}).filter(([,P])=>P!==void 0))}),b=Is(w,ow(u,h,g)),k=s.byPath.has(o.path),$=`Decision point ${l}: withdrawn by ${t.join(", ")}${f?` (${f})`:""}`,x=await sw(a,r,o.path,b,!1,!!e.dryRun,{source:n.read.source,ledger:s,onLedger:k,message:$,who:{verb:"points withdraw",by:t.join(", ")}}),R={...o,data:w,valid:!0,reasons:[],warnings:x.warnings};return{$schema:ho,contract:go,verb:"withdraw",kind:a.view,id:e.id,path:o.path,reused:!1,written:!e.dryRun,dryRun:!!e.dryRun,question:gu(R,u,k?x.ledger??s.byPath.get(o.path)?.ledger??null:null),...e.dryRun?{text:b}:{}}}catch(t){return Tc("withdraw",t)}}var go,ho,ONe,wt,vG,ES,_c,RS,Pre,AS=v(()=>{"use strict";oh();Qi();un();Ei();dh();Ag();Tt();Pl();Go();Ei();jl();Tl();Bo();Pt();wh();el();go=1,ho="https://intentius.io/chant/schemas/workspace/points-write/v1/points-write.schema.json",ONe=[...lc,"write-usage-invalid","write-input-invalid","points-undeclared","points-invalid","point-unknown","point-inputs-invalid","point-decider-failed","answer-not-candidate","quorum-not-met","record-not-found","record-closed","record-id-taken","answer-in-steward-turn","answer-never-over-mcp","principal-unidentified","answer-not-answered","answer-field-unsupported","point-candidates-invalid",...ac,...Ua],wt=class extends Error{constructor(n,i){super(i);this.code=n;this.name="PointsWriteError"}};vG="chant-steward";ES=()=>new Date().toISOString().slice(0,10),_c=(e,t)=>t==="noul"?e?"yes":"no":String(e);RS=e=>{let t=e?.trim();return t||void 0};Pre=e=>e==="acp"?"ACP":"MCP"});function cf(e){return!!e&&typeof e=="object"&&e[Dre]===!0&&"question"in e}async function BNe(e,t){if(e.capabilities!==void 0)return{capabilities:e.capabilities,vault:e.vault??null};let{discoverStewards:n}=await Promise.resolve().then(()=>(qo(),qj)),i=(await n({cwd:t})).stewards.get(e.steward)?.declaration;return{capabilities:i?.capabilities??[],vault:i?.vault??null}}async function FR(e,t){let n=t.capability??KQ,i={capability:n,broker:t.broker??null},r=t.turn===void 0?Ho():t.turn;if(!r)return a=>e(a,i);let{capabilities:o,vault:s}=await BNe(r,t.cwd);if(!o.includes(n)){let a=s!==null?`the steward ${r.steward} holds the vault ${s} and names no brokered capabilities, and a steward's model call goes through the broker`:`the steward ${r.steward} does not name the brokered capability ${n}`+(o.length?` (it names ${o.join(", ")})`:"")+", and a steward holds no credential of its own";return async()=>{throw new Error(a)}}return a=>e(a,i)}async function z1(e){let t=e.turn===void 0?Ho():e.turn,n=e.ask?await FR(e.ask,{capability:e.capability,broker:e.broker,turn:t,cwd:e.cwd}):void 0,{askPoint:i}=await Promise.resolve().then(()=>(AS(),OG)),r=await i({cwd:e.cwd,point:e.point,inputs:e.inputs,...e.subject!==void 0?{subject:e.subject}:{},...e.kind!==void 0?{kind:e.kind}:{},...n?{ask:n}:{},...e.on!==void 0?{on:e.on}:{},...e.store!==void 0?{store:e.store}:{},...t?{steward:{name:t.steward,...t.run?{run:t.run}:{}}}:{}});if("error"in r)throw new Error(`decision point ${e.point}: ${r.error.code}: ${r.error.message}`);let o=r.question;if(o.state==="answered"&&o.answer!==null)return{answer:o.answer,question:o};throw new MR({id:o.id,point:o.point,state:o.state==="proposed"?"proposed":"escalated",path:o.path,subject:o.subject,steward:o.askedBy?.steward??null})}var KQ,Dre,Tre,Ire,MR,Ey=v(()=>{"use strict";jl();KQ="inference",Dre=Symbol.for("chant.op.PointWait"),MR=class extends(Ire=Error,Tre=Dre,Ire){constructor(n){super(`waiting on decision point ${n.point} (${n.id}, ${n.state}): a person answers it through hud or \`chant workspace points answer ${n.id}\``);this.question=n;this[Tre]=!0;this.name="PointWait"}}});function AG(e,t,n){return async(i,r,o)=>{let s=`${zNe(e)}${r}`,a=await n(s,{method:i,headers:{...t,...o!==void 0?{"Content-Type":"application/json"}:{}},...o!==void 0?{body:JSON.stringify(o)}:{}}),c=await a.text();if(!a.ok)throw new tc(i,s,a.status,c);if(!c)return null;try{return JSON.parse(c)}catch{return c}}}async function PG(e,t){let n=t.fetch??globalThis.fetch,i=e.url?{url:e.url}:{},r=g=>({status:"skipped",forge:e.forge,reason:g,...i}),o=g=>({status:"would-resume",forge:e.forge,how:`would ${g}`,...i});if(e.forge==="github"){let g=AG(e.api,{Authorization:`Bearer ${t.token}`,Accept:"application/vnd.github+json"},n),h=`/repos/${e.repo}/actions/runs/${e.run}`,w=await g("GET",h);if(!Js(w))throw new Error(`GET ${h} returned no run`);if(w.status!=="completed")return r(`run ${e.run} is ${String(w.status)}, not finished`);let b=typeof w.run_attempt=="number"?w.run_attempt:void 0;return e.attempt!==void 0&&b!==void 0&&b>e.attempt?r(`run ${e.run} was already re-run (attempt ${b}; attempt ${e.attempt} waited)`):w.conclusion==="success"?r(`run ${e.run} succeeded`):t.dryRun?o(`re-run the failed jobs of run ${e.run}`):(await g("POST",`${h}/rerun-failed-jobs`,{}),{status:"resumed",forge:"github",how:`re-ran the failed jobs of run ${e.run}`,...i})}if(e.forge==="gitlab"){let g=AG(e.api,{"PRIVATE-TOKEN":t.token},n),h=`/projects/${encodeURIComponent(decodeURIComponent(e.repo))}`,w=await g("GET",`${h}/jobs/${e.job}`);if(!Js(w))throw new Error(`GET ${h}/jobs/${e.job} returned no job`);let b=String(w.status);if(b==="success")return r(`job ${e.job} succeeded`);if(!["failed","canceled","skipped"].includes(b))return r(`job ${e.job} is ${b}, not finished`);let k=e.jobName??(typeof w.name=="string"?w.name:void 0);if(k){let R=await g("GET",`${h}/pipelines/${e.run}/jobs?per_page=100`),P=Array.isArray(R)?R.find(I=>Js(I)&&I.name===k):void 0;if(Js(P)&&String(P.id)!==String(e.job))return r(`job ${e.job} (${k}) was already retried as job ${String(P.id)}`)}if(t.dryRun)return o(`retry job ${e.job}`);let $=await g("POST",`${h}/jobs/${e.job}/retry`),x=Js($)&&$.id!==void 0?` as job ${String($.id)}`:"";return{status:"resumed",forge:"gitlab",how:`retried job ${e.job}${x}`,...i}}let s=AG(e.api,{Authorization:`token ${t.token}`,Accept:"application/json"},n),a=`/repos/${e.repo}`,c=await s("GET",`${a}/actions/runs/${e.run}`);if(!Js(c))throw new Error(`GET ${a}/actions/runs/${e.run} returned no run`);let l=String(c.status);if(l==="success")return r(`run ${e.run} succeeded`);if(["waiting","running","blocked","unknown"].includes(l))return r(`run ${e.run} is ${l}, not finished`);let u=await s("GET",`${a}/actions/runs?workflow_id=${encodeURIComponent(e.workflow)}&limit=50`),d=Js(u)&&Array.isArray(u.workflow_runs)?u.workflow_runs:Array.isArray(u)?u:[],p=t.since?Math.floor(new Date(t.since).getTime()/1e3)*1e3:void 0,f=d.find(g=>Js(g)&&Number(g.id)>Number(e.run)&&(g.prettyref===void 0||g.prettyref===e.ref)&&(p===void 0||typeof g.created=="string"&&new Date(g.created).getTime()>=p));return Js(f)?r(`run ${String(f.id)} of ${e.workflow} started after the approval`):t.dryRun?o(`dispatch ${e.workflow} on ${e.ref}`):(await s("POST",`${a}/actions/workflows/${encodeURIComponent(e.workflow)}/dispatches`,{ref:e.ref}),{status:"resumed",forge:"forgejo",how:`dispatched ${e.workflow} on ${e.ref}`,...i})}function CG(e,t=process.env){return t.CHANT_FORGE_TOKEN?t.CHANT_FORGE_TOKEN:e==="gitlab"?t.GITLAB_TOKEN:t.GITHUB_TOKEN??t.GH_TOKEN}var zNe,Js,jre=v(()=>{"use strict";Ej();Ga();zNe=e=>e.replace(/\/+$/,""),Js=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function _G(e,t,n=[t]){let i=t.environment,r=e.filter(o=>i===void 0||o.environment===i);if(t.approval){let o=Ya(r,t.gate,t.timestamp,t.planDigest,t.approval,Qa(n,t));return o.permit?o.permit:o.counted.length>=o.need?o.counted[o.counted.length-1]:void 0}return Qr(r,t.gate,t.timestamp,t.planDigest).resolution}var Nre=v(()=>{"use strict";Mr();Uo();jre()});var jG={};_e(jG,{readAppliedGateFile:()=>Mre,resumeAfterAnswer:()=>HNe,resumeAfterApproval:()=>VNe,resumeCandidate:()=>TG,resumeOpGates:()=>PS,resumeStanding:()=>UNe,resumeWaitingGates:()=>Fre,runResumeCommand:()=>DG,workspaceQuestions:()=>Lre});async function Lre(e){let{workspacePoints:t}=await Promise.resolve().then(()=>(cw(),_S)),n=await t({cwd:e}).catch(()=>{});return!n||!("questions"in n)?new Map:new Map(n.questions.map(i=>[i.id,{id:i.id,state:i.state,answer:i.answer,answeredBy:i.answeredBy,answeredOn:i.answeredOn}]))}async function UNe(e,t,n={},i=[e]){let[r]=LR({op:e.op,pending:[e],resolutions:t,applied:n.applied??[],now:e.timestamp,...n.questions?{questions:n.questions}:{},answering:(o,s)=>_G(o,s,i)});return TG(r,n)}async function TG(e,t={}){let n={op:e.op,gate:e.gate,...e.environment!==void 0?{environment:e.environment}:{},source:e.source,status:"not-approved",reason:e.reason,resumable:e.resumable,message:e.message,...e.planDigest!==void 0?{planDigest:e.planDigest}:{},...e.approvedBy!==void 0?{approvedBy:e.approvedBy}:{},...e.approvedAt!==void 0?{approvedAt:e.approvedAt}:{},...e.run?.url?{url:e.run.url}:{},...e.run?{run:e.run}:{},...e.spent?{spent:e.spent}:{},...e.stopped?{stopped:{...e.stopped}}:{}};if(e.reason==="spent")return{...n,status:"spent"};if(!e.resumable)return n;if(!e.run)return{...n,status:"no-job",message:"its pending fact names no CI job (it was recorded outside CI); run it again by hand"};let i=e.source==="stopped",r=CG(e.run.forge,t.env??process.env);if(t.dryRun&&!i)return{...n,status:"would-resume",message:`would resume ${e.run.forge} run ${e.run.run}; ${e.message}`};if(!r){let o=`${e.run.forge==="gitlab"?"GITLAB_TOKEN":"GITHUB_TOKEN"}`;return{...n,...i?{resumable:!1}:{},status:"no-token",message:i?`${e.message}; whether run ${e.run.run} is gone needs a token to read ${e.run.forge} with: set CHANT_FORGE_TOKEN (or ${o})`:`no token to call ${e.run.forge} with: set CHANT_FORGE_TOKEN (or ${o})`}}try{let o=i?e.stopped.appliedAt:e.approvedAt,s=await PG(e.run,{token:r,...o?{since:o}:{},...t.fetch?{fetch:t.fetch}:{},...t.dryRun?{dryRun:!0}:{}}),a=s.status==="skipped"?s.reason:s.how;if(!i)return{...n,status:s.status,message:a};let c=s.status!=="skipped";return{...n,status:s.status,resumable:c,message:c?`the apply that began at ${e.stopped.appliedAt} stopped and its run is gone: ${a}`:`the apply that began at ${e.stopped.appliedAt} is left alone: ${a}`,stopped:{...e.stopped,runGone:c}}}catch(o){return{...n,status:"failed",message:o instanceof Error?o.message:String(o)}}}async function Mre(e){let{dir:t,file:n}=yl(e),i=await At(t,n);return i?z4(i):{applied:[],finished:[]}}async function PS(e,t,n={}){let i=await Kn(e),r=n.applied?{applied:n.applied,finished:n.finished??[]}:await Mre(e),o=n.now??new Date().toISOString(),s=n.questions??(i.pending.some(l=>l.answer)?await Lre(process.cwd()):void 0),a=LR({op:e,pending:i.pending,resolutions:i.resolutions,applied:r.applied,finished:r.finished,now:o,...t!==void 0?{gate:t}:{},...s?{questions:s}:{},answering:_G}),c=[];for(let l of a)c.push(await TG(l,n));return c}function IG(e){let t=`${e.op} / ${e.gate}${e.environment!==void 0?` (${e.environment})`:""}`,n=e.approvedBy?`, approved by ${e.approvedBy}`:"",i=e.url?` ${e.url}`:"";e.status==="resumed"?console.error(xf(`${t}${n}: ${e.message}${i}`)):e.status==="would-resume"?console.error(Qn(`${t}${n}: ${e.message}${i}`)):e.status==="failed"||e.status==="no-token"?console.error(we({message:`${t}${n}: not resumed: ${e.message}`,hint:"GitHub needs actions: write; GitLab a token with the api scope and the Developer role; Forgejo a token with write:repository."})):console.error(Qn(`${t}${n}: not resumed: ${e.message}${i}`))}async function VNe(e,t,n,i){if(!i)return console.error(si({message:"Not resuming: the approval did not reach the remote, so the resumed job would not see it.",hint:"Push chant/lifecycle, then run `chant run resume --op "+e+"`."})),1;let r=(await PS(e,t)).filter(o=>n===void 0||o.environment===n);if(r.length===0)return console.error(Qn(`No pending fact for ${e} / ${t} is waiting, so there is nothing to resume.`)),0;for(let o of r)IG(o);return r.some(o=>o.status==="failed"||o.status==="no-token")?1:0}async function HNe(e,t=process.cwd()){let n=hx(e.subject);if(!n)return console.error(Qn(`Question ${e.id} names no gate in its subject, so there is nothing to resume.`)),0;if(e.ledger===null)return console.error(si({message:`Not resuming: the answer to ${e.id} is in the working tree, and the resumed job would not see it.`,hint:`Commit and push it, then run \`chant run resume --op ${n.op}\`.`})),1;if((await Ta({cwd:t})).status!=="pushed")return console.error(si({message:"Not resuming: the answer did not reach the remote, so the resumed job would not see it.",hint:`Push chant/lifecycle, then run \`chant run resume --op ${n.op}\`.`})),1;let i=(await PS(n.op,n.gate)).filter(r=>r.environment===void 0);if(i.length===0)return console.error(Qn(`No pending fact for ${n.op} / ${n.gate} is waiting, so there is nothing to resume.`)),0;for(let r of i)IG(r);return i.some(r=>r.status==="failed"||r.status==="no-token")?1:0}async function Fre(e={}){let{op:t,gate:n,...i}=e,r=t?[t]:(await Zi(Ak)).filter(s=>s.endsWith(".jsonl")).map(s=>s.slice(0,-6)),o=[];for(let s of r)o.push(...await PS(s,n,i));return o}async function DG(e){try{await Lr()}catch(i){return console.error(we({message:`Cannot read the gate ledgers: ${i instanceof Error?i.message:String(i)}`})),1}let t=e.args.dryRun===!0,n=await Fre({...e.args.op?{op:e.args.op}:{},...e.args.gate?{gate:e.args.gate}:{},dryRun:t});if(e.args.json)console.log(JSON.stringify({dryRun:t,reports:n},null,2));else{for(let o of n.filter(s=>s.status!=="not-approved"))IG(o);let i=n.filter(o=>o.status==="not-approved").length,r=t?`${n.filter(o=>o.resumable).length} would resume`:`${n.filter(o=>o.status==="resumed").length} resumed`;console.error(Qn(`${r}, ${i} still waiting for an approval or a passing answer.`))}return n.some(i=>i.status==="failed"||!t&&i.status==="no-token")?1:0}var CS=v(()=>{"use strict";Mr();Ma();Pt();Ps();Nre();M1();ur()});var _S={};_e(_S,{POINTS_CONTRACT_VERSION:()=>Bre,POINTS_ERROR_CODES:()=>ZNe,POINTS_OUTPUT_SCHEMA_ID:()=>zre,POINTS_SOURCE_REASON_CODES:()=>YNe,formatPoints:()=>Ure,readQuestionStates:()=>XNe,responseAsk:()=>Vre,runWorkspacePoints:()=>MG,workspacePoints:()=>LG});import{readFileSync as qNe}from"node:fs";import{relative as KNe,resolve as Wre,sep as JNe}from"node:path";async function LG(e){let t={$schema:zre,contract:Bre,chant:en()},n,i;try{n=qt(e.cwd,e.at),i=_t(n.tree)}catch(l){if(!(l instanceof ve))throw l;return{...t,error:{code:l.code,message:l.message,location:l.location??null}}}let r=e.kind!==void 0?[{shown:e.kind,file:Wre(e.cwd,e.kind),given:!0}]:yr(i).map(l=>({shown:l.path,file:Ri(l,n.rootOnDisk),given:!1})),o=[],s=[],a=[];for(let l of r)try{let u=await Ht(l.file);if(!u.kind.answers){l.given&&o.push({kind:l.shown,points:null,reason:{code:"kind-invalid",message:`the ${u.kind.name} kind has no answers block, so it holds no answers to decision points`}});continue}let d,p=await ii({kind:l.file,cwd:e.cwd,at:e.at,overlay:async(b,{loaded:k,root:$})=>(d=await hh({file:k.file,name:k.kind.name,dirRel:KNe($,k.dir).split(JNe).join("/")||"."}),yh(b,d))}),f=p.at!==null&&p.top?xi(p.top,p.at):ip(p.root),g=np(p.loaded,p.root),h=rp(f,g),w="points"in h?h.points:{};o.push({kind:l.shown,points:g,reason:"error"in h?{code:"points-invalid",message:h.error}:null});for(let[b,k]of Object.entries(w))s.push({name:b,title:k.title,kind:l.shown,file:g,version:za(k),questionType:k.question.type,instructions:k.question.instructions,candidates:k.adhoc?[]:Fo(k.question),criteria:k.question.criteria??(k.question.type==="score"?[]:{}),adhoc:!!k.adhoc,inputs:Object.entries(k.inputs).map(([$,x])=>({name:$,output:$l($),description:x})),deciders:k.deciders,quorum:tp(k)});for(let b of p.result.records){let k=gu(b,typeof b.data?.point=="string"?w[b.data.point]:void 0,d?.byPath.get(b.path)?.ledger??null);k&&(!e.open||k.open)&&a.push(k)}}catch(u){if(!(u instanceof Xe))throw u;o.push({kind:l.shown,points:null,reason:{code:u.code,message:u.message}})}let c=l=>a.filter(u=>u.state===l).length;return{...t,at:n.at,workspace:{name:i.name,root:n.root},open:!!e.open,sources:o,points:s,questions:a,summary:{points:s.length,questions:a.length,open:a.filter(l=>l.open).length,escalated:c("escalated"),proposed:c("proposed"),answered:c("answered"),withdrawn:a.filter(l=>l.withdrawn!==null).length}}}async function XNe(e){try{let t=await LG({cwd:e});return!("questions"in t)||t.sources.some(n=>n.reason!==null)?null:new Map(t.questions.map(n=>[n.id,n.state]))}catch{return null}}function Ure(e){let t=[];for(let i of e.sources)i.reason&&t.push(`${i.kind}: ${i.reason.code}: ${i.reason.message}`);for(let i of e.points)t.push(`${i.name} ${i.questionType}${i.adhoc?", ad hoc":""} ${i.title} (${i.deciders.map(r=>r.kind).join(", ")})`);e.points.length===0&&t.push("no decision points are declared"),t.push("");for(let i of e.questions){let r=i.model&&i.state!=="answered"?` model ${JSON.stringify(i.model.answer)} at ${i.model.confidence??"?"}${i.model.observed?"":`, below ${i.model.threshold??"?"}`}`:"";t.push(`${i.id} ${i.withdrawn?"withdrawn":i.state} ${i.title}${r}`)}let n=e.summary.questions;return t.push(e.open?`${n} open ${n===1?"question":"questions"}`:`${n} ${n===1?"question":"questions"}, ${e.summary.open} open`),t.join(`
342
342
  `)}function Vre(e){return async t=>{let n=e;if(n===null||typeof n!="object")throw new Error("the response is not a JSON object");if(typeof n.model!="string"||n.model==="")throw new Error("the response names no model");let i=n.answers?.[t.point];if(i===null||typeof i!="object")throw new Error(`the response has no answer for ${t.point}`);return{model:n.model,answer:i}}}function ls(e,t){return{$schema:ho,contract:go,verb:e,error:{code:"write-usage-invalid",message:t}}}function NG(e,t,n,i){let r;try{r=QNe(n)?n:qNe(n==="-"?0:Wre(i,n),"utf-8")}catch(o){return{$schema:ho,contract:go,verb:e,error:{code:"write-input-invalid",message:`${t} ${n} could not be read: ${o instanceof Error?o.message:String(o)}`}}}try{return{value:JSON.parse(r)}}catch(o){return{$schema:ho,contract:go,verb:e,error:{code:"write-input-invalid",message:`${t} ${n} is not JSON: ${o instanceof Error?o.message:String(o)}`}}}}async function MG(e){let{args:t}=e,n=process.cwd(),i=s=>(console.log(JSON.stringify(s,null,2)),"error"in s?1:0),r=t.extraPositional;if(r==="ask"){let s=t.extraPositional2;if(!s)return i(ls("ask","ask needs the point's name"));if(t.inputs===void 0)return i(ls("ask","--inputs <file|-|json> is required"));if(t.inputs==="-"&&t.candidates==="-")return i(ls("ask","--inputs and --candidates can't both read standard input: give one as a file or as JSON"));let a=NG("ask","--inputs",t.inputs,n);if(!("value"in a))return i(a);let c;if(t.candidates!==void 0){let u=NG("ask","--candidates",t.candidates,n);if(!("value"in u))return i(u);c=u.value}let l;if(t.response!==void 0){let u=NG("ask","--response",t.response,n);if(!("value"in u))return i(u);l=Vre(u.value)}return i(await xG({cwd:n,point:s,inputs:a.value,candidates:c,subject:t.subject,kind:t.kind,ask:l,...t.store?{store:t.store}:{},dryRun:t.dryRun}))}if(r==="answer"){let s=t.extraPositional2;if(!s)return i(ls("answer","answer needs the question's id"));if(t.answer===void 0)return i(ls("answer","--answer <value> is required"));if(!t.bys||t.bys.length===0)return i(ls("answer","--by <name> is required, once for each person who answered"));let a=await RG({cwd:n,id:s,answer:t.answer,by:t.bys,note:t.note,relayedBy:t.relayedBy,kind:t.kind,dryRun:t.dryRun}),c=i(a);if(c!==0||t.dryRun||!(t.resumeRun||t.resume!==void 0)||!("question"in a))return c;let{resumeAfterAnswer:l}=await Promise.resolve().then(()=>(CS(),jG));return l(a.question,n)}if(r==="retract"){let s=t.extraPositional2;return s?!t.bys||t.bys.length===0?i(ls("retract","--by <name> is required, once for each person who takes the answer back")):i(await SG({cwd:n,id:s,by:t.bys,note:t.note,kind:t.kind,dryRun:t.dryRun})):i(ls("retract","retract needs the question's id"))}if(r==="withdraw"){let s=t.extraPositional2;return s?!t.bys||t.bys.length===0?i(ls("withdraw","--by <name> is required: who withdraws the question")):i(await EG({cwd:n,id:s,by:t.bys,note:t.note,kind:t.kind,dryRun:t.dryRun})):i(ls("withdraw","withdraw needs the question's id"))}if(r!==void 0)return console.error(we({message:`chant workspace points takes no argument but ask, answer, retract or withdraw (got ${r})`,hint:Gre})),1;let o=await LG({cwd:n,at:t.at,open:t.open,kind:t.kind});return t.json?console.log(JSON.stringify(o,null,2)):"error"in o?console.error(we({message:`${o.error.code}: ${o.error.message}`,hint:Gre})):console.log(Ure(o)),"error"in o?1:0}var Bre,zre,ZNe,YNe,Gre,QNe,cw=v(()=>{"use strict";ur();Tt();cc();AS();Ag();Qi();wh();un();Ei();Wr();Bre=1,zre="https://intentius.io/chant/schemas/workspace/points/v1/points.schema.json",ZNe=["declaration-missing","declaration-ambiguous","declaration-unparseable","declaration-invalid","placement-invalid","reader-too-old","root-chant-required","not-a-git-repository","revision-unknown"],YNe=["kind-unreadable","kind-invalid","schema-unreadable","schema-id-mismatch","schema-invalid","location-missing","points-invalid"];Gre=["chant workspace points [--open] [--kind <kind file>] [--at <rev>] [--json]","chant workspace points ask <point> --inputs <file|-|json> [--candidates <file|-|json>] [--response <file>] [--subject <id>] [--kind <kind file>] [--dry-run]","chant workspace points answer <id> --answer <value> --by <name> [--by <name>...] [--note <text>] [--relayed-by <principal>] [--kind <kind file>] [--resume] [--dry-run]","chant workspace points retract <id> --by <name> [--by <name>...] [--note <text>] [--kind <kind file>] [--dry-run]","chant workspace points withdraw <id> --by <name> [--by <name>...] [--note <text>] [--kind <kind file>] [--dry-run]"].join(`
343
343
  `);QNe=e=>/^\s*[[{]/.test(e)});var WG={};_e(WG,{DEFAULT_TIMEOUT_MS:()=>FG,DecideConfigError:()=>Ic,SYSTEMONE_PATH:()=>qre,backendAsk:()=>tLe,brokeredCapability:()=>GG,checkKey:()=>eLe,postQuestion:()=>Zre,questionName:()=>Kre,resolveKey:()=>Jre});function GG(e,t){let n;try{n=_t(qt(t).tree).members}catch(s){throw new Ic(`the key names the brokered capability ${e.capability}, and the workspace declaration can't be read: ${s instanceof Error?s.message:String(s)}`)}let i=n.filter(s=>(e.member===void 0||s.name===e.member)&&s.box?.capabilities.some(a=>a.name===e.capability));if(i.length===0){let s=e.member!==void 0?`member ${e.member}'s box does not declare the capability ${e.capability}`:`no member's box declares the capability ${e.capability}`;throw new Ic(`${s} (box.capabilities in chant.workspace.json, #2726)`)}if(i.length>1)throw new Ic(`the capability ${e.capability} is declared by ${i.map(s=>s.name).join(" and ")}: name the member in the key`);let r=i[0],o=r.box.capabilities.find(s=>s.name===e.capability);if(o.broker===null)throw new Ic(`member ${r.name}'s capability ${e.capability} names no broker (WSP122), so nothing holds its key`);return{member:r.name,broker:o.broker,scope:o.scope}}function eLe(e,t,n){if(e!==void 0){if(typeof e=="string")throw new Ic(`${t} is a literal string; a key is { env: "<VARIABLE>" } or a brokered capability, never the key itself (SYS001)`);e!==null&&typeof e=="object"&&"capability"in e&&GG(e,n)}}function Jre(e,t,n=process.env){if(e===void 0)return;if("capability"in e){let r=GG(e,t);if(e.env===void 0)return;let o=n[e.env];if(!o)throw new Error(`the broker ${r.broker} has not set ${e.env} for the capability ${e.capability}`);return o}let i=n[e.env];if(!i)throw new Error(`the environment variable ${e.env} is not set`);return i}function Hre(e){let t=e.replace(/\s+/g," ").trim();return t.length>300?`${t.slice(0,300)}...`:t}async function Zre(e,t,n,i){let r=Jre(e.key,i.cwd,i.env),o=Kre(n.point),s={model:n.model,state:n.state,questions:{[o]:{type:n.question.type,instructions:n.question.instructions,criteria:n.question.criteria}}},a=`${e.url.replace(/\/+$/,"")}${qre}`,c=AbortSignal.timeout(e.timeoutMs??FG),l=i.signal?AbortSignal.any([i.signal,c]):c,u;try{u=await(i.transport??fetch)(a,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...r?{authorization:`Bearer ${r}`}:{}},body:JSON.stringify(s),signal:l})}catch(h){let w=c.aborted?`no answer within ${e.timeoutMs??FG} ms`:h instanceof Error?h.message:String(h);throw new Error(`${t} at ${a}: ${w}`)}let d=await u.text();if(!u.ok)throw new Error(`${t} at ${a} answered ${u.status}${d?`: ${Hre(d)}`:""}`);let p;try{p=JSON.parse(d)}catch{throw new Error(`${t} at ${a} answered with something that is not JSON: ${Hre(d)}`)}let f=p;if(f===null||typeof f!="object")throw new Error(`${t} answered with no JSON object`);if(typeof f.model!="string"||f.model==="")throw new Error(`${t}'s response names no model`);let g=f.answers?.[o];if(g===null||typeof g!="object")throw new Error(`${t}'s response has no answer to ${o}`);return{model:f.model,answer:g,response:f}}function tLe(e){return async t=>{let n=e.backends[t.backend];if(!n)throw new Error(`no backend named ${t.backend} is configured (decide.backends)`);let{model:i,answer:r,response:o}=await Zre(n,t.backend,t,e);return e.onResponse?.(t.backend,o),{model:i,answer:r}}}var qre,FG,Kre,Ic,BG=v(()=>{"use strict";Tt();Wr();qre="/v1/systemone",FG=3e4,Kre=e=>e,Ic=class extends Error{constructor(t){super(t),this.name="DecideConfigError"}}});function Yre(e,t){let n=e;for(let i of t.split(".")){if(n===null||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,i))return;n=n[i]}return n}function Xre(e,t,n="acceptance"){let i=e??{},r=Array.isArray(i[n])?i[n]:[],o=zG(Yre(i,"source.ask.said"))||zG(Yre(i,"source.intent.answer")),s=t.split(`
344
344
  `).filter(u=>!nLe.test(u)),a=r.map(u=>typeof u=="string"?u:zG(u?.text)),c=[o,...s,...a].join(`
345
345
  `),l=new Set([...c.matchAll(/`([^`\s]+)`/g)].map(u=>u[1]).filter(u=>rLe.test(u)));return{criteria:r.length,files:l.size,words:c.split(/\s+/).filter(Boolean).length}}function iLe(e,t){return t?["criteria","files","words"].every(n=>t[n]===void 0||e[n]<=t[n]):!1}function Qre(e,t=UG){let n={criteria:e.criteria,files:e.files,words:e.words};for(let[i,r]of Object.entries(t))n[`fits_${i}`]=iLe(e,r);return n}var UG,nLe,rLe,zG,eie=v(()=>{"use strict";UG=Object.freeze({small:{criteria:10,files:5,words:150},medium:{criteria:20,files:10,words:300}}),nLe=/^\s*#/,rLe=/^[\w@.-]+(\/[\w@.*-]+)+\/?$|^[\w@-][\w@.-]*\.[a-z]{1,5}$/i,zG=e=>typeof e=="string"?e:""});var tie={};_e(tie,{InputReadError:()=>Dc,READABLE_OUTPUTS:()=>VG,fieldOf:()=>TS,readInputs:()=>dLe});import{readFileSync as oLe}from"node:fs";import{join as sLe}from"node:path";function TS(e,t){let n=e;for(let i of t.split(".")){if(n===null||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,i))return;n=n[i]}return n}async function aLe(e,t,n){let i=Si(t),r=await $S(i,{cwd:t}),o=[];for(let[s,a]of r.kinds.entries()){if("error"in a){o.push(`${a.declared.path}: ${a.error.code}`);continue}let c=a.records.find(l=>l.id===e);if(c){let l=c;return n==="work-item"?{...l,...await cLe(i[s].file,c.path,c.data,t)}:l}}throw new Dc(`no declared record kind holds a record with id ${e} (read for ${n})${o.length?`; not read: ${o.join(", ")}`:""}`)}async function cLe(e,t,n,i){let o=(await Ht(e,i)).kind.work;if(!o)return{};let s=qt(i),a="";try{a=MD(oLe(sLe(s.top??s.rootOnDisk,...t.split("/")),"utf-8"))}catch{}let c=Xre(n,a,o.acceptance?.field??"acceptance");return Qre(c,o.tier?.limits??UG)}function lLe(e,t){let n=Cte({cwd:t});if("error"in n)throw new Dc(`the workspace can't be listed: ${n.error.code}: ${n.error.message}`);let i=n.members.find(r=>r.name===e);if(!i)throw new Dc(`the workspace has no member named ${e}`);return i}function uLe(e,t,n){let i=e.length>t.length?e.slice(t.length+1):"";if(i==="")return n;if(t==="member")return TS(n,i);let r=TS(n.data,i);return r!==void 0?r:TS(n,i)}async function dLe(e,t,n){let i=new Set(e.map($l));for(let a of Object.keys(t)){if(!VG.includes(a))throw new Dc(`${a} is not read by id here; pass its values in inputs, as the read contract printed them (read takes ${VG.join(", ")})`);if(!i.has(a))throw new Dc(`the point reads no ${a} input (its inputs are ${e.join(", ")})`)}let r=new Map;for(let[a,c]of Object.entries(t))r.set(a,a==="member"?lLe(c,n):await aLe(c,n,a));let o={},s=[];for(let a of e){let c=$l(a),l=r.get(c);if(l===void 0)continue;let u=uLe(a,c,l);u===void 0?s.push(a):o[a]=u}return{inputs:o,missing:s}}var VG,Dc,nie=v(()=>{"use strict";Ei();LF();Ag();un();Wr();eie();VG=["record","decision","work-item","member"],Dc=class extends Error{constructor(t){super(t),this.name="InputReadError"}}});var oie={};_e(oie,{DecideError:()=>Di,decide:()=>mLe,runDecide:()=>iie});async function pLe(e,t){let{checkKey:n,DecideConfigError:i}=await Promise.resolve().then(()=>(BG(),WG)),r=e.backends;if(r===void 0){let{config:s}=await nd(t);r=s.decide?.backends??{}}if(r===null||typeof r!="object"||Array.isArray(r))throw new i("backends must be an object of backend name to { url, key? }");let o={};for(let[s,a]of Object.entries(r)){n(a?.key,`backend ${s}'s key`,t);let c=Qu.safeParse(a);if(!c.success)throw new i(`backend ${s} is not { url, key?, timeoutMs? }: ${c.error.issues.map(l=>`${l.path.join(".")||"(backend)"} ${l.message}`).join("; ")}`);o[s]=c.data}return o}async function fLe(e,t){let{workspacePoints:n}=await Promise.resolve().then(()=>(cw(),_S)),i=await n({cwd:t,...e.kind!==void 0?{kind:e.kind}:{}});if("error"in i)throw new Di(i.error.code,i.error.message);let r=i.points.find(o=>o.name===e.point);if(!r){let o=i.sources.find(s=>s.reason);throw new Di("point-unknown",`no points file declares ${JSON.stringify(e.point)}${o?` (${o.kind}: ${o.reason.message})`:i.points.length?` (the points are ${i.points.map(s=>s.name).join(", ")})`:""}`)}return r}function rie(e,t){let n=typeof e.decider.kind=="string"?e.decider.kind:"quorum",i=n==="model";return{id:e.id,path:e.path,state:e.state,open:e.open,answer:e.answer,decider:n,model:i?e.model?.model??null:null,backend:i?e.model?.backend??null:null,confidence:i?e.confidence:null,threshold:i?e.threshold:null,reason:i?e.reason:null,answeredBy:e.answeredBy,escalations:e.escalations,missing:t}}async function iie(e,t={},n){if(typeof e?.point!="string"||e.point==="")throw new Di("write-usage-invalid","decide needs the point's name");let i=e.cwd??process.cwd(),{backendAsk:r,brokeredCapability:o,checkKey:s,DecideConfigError:a}=await Promise.resolve().then(()=>(BG(),WG)),c=$=>{try{return $()}catch(x){throw x instanceof a?new Di("backend-invalid",x.message):x}},l;try{l=await pLe(e,i)}catch($){throw $ instanceof a?new Di("backend-invalid",$.message):$}let u=await fLe(e,i),d;for(let $ of u.deciders){if($.kind!=="model")continue;let x=l[$.backend];if(!x)throw new Di("backend-invalid",`${e.point}'s model decider names the backend ${$.backend}, and none is configured (decide.backends${Object.keys(l).length?`: ${Object.keys(l).join(", ")}`:" is empty"})`);if(c(()=>s(x.key,`backend ${$.backend}'s key`,i)),d===void 0&&x.key&&"capability"in x.key){let R=x.key;d={capability:R.capability,broker:c(()=>o(R,i)).broker}}}let p={inputs:{},missing:[]};if(e.read&&Object.keys(e.read).length>0)try{let{readInputs:$}=await Promise.resolve().then(()=>(nie(),tie));p=await $(u.inputs.map(x=>x.name),e.read,i)}catch($){throw new Di("point-inputs-invalid",$ instanceof Error?$.message:String($))}let f={...p.inputs,...e.inputs??{}},g=p.missing.filter($=>!($ in f)),h=r({backends:l,cwd:i,...t.transport?{transport:t.transport}:{},...t.env?{env:t.env}:{},...n?{signal:n}:{},...t.onResponse?{onResponse:t.onResponse}:{}}),w=Ho(),b=async $=>{let x=l[$.backend]?.key;if(w&&x&&!("capability"in x))throw new Error(`in the steward ${w.steward}'s turn a model call goes through the broker, and backend ${$.backend}'s key is the environment variable ${x.env}, a credential the steward would hold`);return h($)},k={cwd:i,point:e.point,inputs:f,...e.subject!==void 0?{subject:e.subject}:{},...e.kind!==void 0?{kind:e.kind}:{},...e.store!==void 0?{store:e.store}:{},...t.on?{on:t.on}:{}};if(e.dryRun){let{askPoint:$}=await Promise.resolve().then(()=>(AS(),OG)),x=await $({...k,ask:await FR(b,{...d||{},turn:w??null,cwd:i}),...w?{steward:{name:w.steward,...w.run?{run:w.run}:{}}}:{client:{name:"chant decide"}},dryRun:!0});if("error"in x)throw new Di(x.error.code,`${x.error.code}: ${x.error.message}`);return rie(x.question,g)}try{let{question:$}=await z1({...k,ask:b,...d?{capability:d.capability,broker:d.broker}:{},turn:w??null});return rie($,g)}catch($){if(cf($))throw $;let x=$ instanceof Error?/^decision point [^:]+: ([a-z0-9-]+): /.exec($.message):null;throw x?new Di(x[1],$ instanceof Error?$.message:String($)):$}}async function mLe(e,t){return iie(e,{},t)}var Di,sie=v(()=>{"use strict";zn();Ey();jl();pv();Di=class extends Error{constructor(n,i){super(i);this.code=n;this.name="DecideError"}}});var aie={};_e(aie,{evaluatePointGate:()=>Xg,pointGateResumable:()=>Qg,workspaceGatePointAsker:()=>L1});function L1(e){return{async ask(t){let{workspacePoints:n}=await Promise.resolve().then(()=>(cw(),_S)),i=await n({cwd:e});if("error"in i)throw new Error(`decision point ${t.point}: ${i.error.code}: ${i.error.message}`);let r=i.points.find(c=>c.name===t.point);if(!r){let c=i.sources.find(l=>l.reason);throw new Error(`gate "${t.facts.name}" asks decision point ${t.point}, and no points file declares it${c?` (${c.kind}: ${c.reason.message})`:""}`)}let o=Dl(t.point,r.inputs.map(c=>c.name),t.facts,t.inputs),{runDecide:s}=await Promise.resolve().then(()=>(sie(),oie)),a=r.deciders.some(c=>c.kind==="model");try{let c=t.store??vp(),l=await s({point:t.point,inputs:o,subject:t.subject,cwd:e,...c?{store:c}:{},...a?{}:{backends:{}}});return{id:l.id,point:t.point,path:l.path,state:l.state,answer:l.answer,decider:l.decider,answeredBy:l.answeredBy,subject:t.subject,steward:null}}catch(c){if(!cf(c))throw c;let l=c.question;return{id:l.id,point:l.point,path:l.path,state:l.state,answer:null,decider:"quorum",answeredBy:[],subject:l.subject,steward:l.steward}}}}}var NR=v(()=>{"use strict";Ps();Ey();Sx()});import{execFileSync as IS,spawnSync as gLe}from"node:child_process";import{existsSync as pie,mkdirSync as NS,readFileSync as yu,rmSync as lw,writeFileSync as KG}from"node:fs";import{dirname as JG,isAbsolute as f$t,join as Ln,posix as hLe}from"node:path";function Oy(e,t){let n;try{n=JSON.parse(e)}catch(o){throw new Error(`${t}: ${o instanceof Error?o.message:String(o)}`)}let i=n?.waves,r=Array.isArray(i)?n:i;if(!r||typeof r!="object"||!Array.isArray(r.waves))throw new Error(`${t} must hold an Op waves spec: { "name", "op", "plan", "waves": [...] }, or { "waves": <that>, "options": {...} }`);return r}function JQ(e,t,n,i,r=wLe){let{sha:o,text:s}=r(n,e.replace(/^\.\//,"").split("\\").join(hLe.sep),i),a={policy:"always",approval:"ledger",source:"absent-at-base",base:o,hooks:cie(),spend:!1,applyHooksRunBy:"chant",neverOverMcp:!1};if(s===null)return a;let c;try{c=Oy(s,`${e} at ${n}`)}catch{return a}let l=c.approvals?.spend===!0,u=c.neverOverMcp===!0,d=bLe(c,t,`${e} at ${o.slice(0,12)}`),p=c.waves.find(w=>w.name===t);if(!p)return{...a,spend:l,neverOverMcp:u,...d};let f=p.gate??"always",g=p.approval===void 0?"ledger":ec.includes(p.approval)?p.approval:"sealed",h={policy:Ug.includes(f)?f:"always",approval:g,source:"base",base:o,hooks:cie(),spend:l,applyHooksRunBy:"chant",neverOverMcp:u,...d};try{xp(`${e} at ${o.slice(0,12)}`,c.hooks),xp(`${e} at ${o.slice(0,12)}, wave "${t}"`,p.hooks),h.hooks=vx(c,t),h.applyHooksRunBy=kx(c,t)}catch(w){h.hooksRefused=`the hooks at base cannot be run (${w instanceof Error?w.message:String(w)})`}return h}function bLe(e,t,n){let i=e.waves.find(o=>o.name===t)?.point??e.point;if(i===void 0)return{};let r=yx(i);return r.length>0?{pointRefused:`the decision point at base cannot be asked (${n}: ${r.join("; ")})`}:{point:vj(e,t)}}function vf(e,t){let n=[["{op}",t.op],["{target}",t.target],["{wave}",t.wave],["{plans}",t.plans],["{plan}",t.plan],["{runs}",t.runs]];return e.map(i=>n.reduce((r,[o,s])=>s===void 0?r:r.replaceAll(o,s),i))}function LS(e,t,n){return`.chant/op-waves/${e.name}/wave-${t}/${n.replace(/[^A-Za-z0-9._-]/g,"_")}.plan.json`}function V1(e,t){return`.chant/op-waves/${e.name}/wave-${t}/runs.json`}function H1(e,t){return`.chant/op-waves/${e.name}/wave-${t}/plans.json`}function vLe(e,t,n){let i=n.op??e.spec.op,r=LS(e.spec,e.wave,n.target);NS(JG(Ln(e.cwd,r)),{recursive:!0});let o=e.exec(vf(e.spec.plan,{op:i,target:n.target,wave:t,plan:r}),e.cwd);if(o!==0)throw new Error(`planning ${n.target} exited ${o}`);let s;try{s=JSON.parse(yu(Ln(e.cwd,r),"utf-8"))}catch(a){throw new Error(`planning ${n.target} wrote no readable plan file at ${r}: ${a instanceof Error?a.message:String(a)}`)}if(typeof s.planDigest!="string"||s.planDigest==="")throw new Error(`the plan file for ${n.target} (${r}) has no planDigest`);return mie(n.target,i,s)}function mie(e,t,n){let i=n.denied;if(i!==void 0){let r=i;if(!r||typeof r!="object"||!Array.isArray(r.rules)||r.rules.length===0||!r.rules.every(o=>typeof o=="string"&&o.trim()!=="")||r.reason!==void 0&&typeof r.reason!="string")throw new Error(`the plan of ${e} has denied ${JSON.stringify(i)}; a denial is { "rules": ["<rule id>", ...], "reason"?: "<text>" }`)}return{member:e,planDigest:n.planDigest,op:t,...n.destructive===!0?{destructive:!0}:{},...n.empty===!0?{empty:!0}:{},...n.denied?{denied:{rules:n.denied.rules,...n.denied.reason?{reason:n.denied.reason}:{}}}:{}}}function DS(e,t,n,i,r=V1(e.spec,e.k),o=!1){let s={wave:e.wave.name,number:e.k,...i?{digest:i}:{},...o?{discover:!0}:{},runs:t.map(a=>{let c=n?.get(a.target);return{target:a.target,op:a.op??e.spec.op,...c?{planDigest:c.planDigest,...c.destructive?{destructive:!0}:{},...c.empty?{empty:!0}:{}}:{}}})};return NS(JG(Ln(e.cwd,r)),{recursive:!0}),KG(Ln(e.cwd,r),JSON.stringify(s,null,2)+`
346
346
  `),r}function HG(e,t,n=!1){let{spec:i,k:r,wave:o,cwd:s,exec:a}=e;if(!i.planWave)return{members:t.map(I=>vLe({spec:i,wave:r,cwd:s,exec:a},o.name,I))};let c=DS(e,t,void 0,void 0,void 0,n),l=H1(i,r);lw(Ln(s,l),{force:!0});let u=a(vf(i.planWave,{op:i.op,wave:o.name,runs:c,plans:l}),s);if(u!==0)throw new Error(`planning wave ${r} (${o.name}) exited ${u}`);let d;try{d=JSON.parse(yu(Ln(s,l),"utf-8"))}catch(I){throw new Error(`planning wave ${r} (${o.name}) wrote no readable plans file at ${l}: ${I instanceof Error?I.message:String(I)}`)}let p=Array.isArray(d)?d:d?.runs;if(!Array.isArray(p))throw new Error(`the plans file of wave ${r} (${l}) must hold { "runs": [{ "target", "planDigest" }] }`);let f=new Set(t.map(I=>I.target)),g=new Map,h=[];for(let I of p){let A=I?.target;if(n&&typeof A=="string"&&A!==""&&!g.has(A)){if(I.op!==void 0&&(typeof I.op!="string"||I.op===""))throw new Error(`the plans file of wave ${r} (${l}) gives ${A} an op that is not a name`);h.push({target:A,...I.op&&I.op!==i.op?{op:I.op}:{}}),f.add(A)}if(typeof A!="string"||!f.has(A))throw new Error(`the plans file of wave ${r} (${l}) plans ${JSON.stringify(A)}, which is not a run it was asked to plan`);if(g.has(A))throw new Error(`the plans file of wave ${r} (${l}) plans ${A} twice`);if(typeof I.planDigest!="string"||I.planDigest==="")throw new Error(`the plans file of wave ${r} (${l}) has no planDigest for ${A}`);g.set(A,I)}let w=t.filter(I=>!g.has(I.target)).map(I=>I.target);if(w.length>0)throw new Error(`the plans file of wave ${r} (${l}) has no plan for ${w.join(", ")}`);n&&(t=h);let b=Array.isArray(d)?void 0:kLe(d.members,new Set(t.map(I=>I.target)),`the plans file of wave ${r} (${l})`),k=Array.isArray(d)?void 0:d.waves;if(k!==void 0&&(!Number.isInteger(k)||k<0))throw new Error(`the plans file of wave ${r} (${l}): \`waves\` must be the number of waves found, a whole number`);let $=Array.isArray(d)?void 0:gie(d.pending,`the plans file of wave ${r} (${l})`),x=t.map(I=>{let A=mie(I.target,I.op??i.op,g.get(I.target)),B=Ln(s,LS(i,r,I.target));return KG(B,JSON.stringify({planDigest:A.planDigest,...A.destructive?{destructive:!0}:{},...A.empty?{empty:!0}:{},...A.denied?{denied:A.denied}:{}})+`
347
- `),A}),R=Array.isArray(d)?void 0:d.overriders,P=Array.isArray(d)?void 0:d.overridersSource;if(P!==void 0&&(typeof P!="string"||P.trim()===""))throw new Error(`the plans file of wave ${r} (${l}): \`overridersSource\` must be a label for where the overriders come from, such as "policy.override in terragucci.yml"`);if(R!==void 0&&(!Array.isArray(R)||!R.every(I=>typeof I=="string")))throw new Error(`the plans file of wave ${r} (${l}): \`overriders\` must be a list of principals`);return{members:x,...$?{pending:$}:{},...R?{overriders:R}:{},...R&&P?{overridersSource:P}:{},...b?{extras:b}:{},...k!==void 0?{waves:k}:{}}}function kLe(e,t,n){if(e===void 0)return;if(!Array.isArray(e))throw new Error(`${n}: \`members\` must be a list of { "member", "planDigest" }`);let i=new Set,r=[];for(let o of e){if(!o||typeof o.member!="string"||o.member===""||typeof o.planDigest!="string"||o.planDigest==="")throw new Error(`${n}: each of \`members\` needs a member and a planDigest`);if(t.has(o.member))throw new Error(`${n}: member ${o.member} is also a run's target; a digest member that is no run needs a name of its own`);if(i.has(o.member))throw new Error(`${n}: names member ${o.member} twice`);i.add(o.member),r.push({member:o.member,planDigest:o.planDigest})}return r.length>0?r:void 0}function gie(e,t){if(e===void 0)return;if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t}: \`pending\` must be an object of fields for the pending fact`);let n=Object.keys(e).filter(i=>yLe.includes(i));if(n.length>0)throw new Error(`${t}: \`pending\` sets ${n.join(", ")}, which chant writes itself`);if("description"in e&&typeof e.description!="string")throw new Error(`${t}: pending.description must be a string`);return Object.keys(e).length>0?e:void 0}function q1(e,t,n=[]){return gj(hj(t,{...e.digest?.over?{over:e.digest.over}:{},extras:n}))}function hie(e,t,n){if(pie(e))try{let i=JSON.parse(yu(e,"utf-8"));if(typeof i.gate!="string"||i.gate===""||typeof i.digest!="string"||i.digest==="")throw new Error("it names no gate and digest");if(i.op!==void 0&&(typeof i.op!="string"||i.op===""))throw new Error("its op is not a name");return{gate:i.gate,digest:i.digest,...i.op?{op:i.op}:{},...typeof i.description=="string"?{description:i.description}:{},...i.pending?{pending:gie(i.pending,`the hold ${n} wrote`)??{}}:{}}}catch(i){t(`${n} wrote a hold file that cannot be read (${i instanceof Error?i.message:String(i)}), so it holds the wave on its set digest`);return}}function xLe(e,t,n,i,r,o={}){let s={holds:[],outcomes:[],otherGates:[]};if(!n||n.length===0)return s;let{name:a,op:c,waveName:l,k:u,cwd:d,exec:p,log:f}=e,g=`.chant/op-waves/${a}/wave-${u}/hold.json`,h={CHANT_OP_WAVES:a,CHANT_WAVE:l,CHANT_WAVE_NUMBER:String(u),CHANT_HOOK:t,CHANT_RUNS:r,CHANT_HOLD:g,...o};for(let w of n){let b=w.name??(w.command.join(" ").length>60?`${w.command.join(" ").slice(0,57)}...`:w.command.join(" ")),k=w.perRun?i.map($=>({target:$.target,argv:vf(w.command,{op:$.op,wave:l,target:$.target,runs:r,...$.plan?{plan:$.plan}:{}}),env:{...h,CHANT_TARGET:$.target,...$.plan?{CHANT_PLAN:$.plan}:{}}})):[{target:void 0,argv:vf(w.command,{op:c,wave:l,runs:r}),env:h}];for(let $ of k){let x=`${t} hook ${b}${$.target?` (${$.target})`:""}`,R;lw(Ln(d,g),{force:!0});try{R=p($.argv,d,$.env)}catch(I){f(`${x} did not run: ${I instanceof Error?I.message:String(I)}`),R=127}let P={moment:t,name:b,...$.target?{target:$.target}:{},exit:R};if(R===0){s.outcomes.push({...P,outcome:"passed"});continue}if(w.onFailure==="approve"){s.outcomes.push({...P,outcome:"held"});let I=hie(Ln(d,g),f,x);if(I){s.otherGates.push({label:x,name:b,moment:t,...$.target?{target:$.target}:{},argv:$.argv,env:$.env,request:I}),f(`${x} exited ${R} and holds wave ${u} (${l}) on gate ${I.op??a} / ${I.gate}, digest ${I.digest}`);continue}s.holds.push(x),f(`${x} exited ${R}, so wave ${u} (${l}) waits for an approval of its set digest`);continue}return s.outcomes.push({...P,outcome:"failed"}),s.failed=`${x} exited ${R}`,f(s.failed),s}}return s}async function hu(e,t,n,i,r,o,s={}){if(!n||n.length===0)return{holds:[]};let a=DS(e,i,r,o),c=xLe($Le(e),t,n,yie(e.spec,e.k,i,r),a,s);e.result.hooks.push(...c.outcomes);let l={holds:c.holds,...c.failed?{failed:c.failed}:{}};if(c.failed)return l;for(let u of c.otherGates){let d=u,p=[];for(;;){let f=await RLe(e,d);if(f.status==="waiting"){p.length>0&&(f.after=p),l.waitingOn??=f;break}let g={op:f.op,gate:f.gate,digest:f.digest,approvedBy:f.approvedBy,approvedAt:f.approvedAt};p.push(g);let h={...d.env,CHANT_HOLD_APPROVED:JSON.stringify(g),CHANT_HOLDS_APPROVED:JSON.stringify(p)},w=Ln(e.cwd,d.env.CHANT_HOLD);lw(w,{force:!0});let b;try{b=e.exec(d.argv,e.cwd,h)}catch(R){e.log(`${d.label} did not run: ${R instanceof Error?R.message:String(R)}`),b=127}let k=d.target?{target:d.target}:{};if(b===0){e.result.hooks.push({moment:t,name:d.name,...k,exit:b,outcome:"passed"}),e.log(`${d.label}: ${f.approvedBy} approved ${f.op} / ${f.gate} at ${f.digest}, and the hook ran again and passed`);break}let $=hie(w,e.log,d.label),x=$?p.some(R=>R.op===($.op??e.spec.name)&&R.gate===$.gate&&R.digest===$.digest)?`${d.label} exited ${b} after ${f.approvedBy} approved ${f.gate}, and holds the wave again on ${$.op??e.spec.name} / ${$.gate} at ${$.digest}, which is already approved`:p.length>=lie?`${d.label} held the wave on ${p.length} gates in turn and asks for one more; a hook call holds on at most ${lie}`:void 0:`${d.label} exited ${b} after ${f.approvedBy} approved ${f.gate}`;if(x)return e.result.hooks.push({moment:t,name:d.name,...k,exit:b,outcome:"failed"}),l.failed=x,e.log(l.failed),l;e.result.hooks.push({moment:t,name:d.name,...k,exit:b,outcome:"held"}),e.log(`${d.label}: ${f.approvedBy} approved ${f.op} / ${f.gate}; the hook ran again, exited ${b} and holds wave ${e.k} (${e.wave.name}) on gate ${$.op??e.spec.name} / ${$.gate}, digest ${$.digest}`),d={...d,request:$}}}return l}async function wie(e,t,n,i,r){let o=e.gates??Xa({cwd:t}),s=l=>o.approvalRule?.(l,{base:r})??Promise.resolve(null);if(i!=="sealed")return{ledger:o,port:o.approvalRule?{...o,approvalRule:s}:o};let a=await Promise.resolve().then(()=>(Jg(),Kg)),c=a.sealedApprovalRule(n,(e.trust??(l=>a.trustPolicyAt(t,l)))(r));return{ledger:o,port:{...o,async approvalRule(l){let u=await s(l);return l===n?a.bothRules(u,c):u}}}}function bie(e,t,n){if(!n.satisfied)for(let{resolution:i,reason:r}of n.refused??[])e(`${t}: the approval by ${i.resolvedBy} at ${i.timestamp} does not count: ${r}`)}async function RLe(e,t){let{spec:n,k:i,wave:r,log:o}=e,s=e.gateRule,a=t.request.op??n.name,c=s.approval==="sealed"?"sealed":"ledger",{port:l}=await wie(e.options,e.cwd,t.request.gate,c,s.base),u=s.neverOverMcp,d=e.options.now??new Date().toISOString(),p=await yp(l,{op:a,gate:t.request.gate,planDigest:t.request.digest,description:t.request.description??`wave ${i} (${r.name}) of ${n.name} is held on it by ${t.label}`,now:d,fields:{...t.request.pending,approvalMode:s.approval,wave:{number:i,name:r.name,op:n.name},heldBy:{hook:t.name,moment:t.moment,...t.target?{target:t.target}:{}}},...u?{neverOverMcp:!0}:{}}),f={op:a,gate:t.request.gate,digest:t.request.digest,hook:t.label};if(bie(o,`${a} / ${t.request.gate}`,p),p.satisfied)return{...f,status:"approved",approvedBy:p.resolution.resolvedBy,approvedAt:p.resolution.timestamp};let g=wp(a,t.request.gate,void 0,t.request.digest,c==="sealed");return o(`wave ${i} (${r.name}) waits on ${a} / ${t.request.gate}, which ${t.label} holds it on: nobody approved ${t.request.digest}. Approve: ${g}`),{...f,status:"waiting",approve:g,waitingSince:p.pending.timestamp,recorded:p.recorded,...p.mismatch?{mismatch:p.mismatch}:{}}}function ZQ(e,t){return e==="never"||t.every(n=>n.empty===!0)?!1:e==="on-destructive"?t.some(n=>n.destructive===!0):!0}function SLe(e,t){let{hooks:n,base:i}=t,r=vx(e.spec,e.wave.name);(JSON.stringify(r)!==JSON.stringify(n)||kx(e.spec,e.wave.name)!==t.applyHooksRunBy)&&e.log(`wave ${e.k} (${e.wave.name}): its hooks are read at ${i.slice(0,12)}, and this change's differ; the ones at base run`)}async function K1(e){let{spec:t}=e;Vg(t);let n=e.log??(a=>console.error(a)),i=t.waves[t.waves.length-1],r=[],o=[];return{...await NZ({first:e.wave,plan:a=>ELe(e,a),digest:(a,c)=>c.kind==="share"?c.decision.digest:q1(t,c.members,c.extras),decide:(a,c,l)=>c.kind==="share"?OLe(c):ALe(e,a,c,l),apply:(a,c,l)=>PLe(e,c,l),replan:(a,c)=>c.replan!==void 0,maxPasses:J1,passesSpent({k:a},c){return n(`wave ${a}: its apply asked to plan again ${J1} times, so the wave stops here`),c.exitCode=1,c},replanning({k:a},c){n(`wave ${a}: the apply applied nothing and asks to plan again${c.replan.reason?` (${c.replan.reason})`:""}; planning again`)},onward(a,c){r.push(...c.applied);let l=c.decision?.discovered?.waves,u=a>=t.waves.length&&i.rest===!0&&e.share===void 0&&e.group===void 0&&!e.decide&&c.exitCode===0&&l!==void 0&&a<l;return(o.length>0||u)&&o.push({wave:a,exitCode:c.exitCode,...c.decision?{digest:c.decision.digest}:{}}),u&&n(`wave ${a} applied; the plan found ${l} waves, so this job goes on to wave ${a+1}`),u}}),applied:r,...o.length>0?{rest:o}:{}}}function vie(e){return e.group===void 0?`share ${e.share}`:`${e.share!==void 0?`share ${e.share} of `:""}job group "${e.group}"`}async function ELe(e,{k:t,pass:n}){let{spec:i}=e,r=e.cwd??process.cwd(),o=e.exec??fie,s=e.log??(re=>console.error(re)),a=i.waves[i.waves.length-1],c=i.waves[t-1]??(a.rest?a:void 0);if(!c)throw new Error(`Op waves "${i.name}" has ${i.waves.length} waves; there is no wave ${t}.`);let l=e.group===void 0?void 0:c.jobs?.find(re=>re.name===e.group);if(e.group!==void 0&&!l){let re=(c.jobs??[]).map(be=>be.name);throw new Error(`wave ${t} (${c.name}) has ${re.length>0?`the job groups ${re.join(", ")}`:"no job groups"}; there is no group "${e.group}".`)}if(e.share!==void 0&&e.group===void 0&&c.jobs!==void 0)throw new Error(`wave ${t} (${c.name}) is split into job groups; name the group a share belongs to with --group.`);let u=l?l.shares??1:c.shares??1;if(e.share!==void 0&&(e.share<1||e.share>u))throw new Error(`${l?`job group "${l.name}" of `:""}wave ${t} (${c.name}) has ${u} share${u===1?"":"s"}; there is no share ${e.share}.`);let d=vie(e),p=Ln(r,bx(i,t)),f={exitCode:0,applied:[],failed:[],moved:[],hooks:[]},g={spec:i,k:t,wave:c,cwd:r,exec:o,log:s,result:f,options:e,gateRule:{approval:"ledger",base:"HEAD",neverOverMcp:i.neverOverMcp===!0}};if(n>0&&s(`wave ${t} (${c.name}): plan ${n+1}`),e.share!==void 0||l!==void 0){let re;try{re=JSON.parse(yu(p,"utf-8"))}catch{throw new Error(`${d} of wave ${t} (${c.name}) found no decision at ${bx(i,t)}. Run the deciding job first.`)}if(f.decision=re,g.gateRule={approval:re.approval,base:re.base,neverOverMcp:re.neverOverMcp===!0},re.status==="waiting"||re.status==="refused")return s(`wave ${t} (${c.name}) is ${re.status==="refused"?"refused by its policy":`waiting on ${re.heldOn?.gate??re.gate}`}; nothing applied. ${re.approve??""}`.trim()),{end:{...f,exitCode:re.status==="refused"?YG(re):3}};c.discover&&(c={...c,runs:re.members.map(ge=>({target:ge.member,...ge.op!==i.op?{op:ge.op}:{}}))},g.wave=c);let be=Rj(l?BZ(l,c.runs):c.runs,e.share??1,u);if(l&&be.length===0)return s(`${d} of wave ${t} (${c.name}) holds none of the wave's runs; nothing to apply`),{end:f};let Be=await hu(g,"before-plan",re.hooks?.["before-plan"],be);if(Be.failed)return{end:yo(g,`a hook before the plan failed, so nothing in ${d} of wave ${t} was planned or applied`)};if(Be.waitingOn)return{end:await uie(g,re,Be.waitingOn)};let{members:dt}=HG(g,be),ne=new Map(dt.map(ge=>[ge.member,ge])),ye=await hu(g,"after-plan",re.hooks?.["after-plan"],be,ne);return ye.failed?{end:yo(g,`a hook after the plan failed, so nothing in ${d} of wave ${t} was applied`)}:ye.waitingOn?{end:await uie(g,re,ye.waitingOn)}:{go:{kind:"share",ctx:g,decision:re,slice:be,planned:ne,holds:[...Be.holds,...ye.holds]}}}let h=JQ(e.specFile,c.name,e.base??i.base??"HEAD^1",r,e.show),{policy:w,approval:b,source:k,base:$}=h,x=h.neverOverMcp||i.neverOverMcp===!0;if(g.gateRule={approval:b,base:$,neverOverMcp:x},SLe(g,h),h.pointRefused)return{end:yo(g,`wave ${t} (${c.name}): ${h.pointRefused}, so nothing in it was planned or applied`)};let R=vj(i,c.name);JSON.stringify(R)!==JSON.stringify(h.point)&&s(`wave ${t} (${c.name}): its gate's decision point is read at ${$.slice(0,12)} (${h.point?.name??"none"}), and this change's differs (${R?.name??"none"}); the one at base holds`);let P=[];h.hooksRefused&&(P.push(h.hooksRefused),s(`wave ${t} (${c.name}): ${h.hooksRefused}, so none run and the wave waits for an approval`));let I=kj(i,t),A=Object.fromEntries(Object.entries(h.hooks).filter(([,re])=>re.length>0)),B={wave:t,name:c.name,op:i.name,gate:I,policy:w,approval:b,policySource:k,base:$,digest:"",members:[],status:"not-required",...Object.keys(A).length>0?{hooks:A}:{},...h.spend?{spend:"base"}:i.approvals?.spend===!0?{spend:"change"}:{},...h.applyHooksRunBy==="apply"?{applyHooksRunBy:"apply"}:{},...i.digest?.over==="changing"?{digestOver:"changing"}:{},...x?{neverOverMcp:!0}:{},...h.point?{point:{...h.point}}:{}},C=await hu(g,"before-plan",h.hooks["before-plan"],c.runs);if(C.failed)return{end:yo(g,`a hook before the plan failed, so nothing in wave ${t} was planned or applied`)};if(C.waitingOn)return{end:await qG(g,B,p,C.waitingOn)};let{members:q,pending:L,overriders:M,overridersSource:_,extras:T,waves:W}=HG(g,c.runs,c.discover===!0);if(c.discover){c={...c,runs:q.map(be=>({target:be.member,...be.op!==i.op?{op:be.op}:{}}))},g.wave=c,B.discovered={...W!==void 0?{waves:W}:{}},s(`wave ${t} (${c.name}): the plan found ${q.length} run${q.length===1?"":"s"}${W!==void 0?` of ${W} waves`:""}${q.length?`: ${q.map(be=>be.member).join(", ")}`:""}`);let re=c.jobs?$j(c,q.map(be=>be.member)):void 0;if(re)return{end:yo(g,`wave ${t} (${c.name}): ${re}, so nothing in it was applied`)}}let ve=new Map(q.map(re=>[re.member,re]));return{go:{kind:"decide",ctx:g,recordPath:p,rules:h,decision:B,holds:P,before:C.holds,members:q,planned:ve,...L?{pending:L}:{},...M?{overriders:M}:{},..._?{overridersSource:_}:{},...T?{extras:T}:{}}}}async function OLe(e){let{ctx:t,decision:n,slice:i,holds:r}=e,o=new Map(n.members.map(a=>[a.member,a.planDigest])),s=[];for(let a of i){let c=e.planned.get(a.target);if(o.get(a.target)!==c.planDigest){t.log(`${a.target}: its plan moved since wave ${t.k} was decided, so it was not applied. decided: ${o.get(a.target)??"(not in the decision)"}; planned now: ${c.planDigest}`),t.result.moved.push(a.target);continue}s.push(a)}return{go:{runs:s,earlierHolds:r}}}async function ALe(e,{prior:t},n,i){let{ctx:r,recordPath:o,decision:s,holds:a,members:c,pending:l,overriders:u,overridersSource:d,extras:p}=n,{k:f,wave:g,log:h,result:w}=r,{policy:b,source:k,base:$}=n.rules;s.digest=i,s.members=c,p&&(s.extras=p),l&&(s.pending=l);let x=await hu(r,"after-plan",n.rules.hooks["after-plan"],g.runs,n.planned,i);if(x.failed)return{end:yo(r,`a hook after the plan failed, so nothing in wave ${f} was applied`)};if(a.push(...n.before,...x.holds),a.length>0&&(s.heldBy=a),x.waitingOn)return{end:await qG(r,s,o,x.waitingOn)};let R=t?.decision,P=R!==void 0&&(R.status==="approved"||R.status==="not-required")&&R.digest===i;if(P){let A=new Map(R.members.map(B=>[B.member,B.override]));for(let B of c)B.denied&&A.get(B.member)&&(B.override=A.get(B.member));R.overridesSpentAt&&(s.overridesSpentAt=R.overridesSpentAt)}if(c.some(A=>A.denied&&!A.override)&&await _Le(r,s,u,d),P&&R.status==="approved"&&s.status!=="refused"){for(let A of["via","approvedBy","approvedAt","review","spentAt"])R[A]!==void 0&&(s[A]=R[A]);s.status="approved",h(`wave ${f} (${g.name}): planned again to the same digest, so the approval by ${R.approvedBy} still holds`)}else s.status!=="refused"&&(ZQ(b,c)||a.length>0)&&await $ie(e,r,s);let I=await qG(r,s,o);return I.exitCode!==0?{end:I}:(h(`wave ${f} (${g.name}): gate ${b} (read at ${$.slice(0,12)}${k==="absent-at-base"?", where the wave is absent":""}), digest ${i}: ${s.status}${s.approvedBy?` by ${s.approvedBy}`:""}`+(s.via==="pr-review"?` (review of #${s.review?.pr})`:"")+(a.length>0?`; held by ${a.join(", ")}`:"")),e.decide?!await XG(e,r,s)||!await xie(r,s)?{end:r.result}:((s.spentAt||s.overridesSpentAt)&&us(o,s,w),{end:w}):{go:{runs:g.runs,earlierHolds:[],recordPath:o}})}async function PLe(e,t,n){let{ctx:i,decision:r}=t;return await DLe(e,i,r,n.runs,t.planned,n.earlierHolds,n.recordPath),t.kind==="share"&&i.result.exitCode===0&&i.result.moved.length>0&&(i.result.exitCode=4),i.result}async function qG(e,t,n,i){let{k:r,wave:o,log:s,result:a}=e;i&&ZG(t,i),NS(JG(n),{recursive:!0}),us(n,t,a),a.decision=t,t.approval==="pr-review"&&t.status==="waiting"&&t.review?.reason&&s(`The pull request's review does not approve wave ${r}: ${t.review.reason}`);let c=await jS(e,t,n);return t.status==="waiting"?(s(`Nothing in wave ${r} or after it ran. ${t.heldOn?`It waits on ${t.heldOn.op} / ${t.heldOn.gate}.`:"Read the plans, then"} approve: ${t.approve} (with --resume, the approval also starts this job again)`),{...a,exitCode:3}):t.status==="refused"&&t.refused?.reason==="point"?(s(`Nothing in wave ${r} (${o.name}) or after it ran: ${t.refused.message}`),{...a,exitCode:8}):t.status==="refused"?(s(`Nothing in wave ${r} (${o.name}) or after it ran: the policy denied ${t.refused?.runs.join(", ")}, and no override counts for ${t.refused?.runs.length===1?"it":"them"}.`),{...a,exitCode:7}):c.failed?yo(e,`wave ${r} (${o.name}): ${c.failed}, so nothing in it was applied`):a}function ZG(e,t){e.heldOn=t,e.status="waiting",e.approve=t.approve,t.waitingSince&&(e.waitingSince=t.waitingSince),t.recorded!==void 0&&(e.recorded=t.recorded)}async function uie(e,t,n){return ZG(t,n),e.log(`${vie(e.options)} of wave ${e.k} (${e.wave.name}) waits on ${n.op} / ${n.gate}; nothing in it applied. Approve: ${n.approve}`),{...e.result,decision:t,exitCode:3}}async function jS(e,t,n){let i=t.hooks?.["after-gate"];if(!i?.length)return{holds:[]};let r=t.heldOn,o={CHANT_GATE_STATUS:t.status,CHANT_GATE_OP:r?.op??t.op,CHANT_GATE:r?.gate??t.gate,CHANT_GATE_DIGEST:r?.digest??t.digest,CHANT_DECISION:CLe(e.cwd,n),...t.approve?{CHANT_GATE_APPROVE:t.approve}:{},...t.waitingSince?{CHANT_GATE_WAITING_SINCE:t.waitingSince}:{},...t.recorded!==void 0?{CHANT_GATE_RECORDED:String(t.recorded)}:{}},s=new Map(t.members.map(c=>[c.member,c])),a=await hu(e,"after-gate",i,e.wave.runs,s.size>0?s:void 0,t.digest||void 0,o);return us(n,t,e.result),a.failed&&t.status!=="approved"&&t.status!=="not-required"&&e.log(`${a.failed}; the wave is ${t.status} whatever the hook came to`),a}function CLe(e,t){return t.startsWith(e+"/")?t.slice(e.length+1):t}async function _Le(e,t,n,i){let{spec:r,k:o,wave:s,cwd:a,log:c,options:l}=e,u=await Promise.resolve().then(()=>(Zg(),Tj)),d=l.gates??Xa({cwd:a}),p=r.override?.overriders??u.OVERRIDERS_PATH,f=n??u.overridersAt(a,t.base,p).principals,g=t.approval==="sealed",h=g?(l.signers??(await Promise.resolve().then(()=>(Dj(),Ij))).gateSignersAt.bind(null,a))(t.base):void 0,w=await d.read(u.OVERRIDE_OP),b=await d.readApplied?.(u.OVERRIDE_OP)??[],k=l.now??new Date().toISOString(),$=[],x=!1;for(let R of t.members){if(!R.denied||R.override)continue;let P=u.decideOverride({ledger:w,applied:b,subject:R.member,planDigest:R.planDigest,rules:R.denied.rules,overriders:f,overridersPath:n?i??"the overriders the plans file names":p,mode:g?"sealed":"ledger",...h?{signers:h}:{},now:k});if(P.status==="overridden"){let I=P.override;R.override={by:I.by,at:I.at,digest:I.digest,reason:I.reason},c(`${R.member}: the policy denial (${I.rules.join(", ")}) is overridden by ${I.by} at ${I.at}${I.sealed?", sealed":""}: ${I.reason}`);continue}$.push(R.member);for(let I of P.refusals)c(`${R.member}: an override does not count: ${I}`);if(P.status==="moved"&&(x=!0,c(`${R.member}: ${P.by} overrode an earlier plan or other rules (${P.was??"no digest"}); this plan and its rules give ${P.digest}, so that override counts for nothing`)),!P.standing){let{version:I,kind:A,...B}=u.overridePending({subject:R.member,planDigest:R.planDigest,rules:R.denied.rules,timestamp:k,expiresAt:new Date(new Date(k).getTime()+1728e5).toISOString(),description:R.denied.reason??`wave ${o} (${s.name}) of ${r.name}: ${R.member}: plan ${R.planDigest} denied by ${u.sortedRules(R.denied.rules).join(", ")}`});try{await d.appendPending({...B,members:[{member:R.member,planDigest:R.planDigest}],wave:{number:o,name:s.name,op:r.name}})}catch(C){c(`${R.member}: the denial was not recorded for an override: ${C instanceof Error?C.message:String(C)}`)}}c(`${R.member}: ${f.length?`${f.join(", ")} may`:"nobody listed may"} override it with: ${u.overrideCommand(R.member,R.denied.rules,g)}`)}$.length>0&&(t.status="refused",t.refused={reason:x?"override-moved":"policy",runs:$.sort(),...n&&i?{overridersSource:i}:{}})}function kie(e){if(!(e.pushed||cg(e.pushWarning)))throw new Error(`the record did not reach the remote the next run reads: ${e.pushWarning??"the push did not land"}`)}async function xie(e,t){let n=t.members.filter(d=>d.override);if(n.length===0||t.overridesSpentAt)return!0;let{k:i,wave:r,cwd:o,log:s,options:a}=e,c=await Promise.resolve().then(()=>(Zg(),Tj)),l=a.gates??Xa({cwd:o}),u=a.now??new Date().toISOString();try{if(!l.appendApplied)throw new Error("this gate ledger cannot record an applied override");for(let d of n){let p=c.appliedOverride({subject:d.member,digest:d.override.digest,at:d.override.at,by:d.override.by},{timestamp:u});kie(await l.appendApplied(p))}}catch(d){return yo(e,`wave ${i} (${r.name}) could not record the overrides it applies under, so nothing applied: ${d instanceof Error?d.message:String(d)}`),!1}return t.overridesSpentAt=u,s(`wave ${i} (${r.name}) applies ${n.map(d=>d.member).join(", ")} under their overrides, which are now spent`),!0}function YG(e){return e.refused?.reason==="point"?8:7}function yo(e,t){return e.log(t),e.result.exitCode=1,e.result}async function $ie(e,t,n){if(n.point)return TLe(e,t,n,n.point);let{spec:i,k:r,wave:o,cwd:s}=t,{gate:a,digest:c,approval:l,base:u,policy:d,members:p}=n,{ledger:f,port:g}=await wie(e,s,a,l,u),h=e.now??new Date().toISOString(),w=n.spend==="base"?(await f.readApplied?.(i.name)??[]).filter(x=>x.gate===a):void 0,b=n.heldBy?.length?`, held by ${n.heldBy.join(", ")}`:"",k=await DZ(g,{op:i.name,gate:a,digest:c,description:(typeof n.pending?.description=="string"?n.pending.description:void 0)??`wave ${r} (${o.name}): ${p.length} run${p.length===1?"":"s"}, gate ${d}, approval ${l}${b}`,now:h,...w?{spent:w}:{},fields:{...n.pending,approvalMode:l},...n.neverOverMcp?{neverOverMcp:!0}:{}});if(k.satisfied){n.status="approved",n.via="ledger",n.approvedBy=k.resolution.resolvedBy,n.approvedAt=k.resolution.timestamp;return}bie(t.log,`wave ${r} (${o.name})`,k),n.pendingFact=k.pending,n.recorded=k.recorded,n.waitingSince=k.pending.timestamp,k.mismatch&&(n.mismatch=k.mismatch);let $=w?.filter(x=>sr([x],{gate:a,planDigest:c,timestamp:x.approvedAt})).pop();if($&&t.log(`wave ${r} (${o.name}): the approval of ${c} by ${$.approvedBy} at ${$.approvedAt} is spent: a wave applied under it at ${$.timestamp}. Applying it again needs a new approval`),l==="pr-review"){let x=await jLe(e,{op:i.name,gate:a,k:r,digest:c,cwd:s,now:h,port:f,...w?{spent:w}:{}});if(n.review=x.review,x.approved){for(let R of["pendingFact","recorded","waitingSince","mismatch"])delete n[R];n.status="approved",n.via="pr-review",n.approvedBy=x.review.approvers.join(", "),n.approvedAt=h;return}n.status="waiting",n.approve=wp(i.name,a,void 0,c);return}n.status="waiting",n.approve=wp(i.name,a,void 0,c,l==="sealed")}async function TLe(e,t,n,i){let{spec:r,k:o,wave:s,cwd:a,log:c}=t,{gate:l,digest:u,policy:d,members:p}=n;n.approval!=="ledger"&&c(`wave ${o} (${s.name}): its gate asks decision point ${i.name}, so its approval mode (${n.approval}) does not apply`);let{evaluatePointGate:f}=await Promise.resolve().then(()=>(Sx(),u5)),g=e.points??(await Promise.resolve().then(()=>(NR(),aie))).workspaceGatePointAsker(a),h=n.heldBy?.length?`, held by ${n.heldBy.join(", ")}`:"",w=await f(e.gates??Xa({cwd:a}),g,{op:r.name,gate:l,point:{name:i.name,...i.pass?{pass:i.pass}:{},...i.store?{store:i.store}:{}},...i.inputs?{inputs:i.inputs}:{},description:(typeof n.pending?.description=="string"?n.pending.description:void 0)??`wave ${o} (${s.name}): ${p.length} run${p.length===1?"":"s"}, gate ${d}, decision point ${i.name}${h}`,...i.timeout?{timeout:i.timeout}:{},planDigest:u,...e.now?{now:e.now}:{},fields:{...n.pending,approvalMode:n.approval},...n.neverOverMcp?{neverOverMcp:!0}:{}});if(w.satisfied){n.status="approved",n.via="point",n.approvedBy=w.resolution.resolvedBy,n.approvedAt=w.resolution.timestamp,i.answer=w.answer;return}if("refused"in w){n.status="refused",n.refused={reason:"point",runs:p.map(b=>b.member),message:w.refused},i.answer=w.answer;return}n.status="waiting",n.pendingFact=w.pending,n.recorded=w.recorded,n.waitingSince=w.pending.timestamp,i.question=w.waiting,n.approve=`chant workspace points answer ${w.waiting.id} --answer <answer> --by <your name>`,c(`wave ${o} (${s.name}) asks decision point ${i.name} about ${u}: question ${w.waiting.id} is ${w.waiting.state}`)}function us(e,t,n){n.hooks.length>0&&(t.outcomes=[...n.hooks]),jZ(e,t)}async function Rie(e,t,n,i,r){let{k:o,wave:s,log:a,result:c}=t;return i.length===0||n.status==="approved"?!0:(n.heldBy=[...n.heldBy??[],...i],await $ie(e,t,n),r&&us(r,n,c),n.status==="refused"?(r&&await jS(t,n,r),a(`wave ${o} (${s.name}) is held by ${i.join(", ")}; nothing applied: ${n.refused?.message??"refused"}`),c.exitCode=YG(n),!1):n.status==="waiting"?(r&&await jS(t,n,r),a(`wave ${o} (${s.name}) is held by ${i.join(", ")}, and nobody approved ${n.digest}; nothing applied. Approve: ${n.approve}`),c.exitCode=3,!1):(a(`wave ${o} (${s.name}) is held by ${i.join(", ")}, and ${n.approvedBy} approved its digest`),!0))}function ILe(e,t,n){if(pie(e))try{let i=JSON.parse(yu(e,"utf-8"));if(!U1.includes(i.outcome))throw new Error(`outcome ${JSON.stringify(i.outcome)} is none of ${U1.join(", ")}`);if(i.reason!==void 0&&typeof i.reason!="string")throw new Error("its reason is not text");let r=i.holder&&typeof i.holder=="object"&&typeof i.holder.run=="string"?{run:i.holder.run,...typeof i.holder.url=="string"?{url:i.holder.url}:{}}:void 0;return{outcome:i.outcome,...i.reason?{reason:i.reason}:{},...r?{holder:r}:{}}}catch(i){n(`${t}: the apply wrote an outcome that cannot be read (${i instanceof Error?i.message:String(i)}), so its exit code decides`);return}}async function die(e,t,n,i,r,o,s,a){let{spec:c,k:l,wave:u,cwd:d,exec:p,log:f,result:g}=t,h=n.applyHooksRunBy==="apply",w=`.chant/op-waves/${c.name}/wave-${l}`,b=`${w}/${s.key}.json`,k=`${w}/${s.key}-result.json`,$=`${w}/${s.key}-outcome.json`,x={};if(h)for(let R of["before-apply","after-apply"])n.hooks?.[R]?.length&&(x[R]=n.hooks[R]);for(let R=0;R<2;R++){let P=n.status==="approved",I={version:1,opWaves:c.name,op:c.op,wave:u.name,number:l,base:n.base,digest:n.digest,approved:P,...n.heldBy?.length?{heldBy:n.heldBy}:{},runBy:h?"apply":"chant",runs:yie(c,l,i,r),runsFile:s.runsPath,hooks:x,outcomes:[...g.hooks],...h?{result:k}:{}};NS(Ln(d,w),{recursive:!0}),KG(Ln(d,b),JSON.stringify(I,null,2)+`
347
+ `),A}),R=Array.isArray(d)?void 0:d.overriders,P=Array.isArray(d)?void 0:d.overridersSource;if(P!==void 0&&(typeof P!="string"||P.trim()===""))throw new Error(`the plans file of wave ${r} (${l}): \`overridersSource\` must be a label for where the overriders come from, such as "policy.override in terragucci.yml"`);if(R!==void 0&&(!Array.isArray(R)||!R.every(I=>typeof I=="string")))throw new Error(`the plans file of wave ${r} (${l}): \`overriders\` must be a list of principals`);return{members:x,...$?{pending:$}:{},...R?{overriders:R}:{},...R&&P?{overridersSource:P}:{},...b?{extras:b}:{},...k!==void 0?{waves:k}:{}}}function kLe(e,t,n){if(e===void 0)return;if(!Array.isArray(e))throw new Error(`${n}: \`members\` must be a list of { "member", "planDigest" }`);let i=new Set,r=[];for(let o of e){if(!o||typeof o.member!="string"||o.member===""||typeof o.planDigest!="string"||o.planDigest==="")throw new Error(`${n}: each of \`members\` needs a member and a planDigest`);if(t.has(o.member))throw new Error(`${n}: member ${o.member} is also a run's target; a digest member that is no run needs a name of its own`);if(i.has(o.member))throw new Error(`${n}: names member ${o.member} twice`);i.add(o.member),r.push({member:o.member,planDigest:o.planDigest})}return r.length>0?r:void 0}function gie(e,t){if(e===void 0)return;if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t}: \`pending\` must be an object of fields for the pending fact`);let n=Object.keys(e).filter(i=>yLe.includes(i));if(n.length>0)throw new Error(`${t}: \`pending\` sets ${n.join(", ")}, which chant writes itself`);if("description"in e&&typeof e.description!="string")throw new Error(`${t}: pending.description must be a string`);return Object.keys(e).length>0?e:void 0}function q1(e,t,n=[]){return gj(hj(t,{...e.digest?.over?{over:e.digest.over}:{},extras:n}))}function hie(e,t,n){if(pie(e))try{let i=JSON.parse(yu(e,"utf-8"));if(typeof i.gate!="string"||i.gate===""||typeof i.digest!="string"||i.digest==="")throw new Error("it names no gate and digest");if(i.op!==void 0&&(typeof i.op!="string"||i.op===""))throw new Error("its op is not a name");return{gate:i.gate,digest:i.digest,...i.op?{op:i.op}:{},...typeof i.description=="string"?{description:i.description}:{},...i.pending?{pending:gie(i.pending,`the hold ${n} wrote`)??{}}:{}}}catch(i){t(`${n} wrote a hold file that cannot be read (${i instanceof Error?i.message:String(i)}), so it holds the wave on its set digest`);return}}function xLe(e,t,n,i,r,o={}){let s={holds:[],outcomes:[],otherGates:[]};if(!n||n.length===0)return s;let{name:a,op:c,waveName:l,k:u,cwd:d,exec:p,log:f}=e,g=`.chant/op-waves/${a}/wave-${u}/hold.json`,h={CHANT_OP_WAVES:a,CHANT_WAVE:l,CHANT_WAVE_NUMBER:String(u),CHANT_HOOK:t,CHANT_RUNS:r,CHANT_HOLD:g,...o};for(let w of n){let b=w.name??(w.command.join(" ").length>60?`${w.command.join(" ").slice(0,57)}...`:w.command.join(" ")),k=w.perRun?i.map($=>({target:$.target,argv:vf(w.command,{op:$.op,wave:l,target:$.target,runs:r,...$.plan?{plan:$.plan}:{}}),env:{...h,CHANT_TARGET:$.target,...$.plan?{CHANT_PLAN:$.plan}:{}}})):[{target:void 0,argv:vf(w.command,{op:c,wave:l,runs:r}),env:h}];for(let $ of k){let x=`${t} hook ${b}${$.target?` (${$.target})`:""}`,R;lw(Ln(d,g),{force:!0});try{R=p($.argv,d,$.env)}catch(I){f(`${x} did not run: ${I instanceof Error?I.message:String(I)}`),R=127}let P={moment:t,name:b,...$.target?{target:$.target}:{},exit:R};if(R===0){s.outcomes.push({...P,outcome:"passed"});continue}if(w.onFailure==="approve"){s.outcomes.push({...P,outcome:"held"});let I=hie(Ln(d,g),f,x);if(I){s.otherGates.push({label:x,name:b,moment:t,...$.target?{target:$.target}:{},argv:$.argv,env:$.env,request:I}),f(`${x} exited ${R} and holds wave ${u} (${l}) on gate ${I.op??a} / ${I.gate}, digest ${I.digest}`);continue}s.holds.push(x),f(`${x} exited ${R}, so wave ${u} (${l}) waits for an approval of its set digest`);continue}return s.outcomes.push({...P,outcome:"failed"}),s.failed=`${x} exited ${R}`,f(s.failed),s}}return s}async function hu(e,t,n,i,r,o,s={}){if(!n||n.length===0)return{holds:[]};let a=DS(e,i,r,o),c=xLe($Le(e),t,n,yie(e.spec,e.k,i,r),a,s);e.result.hooks.push(...c.outcomes);let l={holds:c.holds,...c.failed?{failed:c.failed}:{}};if(c.failed)return l;for(let u of c.otherGates){let d=u,p=[];for(;;){let f=await RLe(e,d);if(f.status==="waiting"){p.length>0&&(f.after=p),l.waitingOn??=f;break}let g={op:f.op,gate:f.gate,digest:f.digest,approvedBy:f.approvedBy,approvedAt:f.approvedAt};p.push(g);let h={...d.env,CHANT_HOLD_APPROVED:JSON.stringify(g),CHANT_HOLDS_APPROVED:JSON.stringify(p)},w=Ln(e.cwd,d.env.CHANT_HOLD);lw(w,{force:!0});let b;try{b=e.exec(d.argv,e.cwd,h)}catch(R){e.log(`${d.label} did not run: ${R instanceof Error?R.message:String(R)}`),b=127}let k=d.target?{target:d.target}:{};if(b===0){e.result.hooks.push({moment:t,name:d.name,...k,exit:b,outcome:"passed"}),e.log(`${d.label}: ${f.approvedBy} approved ${f.op} / ${f.gate} at ${f.digest}, and the hook ran again and passed`);break}let $=hie(w,e.log,d.label),x=$?p.some(R=>R.op===($.op??e.spec.name)&&R.gate===$.gate&&R.digest===$.digest)?`${d.label} exited ${b} after ${f.approvedBy} approved ${f.gate}, and holds the wave again on ${$.op??e.spec.name} / ${$.gate} at ${$.digest}, which is already approved`:p.length>=lie?`${d.label} held the wave on ${p.length} gates in turn and asks for one more; a hook call holds on at most ${lie}`:void 0:`${d.label} exited ${b} after ${f.approvedBy} approved ${f.gate}`;if(x)return e.result.hooks.push({moment:t,name:d.name,...k,exit:b,outcome:"failed"}),l.failed=x,e.log(l.failed),l;e.result.hooks.push({moment:t,name:d.name,...k,exit:b,outcome:"held"}),e.log(`${d.label}: ${f.approvedBy} approved ${f.op} / ${f.gate}; the hook ran again, exited ${b} and holds wave ${e.k} (${e.wave.name}) on gate ${$.op??e.spec.name} / ${$.gate}, digest ${$.digest}`),d={...d,request:$}}}return l}async function wie(e,t,n,i,r){let o=e.gates??Xa({cwd:t}),s=l=>o.approvalRule?.(l,{base:r})??Promise.resolve(null);if(i!=="sealed")return{ledger:o,port:o.approvalRule?{...o,approvalRule:s}:o};let a=await Promise.resolve().then(()=>(Jg(),Kg)),c=a.sealedApprovalRule(n,(e.trust??(l=>a.trustPolicyAt(t,l)))(r));return{ledger:o,port:{...o,async approvalRule(l){let u=await s(l);return l===n?a.bothRules(u,c):u}}}}function bie(e,t,n){if(!n.satisfied)for(let{resolution:i,reason:r}of n.refused??[])e(`${t}: the approval by ${i.resolvedBy} at ${i.timestamp} does not count: ${r}`)}async function RLe(e,t){let{spec:n,k:i,wave:r,log:o}=e,s=e.gateRule,a=t.request.op??n.name,c=s.approval==="sealed"?"sealed":"ledger",{port:l}=await wie(e.options,e.cwd,t.request.gate,c,s.base),u=s.neverOverMcp,d=e.options.now??new Date().toISOString(),p=await yp(l,{op:a,gate:t.request.gate,planDigest:t.request.digest,description:t.request.description??`wave ${i} (${r.name}) of ${n.name} is held on it by ${t.label}`,now:d,fields:{...t.request.pending,approvalMode:s.approval,wave:{number:i,name:r.name,op:n.name},heldBy:{hook:t.name,moment:t.moment,...t.target?{target:t.target}:{}}},...u?{neverOverMcp:!0}:{}}),f={op:a,gate:t.request.gate,digest:t.request.digest,hook:t.label};if(bie(o,`${a} / ${t.request.gate}`,p),p.satisfied)return{...f,status:"approved",approvedBy:p.resolution.resolvedBy,approvedAt:p.resolution.timestamp};let g=wp(a,t.request.gate,void 0,t.request.digest,c==="sealed");return o(`wave ${i} (${r.name}) waits on ${a} / ${t.request.gate}, which ${t.label} holds it on: nobody approved ${t.request.digest}. Approve: ${g}`),{...f,status:"waiting",approve:g,waitingSince:p.pending.timestamp,recorded:p.recorded,...p.mismatch?{mismatch:p.mismatch}:{}}}function ZQ(e,t){return e==="never"||t.every(n=>n.empty===!0)?!1:e==="on-destructive"?t.some(n=>n.destructive===!0):!0}function SLe(e,t){let{hooks:n,base:i}=t,r=vx(e.spec,e.wave.name);(JSON.stringify(r)!==JSON.stringify(n)||kx(e.spec,e.wave.name)!==t.applyHooksRunBy)&&e.log(`wave ${e.k} (${e.wave.name}): its hooks are read at ${i.slice(0,12)}, and this change's differ; the ones at base run`)}async function K1(e){let{spec:t}=e;Vg(t);let n=e.log??(a=>console.error(a)),i=t.waves[t.waves.length-1],r=[],o=[];return{...await NZ({first:e.wave,plan:a=>ELe(e,a),digest:(a,c)=>c.kind==="share"?c.decision.digest:q1(t,c.members,c.extras),decide:(a,c,l)=>c.kind==="share"?OLe(c):ALe(e,a,c,l),apply:(a,c,l)=>PLe(e,c,l),replan:(a,c)=>c.replan!==void 0,maxPasses:J1,passesSpent({k:a},c){return n(`wave ${a}: its apply asked to plan again ${J1} times, so the wave stops here`),c.exitCode=1,c},replanning({k:a},c){n(`wave ${a}: the apply applied nothing and asks to plan again${c.replan.reason?` (${c.replan.reason})`:""}; planning again`)},onward(a,c){r.push(...c.applied);let l=c.decision?.discovered?.waves,u=a>=t.waves.length&&i.rest===!0&&e.share===void 0&&e.group===void 0&&!e.decide&&c.exitCode===0&&l!==void 0&&a<l;return(o.length>0||u)&&o.push({wave:a,exitCode:c.exitCode,...c.decision?{digest:c.decision.digest}:{}}),u&&n(`wave ${a} applied; the plan found ${l} waves, so this job goes on to wave ${a+1}`),u}}),applied:r,...o.length>0?{rest:o}:{}}}function vie(e){return e.group===void 0?`share ${e.share}`:`${e.share!==void 0?`share ${e.share} of `:""}job group "${e.group}"`}async function ELe(e,{k:t,pass:n}){let{spec:i}=e,r=e.cwd??process.cwd(),o=e.exec??fie,s=e.log??(re=>console.error(re)),a=i.waves[i.waves.length-1],c=i.waves[t-1]??(a.rest?a:void 0);if(!c)throw new Error(`Op waves "${i.name}" has ${i.waves.length} waves; there is no wave ${t}.`);let l=e.group===void 0?void 0:c.jobs?.find(re=>re.name===e.group);if(e.group!==void 0&&!l){let re=(c.jobs??[]).map(be=>be.name);throw new Error(`wave ${t} (${c.name}) has ${re.length>0?`the job groups ${re.join(", ")}`:"no job groups"}; there is no group "${e.group}".`)}if(e.share!==void 0&&e.group===void 0&&c.jobs!==void 0)throw new Error(`wave ${t} (${c.name}) is split into job groups; name the group a share belongs to with --group.`);let u=l?l.shares??1:c.shares??1;if(e.share!==void 0&&(e.share<1||e.share>u))throw new Error(`${l?`job group "${l.name}" of `:""}wave ${t} (${c.name}) has ${u} share${u===1?"":"s"}; there is no share ${e.share}.`);let d=vie(e),p=Ln(r,bx(i,t)),f={exitCode:0,applied:[],failed:[],moved:[],hooks:[]},g={spec:i,k:t,wave:c,cwd:r,exec:o,log:s,result:f,options:e,gateRule:{approval:"ledger",base:"HEAD",neverOverMcp:i.neverOverMcp===!0}};if(n>0&&s(`wave ${t} (${c.name}): plan ${n+1}`),e.share!==void 0||l!==void 0){let re;try{re=JSON.parse(yu(p,"utf-8"))}catch{throw new Error(`${d} of wave ${t} (${c.name}) found no decision at ${bx(i,t)}. Run the deciding job first.`)}if(f.decision=re,g.gateRule={approval:re.approval,base:re.base,neverOverMcp:re.neverOverMcp===!0},re.status==="waiting"||re.status==="refused")return s(`wave ${t} (${c.name}) is ${re.status==="refused"?"refused by its policy":`waiting on ${re.heldOn?.gate??re.gate}`}; nothing applied. ${re.approve??""}`.trim()),{end:{...f,exitCode:re.status==="refused"?YG(re):3}};c.discover&&(c={...c,runs:re.members.map(ge=>({target:ge.member,...ge.op!==i.op?{op:ge.op}:{}}))},g.wave=c);let be=Rj(l?BZ(l,c.runs):c.runs,e.share??1,u);if(l&&be.length===0)return s(`${d} of wave ${t} (${c.name}) holds none of the wave's runs; nothing to apply`),{end:f};let Be=await hu(g,"before-plan",re.hooks?.["before-plan"],be);if(Be.failed)return{end:yo(g,`a hook before the plan failed, so nothing in ${d} of wave ${t} was planned or applied`)};if(Be.waitingOn)return{end:await uie(g,re,Be.waitingOn)};let{members:dt}=HG(g,be),ne=new Map(dt.map(ge=>[ge.member,ge])),ye=await hu(g,"after-plan",re.hooks?.["after-plan"],be,ne);return ye.failed?{end:yo(g,`a hook after the plan failed, so nothing in ${d} of wave ${t} was applied`)}:ye.waitingOn?{end:await uie(g,re,ye.waitingOn)}:{go:{kind:"share",ctx:g,decision:re,slice:be,planned:ne,holds:[...Be.holds,...ye.holds]}}}let h=JQ(e.specFile,c.name,e.base??i.base??"HEAD^1",r,e.show),{policy:w,approval:b,source:k,base:$}=h,x=h.neverOverMcp||i.neverOverMcp===!0;if(g.gateRule={approval:b,base:$,neverOverMcp:x},SLe(g,h),h.pointRefused)return{end:yo(g,`wave ${t} (${c.name}): ${h.pointRefused}, so nothing in it was planned or applied`)};let R=vj(i,c.name);JSON.stringify(R)!==JSON.stringify(h.point)&&s(`wave ${t} (${c.name}): its gate's decision point is read at ${$.slice(0,12)} (${h.point?.name??"none"}), and this change's differs (${R?.name??"none"}); the one at base holds`);let P=[];h.hooksRefused&&(P.push(h.hooksRefused),s(`wave ${t} (${c.name}): ${h.hooksRefused}, so none run and the wave waits for an approval`));let I=kj(i,t),A=Object.fromEntries(Object.entries(h.hooks).filter(([,re])=>re.length>0)),B={wave:t,name:c.name,op:i.name,gate:I,policy:w,approval:b,policySource:k,base:$,digest:"",members:[],status:"not-required",...Object.keys(A).length>0?{hooks:A}:{},...h.spend?{spend:"base"}:i.approvals?.spend===!0?{spend:"change"}:{},...h.applyHooksRunBy==="apply"?{applyHooksRunBy:"apply"}:{},...i.digest?.over==="changing"?{digestOver:"changing"}:{},...x?{neverOverMcp:!0}:{},...h.point?{point:{...h.point}}:{}},C=await hu(g,"before-plan",h.hooks["before-plan"],c.runs);if(C.failed)return{end:yo(g,`a hook before the plan failed, so nothing in wave ${t} was planned or applied`)};if(C.waitingOn)return{end:await qG(g,B,p,C.waitingOn)};let{members:q,pending:L,overriders:M,overridersSource:_,extras:T,waves:W}=HG(g,c.runs,c.discover===!0);if(c.discover){c={...c,runs:q.map(be=>({target:be.member,...be.op!==i.op?{op:be.op}:{}}))},g.wave=c,B.discovered={...W!==void 0?{waves:W}:{}},s(`wave ${t} (${c.name}): the plan found ${q.length} run${q.length===1?"":"s"}${W!==void 0?` of ${W} waves`:""}${q.length?`: ${q.map(be=>be.member).join(", ")}`:""}`);let re=c.jobs?$j(c,q.map(be=>be.member)):void 0;if(re)return{end:yo(g,`wave ${t} (${c.name}): ${re}, so nothing in it was applied`)}}let ke=new Map(q.map(re=>[re.member,re]));return{go:{kind:"decide",ctx:g,recordPath:p,rules:h,decision:B,holds:P,before:C.holds,members:q,planned:ke,...L?{pending:L}:{},...M?{overriders:M}:{},..._?{overridersSource:_}:{},...T?{extras:T}:{}}}}async function OLe(e){let{ctx:t,decision:n,slice:i,holds:r}=e,o=new Map(n.members.map(a=>[a.member,a.planDigest])),s=[];for(let a of i){let c=e.planned.get(a.target);if(o.get(a.target)!==c.planDigest){t.log(`${a.target}: its plan moved since wave ${t.k} was decided, so it was not applied. decided: ${o.get(a.target)??"(not in the decision)"}; planned now: ${c.planDigest}`),t.result.moved.push(a.target);continue}s.push(a)}return{go:{runs:s,earlierHolds:r}}}async function ALe(e,{prior:t},n,i){let{ctx:r,recordPath:o,decision:s,holds:a,members:c,pending:l,overriders:u,overridersSource:d,extras:p}=n,{k:f,wave:g,log:h,result:w}=r,{policy:b,source:k,base:$}=n.rules;s.digest=i,s.members=c,p&&(s.extras=p),l&&(s.pending=l);let x=await hu(r,"after-plan",n.rules.hooks["after-plan"],g.runs,n.planned,i);if(x.failed)return{end:yo(r,`a hook after the plan failed, so nothing in wave ${f} was applied`)};if(a.push(...n.before,...x.holds),a.length>0&&(s.heldBy=a),x.waitingOn)return{end:await qG(r,s,o,x.waitingOn)};let R=t?.decision,P=R!==void 0&&(R.status==="approved"||R.status==="not-required")&&R.digest===i;if(P){let A=new Map(R.members.map(B=>[B.member,B.override]));for(let B of c)B.denied&&A.get(B.member)&&(B.override=A.get(B.member));R.overridesSpentAt&&(s.overridesSpentAt=R.overridesSpentAt)}if(c.some(A=>A.denied&&!A.override)&&await _Le(r,s,u,d),P&&R.status==="approved"&&s.status!=="refused"){for(let A of["via","approvedBy","approvedAt","review","spentAt"])R[A]!==void 0&&(s[A]=R[A]);s.status="approved",h(`wave ${f} (${g.name}): planned again to the same digest, so the approval by ${R.approvedBy} still holds`)}else s.status!=="refused"&&(ZQ(b,c)||a.length>0)&&await $ie(e,r,s);let I=await qG(r,s,o);return I.exitCode!==0?{end:I}:(h(`wave ${f} (${g.name}): gate ${b} (read at ${$.slice(0,12)}${k==="absent-at-base"?", where the wave is absent":""}), digest ${i}: ${s.status}${s.approvedBy?` by ${s.approvedBy}`:""}`+(s.via==="pr-review"?` (review of #${s.review?.pr})`:"")+(a.length>0?`; held by ${a.join(", ")}`:"")),e.decide?!await XG(e,r,s)||!await xie(r,s)?{end:r.result}:((s.spentAt||s.overridesSpentAt)&&us(o,s,w),{end:w}):{go:{runs:g.runs,earlierHolds:[],recordPath:o}})}async function PLe(e,t,n){let{ctx:i,decision:r}=t;return await DLe(e,i,r,n.runs,t.planned,n.earlierHolds,n.recordPath),t.kind==="share"&&i.result.exitCode===0&&i.result.moved.length>0&&(i.result.exitCode=4),i.result}async function qG(e,t,n,i){let{k:r,wave:o,log:s,result:a}=e;i&&ZG(t,i),NS(JG(n),{recursive:!0}),us(n,t,a),a.decision=t,t.approval==="pr-review"&&t.status==="waiting"&&t.review?.reason&&s(`The pull request's review does not approve wave ${r}: ${t.review.reason}`);let c=await jS(e,t,n);return t.status==="waiting"?(s(`Nothing in wave ${r} or after it ran. ${t.heldOn?`It waits on ${t.heldOn.op} / ${t.heldOn.gate}.`:"Read the plans, then"} approve: ${t.approve} (with --resume, the approval also starts this job again)`),{...a,exitCode:3}):t.status==="refused"&&t.refused?.reason==="point"?(s(`Nothing in wave ${r} (${o.name}) or after it ran: ${t.refused.message}`),{...a,exitCode:8}):t.status==="refused"?(s(`Nothing in wave ${r} (${o.name}) or after it ran: the policy denied ${t.refused?.runs.join(", ")}, and no override counts for ${t.refused?.runs.length===1?"it":"them"}.`),{...a,exitCode:7}):c.failed?yo(e,`wave ${r} (${o.name}): ${c.failed}, so nothing in it was applied`):a}function ZG(e,t){e.heldOn=t,e.status="waiting",e.approve=t.approve,t.waitingSince&&(e.waitingSince=t.waitingSince),t.recorded!==void 0&&(e.recorded=t.recorded)}async function uie(e,t,n){return ZG(t,n),e.log(`${vie(e.options)} of wave ${e.k} (${e.wave.name}) waits on ${n.op} / ${n.gate}; nothing in it applied. Approve: ${n.approve}`),{...e.result,decision:t,exitCode:3}}async function jS(e,t,n){let i=t.hooks?.["after-gate"];if(!i?.length)return{holds:[]};let r=t.heldOn,o={CHANT_GATE_STATUS:t.status,CHANT_GATE_OP:r?.op??t.op,CHANT_GATE:r?.gate??t.gate,CHANT_GATE_DIGEST:r?.digest??t.digest,CHANT_DECISION:CLe(e.cwd,n),...t.approve?{CHANT_GATE_APPROVE:t.approve}:{},...t.waitingSince?{CHANT_GATE_WAITING_SINCE:t.waitingSince}:{},...t.recorded!==void 0?{CHANT_GATE_RECORDED:String(t.recorded)}:{}},s=new Map(t.members.map(c=>[c.member,c])),a=await hu(e,"after-gate",i,e.wave.runs,s.size>0?s:void 0,t.digest||void 0,o);return us(n,t,e.result),a.failed&&t.status!=="approved"&&t.status!=="not-required"&&e.log(`${a.failed}; the wave is ${t.status} whatever the hook came to`),a}function CLe(e,t){return t.startsWith(e+"/")?t.slice(e.length+1):t}async function _Le(e,t,n,i){let{spec:r,k:o,wave:s,cwd:a,log:c,options:l}=e,u=await Promise.resolve().then(()=>(Zg(),Tj)),d=l.gates??Xa({cwd:a}),p=r.override?.overriders??u.OVERRIDERS_PATH,f=n??u.overridersAt(a,t.base,p).principals,g=t.approval==="sealed",h=g?(l.signers??(await Promise.resolve().then(()=>(Dj(),Ij))).gateSignersAt.bind(null,a))(t.base):void 0,w=await d.read(u.OVERRIDE_OP),b=await d.readApplied?.(u.OVERRIDE_OP)??[],k=l.now??new Date().toISOString(),$=[],x=!1;for(let R of t.members){if(!R.denied||R.override)continue;let P=u.decideOverride({ledger:w,applied:b,subject:R.member,planDigest:R.planDigest,rules:R.denied.rules,overriders:f,overridersPath:n?i??"the overriders the plans file names":p,mode:g?"sealed":"ledger",...h?{signers:h}:{},now:k});if(P.status==="overridden"){let I=P.override;R.override={by:I.by,at:I.at,digest:I.digest,reason:I.reason},c(`${R.member}: the policy denial (${I.rules.join(", ")}) is overridden by ${I.by} at ${I.at}${I.sealed?", sealed":""}: ${I.reason}`);continue}$.push(R.member);for(let I of P.refusals)c(`${R.member}: an override does not count: ${I}`);if(P.status==="moved"&&(x=!0,c(`${R.member}: ${P.by} overrode an earlier plan or other rules (${P.was??"no digest"}); this plan and its rules give ${P.digest}, so that override counts for nothing`)),!P.standing){let{version:I,kind:A,...B}=u.overridePending({subject:R.member,planDigest:R.planDigest,rules:R.denied.rules,timestamp:k,expiresAt:new Date(new Date(k).getTime()+1728e5).toISOString(),description:R.denied.reason??`wave ${o} (${s.name}) of ${r.name}: ${R.member}: plan ${R.planDigest} denied by ${u.sortedRules(R.denied.rules).join(", ")}`});try{await d.appendPending({...B,members:[{member:R.member,planDigest:R.planDigest}],wave:{number:o,name:s.name,op:r.name}})}catch(C){c(`${R.member}: the denial was not recorded for an override: ${C instanceof Error?C.message:String(C)}`)}}c(`${R.member}: ${f.length?`${f.join(", ")} may`:"nobody listed may"} override it with: ${u.overrideCommand(R.member,R.denied.rules,g)}`)}$.length>0&&(t.status="refused",t.refused={reason:x?"override-moved":"policy",runs:$.sort(),...n&&i?{overridersSource:i}:{}})}function kie(e){if(!(e.pushed||cg(e.pushWarning)))throw new Error(`the record did not reach the remote the next run reads: ${e.pushWarning??"the push did not land"}`)}async function xie(e,t){let n=t.members.filter(d=>d.override);if(n.length===0||t.overridesSpentAt)return!0;let{k:i,wave:r,cwd:o,log:s,options:a}=e,c=await Promise.resolve().then(()=>(Zg(),Tj)),l=a.gates??Xa({cwd:o}),u=a.now??new Date().toISOString();try{if(!l.appendApplied)throw new Error("this gate ledger cannot record an applied override");for(let d of n){let p=c.appliedOverride({subject:d.member,digest:d.override.digest,at:d.override.at,by:d.override.by},{timestamp:u});kie(await l.appendApplied(p))}}catch(d){return yo(e,`wave ${i} (${r.name}) could not record the overrides it applies under, so nothing applied: ${d instanceof Error?d.message:String(d)}`),!1}return t.overridesSpentAt=u,s(`wave ${i} (${r.name}) applies ${n.map(d=>d.member).join(", ")} under their overrides, which are now spent`),!0}function YG(e){return e.refused?.reason==="point"?8:7}function yo(e,t){return e.log(t),e.result.exitCode=1,e.result}async function $ie(e,t,n){if(n.point)return TLe(e,t,n,n.point);let{spec:i,k:r,wave:o,cwd:s}=t,{gate:a,digest:c,approval:l,base:u,policy:d,members:p}=n,{ledger:f,port:g}=await wie(e,s,a,l,u),h=e.now??new Date().toISOString(),w=n.spend==="base"?(await f.readApplied?.(i.name)??[]).filter(x=>x.gate===a):void 0,b=n.heldBy?.length?`, held by ${n.heldBy.join(", ")}`:"",k=await DZ(g,{op:i.name,gate:a,digest:c,description:(typeof n.pending?.description=="string"?n.pending.description:void 0)??`wave ${r} (${o.name}): ${p.length} run${p.length===1?"":"s"}, gate ${d}, approval ${l}${b}`,now:h,...w?{spent:w}:{},fields:{...n.pending,approvalMode:l},...n.neverOverMcp?{neverOverMcp:!0}:{}});if(k.satisfied){n.status="approved",n.via="ledger",n.approvedBy=k.resolution.resolvedBy,n.approvedAt=k.resolution.timestamp;return}bie(t.log,`wave ${r} (${o.name})`,k),n.pendingFact=k.pending,n.recorded=k.recorded,n.waitingSince=k.pending.timestamp,k.mismatch&&(n.mismatch=k.mismatch);let $=w?.filter(x=>sr([x],{gate:a,planDigest:c,timestamp:x.approvedAt})).pop();if($&&t.log(`wave ${r} (${o.name}): the approval of ${c} by ${$.approvedBy} at ${$.approvedAt} is spent: a wave applied under it at ${$.timestamp}. Applying it again needs a new approval`),l==="pr-review"){let x=await jLe(e,{op:i.name,gate:a,k:r,digest:c,cwd:s,now:h,port:f,...w?{spent:w}:{}});if(n.review=x.review,x.approved){for(let R of["pendingFact","recorded","waitingSince","mismatch"])delete n[R];n.status="approved",n.via="pr-review",n.approvedBy=x.review.approvers.join(", "),n.approvedAt=h;return}n.status="waiting",n.approve=wp(i.name,a,void 0,c);return}n.status="waiting",n.approve=wp(i.name,a,void 0,c,l==="sealed")}async function TLe(e,t,n,i){let{spec:r,k:o,wave:s,cwd:a,log:c}=t,{gate:l,digest:u,policy:d,members:p}=n;n.approval!=="ledger"&&c(`wave ${o} (${s.name}): its gate asks decision point ${i.name}, so its approval mode (${n.approval}) does not apply`);let{evaluatePointGate:f}=await Promise.resolve().then(()=>(Sx(),u5)),g=e.points??(await Promise.resolve().then(()=>(NR(),aie))).workspaceGatePointAsker(a),h=n.heldBy?.length?`, held by ${n.heldBy.join(", ")}`:"",w=await f(e.gates??Xa({cwd:a}),g,{op:r.name,gate:l,point:{name:i.name,...i.pass?{pass:i.pass}:{},...i.store?{store:i.store}:{}},...i.inputs?{inputs:i.inputs}:{},description:(typeof n.pending?.description=="string"?n.pending.description:void 0)??`wave ${o} (${s.name}): ${p.length} run${p.length===1?"":"s"}, gate ${d}, decision point ${i.name}${h}`,...i.timeout?{timeout:i.timeout}:{},planDigest:u,...e.now?{now:e.now}:{},fields:{...n.pending,approvalMode:n.approval},...n.neverOverMcp?{neverOverMcp:!0}:{}});if(w.satisfied){n.status="approved",n.via="point",n.approvedBy=w.resolution.resolvedBy,n.approvedAt=w.resolution.timestamp,i.answer=w.answer;return}if("refused"in w){n.status="refused",n.refused={reason:"point",runs:p.map(b=>b.member),message:w.refused},i.answer=w.answer;return}n.status="waiting",n.pendingFact=w.pending,n.recorded=w.recorded,n.waitingSince=w.pending.timestamp,i.question=w.waiting,n.approve=`chant workspace points answer ${w.waiting.id} --answer <answer> --by <your name>`,c(`wave ${o} (${s.name}) asks decision point ${i.name} about ${u}: question ${w.waiting.id} is ${w.waiting.state}`)}function us(e,t,n){n.hooks.length>0&&(t.outcomes=[...n.hooks]),jZ(e,t)}async function Rie(e,t,n,i,r){let{k:o,wave:s,log:a,result:c}=t;return i.length===0||n.status==="approved"?!0:(n.heldBy=[...n.heldBy??[],...i],await $ie(e,t,n),r&&us(r,n,c),n.status==="refused"?(r&&await jS(t,n,r),a(`wave ${o} (${s.name}) is held by ${i.join(", ")}; nothing applied: ${n.refused?.message??"refused"}`),c.exitCode=YG(n),!1):n.status==="waiting"?(r&&await jS(t,n,r),a(`wave ${o} (${s.name}) is held by ${i.join(", ")}, and nobody approved ${n.digest}; nothing applied. Approve: ${n.approve}`),c.exitCode=3,!1):(a(`wave ${o} (${s.name}) is held by ${i.join(", ")}, and ${n.approvedBy} approved its digest`),!0))}function ILe(e,t,n){if(pie(e))try{let i=JSON.parse(yu(e,"utf-8"));if(!U1.includes(i.outcome))throw new Error(`outcome ${JSON.stringify(i.outcome)} is none of ${U1.join(", ")}`);if(i.reason!==void 0&&typeof i.reason!="string")throw new Error("its reason is not text");let r=i.holder&&typeof i.holder=="object"&&typeof i.holder.run=="string"?{run:i.holder.run,...typeof i.holder.url=="string"?{url:i.holder.url}:{}}:void 0;return{outcome:i.outcome,...i.reason?{reason:i.reason}:{},...r?{holder:r}:{}}}catch(i){n(`${t}: the apply wrote an outcome that cannot be read (${i instanceof Error?i.message:String(i)}), so its exit code decides`);return}}async function die(e,t,n,i,r,o,s,a){let{spec:c,k:l,wave:u,cwd:d,exec:p,log:f,result:g}=t,h=n.applyHooksRunBy==="apply",w=`.chant/op-waves/${c.name}/wave-${l}`,b=`${w}/${s.key}.json`,k=`${w}/${s.key}-result.json`,$=`${w}/${s.key}-outcome.json`,x={};if(h)for(let R of["before-apply","after-apply"])n.hooks?.[R]?.length&&(x[R]=n.hooks[R]);for(let R=0;R<2;R++){let P=n.status==="approved",I={version:1,opWaves:c.name,op:c.op,wave:u.name,number:l,base:n.base,digest:n.digest,approved:P,...n.heldBy?.length?{heldBy:n.heldBy}:{},runBy:h?"apply":"chant",runs:yie(c,l,i,r),runsFile:s.runsPath,hooks:x,outcomes:[...g.hooks],...h?{result:k}:{}};NS(Ln(d,w),{recursive:!0}),KG(Ln(d,b),JSON.stringify(I,null,2)+`
348
348
  `),lw(Ln(d,k),{force:!0}),lw(Ln(d,$),{force:!0});let A;try{A=p(o,d,{CHANT_HOOKS:b,CHANT_APPLY_OUTCOME:$,...h?{CHANT_HOOKS_RESULT:k}:{}})}catch(W){f(`${s.label}: the apply did not run: ${W instanceof Error?W.message:String(W)}`),A=127}let B=ILe(Ln(d,$),s.label,f);if(B){if(h)try{let W=JSON.parse(yu(Ln(d,k),"utf-8"));Array.isArray(W?.outcomes)&&g.hooks.push(...W.outcomes)}catch{}return f(`${s.label}: the apply applied nothing: ${B.outcome}${B.reason?` (${B.reason})`:""}${B.holder?`, held by run ${B.holder.run}`:""}`),{outcome:"applied-nothing",said:B}}if(!h)return{outcome:A===0?"applied":"failed"};let C=null;try{C=JSON.parse(yu(Ln(d,k),"utf-8"))}catch{C=null}let q=Array.isArray(C?.outcomes)?C.outcomes:[],L=Array.isArray(C?.moments)?C.moments:[];g.hooks.push(...q);let M=q.filter(W=>W.moment==="before-apply"&&W.outcome==="held").map(W=>`${W.moment} hook ${W.name}${W.target?` (${W.target})`:""}`);if(M.length>0&&!P){if(A===0)return f(`${s.label}: the apply exited 0 although ${M.join(", ")} held it and no approval stood; an apply applies nothing on a hold`),{outcome:"failed"};if(R>0||!await Rie(e,t,n,M,a))return{outcome:"waiting"};if(!await XG(e,t,n))return{outcome:"failed"};a&&n.spentAt&&us(a,n,g);continue}let _=q.find(W=>W.moment==="after-apply"&&W.outcome==="failed");if(_)return{outcome:"applied",problem:`${s.label} applied, and then the after-apply hook ${_.name} failed`};if(A!==0)return{outcome:"failed"};let T=["before-apply","after-apply"].filter(W=>x[W]&&!L.includes(W));return T.length>0?{outcome:"applied",problem:`${s.label}: the apply exited 0 without running its ${T.join(" and ")} hooks (runOpWaveApplyHooks with CHANT_HOOKS), which the spec at base hands it`}:{outcome:"applied"}}return{outcome:"failed"}}async function DLe(e,t,n,i,r,o,s){let{spec:a,k:c,wave:l,log:u,result:d}=t;if(i.length===0)return;let p=n.applyHooksRunBy==="apply",f=[...o];if(!p){let b=await hu(t,"before-apply",n.hooks?.["before-apply"],i,r,n.digest);if(b.failed){yo(t,`a hook before the apply failed, so nothing in wave ${c} was applied`);return}if(b.waitingOn){ZG(n,b.waitingOn),s&&(us(s,n,d),await jS(t,n,s)),d.decision=n,d.exitCode=3;return}f.push(...b.holds)}if(!await Rie(e,t,n,f,s)||!await XG(e,t,n)||!await xie(t,n))return;s&&(n.spentAt||n.overridesSpentAt)&&us(s,n,d);let g=[],h=!1,w;if(a.applyWave){let b=DS(t,i,r,n.digest),k=vf(a.applyWave,{op:a.op,wave:l.name,runs:b,plans:H1(a,c)}),$=await die(e,t,n,i,r,k,{label:`wave ${c} (${l.name})`,key:"hooks",runsPath:b},s);$.outcome==="applied-nothing"?w=$.said:$.outcome==="applied"?(d.applied.push(...i.map(x=>x.target)),$.problem&&g.push($.problem)):$.outcome==="waiting"?h=!0:(u(`wave ${c} (${l.name}): apply failed, so none of ${i.map(x=>x.target).join(", ")} counts as applied`),d.failed.push(...i.map(x=>x.target)))}else for(let b of i){let k=b.target.replace(/[^A-Za-z0-9._-]/g,"_"),$=p?DS(t,[b],r,n.digest,`.chant/op-waves/${a.name}/wave-${c}/${k}.runs.json`):V1(a,c),x=vf(a.apply??xj,{op:b.op??a.op,target:b.target,wave:l.name,plan:LS(a,c,b.target)}),R=await die(e,t,n,[b],r,x,{label:b.target,key:`${k}.hooks`,runsPath:$},s);if(R.outcome==="applied-nothing"){w=R.said;break}if(R.outcome==="waiting"){h=!0;break}R.outcome==="applied"?(d.applied.push(b.target),R.problem&&g.push(R.problem)):(u(`${b.target}: apply failed`),d.failed.push(b.target))}if(s&&p&&us(s,n,d),w){if(w.outcome==="replan"){d.replan={...w.reason?{reason:w.reason}:{}};return}d.outcome=w,d.exitCode=w.outcome==="stood-down"?6:5,s&&us(s,n,d);return}if(h){d.exitCode=n.status==="refused"?YG(n):3;return}if(d.failed.length>0){d.exitCode=1;return}if(g.length>0){for(let b of g)u(b);d.exitCode=1;return}p||(await hu(t,"after-apply",n.hooks?.["after-apply"],i,r,n.digest)).failed&&yo(t,`wave ${c} (${l.name}) applied, and then a hook after the apply failed`),s&&d.hooks.length>0&&us(s,n,d)}async function XG(e,t,n){if(!n.spend||n.status!=="approved"||n.spentAt||!n.approvedAt)return!0;let{spec:i,k:r,wave:o,cwd:s,log:a}=t,c=e.gates??Xa({cwd:s}),l=e.now??new Date().toISOString(),u={version:1,kind:"applied",op:i.name,gate:n.gate,planDigest:n.digest,approvedAt:n.approvedAt,approvedBy:n.approvedBy??"",timestamp:l,wave:{number:r,name:o.name},...n.via==="pr-review"&&n.review?{review:{...n.review.pr!==void 0?{pr:n.review.pr}:{},...n.review.head?{head:n.review.head}:{}}}:{}};try{if(!c.appendApplied)throw new Error("this gate ledger cannot record an applied approval");let d=await c.appendApplied(u);kie(d),!d.pushed&&d.pushWarning&&a(`wave ${r} (${o.name}): ${d.pushWarning}`)}catch(d){return yo(t,`wave ${r} (${o.name}) could not record that it applies under the approval by ${u.approvedBy}, so nothing applied: ${d instanceof Error?d.message:String(d)}`),!1}return n.spentAt=l,a(`wave ${r} (${o.name}) applies under the approval by ${u.approvedBy} at ${u.approvedAt}, which is now spent`),!0}async function jLe(e,t){let n=await Promise.resolve().then(()=>(Jg(),Kg)),i=e.head??IS("git",["rev-parse","HEAD"],{cwd:t.cwd,encoding:"utf-8"}).trim(),r;try{r=await(e.reviews??n.reviewSourceFromEnv()).mergedReview(i)}catch(l){return{approved:!1,review:{reason:`the forge's review could not be read: ${l instanceof Error?l.message:String(l)}`}}}if(!r)return{approved:!1,review:{reason:`no merged pull request produced ${i.slice(0,12)}`}};let o=r.approvers.length===0?null:await(e.headPlans??((l,u)=>NLe(l,u,t.cwd)))(e.spec.name,r.head),{reviewApproval:s}=await Promise.resolve().then(()=>(Dj(),Ij)),a=s(r,o?.waves.find(l=>l.wave===t.k)?.digest,t.digest);if(!a.approved)return a;if(t.spent&&sr(t.spent,{gate:t.gate,planDigest:t.digest,review:{head:r.head}}))return{approved:!1,review:{...a.review,reason:`a wave already applied ${t.digest} under the review of #${r.pr} at ${r.head.slice(0,12)}, so the review is spent`}};let c=`approved by the review of #${r.pr} at ${r.head.slice(0,12)}: ${r.approvers.join(", ")}`;return await t.port.appendResolution?.({op:t.op,gate:t.gate,resolvedBy:r.approvers[0],timestamp:t.now,planDigest:t.digest,approver:{kind:"human"},gitSha:i,...vl()?{runId:vl()}:{},note:c,...r.url?{url:r.url}:{},review:{pr:r.pr,head:r.head,approvers:r.approvers}}),a}async function NLe(e,t,n){let{gitLedgerReadPort:i,requireLifecycleLedger:r}=await Promise.resolve().then(()=>(Pt(),MI)),{readHeadPlans:o}=await Promise.resolve().then(()=>(Aj(),VZ));return await r({cwd:n}),o(i({cwd:n}),e,t)}async function Z1(e){let{spec:t}=e;Vg(t);let n=e.cwd??process.cwd(),i=e.exec??fie,r=await Promise.resolve().then(()=>(Jg(),Kg)),o=e.head??r.pullRequestHeadFromEnv()??IS("git",["rev-parse","HEAD"],{cwd:n,encoding:"utf-8"}).trim(),s={version:1,name:t.name,head:o,timestamp:e.now??new Date().toISOString(),waves:[]},a=t.waves[t.waves.length-1];for(let c=1;;c++){let l=t.waves[c-1]??a,{members:u,extras:d,waves:p}=HG({spec:t,k:c,wave:l,cwd:n,exec:i},l.runs,l.discover===!0);if(s.waves.push({wave:c,name:l.name,digest:q1(t,u,d)}),c>=t.waves.length&&!(a.rest&&p!==void 0&&c<p))break}return await(e.write??(c=>LLe(c,n)))(s),s}async function LLe(e,t){let{pushLifecycle:n,requireLifecycleLedger:i,writeBlobToPath:r}=await Promise.resolve().then(()=>(Pt(),MI)),{headPlansPath:o}=await Promise.resolve().then(()=>(Jg(),Kg));await i({cwd:t});let{dir:s,file:a}=o(e.name,e.head);if(await r(s,a,JSON.stringify(e,null,2)+`
349
349
  `,`Op waves plans of ${e.name} at ${e.head.slice(0,12)}`,{cwd:t}),!await n({cwd:t}))throw new Error("the plans were recorded locally only: chant/lifecycle has no remote to push to")}var yLe,U1,fie,wLe,cie,$Le,yie,lie,J1,Y1=v(()=>{"use strict";LZ();Uo();Ma();lg();Ga();$p();yLe=["version","kind","op","gate","timestamp","expiresAt","planDigest","runId","url","resume","environment","origin","neverOverMcp","approval","approvalMode","answer","wave","heldBy"],U1=["stood-down","held","replan"],fie=(e,t,n)=>{let i=gLe(e[0],e.slice(1),{cwd:t,stdio:"inherit",...n?{env:{...process.env,...n}}:{}});if(i.error)throw i.error;return i.status??1},wLe=(e,t,n)=>{let i;try{i=IS("git",["rev-parse","--verify",`${e}^{commit}`],{cwd:n,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim()}catch{throw new Error(`the gate policy is read at ${e}, which this checkout does not have. Check out the full history (fetch-depth: 0 on GitHub and Forgejo, GIT_DEPTH: "0" on GitLab), or set the spec's base.`)}try{let r=IS("git",["show",`${i}:./${t}`],{cwd:n,encoding:"utf-8",stdio:["ignore","pipe","pipe"]});return{sha:i,text:r}}catch{return{sha:i,text:null}}};cie=()=>Object.fromEntries(wx.map(e=>[e,[]]));$Le=e=>({name:e.spec.name,op:e.spec.op,waveName:e.wave.name,k:e.k,cwd:e.cwd,exec:e.exec,log:e.log}),yie=(e,t,n,i)=>n.map(r=>({target:r.target,op:r.op??e.op,...i?.has(r.target)?{plan:LS(e,t,r.target)}:{}}));lie=10;J1=10});var Aie=v(()=>{"use strict";Dn()});var QG,Pie=v(()=>{"use strict";Aie();QG=/^pr-\d+(?:-[a-z0-9][a-z0-9-]*)?$/});async function Cie(e){let{resolutions:t,pending:n}=await Kn(Zn,e),i=await At(FLe,GLe,e);return{resolutions:t,pending:n,applied:i?_j(i):[]}}var FLe,GLe,_ie=v(()=>{"use strict";Wt();Mr();Pt();Zg();FLe=`_gates/${Zn}`,GLe="applied.jsonl"});var Iie={};_e(Iie,{runOverrideApprove:()=>WLe});async function WLe(e){let t=e.args.extraPositional,n=xx(t,e.args.rules?.length?e.args.rules:["<id>"]);if(e.args.reason!==void 0&&e.args.note!==void 0&&e.args.reason.trim()!==e.args.note.trim())return console.error(we({message:"Give the override's reason once: --reason <text> (--note is the same field)",hint:n})),1;let i=(e.args.reason??e.args.note)?.trim(),r=nc(e.args.rules??[]);if(r.length===0)return console.error(we({message:"An override names each rule it overrides with --rule <id>",hint:n})),1;if(!i)return console.error(we({message:"An override needs --reason <text>: why this plan goes out although the policy denies it",hint:n})),1;if(e.args.agent||di(bs()))return console.error(we({message:"An override is a person's: it is never recorded by an agent or over MCP or ACP",hint:`${n}, at a shell.`})),1;try{await Lr()}catch(d){return console.error(we({message:`Cannot record the override: ${d instanceof Error?d.message:String(d)}`})),1}let o=await Cie(),s=$x(o.pending),a=s.find(d=>d.gate===t);if(!a)return console.error(we({message:`No denial of ${t} is recorded on ${Zn}`+(s.length?`; denied: ${s.map(d=>d.gate).join(", ")}`:""),hint:"A run records one when its policy denies the plan. An override answers that denial, for that plan."})),1;if(a.rules.join(`
350
350
  `)!==r.join(`
351
- `))return console.error(we({message:`${t} was denied by ${a.rules.join(", ")||"no rule it named"}; an override names exactly those rules, and --rule gave ${r.join(", ")}`,hint:xx(t,a.rules)})),1;if(e.args.plan!==void 0&&!mt(e.args.plan,a.plan)&&!mt(e.args.plan,a.planDigest))return console.error(we({message:`--plan ${e.args.plan} is not the plan denied for ${t}: the newest denial is of ${a.plan||a.planDigest}`,hint:"Run the plan again, or override the denial that stands."})),1;let c=await eW(Zn,t,{actor:e.args.approver??e.args.actor,note:i,url:e.args.url,plan:a.planDigest,allowSameOrigin:e.args.allowSameOrigin,...e.args.roles?{roles:e.args.roles}:{},...e.args.sign!==void 0?{sign:e.args.sign}:{},...e.args.relayedBy!==void 0?{relayedBy:e.args.relayedBy}:{}});if(!c.ok)return 1;if(console.error(Qn(`This overrides the denial of ${t} by ${r.join(", ")} for the plan ${a.plan||a.planDigest}. The next run that plans it applies it once; a plan that moves, or rules that change, need their own override.`)),process.env.CHANT_OVERRIDERS_FROM?.trim())return 0;let u=Cj(process.cwd(),"HEAD");return u.active?u.principals.map(Tie).includes(Tie(c.record.resolvedBy))||console.error(si({message:`${c.record.resolvedBy} is not in ${Rp} here (${u.principals.join(", ")||"nobody"}), so a run that reads it at base does not count this override`})):console.error(si({message:`This checkout has no ${Rp}: unless the run reads its overriders from elsewhere at base, no override counts (a tool that does sets CHANT_OVERRIDERS_FROM to say so)`})),0}var Tie,Die=v(()=>{"use strict";el();Pt();_ie();Dn();Zg();ur();tW();Tie=e=>e.normalize("NFKC").trim().toLowerCase()});async function jie(e){let{pushed:t,pushWarning:n}=await Ia();return t?{pushed:t,suffix:""}:cg(n)?{pushed:t,suffix:` (${jd})`}:(console.error(si({message:`The push to the remote did not land: ${n??"no reason given"}`,hint:e})),{pushed:t,suffix:" (local only \u2014 the push did not land)"})}async function Nie(e){let t=e.args.path,n=e.args.extraPositional;if(!t||t==="."||!n)return console.error(we({message:"Usage: chant approve <op> <gate>"})),1;if(e.args.expire){try{await Lr()}catch(a){return console.error(we({message:`Cannot expire the gate: ${a instanceof Error?a.message:String(a)}`})),1}let r=new Date().toISOString(),o=yn((await Kn(t)).pending,n);if(!o||On(o,r))return console.error(si({message:`Gate "${n}" on "${t}" has no standing pending fact \u2014 nothing to expire`})),0;await zd({op:t,gate:n,timestamp:r,expiresAt:r,...o.description?{description:o.description}:{},...o.runId?{runId:o.runId}:{},...o.gitSha?{gitSha:o.gitSha}:{}});let s=await jie(`The expiry is recorded locally on ${uw}. Until it reaches the remote, a run in another checkout still sees the old pending fact.`);return console.error(xf(`Gate "${n}" on "${t}" expired at ${r} \u2014 not approved`+s.suffix)),console.error(Qn(t===id?"The next `chant components fan-out` decides this gate from scratch and records a fresh pending fact.":QG.test(t)?"The next `chant components pr-apply` decides this gate from scratch and records a fresh pending fact.":t===od?`The next \`chant workspace upgrade ${n}\` decides this gate from scratch and records a fresh pending fact.`:t===ui?"The next `chant components promote --release` decides this gate from scratch and records a fresh pending fact.":`The next \`chant run ${t}\` decides this gate from scratch and records a fresh pending fact.`)),0}if(t===pa){let{runOverrideApprove:r}=await Promise.resolve().then(()=>(Die(),Iie));return r(e)}if(e.args.rules!==void 0||e.args.reason!==void 0)return console.error(we({message:`--rule and --reason override a denied plan: chant approve ${pa} <subject> --rule <id> --reason <text>`,hint:`To approve gate "${n}" on "${t}", put any prose in --note.`})),1;let i=await eW(t,n,{actor:e.args.approver??e.args.actor,note:e.args.note,url:e.args.url,plan:e.args.plan,...e.args.env!==void 0?{environment:e.args.env}:{},allowSameOrigin:e.args.allowSameOrigin,...e.args.roles?{roles:e.args.roles}:{},...e.args.agent?{agent:!0}:{},...e.args.sign!==void 0?{sign:e.args.sign}:{},...e.args.relayedBy!==void 0?{relayedBy:e.args.relayedBy}:{}});if(!i.ok)return 1;if(e.args.resumeRun||e.args.resume!==void 0){let{resumeAfterApproval:r}=await Promise.resolve().then(()=>(CS(),jG));return r(t,n,i.record.environment,i.pushed)}return console.error(Qn("This records the resolution as a fact; it does not itself re-run anything. "+(t===id?`Repeat the \`chant components fan-out\` command and it walks through gate "${n}".`:QG.test(t)?`The pull request's apply (\`chant components pr-apply\`) walks through gate "${n}" when it plans this same digest.`:t===od?`Repeat \`chant workspace upgrade ${n}\` with the same target, and it applies the patch this approval names.`:t===ui?`Repeat the same \`chant components promote --release\`, and it walks through gate "${n}" when it plans this same change set for this release.`:`Run \`chant run ${t}\` and it walks through gate "${n}".`))),0}async function BLe(e,t,n,i){let{readRelease:r,readCuts:o,labelsByDigest:s}=await Promise.resolve().then(()=>(cu(),wy)),{readRevokedCommits:a,revocationOf:c,revokedRefusal:l}=await Promise.resolve().then(()=>(rS(),AF)),u=await r(n,{cwd:i}).catch(()=>null);if(!u)return console.error(we({message:`Gate "${t}" on "${e}" binds release ${n}, which can't be read from ${uw}, so whether it is revoked is unknown [release-unreadable]`,hint:`Fetch the ledger branch (git fetch origin ${uw}:${uw}) and approve again from the member's directory.`})),!0;let d;try{d=await a(i)}catch(g){return console.error(we({message:`Gate "${t}" on "${e}" binds release ${n}, and the ci tags can't be judged: ${g instanceof Error?g.message:String(g)} [declaration-invalid]`,hint:"Fix ci.green in chant.workspace.json at base; chant workspace check names the problem."})),!0}let p=c(u,d);if(!p)return!1;let f=s((await o({cwd:i}).catch(()=>({cuts:[]}))).cuts).get(n)??null;return console.error(we(l({releaseDigest:n,label:f},p,`Clear the pending gate with \`chant approve ${e} ${t} --expire\`, then promote a release cut from a green commit: \`chant ci last-green\` names the newest, and \`chant release list\` marks the revoked releases.`))),!0}async function eW(e,t,n){if(Ki())return console.error(we({message:`Cannot record the approval of "${t}": ${vk} is set, so nothing is written to chant/lifecycle`,hint:`Unset ${vk} to approve the gate.`})),{ok:!1};let{ops:i}=await ic(),r=lQ([...i.values()].map(T=>T.config),e,t);!r&&!i.has(e)&&e!==id&&e!==od&&e!==pa&&e!==ui&&console.error(si({message:`Op "${e}" was not found among discovered *.op.ts declarations \u2014 recording the resolution anyway`}));try{await Lr()}catch(T){return console.error(we({message:`Cannot record the approval: ${T instanceof Error?T.message:String(T)}`,hint:"The pending fact this answers lives on that branch; appending without it would drop it."})),{ok:!1}}if(r){let T=yn((await Kn(r.op)).pending,r.gate);if(T&&!On(T,new Date().toISOString()))return console.error(we({message:`Gate "${t}" on "${e}" is now gate "${r.gate}" on "${r.op}", which lists it as an alias, and "${r.gate}" has a standing pending fact`,hint:`Approve that gate instead: chant approve ${r.op} ${r.gate}`})),{ok:!1};console.error(Qn(`Gate "${t}" on "${e}" is an alias of gate "${r.gate}" on "${r.op}": the next run of ${r.op} counts this approval there while the pending fact it answers stands and the plan is the same.`))}let o=n.url??ja();if(o&&!Ek(o))return console.error(we({message:`--url must be an absolute http/https URL (got "${o}")`,hint:"Pass the PR/MR link, or omit --url and put prose in --note."})),{ok:!1};let s=await Kn(e),a=T=>T.some(ve=>ve.gate===t&&ve.environment!==void 0)&&n.environment!==void 0?T.filter(ve=>ve.environment===n.environment):T,c=yn(a(s.pending),t),l=c?.environment,u;if(n.plan!==void 0){if(!zI(n.plan))return console.error(we({message:`--plan must be a plan digest ("jcs1-sha256:" or "sha256:", then 64 hex characters), got "${n.plan}"`,hint:"Copy it from the gated run's `plan :` line, or from the pending-gate summary. It is not a plan file path."})),{ok:!1};u=n.plan}else{if(!c)return console.error(we({message:n.environment!==void 0&&s.pending.some(T=>T.gate===t&&T.environment!==void 0)?`Gate "${t}" on "${e}" has no pending fact in environment "${n.environment}", so there is no plan to approve`:`Gate "${t}" on "${e}" has no pending fact, so there is no plan to approve`,hint:`Run \`chant run ${e}\` first \u2014 it plans, stops at the gate, and records the plan this approval would be for. To approve a plan you already have the digest for, pass \`--plan <digest>\`.`})),{ok:!1};u=c.planDigest}let d=c?.checkpointDigest!==void 0&&mt(u,c.planDigest)?c.checkpointDigest:void 0,p=c?.releaseDigest!==void 0&&mt(u,c.planDigest)?c.releaseDigest:void 0;if(c?.releaseDigest!==void 0&&await BLe(e,t,c.releaseDigest,n.cwd??process.cwd()))return{ok:!1};let f=n.origin??bs(),g=await Kn(e),h=yn(a(g.pending),t);if(di(f)&&(h?.neverOverMcp||i.get(e)?.config.neverOverMcp))return console.error(we({message:`Gate "${t}" on "${e}" is never resolved over ${f==="acp"?"ACP":"MCP"}`,hint:`Approvals belong to people: \`chant approve ${e} ${t}\` at a shell.`})),{ok:!1};if(h?.answer)return console.error(we({message:`Gate "${t}" on "${e}" asks decision point ${h.answer.point}, so its answer passes the gate, not an approval`,hint:`Answer the question: \`chant workspace points answer ${h.answer.id} --answer <value> --by <name>\`, then run \`chant run ${e}\` again.`})),{ok:!1};let w=DV(h?.origin,f);if(w&&!n.allowSameOrigin)return console.error(we({message:`Gate "${t}" on "${e}" cannot be resolved from here: ${w}`,hint:`Approve it from a channel the run did not come from \u2014 \`chant approve ${e} ${t}\` at a shell is the usual one. If resolving from the same channel genuinely is the intent, pass --allow-same-origin, which records that it was deliberate.`})),{ok:!1};let b=n.relayedBy?.trim();if(n.relayedBy!==void 0&&(!b||/[\r\n]/.test(b)))return console.error(we({message:`--relayed-by needs one principal on one line (got ${JSON.stringify(n.relayedBy)})`,hint:"Name who relayed the approval, such as --relayed-by github:<login> or a principal the signers file lists."})),{ok:!1};let k=n.actor??(di(f)?kv:process.env.GITHUB_ACTOR??process.env.GITLAB_USER_LOGIN??process.env.USER??"unknown"),$={kind:n.agent||di(f)?"agent":"human",...n.roles&&n.roles.length>0?{roles:[...new Set(n.roles)]}:{}},x=n.cwd??process.cwd(),R=await Promise.resolve().then(()=>(Tl(),aj)),{scopeSource:P}=await Promise.resolve().then(()=>(Bo(),oj)),I=P(x);try{R.refuseUnidentified(I,[k],n.actor!==void 0?"--actor":"the approver"),b&&R.refuseUnidentified(I,[b],"--relayed-by")}catch(T){if(!(T instanceof R.IdentityError))throw T;return console.error(we({message:`Gate "${t}" on "${e}" was not approved: ${T.message}`,hint:"Pass --actor <forge identity or signer>, as the surface that signed the person in maps them, for example --actor github:<login>."})),{ok:!1}}let A=R.gateAdmissionFrom(I,t);if(A&&n.sign===void 0)return console.error(we({message:`Gate "${t}" needs a signed approval: chant.workspace.json at base names it in identity.gates`+(A.requirement.class!==null?`, from the class ${A.requirement.class}`:"")+", and this approval is not signed",hint:`chant approve ${e} ${t} --actor <principal> --sign [<key file>], with a key ${I.policy.signersPath} at base lists for that principal.`})),{ok:!1};let B=new Date().toISOString(),C;if(n.sign!==void 0){let{resolveSigningKey:T,sealGateApproval:W,gateSealVersion:ve,SealError:re}=await Promise.resolve().then(()=>(Op(),Ep));try{let be=T(n.sign,x);try{let Be={op:e,gate:t,...l!==void 0?{environment:l}:{},...u!==void 0?{planDigest:u}:{},resolvedBy:k,...b?{relayedBy:b}:{},timestamp:B,...d!==void 0?{checkpointDigest:d}:{}};C={...W(be.file,Be),...ve(Be)===2?{version:2}:{}}}finally{be.cleanup()}}catch(be){if(!(be instanceof re))throw be;return console.error(we({message:`Gate "${t}" on "${e}" was not approved: ${be.message}`})),{ok:!1}}}if(A){let T=A.refuses({op:e,gate:t,...l!==void 0?{environment:l}:{},...u!==void 0?{planDigest:u}:{},resolvedBy:k,...b?{relayedBy:b}:{},timestamp:B,...d!==void 0?{checkpointDigest:d}:{},seal:C});if(T!==null)return console.error(we({message:`Gate "${t}" on "${e}" was not approved: ${T}`,hint:`identity.gates.${t} in chant.workspace.json at base counts only an approval signed by a key ${I.policy.signersPath} lists for the approver`+(A.requirement.class!==null?`, who holds the role of the class ${A.requirement.class}`:"")+"."})),{ok:!1}}let q=h?.approval,L;if(q?.policy)try{let W=await(n.evaluator??await VI(q.policy.lexicon)).evaluateGatePolicy(q.policy,HI({op:e,gate:t,resolvedBy:k,approver:$,...u!==void 0?{planDigest:u}:{},...q.context?{context:q.context}:{}}));L={policy:q.policy.name,version:q.policy.version,mode:q.mode,contextDigest:bg(q.context),decision:W.decision,determining:W.determining,errors:W.errors}}catch(T){return console.error(we({message:`Gate "${t}" on "${e}" declares policy "${q.policy.name}", which could not be evaluated: ${T instanceof Error?T.message:String(T)}`,hint:`Install the ${q.policy.lexicon} lexicon in this project, or approve from a checkout that has it.`})),{ok:!1}}let{record:M}=await yg({op:e,gate:t,resolvedBy:k,...b?{relayedBy:b}:{},timestamp:B,...C?{seal:C}:{},approver:$,...L?{policyDecision:L}:{},...n.note?{note:n.note}:{},...o?{url:o}:{},...u!==void 0?{planDigest:u}:{},...d!==void 0?{checkpointDigest:d}:{},...l!==void 0?{environment:l}:{},...p!==void 0?{releaseDigest:p}:{},...c?.gitSha?{gitSha:c.gitSha}:{},...c?.runId?{runId:c.runId}:{},origin:f,...w&&n.allowSameOrigin?{sameOriginOverride:!0}:{}}),_=await jie(`The resolution is recorded locally on ${uw}. Until it reaches the remote, a run in another checkout will not see it.`);if(console.error(xf(`Gate "${t}" on "${e}" resolved by ${M.resolvedBy}`+(M.relayedBy?`, relayed by ${M.relayedBy},`:"")+` at ${M.timestamp}`+(M.url?` (${M.url})`:"")+(M.seal?`, signed with ${M.seal.key}`:"")+_.suffix)),M.planDigest&&console.error(Qn(`This approves the plan ${M.planDigest}`+(M.environment!==void 0?` in environment "${M.environment}"`:"")+(M.releaseDigest!==void 0?` for release ${M.releaseDigest}`:"")+", and only that plan. A run whose fresh plan differs refuses rather than applying it.")),M.checkpointDigest&&console.error(Qn(`The next run resumes at this gate from run ${c?.runId??"(unknown)"}'s checkpoint ${M.checkpointDigest}, after it plans again. A moved plan or another commit starts it at the first phase.`)),q)for(let T of zLe(q,M,g.resolutions,h,g.pending))console.error(Qn(T));return{ok:!0,record:M,pushed:_.pushed}}function zLe(e,t,n,i,r=i?[i]:[]){let o=[],s=t.policyDecision;if(s){let p=s.determining.length>0?` (${s.determining.join(", ")})`:"",f=e.mode==="enforce"?s.decision==="allow"?"In enforce mode this permit passes the gate on its own.":"In enforce mode only a permit passes the gate on its own, so this approval counts only toward the quorum.":"The gate is in log-only mode, so the decision is recorded and does not change the outcome.";o.push(`Policy "${s.policy}" ${s.version}: ${s.decision}${p}. ${f}`);for(let g of s.errors)o.push(`Policy evaluation error: ${g}`)}let a=i?.timestamp??new Date(0).toISOString(),c=i&&mt(i.planDigest,t.planDigest)?Qa(r,i):a,l=Ya([...n,t],t.gate,a,t.planDigest,e,c),u=e.quorum?.roles?` with role ${e.quorum.roles.join(" or ")}`:"",d=l.counted.map(p=>p.resolvedBy).join(", ")||"none yet";return o.push(`Quorum: ${l.counted.length} of ${l.need} human approval(s)${u} for this plan (${d}).`),l.counted.includes(t)||o.push(hp(t).kind==="agent"?"An agent's approval does not count toward the quorum.":`This approval does not count toward the quorum: the approver claims none of its roles (${e.quorum?.roles?.join(", ")}).`),o}var uw,tW=v(()=>{"use strict";qo();TR();el();Mr();Dn();vg();Uo();Yr();Pie();Pt();lg();Nd();ur();uw="chant/lifecycle"});GS();var zie=new Set(["--help","--open","--version","--agents","--agent","--all-projects","--force","--fix","--watch","--verbose","--live","--overlay","--explain","--owned","--verbatim","--skip-undeclarable","--apply-rewrites","--write","--strict","--validate","--use-composites","--composites","--stacks","--components","--pr-build","--up","--down","--include-dependents","--local","--json","--progress-json","--events-json","--follow","--update-snapshot","--update-baseline","--run-examples","--check","--bump","--no-release-record","--no-record","--fold","--no-fold","--no-cache","--sandbox","--yes","--confirm-prod","--once","--rerun-failed","--setup-key","--trust","--unsigned","--in-place","--require-runner-start","--no-push","--no-require-review","--expire","--check-live","--check-snapshot","--fail-on-drift","--durable-requests","--skip-mcp","--current","--uncommitted","--allow-code","--allow-skip","--allow-unsigned","--require-provenance","--root-only","--generated","--decide","--record-plans","--loopback","--artifacts","--push"]);function rW(e){e=e.slice();let t={command:"",path:".",extraPositional:void 0,extraPositional2:void 0,output:void 0,format:"",force:void 0,fix:!1,lexicon:void 0,template:void 0,watch:!1,verbose:!1,help:!1,param:void 0,paramsFile:void 0,report:void 0,local:void 0,profile:void 0,json:void 0,live:!1,migrateFrom:void 0,migrateTo:void 0,emit:void 0,strict:!1,validate:!1,useComposites:!1,reportFile:void 0,skill:void 0,skipMcp:void 0,src:void 0,env:void 0};e=nW(e,zie);let n=0;for(;n<e.length;){let i=e[n];if(i==="--help"||i==="-h")t.help=!0;else if(i==="--version"||i==="-V")t.version=!0;else if(i==="--output"||i==="-o")t.output=e[++n];else if(i==="--format"||i==="-f")t.format=e[++n];else if(i==="--lexicon"||i==="-d")t.lexicon=e[++n];else if(i==="--template"||i==="-t")t.template=e[++n];else if(i==="--force")t.force=!0;else if(i==="--fix")t.fix=!0;else if(i==="--watch"||i==="-w")t.watch=!0;else if(i==="--verbose"||i==="-v")t.verbose=!0;else if(i==="--profile"||i==="-p")t.profile=e[++n];else if(i==="--report"){let r=e[n+1];r&&!r.startsWith("-")?(t.reportFile=r,n++):t.report=!0}else if(i==="--live")t.live=!0;else if(i==="--overlay")t.overlay=!0;else if(i==="--between"){if(t.betweenA=e[++n],t.betweenB=e[++n],!t.betweenA||!t.betweenB)throw new Error("--between needs two snapshot refs: --between <refA> <refB>")}else if(i==="--traffic"){let r=e[++n];if(!r)throw new Error('--traffic needs a level, passed to the engine verbatim: --traffic "100 rps, p50"');t.traffic=r}else if(i==="--overlay-anchor"){let r=e[++n];if(r!=="source"&&r!=="live")throw new Error(`--overlay-anchor must be 'source' or 'live', got '${r}'`);t.overlayAnchor=r}else if(i==="--from")t.migrateFrom=e[++n];else if(i==="--kustomize")t.kustomize=e[++n];else if(i==="--parser-option"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--parser-option needs key or key=value: --parser-option acceptLossyV1");(t.parserOption??=[]).push(r)}else if(i==="--type")t.selectType=e[++n];else if(i==="--name")t.selectName=e[++n];else if(i==="--owned")t.owned=!0;else if(i==="--namespace"){if(t.namespace=e[++n],!t.namespace||t.namespace.startsWith("-"))throw new Error("--namespace needs a namespace: --namespace <ns>")}else if(i==="--verbatim")t.verbatim=!0;else if(i==="--skip-undeclarable")t.skipUndeclarable=!0;else if(i==="--state")t.statePath=e[++n];else if(i==="--select")t.selectAddress=e[++n];else if(i==="--live-name")t.liveName=e[++n];else if(i==="--apply-rewrites")t.applyRewrites=!0;else if(i==="--stack")t.carveStack=e[++n];else if(i==="--write")t.write=!0;else if(i==="--write-source")t.writeSource=!0;else if(i==="--to")t.migrateTo=e[++n];else if(i==="--emit")t.emit=e[++n];else if(i==="--dry-run")t.dryRun=!0;else if(i==="--yes")t.yes=!0;else if(i==="--push")t.push=!0;else if(i==="--confirm-prod")t.confirmProd=!0;else if(i==="--strict")t.strict=!0;else if(i==="--validate")t.validate=!0;else if(i==="--use-composites")t.useComposites=!0;else if(i==="--skill")t.skill=e[++n];else if(i==="--skip-mcp")t.skipMcp=!0;else if(i==="--src")t.src=e[++n];else if(i==="--env")t.env=e[++n];else if(i==="--port"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--port needs a port: --port <container-port>=<host-port>");(t.port??=[]).push(r)}else if(i==="--image"){if(t.image=e[++n],!t.image||t.image.startsWith("-"))throw new Error("--image needs an image reference: --image <name>:<tag>")}else if(i==="--network"){if(t.network=e[++n],!t.network||t.network.startsWith("-"))throw new Error("--network needs a Docker network name: --network <name>")}else if(i==="--setting"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--setting needs a value: --setting <KEY>=<VALUE>");(t.setting??=[]).push(r)}else if(i==="--loopback")t.loopback=!0;else if(i==="--promote-to"){if(t.promoteTo=e[++n],!t.promoteTo||t.promoteTo.startsWith("-"))throw new Error("--promote-to needs an environment: --promote-to <env>")}else if(i==="--tier")t.tier=e[++n];else if(i==="--agents")t.agents=!0;else if(i==="--scope")t.scope=e[++n];else if(i==="--all-projects")t.allProjects=!0;else if(i==="--runtime")t.runtime=e[++n];else if(i==="--fail-on")t.failOn=e[++n];else if(i==="--max-files")t.maxFiles=Number(e[++n]);else if(i==="--theme")t.theme=e[++n];else if(i==="--stacks")t.stacks=!0;else if(i==="--components")t.components=!0;else if(i==="--generate")t.generate=e[++n];else if(i==="--spec")t.opsSpec=e[++n];else if(i==="--dump-outputs")t.dumpOutputs=e[++n];else if(i==="--digest-file")t.digestFile=e[++n];else if(i==="--seed-outputs")(t.seedOutputs??=[]).push(e[++n]);else if(i==="--detail")t.detail=Number(e[++n]);else if(i==="--lens")t.lens=e[++n];else if(i==="--explain")t.explain=!0;else if(i==="--show")t.show=e[++n];else if(i==="--up")t.up=!0;else if(i==="--down")t.down=!0;else if(i==="--node-sizes")t.nodeSizes=e[++n];else if(i==="--layout-engine")t.layoutEngine=e[++n];else if(i==="--base")t.base=e[++n];else if(i==="--head")t.head=e[++n];else if(i==="--include-dependents")t.includeDependents=!0;else if(i==="--from-affected")t.fromAffected=e[++n];else if(i==="--gate")t.gate=e[++n];else if(i==="--wave-gate"){if(t.waveGate=e[++n],!t.waveGate||t.waveGate.startsWith("-"))throw new Error("--wave-gate needs a gate name: --wave-gate <name>")}else if(i==="--wave"){let r=e[++n],o=Number(r);if(!Number.isInteger(o)||o<1)throw new Error(`--wave needs a wave number from 1: got "${r??""}"`);t.wave=o}else if(i==="--decide")t.decide=!0;else if(i==="--record-plans")t.recordPlans=!0;else if(i==="--group"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--group needs a job group's name: --group <name>");t.group=r}else if(i==="--share"){let r=e[++n],o=Number(r);if(!Number.isInteger(o)||o<1)throw new Error(`--share needs a share number from 1: got "${r??""}"`);t.share=o}else if(i==="--canary"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--canary needs a component name: --canary <name>[,<name>...]");(t.canary??=[]).push(...r.split(",").map(o=>o.trim()).filter(Boolean))}else if(i==="--pr"){let r=e[++n],o=Number(r);if(!Number.isInteger(o)||o<1)throw new Error(`--pr needs a pull or merge request number: got "${r??""}"`);t.pr=o}else if(i==="--forge"){if(t.forge=e[++n],!t.forge||t.forge.startsWith("-"))throw new Error("--forge needs a forge: --forge github|gitlab|forgejo")}else if(i==="--require-review")t.requireReview=!0;else if(i==="--report-url"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--report-url needs a URL: --report-url s3://<bucket>/<prefix> or file://<directory>");t.reportUrl=r}else if(i==="--no-status")t.noStatus=!0;else if(i==="--status-url"){if(t.statusUrl=e[++n],!t.statusUrl||t.statusUrl.startsWith("-"))throw new Error("--status-url needs a URL template: --status-url https://host/reports/{key}")}else if(i==="--allow-unsigned")t.allowUnsigned=!0;else if(i==="--require-provenance")t.requireProvenance=!0;else if(i==="--pr-loop")t.prLoop=!0;else if(i==="--apply-on-merge")t.applyOnMerge=!0;else if(i==="--pr-build")t.prBuild=!0;else if(i==="--build-command"){let r=e[++n];if(r===void 0||r==="")throw new Error("--build-command needs a shell line: --build-command '<line>'");t.ciBuildCommand=r}else if(i==="--pr-build-command"){let r=e[++n];if(r===void 0||r==="")throw new Error("--pr-build-command needs a shell line: --pr-build-command '<line>'");t.prBuildCommand=r}else if(i==="--before-script"){let r=e[++n];if(r===void 0||r==="")throw new Error("--before-script needs a shell line: --before-script '<line>'");(t.beforeScript??=[]).push(r)}else if(i==="--resume"){let r=e[n+1];r===void 0||r.startsWith("-")?t.resumeRun=!0:t.resume=e[++n]}else if(i==="--local")t.local=!0;else if(i==="--json")t.json=!0;else if(i==="--progress-json")t.progressJson=!0;else if(i==="--events-json")t.eventsJson=!0;else if(i==="--follow")t.follow=!0;else if(i==="--gated-exit")t.gatedExit=Number(e[++n]);else if(i==="--durable-requests")t.durableRequests=!0;else if(i==="--update-snapshot")t.updateSnapshot=!0;else if(i==="--update-baseline")t.updateBaseline=!0;else if(i==="--deep")t.deep=!0;else if(i==="--at")t.at=e[++n];else if(i==="--kind"){if(t.kind=e[++n],!t.kind||t.kind.startsWith("-"))throw new Error("--kind needs a kind file: --kind <path>");(t.kinds??=[]).push(t.kind)}else if(i==="--composites")t.composites=!0;else if(i==="--intent"){let r=e[n+1];if(r!==void 0&&!r.startsWith("-"))t.intent=e[++n];else if(e.includes("--record"))t.intent="";else throw new Error("--intent needs a region: --intent <path[:start-end]|path#symbol|member/node|sha>, or --intent --record <id>")}else if(i==="--follow-squash")t.followSquash=!0;else if(i==="--record"){if(t.record=e[++n],!t.record||t.record.startsWith("-"))throw new Error("--record needs a record id: --record <id>")}else if(i==="--path"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--path needs a path: --path <path>");(t.paths??=[]).push(r)}else if(i==="--worktree")t.worktree=!0;else if(i==="--max-bytes"){let r=Number(e[++n]);if(!Number.isInteger(r)||r<1)throw new Error("--max-bytes needs a whole number of bytes above 0");t.maxBytes=r}else if(i==="--changes"){if(t.changes=e[++n],!t.changes||t.changes.startsWith("-"))throw new Error("--changes needs a range: --changes <base>..<head>")}else if(i==="--severity"){if(t.severity=e[++n],!t.severity||t.severity.startsWith("-"))throw new Error("--severity needs off, warn or fail")}else if(i==="--current")t.current=!0;else if(i==="--uncommitted")t.uncommitted=!0;else if(i==="--set"){if(t.set=e[++n],!t.set||t.set.startsWith("-")&&t.set!=="-")throw new Error("--set needs a JSON file, or - for standard input: --set <file|->")}else if(i==="--cover"){if(t.cover=e[++n],!t.cover||t.cover.startsWith("-"))throw new Error("--cover needs a PNG, JPEG or WebP file: --cover <image>")}else if(i==="--cover-path"){if(t.coverPath=e[++n],!t.coverPath||t.coverPath.startsWith("-"))throw new Error("--cover-path needs a path from the workspace root: --cover-path <path>")}else if(i==="--records")t.records=!0;else if(i==="--expect"){if(t.expect=e[++n],!t.expect||t.expect.startsWith("-"))throw new Error("--expect needs the record's digest, as records --json prints it: --expect <digest>")}else if(i==="--label"){if(t.label=e[++n],!t.label||t.label.startsWith("-"))throw new Error("--label needs the snapshot's name, such as a turn id: --label <text>")}else if(i==="--branch"){if(t.branch=e[++n],!t.branch||t.branch.startsWith("-"))throw new Error("--branch needs a branch name: --branch <branch>")}else if(i==="--workflow"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--workflow needs a workflow's name: --workflow <name>");t.ciWorkflows=[...t.ciWorkflows??[],r]}else if(i==="--chant"){if(t.ciChant=e[++n],!t.ciChant||t.ciChant.startsWith("-"))throw new Error('--chant needs the command that runs chant, such as "npx tsx packages/core/src/cli/main.ts": --chant <command>')}else if(i==="--commit"){if(t.commit=e[++n],!t.commit||t.commit.startsWith("-"))throw new Error("--commit needs the commit the job runs at: --commit <sha>")}else if(i==="--pass-env"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--pass-env needs a variable's name, such as AWS_PROFILE: --pass-env <NAME>");(t.passEnv??=[]).push(r)}else if(i==="--secrets"){if(t.ciSecrets=e[++n],!t.ciSecrets||t.ciSecrets.startsWith("-"))throw new Error("--secrets needs the host's secrets file, a dotenv or JSON file only its owner can read: --secrets <file>")}else if(i==="--repo"){if(t.ciRepo=e[++n],!t.ciRepo||!/^[^/\s-][^/\s]*\/[^/\s]+$/.test(t.ciRepo))throw new Error("--repo needs the repository as owner/name: --repo <owner/repo>")}else if(i==="--run-index-limit"){let r=Number(e[++n]);if(!Number.isInteger(r)||r<1)throw new Error("--run-index-limit needs a whole number of runs, 1 or more: --run-index-limit <n>");t.runIndexLimit=r}else if(i==="--max-jobs"){let r=Number(e[++n]);if(!Number.isInteger(r)||r<1)throw new Error("--max-jobs needs a whole number of jobs, 1 or more: --max-jobs <n>");t.maxJobs=r}else if(i==="--author"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--author needs a forge login: --author <login>");(t.ciAuthors??=[]).push(r)}else if(i==="--rerun-failed")t.rerunFailed=!0;else if(i==="--install"){if(t.ciInstall=e[++n],!t.ciInstall||t.ciInstall.startsWith("-"))throw new Error('--install needs the install command, such as "npm install": --install <command>')}else if(i==="--token-secret"){if(t.ciTokenSecret=e[++n],!t.ciTokenSecret||t.ciTokenSecret.startsWith("-"))throw new Error("--token-secret needs a repository secret's name, such as CI_GREEN_TOKEN: --token-secret <NAME>")}else if(i==="--app-id-var"){if(t.ciAppIdVar=e[++n],!t.ciAppIdVar||t.ciAppIdVar.startsWith("-"))throw new Error("--app-id-var needs the Actions variable holding the App's id: --app-id-var <VAR>")}else if(i==="--app-key-secret"){if(t.ciAppKeySecret=e[++n],!t.ciAppKeySecret||t.ciAppKeySecret.startsWith("-"))throw new Error("--app-key-secret needs the secret holding the App's private key: --app-key-secret <NAME>")}else if(i==="--runner-key-secret"){if(t.ciRunnerKeySecret=e[++n],!t.ciRunnerKeySecret||t.ciRunnerKeySecret.startsWith("-"))throw new Error("--runner-key-secret needs the repository secret holding the runner key, such as CHANT_RUNNER_KEY: --runner-key-secret <NAME>")}else if(i==="--verdict"){if(t.verdict=e[++n],!t.verdict||t.verdict.startsWith("-"))throw new Error("--verdict needs agree, dissent or abstain")}else if(i==="--class"){if(t.runnerClass=e[++n],!t.runnerClass||t.runnerClass.startsWith("-"))throw new Error("--class needs runner or service: --class <class>")}else if(i==="--by"){if(t.by=e[++n],!t.by||t.by.startsWith("-"))throw new Error("--by needs the reviewer: --by <principal>");(t.bys??=[]).push(t.by)}else if(i==="--open")t.open=!0;else if(i==="--inputs"){if(t.inputs=e[++n],!t.inputs||t.inputs.startsWith("-")&&t.inputs!=="-")throw new Error("--inputs needs a JSON file, - for standard input, or the JSON itself: --inputs <file|-|json>")}else if(i==="--candidates"){if(t.candidates=e[++n],!t.candidates||t.candidates.startsWith("-")&&t.candidates!=="-")throw new Error("--candidates needs a JSON file, - for standard input, or the JSON itself: --candidates <file|-|json>")}else if(i==="--response"){if(t.response=e[++n],!t.response||t.response.startsWith("-"))throw new Error("--response needs a JSON file: --response <file>")}else if(i==="--subject"){if(t.subject=e[++n],!t.subject||t.subject.startsWith("-"))throw new Error("--subject needs what the question is about, such as a work item id: --subject <id>")}else if(i==="--store"){let r=e[++n];if(r!=="tree"&&r!=="ledger")throw new Error("--store is tree (the answer kind's directory in the working tree) or ledger (chant/lifecycle): --store <tree|ledger>");t.store=r}else if(i==="--answer"){if(t.answer=e[++n],t.answer===void 0||t.answer==="")throw new Error("--answer needs one of the question's candidates: --answer <value>")}else if(i==="--sign"){let r=e[n+1];t.sign=r!==void 0&&!r.startsWith("-")?e[++n]:!0}else if(i==="--session"){if(t.session=e[++n],!t.session||t.session.startsWith("-"))throw new Error("--session needs a session id: --session <id>")}else if(i==="--prefix"){if(t.prefix=e[++n],!t.prefix||t.prefix.startsWith("-"))throw new Error("--prefix needs an id prefix: --prefix <prefix>")}else if(i==="--key"||i==="--check-id"||i==="--claim"||i==="--environment"||i==="--envelope"||i==="--threshold"){let r=e[++n];if(r===void 0||r.startsWith("-"))throw new Error(`${i} needs a value`);let o={"--key":"key","--check-id":"checkId","--claim":"claim","--environment":"environment","--envelope":"envelope","--threshold":"threshold"}[i];t[o]=r}else if(i==="--require"){if(t.require=e[++n],!t.require||t.require.startsWith("-"))throw new Error("--require needs a provenance level: --require attested")}else if(i==="--ambient")t.ambient=!0;else if(i==="--check-live")t.checkLive=!0;else if(i==="--check-snapshot")t.checkSnapshot=!0;else if(i==="--fail-on-drift")t.failOnDrift=!0;else if(i==="--run-examples")t.runExamples=!0;else if(i==="--pinned-digest")t.pinnedDigest=e[++n];else if(i==="--check")t.check=!0;else if(i==="--bump")t.bump=!0;else if(i==="--component")t.component=e[++n];else if(i==="--digest")t.digest=e[++n],t.digest!==void 0&&(t.digests??=[]).push(t.digest);else if(i==="--release-plan")t.releasePlanFile=e[++n];else if(i==="--release"){if(t.release=e[++n],!t.release||t.release.startsWith("-"))throw new Error("--release needs a release's label or digest: --release <label|digest>")}else if(i==="--build"){if(t.buildCommand=e[++n],!t.buildCommand)throw new Error("--build needs a shell command: --build '<command>'")}else if(i==="--artifacts")t.artifacts=!0;else if(i==="--git-sha")t.gitSha=e[++n];else if(i==="--run-id")t.runId=e[++n];else if(i==="--actor")t.actor=e[++n];else if(i==="--approver")t.approver=e[++n];else if(i==="--relayed-by"){if(t.relayedBy=e[++n],!t.relayedBy||t.relayedBy.startsWith("-"))throw new Error("--relayed-by needs the principal that relayed it: --relayed-by <principal>")}else if(i==="--on"){if(t.on=e[++n],!t.on||t.on.startsWith("-"))throw new Error("--on needs a runtime name: --on <lexicon>")}else if(i==="--compare-to")t.compareTo=e[++n];else if(i==="--no-release-record")t.noReleaseRecord=!0;else if(i==="--no-record")t.noRecord=!0;else if(i==="--fold")t.fold=!0;else if(i==="--no-cache")t.noCache=!0;else if(i==="--no-fold")t.fold=!1;else if(i==="--sandbox")t.sandbox=!0;else if(i==="--fold-rank"){let r=e[n+1];r&&!r.startsWith("-")?(t.foldRankCollapsedFile=r,n++):t.foldRank=!0}else if(i==="--param")(t.param??=[]).push(e[++n]);else if(i==="--lexicon-output")(t.lexiconOutput??=[]).push(e[++n]);else if(i==="--params-file")t.paramsFile=e[++n];else if(i==="--projection")t.projection=e[++n];else if(i==="--interval")t.interval=e[++n];else if(i==="--lease-ttl")t.leaseTtl=e[++n];else if(i==="--steward"){let r=e[n+1];r!==void 0&&!r.startsWith("-")?(t.steward=r,n++):t.steward=""}else if(i==="--once")t.once=!0;else if(i==="--setup-key")t.setupKey=!0;else if(i==="--trust")t.trustKey=!0;else if(i==="--in-place")t.ciInPlace=!0;else if(i==="--require-runner-start")t.requireRunnerStart=!0;else if(i==="--job"){if(t.ciJob=e[++n],!t.ciJob||t.ciJob.startsWith("-"))throw new Error("--job needs the job as JSON or @<file>: --job @job.json")}else if(i==="--no-push")t.noPush=!0;else if(i==="--no-require-review")t.requireReview=!1;else if(i==="--unsigned")t.unsigned=!0;else if(i==="--principal"){if(t.ciPrincipal=e[++n],!t.ciPrincipal||t.ciPrincipal.startsWith("-"))throw new Error("--principal needs the runner's principal: --principal <name>")}else if(i==="--work"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--work needs a work item id: --work <id>");t.work=r}else if(i==="--holder"||i==="--ttl"||i==="--token"||i==="--outcome"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error(`${i} needs a value: ${i} <${i.slice(2)}>`);t[i.slice(2)]=r}else if(i==="--signer"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--signer needs a principal: --signer <principal>");t.signer=r}else if(i==="--unit"||i==="--decision"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error(`${i} needs an id: ${i} <id>`);t[i.slice(2)]=r}else if(i==="--note")t.note=e[++n];else if(i==="--reason"){if(t.reason=e[++n],t.reason===void 0||t.reason.startsWith("-"))throw new Error("--reason needs the text of the reason: --reason <text>")}else if(i==="--rule"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--rule needs a rule id: --rule <id>");(t.rules??=[]).push(r)}else if(i==="--expire")t.expire=!0;else if(i==="--role"){let r=e[++n]??"";t.roles=[...t.roles??[],...r.split(",").map(o=>o.trim()).filter(Boolean)]}else if(i==="--agent")t.agent=!0;else if(i==="--allow-code")t.allowCode=!0;else if(i==="--allow-skip")t.allowSkip=!0;else if(i==="--source"){if(t.source=e[++n],!t.source||t.source.startsWith("-"))throw new Error("--source needs a template: --source <repo>[#<member>] for workspace upgrade, or a source for ci tick and ci list: --source checks|runs")}else if(i==="--tags"){if(t.tags=e[++n],!t.tags||t.tags.startsWith("-"))throw new Error("--tags needs a tag glob: --tags 'v*'")}else if(i==="--index"){if(t.index=e[++n],!t.index||t.index.startsWith("-"))throw new Error("--index needs a hash index file: --index <file>")}else if(i==="--remove")t.remove=!0;else if(i==="--available")t.available=!0;else if(i==="--root-only")t.rootOnly=!0;else if(i==="--generated")t.generated=!0;else if(i==="--member"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--member needs a member or group name: --member <name>");t.members=[...t.members??[],...r.split(",").map(o=>o.trim()).filter(Boolean)]}else if(i==="--allow-same-origin")t.allowSameOrigin=!0;else if(i==="--plan")t.plan=e[++n];else if(i==="--url")t.url=e[++n];else if(i==="--op")t.op=e[++n];else if(i==="--since")t.since=e[++n];else if(i==="--limit")t.limit=Number(e[++n]);else{if(i.startsWith("--"))throw new Error(`Unknown flag: ${i}
351
+ `))return console.error(we({message:`${t} was denied by ${a.rules.join(", ")||"no rule it named"}; an override names exactly those rules, and --rule gave ${r.join(", ")}`,hint:xx(t,a.rules)})),1;if(e.args.plan!==void 0&&!mt(e.args.plan,a.plan)&&!mt(e.args.plan,a.planDigest))return console.error(we({message:`--plan ${e.args.plan} is not the plan denied for ${t}: the newest denial is of ${a.plan||a.planDigest}`,hint:"Run the plan again, or override the denial that stands."})),1;let c=await eW(Zn,t,{actor:e.args.approver??e.args.actor,note:i,url:e.args.url,plan:a.planDigest,allowSameOrigin:e.args.allowSameOrigin,...e.args.roles?{roles:e.args.roles}:{},...e.args.sign!==void 0?{sign:e.args.sign}:{},...e.args.relayedBy!==void 0?{relayedBy:e.args.relayedBy}:{}});if(!c.ok)return 1;if(console.error(Qn(`This overrides the denial of ${t} by ${r.join(", ")} for the plan ${a.plan||a.planDigest}. The next run that plans it applies it once; a plan that moves, or rules that change, need their own override.`)),process.env.CHANT_OVERRIDERS_FROM?.trim())return 0;let u=Cj(process.cwd(),"HEAD");return u.active?u.principals.map(Tie).includes(Tie(c.record.resolvedBy))||console.error(si({message:`${c.record.resolvedBy} is not in ${Rp} here (${u.principals.join(", ")||"nobody"}), so a run that reads it at base does not count this override`})):console.error(si({message:`This checkout has no ${Rp}: unless the run reads its overriders from elsewhere at base, no override counts (a tool that does sets CHANT_OVERRIDERS_FROM to say so)`})),0}var Tie,Die=v(()=>{"use strict";el();Pt();_ie();Dn();Zg();ur();tW();Tie=e=>e.normalize("NFKC").trim().toLowerCase()});async function jie(e){let{pushed:t,pushWarning:n}=await Ia();return t?{pushed:t,suffix:""}:cg(n)?{pushed:t,suffix:` (${jd})`}:(console.error(si({message:`The push to the remote did not land: ${n??"no reason given"}`,hint:e})),{pushed:t,suffix:" (local only \u2014 the push did not land)"})}async function Nie(e){let t=e.args.path,n=e.args.extraPositional;if(!t||t==="."||!n)return console.error(we({message:"Usage: chant approve <op> <gate>"})),1;if(e.args.expire){try{await Lr()}catch(a){return console.error(we({message:`Cannot expire the gate: ${a instanceof Error?a.message:String(a)}`})),1}let r=new Date().toISOString(),o=yn((await Kn(t)).pending,n);if(!o||On(o,r))return console.error(si({message:`Gate "${n}" on "${t}" has no standing pending fact \u2014 nothing to expire`})),0;await zd({op:t,gate:n,timestamp:r,expiresAt:r,...o.description?{description:o.description}:{},...o.runId?{runId:o.runId}:{},...o.gitSha?{gitSha:o.gitSha}:{}});let s=await jie(`The expiry is recorded locally on ${uw}. Until it reaches the remote, a run in another checkout still sees the old pending fact.`);return console.error(xf(`Gate "${n}" on "${t}" expired at ${r} \u2014 not approved`+s.suffix)),console.error(Qn(t===id?"The next `chant components fan-out` decides this gate from scratch and records a fresh pending fact.":QG.test(t)?"The next `chant components pr-apply` decides this gate from scratch and records a fresh pending fact.":t===od?`The next \`chant workspace upgrade ${n}\` decides this gate from scratch and records a fresh pending fact.`:t===ui?"The next `chant components promote --release` decides this gate from scratch and records a fresh pending fact.":`The next \`chant run ${t}\` decides this gate from scratch and records a fresh pending fact.`)),0}if(t===pa){let{runOverrideApprove:r}=await Promise.resolve().then(()=>(Die(),Iie));return r(e)}if(e.args.rules!==void 0||e.args.reason!==void 0)return console.error(we({message:`--rule and --reason override a denied plan: chant approve ${pa} <subject> --rule <id> --reason <text>`,hint:`To approve gate "${n}" on "${t}", put any prose in --note.`})),1;let i=await eW(t,n,{actor:e.args.approver??e.args.actor,note:e.args.note,url:e.args.url,plan:e.args.plan,...e.args.env!==void 0?{environment:e.args.env}:{},allowSameOrigin:e.args.allowSameOrigin,...e.args.roles?{roles:e.args.roles}:{},...e.args.agent?{agent:!0}:{},...e.args.sign!==void 0?{sign:e.args.sign}:{},...e.args.relayedBy!==void 0?{relayedBy:e.args.relayedBy}:{}});if(!i.ok)return 1;if(e.args.resumeRun||e.args.resume!==void 0){let{resumeAfterApproval:r}=await Promise.resolve().then(()=>(CS(),jG));return r(t,n,i.record.environment,i.pushed)}return console.error(Qn("This records the resolution as a fact; it does not itself re-run anything. "+(t===id?`Repeat the \`chant components fan-out\` command and it walks through gate "${n}".`:QG.test(t)?`The pull request's apply (\`chant components pr-apply\`) walks through gate "${n}" when it plans this same digest.`:t===od?`Repeat \`chant workspace upgrade ${n}\` with the same target, and it applies the patch this approval names.`:t===ui?`Repeat the same \`chant components promote --release\`, and it walks through gate "${n}" when it plans this same change set for this release.`:`Run \`chant run ${t}\` and it walks through gate "${n}".`))),0}async function BLe(e,t,n,i){let{readRelease:r,readCuts:o,labelsByDigest:s}=await Promise.resolve().then(()=>(cu(),wy)),{readRevokedCommits:a,revocationOf:c,revokedRefusal:l}=await Promise.resolve().then(()=>(rS(),AF)),u=await r(n,{cwd:i}).catch(()=>null);if(!u)return console.error(we({message:`Gate "${t}" on "${e}" binds release ${n}, which can't be read from ${uw}, so whether it is revoked is unknown [release-unreadable]`,hint:`Fetch the ledger branch (git fetch origin ${uw}:${uw}) and approve again from the member's directory.`})),!0;let d;try{d=await a(i)}catch(g){return console.error(we({message:`Gate "${t}" on "${e}" binds release ${n}, and the ci tags can't be judged: ${g instanceof Error?g.message:String(g)} [declaration-invalid]`,hint:"Fix ci.green in chant.workspace.json at base; chant workspace check names the problem."})),!0}let p=c(u,d);if(!p)return!1;let f=s((await o({cwd:i}).catch(()=>({cuts:[]}))).cuts).get(n)??null;return console.error(we(l({releaseDigest:n,label:f},p,`Clear the pending gate with \`chant approve ${e} ${t} --expire\`, then promote a release cut from a green commit: \`chant ci last-green\` names the newest, and \`chant release list\` marks the revoked releases.`))),!0}async function eW(e,t,n){if(Ki())return console.error(we({message:`Cannot record the approval of "${t}": ${vk} is set, so nothing is written to chant/lifecycle`,hint:`Unset ${vk} to approve the gate.`})),{ok:!1};let{ops:i}=await ic(),r=lQ([...i.values()].map(T=>T.config),e,t);!r&&!i.has(e)&&e!==id&&e!==od&&e!==pa&&e!==ui&&console.error(si({message:`Op "${e}" was not found among discovered *.op.ts declarations \u2014 recording the resolution anyway`}));try{await Lr()}catch(T){return console.error(we({message:`Cannot record the approval: ${T instanceof Error?T.message:String(T)}`,hint:"The pending fact this answers lives on that branch; appending without it would drop it."})),{ok:!1}}if(r){let T=yn((await Kn(r.op)).pending,r.gate);if(T&&!On(T,new Date().toISOString()))return console.error(we({message:`Gate "${t}" on "${e}" is now gate "${r.gate}" on "${r.op}", which lists it as an alias, and "${r.gate}" has a standing pending fact`,hint:`Approve that gate instead: chant approve ${r.op} ${r.gate}`})),{ok:!1};console.error(Qn(`Gate "${t}" on "${e}" is an alias of gate "${r.gate}" on "${r.op}": the next run of ${r.op} counts this approval there while the pending fact it answers stands and the plan is the same.`))}let o=n.url??ja();if(o&&!Ek(o))return console.error(we({message:`--url must be an absolute http/https URL (got "${o}")`,hint:"Pass the PR/MR link, or omit --url and put prose in --note."})),{ok:!1};let s=await Kn(e),a=T=>T.some(ke=>ke.gate===t&&ke.environment!==void 0)&&n.environment!==void 0?T.filter(ke=>ke.environment===n.environment):T,c=yn(a(s.pending),t),l=c?.environment,u;if(n.plan!==void 0){if(!zI(n.plan))return console.error(we({message:`--plan must be a plan digest ("jcs1-sha256:" or "sha256:", then 64 hex characters), got "${n.plan}"`,hint:"Copy it from the gated run's `plan :` line, or from the pending-gate summary. It is not a plan file path."})),{ok:!1};u=n.plan}else{if(!c)return console.error(we({message:n.environment!==void 0&&s.pending.some(T=>T.gate===t&&T.environment!==void 0)?`Gate "${t}" on "${e}" has no pending fact in environment "${n.environment}", so there is no plan to approve`:`Gate "${t}" on "${e}" has no pending fact, so there is no plan to approve`,hint:`Run \`chant run ${e}\` first \u2014 it plans, stops at the gate, and records the plan this approval would be for. To approve a plan you already have the digest for, pass \`--plan <digest>\`.`})),{ok:!1};u=c.planDigest}let d=c?.checkpointDigest!==void 0&&mt(u,c.planDigest)?c.checkpointDigest:void 0,p=c?.releaseDigest!==void 0&&mt(u,c.planDigest)?c.releaseDigest:void 0;if(c?.releaseDigest!==void 0&&await BLe(e,t,c.releaseDigest,n.cwd??process.cwd()))return{ok:!1};let f=n.origin??bs(),g=await Kn(e),h=yn(a(g.pending),t);if(di(f)&&(h?.neverOverMcp||i.get(e)?.config.neverOverMcp))return console.error(we({message:`Gate "${t}" on "${e}" is never resolved over ${f==="acp"?"ACP":"MCP"}`,hint:`Approvals belong to people: \`chant approve ${e} ${t}\` at a shell.`})),{ok:!1};if(h?.answer)return console.error(we({message:`Gate "${t}" on "${e}" asks decision point ${h.answer.point}, so its answer passes the gate, not an approval`,hint:`Answer the question: \`chant workspace points answer ${h.answer.id} --answer <value> --by <name>\`, then run \`chant run ${e}\` again.`})),{ok:!1};let w=DV(h?.origin,f);if(w&&!n.allowSameOrigin)return console.error(we({message:`Gate "${t}" on "${e}" cannot be resolved from here: ${w}`,hint:`Approve it from a channel the run did not come from \u2014 \`chant approve ${e} ${t}\` at a shell is the usual one. If resolving from the same channel genuinely is the intent, pass --allow-same-origin, which records that it was deliberate.`})),{ok:!1};let b=n.relayedBy?.trim();if(n.relayedBy!==void 0&&(!b||/[\r\n]/.test(b)))return console.error(we({message:`--relayed-by needs one principal on one line (got ${JSON.stringify(n.relayedBy)})`,hint:"Name who relayed the approval, such as --relayed-by github:<login> or a principal the signers file lists."})),{ok:!1};let k=n.actor??(di(f)?kv:process.env.GITHUB_ACTOR??process.env.GITLAB_USER_LOGIN??process.env.USER??"unknown"),$={kind:n.agent||di(f)?"agent":"human",...n.roles&&n.roles.length>0?{roles:[...new Set(n.roles)]}:{}},x=n.cwd??process.cwd(),R=await Promise.resolve().then(()=>(Tl(),aj)),{scopeSource:P}=await Promise.resolve().then(()=>(Bo(),oj)),I=P(x);try{R.refuseUnidentified(I,[k],n.actor!==void 0?"--actor":"the approver"),b&&R.refuseUnidentified(I,[b],"--relayed-by")}catch(T){if(!(T instanceof R.IdentityError))throw T;return console.error(we({message:`Gate "${t}" on "${e}" was not approved: ${T.message}`,hint:"Pass --actor <forge identity or signer>, as the surface that signed the person in maps them, for example --actor github:<login>."})),{ok:!1}}let A=R.gateAdmissionFrom(I,t);if(A&&n.sign===void 0)return console.error(we({message:`Gate "${t}" needs a signed approval: chant.workspace.json at base names it in identity.gates`+(A.requirement.class!==null?`, from the class ${A.requirement.class}`:"")+", and this approval is not signed",hint:`chant approve ${e} ${t} --actor <principal> --sign [<key file>], with a key ${I.policy.signersPath} at base lists for that principal.`})),{ok:!1};let B=new Date().toISOString(),C;if(n.sign!==void 0){let{resolveSigningKey:T,sealGateApproval:W,gateSealVersion:ke,SealError:re}=await Promise.resolve().then(()=>(Op(),Ep));try{let be=T(n.sign,x);try{let Be={op:e,gate:t,...l!==void 0?{environment:l}:{},...u!==void 0?{planDigest:u}:{},resolvedBy:k,...b?{relayedBy:b}:{},timestamp:B,...d!==void 0?{checkpointDigest:d}:{}};C={...W(be.file,Be),...ke(Be)===2?{version:2}:{}}}finally{be.cleanup()}}catch(be){if(!(be instanceof re))throw be;return console.error(we({message:`Gate "${t}" on "${e}" was not approved: ${be.message}`})),{ok:!1}}}if(A){let T=A.refuses({op:e,gate:t,...l!==void 0?{environment:l}:{},...u!==void 0?{planDigest:u}:{},resolvedBy:k,...b?{relayedBy:b}:{},timestamp:B,...d!==void 0?{checkpointDigest:d}:{},seal:C});if(T!==null)return console.error(we({message:`Gate "${t}" on "${e}" was not approved: ${T}`,hint:`identity.gates.${t} in chant.workspace.json at base counts only an approval signed by a key ${I.policy.signersPath} lists for the approver`+(A.requirement.class!==null?`, who holds the role of the class ${A.requirement.class}`:"")+"."})),{ok:!1}}let q=h?.approval,L;if(q?.policy)try{let W=await(n.evaluator??await VI(q.policy.lexicon)).evaluateGatePolicy(q.policy,HI({op:e,gate:t,resolvedBy:k,approver:$,...u!==void 0?{planDigest:u}:{},...q.context?{context:q.context}:{}}));L={policy:q.policy.name,version:q.policy.version,mode:q.mode,contextDigest:bg(q.context),decision:W.decision,determining:W.determining,errors:W.errors}}catch(T){return console.error(we({message:`Gate "${t}" on "${e}" declares policy "${q.policy.name}", which could not be evaluated: ${T instanceof Error?T.message:String(T)}`,hint:`Install the ${q.policy.lexicon} lexicon in this project, or approve from a checkout that has it.`})),{ok:!1}}let{record:M}=await yg({op:e,gate:t,resolvedBy:k,...b?{relayedBy:b}:{},timestamp:B,...C?{seal:C}:{},approver:$,...L?{policyDecision:L}:{},...n.note?{note:n.note}:{},...o?{url:o}:{},...u!==void 0?{planDigest:u}:{},...d!==void 0?{checkpointDigest:d}:{},...l!==void 0?{environment:l}:{},...p!==void 0?{releaseDigest:p}:{},...c?.gitSha?{gitSha:c.gitSha}:{},...c?.runId?{runId:c.runId}:{},origin:f,...w&&n.allowSameOrigin?{sameOriginOverride:!0}:{}}),_=await jie(`The resolution is recorded locally on ${uw}. Until it reaches the remote, a run in another checkout will not see it.`);if(console.error(xf(`Gate "${t}" on "${e}" resolved by ${M.resolvedBy}`+(M.relayedBy?`, relayed by ${M.relayedBy},`:"")+` at ${M.timestamp}`+(M.url?` (${M.url})`:"")+(M.seal?`, signed with ${M.seal.key}`:"")+_.suffix)),M.planDigest&&console.error(Qn(`This approves the plan ${M.planDigest}`+(M.environment!==void 0?` in environment "${M.environment}"`:"")+(M.releaseDigest!==void 0?` for release ${M.releaseDigest}`:"")+", and only that plan. A run whose fresh plan differs refuses rather than applying it.")),M.checkpointDigest&&console.error(Qn(`The next run resumes at this gate from run ${c?.runId??"(unknown)"}'s checkpoint ${M.checkpointDigest}, after it plans again. A moved plan or another commit starts it at the first phase.`)),q)for(let T of zLe(q,M,g.resolutions,h,g.pending))console.error(Qn(T));return{ok:!0,record:M,pushed:_.pushed}}function zLe(e,t,n,i,r=i?[i]:[]){let o=[],s=t.policyDecision;if(s){let p=s.determining.length>0?` (${s.determining.join(", ")})`:"",f=e.mode==="enforce"?s.decision==="allow"?"In enforce mode this permit passes the gate on its own.":"In enforce mode only a permit passes the gate on its own, so this approval counts only toward the quorum.":"The gate is in log-only mode, so the decision is recorded and does not change the outcome.";o.push(`Policy "${s.policy}" ${s.version}: ${s.decision}${p}. ${f}`);for(let g of s.errors)o.push(`Policy evaluation error: ${g}`)}let a=i?.timestamp??new Date(0).toISOString(),c=i&&mt(i.planDigest,t.planDigest)?Qa(r,i):a,l=Ya([...n,t],t.gate,a,t.planDigest,e,c),u=e.quorum?.roles?` with role ${e.quorum.roles.join(" or ")}`:"",d=l.counted.map(p=>p.resolvedBy).join(", ")||"none yet";return o.push(`Quorum: ${l.counted.length} of ${l.need} human approval(s)${u} for this plan (${d}).`),l.counted.includes(t)||o.push(hp(t).kind==="agent"?"An agent's approval does not count toward the quorum.":`This approval does not count toward the quorum: the approver claims none of its roles (${e.quorum?.roles?.join(", ")}).`),o}var uw,tW=v(()=>{"use strict";qo();TR();el();Mr();Dn();vg();Uo();Yr();Pie();Pt();lg();Nd();ur();uw="chant/lifecycle"});GS();var zie=new Set(["--help","--open","--version","--agents","--agent","--all-projects","--force","--fix","--watch","--verbose","--live","--overlay","--explain","--owned","--verbatim","--skip-undeclarable","--apply-rewrites","--write","--strict","--validate","--use-composites","--composites","--stacks","--components","--pr-build","--up","--down","--include-dependents","--local","--json","--progress-json","--events-json","--follow","--update-snapshot","--update-baseline","--run-examples","--check","--bump","--no-release-record","--no-record","--fold","--no-fold","--no-cache","--sandbox","--yes","--confirm-prod","--once","--rerun-failed","--setup-key","--trust","--unsigned","--in-place","--require-runner-start","--no-push","--no-require-review","--expire","--check-live","--check-snapshot","--fail-on-drift","--durable-requests","--skip-mcp","--current","--uncommitted","--allow-code","--allow-skip","--allow-unsigned","--require-provenance","--root-only","--generated","--decide","--record-plans","--loopback","--artifacts","--push"]);function rW(e){e=e.slice();let t={command:"",path:".",extraPositional:void 0,extraPositional2:void 0,output:void 0,format:"",force:void 0,fix:!1,lexicon:void 0,template:void 0,watch:!1,verbose:!1,help:!1,param:void 0,paramsFile:void 0,report:void 0,local:void 0,profile:void 0,json:void 0,live:!1,migrateFrom:void 0,migrateTo:void 0,emit:void 0,strict:!1,validate:!1,useComposites:!1,reportFile:void 0,skill:void 0,skipMcp:void 0,src:void 0,env:void 0};e=nW(e,zie);let n=0;for(;n<e.length;){let i=e[n];if(i==="--help"||i==="-h")t.help=!0;else if(i==="--version"||i==="-V")t.version=!0;else if(i==="--output"||i==="-o")t.output=e[++n];else if(i==="--format"||i==="-f")t.format=e[++n];else if(i==="--lexicon"||i==="-d")t.lexicon=e[++n];else if(i==="--template"||i==="-t")t.template=e[++n];else if(i==="--force")t.force=!0;else if(i==="--fix")t.fix=!0;else if(i==="--watch"||i==="-w")t.watch=!0;else if(i==="--verbose"||i==="-v")t.verbose=!0;else if(i==="--profile"||i==="-p")t.profile=e[++n];else if(i==="--report"){let r=e[n+1];r&&!r.startsWith("-")?(t.reportFile=r,n++):t.report=!0}else if(i==="--live")t.live=!0;else if(i==="--overlay")t.overlay=!0;else if(i==="--between"){if(t.betweenA=e[++n],t.betweenB=e[++n],!t.betweenA||!t.betweenB)throw new Error("--between needs two snapshot refs: --between <refA> <refB>")}else if(i==="--traffic"){let r=e[++n];if(!r)throw new Error('--traffic needs a level, passed to the engine verbatim: --traffic "100 rps, p50"');t.traffic=r}else if(i==="--overlay-anchor"){let r=e[++n];if(r!=="source"&&r!=="live")throw new Error(`--overlay-anchor must be 'source' or 'live', got '${r}'`);t.overlayAnchor=r}else if(i==="--from")t.migrateFrom=e[++n];else if(i==="--kustomize")t.kustomize=e[++n];else if(i==="--parser-option"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--parser-option needs key or key=value: --parser-option acceptLossyV1");(t.parserOption??=[]).push(r)}else if(i==="--type")t.selectType=e[++n];else if(i==="--name")t.selectName=e[++n];else if(i==="--owned")t.owned=!0;else if(i==="--namespace"){if(t.namespace=e[++n],!t.namespace||t.namespace.startsWith("-"))throw new Error("--namespace needs a namespace: --namespace <ns>")}else if(i==="--verbatim")t.verbatim=!0;else if(i==="--skip-undeclarable")t.skipUndeclarable=!0;else if(i==="--state")t.statePath=e[++n];else if(i==="--select")t.selectAddress=e[++n];else if(i==="--live-name")t.liveName=e[++n];else if(i==="--apply-rewrites")t.applyRewrites=!0;else if(i==="--stack")t.carveStack=e[++n];else if(i==="--write")t.write=!0;else if(i==="--write-source")t.writeSource=!0;else if(i==="--to")t.migrateTo=e[++n];else if(i==="--emit")t.emit=e[++n];else if(i==="--dry-run")t.dryRun=!0;else if(i==="--yes")t.yes=!0;else if(i==="--push")t.push=!0;else if(i==="--confirm-prod")t.confirmProd=!0;else if(i==="--strict")t.strict=!0;else if(i==="--validate")t.validate=!0;else if(i==="--use-composites")t.useComposites=!0;else if(i==="--skill")t.skill=e[++n];else if(i==="--skip-mcp")t.skipMcp=!0;else if(i==="--src")t.src=e[++n];else if(i==="--env")t.env=e[++n];else if(i==="--port"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--port needs a port: --port <container-port>=<host-port>");(t.port??=[]).push(r)}else if(i==="--image"){if(t.image=e[++n],!t.image||t.image.startsWith("-"))throw new Error("--image needs an image reference: --image <name>:<tag>")}else if(i==="--network"){if(t.network=e[++n],!t.network||t.network.startsWith("-"))throw new Error("--network needs a Docker network name: --network <name>")}else if(i==="--setting"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--setting needs a value: --setting <KEY>=<VALUE>");(t.setting??=[]).push(r)}else if(i==="--loopback")t.loopback=!0;else if(i==="--promote-to"){if(t.promoteTo=e[++n],!t.promoteTo||t.promoteTo.startsWith("-"))throw new Error("--promote-to needs an environment: --promote-to <env>")}else if(i==="--tier")t.tier=e[++n];else if(i==="--agents")t.agents=!0;else if(i==="--scope")t.scope=e[++n];else if(i==="--all-projects")t.allProjects=!0;else if(i==="--runtime")t.runtime=e[++n];else if(i==="--fail-on")t.failOn=e[++n];else if(i==="--max-files")t.maxFiles=Number(e[++n]);else if(i==="--theme")t.theme=e[++n];else if(i==="--stacks")t.stacks=!0;else if(i==="--components")t.components=!0;else if(i==="--generate")t.generate=e[++n];else if(i==="--spec")t.opsSpec=e[++n];else if(i==="--dump-outputs")t.dumpOutputs=e[++n];else if(i==="--digest-file")t.digestFile=e[++n];else if(i==="--seed-outputs")(t.seedOutputs??=[]).push(e[++n]);else if(i==="--detail")t.detail=Number(e[++n]);else if(i==="--lens")t.lens=e[++n];else if(i==="--explain")t.explain=!0;else if(i==="--show")t.show=e[++n];else if(i==="--up")t.up=!0;else if(i==="--down")t.down=!0;else if(i==="--node-sizes")t.nodeSizes=e[++n];else if(i==="--layout-engine")t.layoutEngine=e[++n];else if(i==="--base")t.base=e[++n];else if(i==="--head")t.head=e[++n];else if(i==="--include-dependents")t.includeDependents=!0;else if(i==="--from-affected")t.fromAffected=e[++n];else if(i==="--gate")t.gate=e[++n];else if(i==="--wave-gate"){if(t.waveGate=e[++n],!t.waveGate||t.waveGate.startsWith("-"))throw new Error("--wave-gate needs a gate name: --wave-gate <name>")}else if(i==="--wave"){let r=e[++n],o=Number(r);if(!Number.isInteger(o)||o<1)throw new Error(`--wave needs a wave number from 1: got "${r??""}"`);t.wave=o}else if(i==="--decide")t.decide=!0;else if(i==="--record-plans")t.recordPlans=!0;else if(i==="--group"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--group needs a job group's name: --group <name>");t.group=r}else if(i==="--share"){let r=e[++n],o=Number(r);if(!Number.isInteger(o)||o<1)throw new Error(`--share needs a share number from 1: got "${r??""}"`);t.share=o}else if(i==="--canary"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--canary needs a component name: --canary <name>[,<name>...]");(t.canary??=[]).push(...r.split(",").map(o=>o.trim()).filter(Boolean))}else if(i==="--pr"){let r=e[++n],o=Number(r);if(!Number.isInteger(o)||o<1)throw new Error(`--pr needs a pull or merge request number: got "${r??""}"`);t.pr=o}else if(i==="--forge"){if(t.forge=e[++n],!t.forge||t.forge.startsWith("-"))throw new Error("--forge needs a forge: --forge github|gitlab|forgejo")}else if(i==="--require-review")t.requireReview=!0;else if(i==="--report-url"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--report-url needs a URL: --report-url s3://<bucket>/<prefix> or file://<directory>");t.reportUrl=r}else if(i==="--no-status")t.noStatus=!0;else if(i==="--status-url"){if(t.statusUrl=e[++n],!t.statusUrl||t.statusUrl.startsWith("-"))throw new Error("--status-url needs a URL template: --status-url https://host/reports/{key}")}else if(i==="--allow-unsigned")t.allowUnsigned=!0;else if(i==="--require-provenance")t.requireProvenance=!0;else if(i==="--pr-loop")t.prLoop=!0;else if(i==="--apply-on-merge")t.applyOnMerge=!0;else if(i==="--pr-build")t.prBuild=!0;else if(i==="--build-command"){let r=e[++n];if(r===void 0||r==="")throw new Error("--build-command needs a shell line: --build-command '<line>'");t.ciBuildCommand=r}else if(i==="--pr-build-command"){let r=e[++n];if(r===void 0||r==="")throw new Error("--pr-build-command needs a shell line: --pr-build-command '<line>'");t.prBuildCommand=r}else if(i==="--before-script"){let r=e[++n];if(r===void 0||r==="")throw new Error("--before-script needs a shell line: --before-script '<line>'");(t.beforeScript??=[]).push(r)}else if(i==="--resume"){let r=e[n+1];r===void 0||r.startsWith("-")?t.resumeRun=!0:t.resume=e[++n]}else if(i==="--local")t.local=!0;else if(i==="--json")t.json=!0;else if(i==="--progress-json")t.progressJson=!0;else if(i==="--events-json")t.eventsJson=!0;else if(i==="--follow")t.follow=!0;else if(i==="--gated-exit")t.gatedExit=Number(e[++n]);else if(i==="--durable-requests")t.durableRequests=!0;else if(i==="--update-snapshot")t.updateSnapshot=!0;else if(i==="--update-baseline")t.updateBaseline=!0;else if(i==="--deep")t.deep=!0;else if(i==="--at")t.at=e[++n];else if(i==="--kind"){if(t.kind=e[++n],!t.kind||t.kind.startsWith("-"))throw new Error("--kind needs a kind file: --kind <path>");(t.kinds??=[]).push(t.kind)}else if(i==="--composites")t.composites=!0;else if(i==="--intent"){let r=e[n+1];if(r!==void 0&&!r.startsWith("-"))t.intent=e[++n];else if(e.includes("--record"))t.intent="";else throw new Error("--intent needs a region: --intent <path[:start-end]|path#symbol|member/node|sha>, or --intent --record <id>")}else if(i==="--follow-squash")t.followSquash=!0;else if(i==="--record"){if(t.record=e[++n],!t.record||t.record.startsWith("-"))throw new Error("--record needs a record id: --record <id>")}else if(i==="--path"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--path needs a path: --path <path>");(t.paths??=[]).push(r)}else if(i==="--worktree")t.worktree=!0;else if(i==="--max-bytes"){let r=Number(e[++n]);if(!Number.isInteger(r)||r<1)throw new Error("--max-bytes needs a whole number of bytes above 0");t.maxBytes=r}else if(i==="--changes"){if(t.changes=e[++n],!t.changes||t.changes.startsWith("-"))throw new Error("--changes needs a range: --changes <base>..<head>")}else if(i==="--severity"){if(t.severity=e[++n],!t.severity||t.severity.startsWith("-"))throw new Error("--severity needs off, warn or fail")}else if(i==="--current")t.current=!0;else if(i==="--uncommitted")t.uncommitted=!0;else if(i==="--set"){if(t.set=e[++n],!t.set||t.set.startsWith("-")&&t.set!=="-")throw new Error("--set needs a JSON file, or - for standard input: --set <file|->")}else if(i==="--cover"){if(t.cover=e[++n],!t.cover||t.cover.startsWith("-"))throw new Error("--cover needs a PNG, JPEG or WebP file: --cover <image>")}else if(i==="--cover-path"){if(t.coverPath=e[++n],!t.coverPath||t.coverPath.startsWith("-"))throw new Error("--cover-path needs a path from the workspace root: --cover-path <path>")}else if(i==="--records")t.records=!0;else if(i==="--expect"){if(t.expect=e[++n],!t.expect||t.expect.startsWith("-"))throw new Error("--expect needs the record's digest, as records --json prints it: --expect <digest>")}else if(i==="--label"){if(t.label=e[++n],!t.label||t.label.startsWith("-"))throw new Error("--label needs the snapshot's name, such as a turn id: --label <text>")}else if(i==="--branch"){if(t.branch=e[++n],!t.branch||t.branch.startsWith("-"))throw new Error("--branch needs a branch name: --branch <branch>")}else if(i==="--security"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--security needs a group: --security verified-releases|supply-chain|who-ran-it|review-rules|isolated-runners");t.securityGroups=[...t.securityGroups??[],r]}else if(i==="--workflow"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--workflow needs a workflow's name: --workflow <name>");t.ciWorkflows=[...t.ciWorkflows??[],r]}else if(i==="--chant"){if(t.ciChant=e[++n],!t.ciChant||t.ciChant.startsWith("-"))throw new Error('--chant needs the command that runs chant, such as "npx tsx packages/core/src/cli/main.ts": --chant <command>')}else if(i==="--commit"){if(t.commit=e[++n],!t.commit||t.commit.startsWith("-"))throw new Error("--commit needs the commit the job runs at: --commit <sha>")}else if(i==="--pass-env"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--pass-env needs a variable's name, such as AWS_PROFILE: --pass-env <NAME>");(t.passEnv??=[]).push(r)}else if(i==="--secrets"){if(t.ciSecrets=e[++n],!t.ciSecrets||t.ciSecrets.startsWith("-"))throw new Error("--secrets needs the host's secrets file, a dotenv or JSON file only its owner can read: --secrets <file>")}else if(i==="--repo"){if(t.ciRepo=e[++n],!t.ciRepo||!/^[^/\s-][^/\s]*\/[^/\s]+$/.test(t.ciRepo))throw new Error("--repo needs the repository as owner/name: --repo <owner/repo>")}else if(i==="--run-index-limit"){let r=Number(e[++n]);if(!Number.isInteger(r)||r<1)throw new Error("--run-index-limit needs a whole number of runs, 1 or more: --run-index-limit <n>");t.runIndexLimit=r}else if(i==="--max-jobs"){let r=Number(e[++n]);if(!Number.isInteger(r)||r<1)throw new Error("--max-jobs needs a whole number of jobs, 1 or more: --max-jobs <n>");t.maxJobs=r}else if(i==="--author"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--author needs a forge login: --author <login>");(t.ciAuthors??=[]).push(r)}else if(i==="--rerun-failed")t.rerunFailed=!0;else if(i==="--install"){if(t.ciInstall=e[++n],!t.ciInstall||t.ciInstall.startsWith("-"))throw new Error('--install needs the install command, such as "npm install": --install <command>')}else if(i==="--token-secret"){if(t.ciTokenSecret=e[++n],!t.ciTokenSecret||t.ciTokenSecret.startsWith("-"))throw new Error("--token-secret needs a repository secret's name, such as CI_GREEN_TOKEN: --token-secret <NAME>")}else if(i==="--app-id-var"){if(t.ciAppIdVar=e[++n],!t.ciAppIdVar||t.ciAppIdVar.startsWith("-"))throw new Error("--app-id-var needs the Actions variable holding the App's id: --app-id-var <VAR>")}else if(i==="--app-key-secret"){if(t.ciAppKeySecret=e[++n],!t.ciAppKeySecret||t.ciAppKeySecret.startsWith("-"))throw new Error("--app-key-secret needs the secret holding the App's private key: --app-key-secret <NAME>")}else if(i==="--runner-key-secret"){if(t.ciRunnerKeySecret=e[++n],!t.ciRunnerKeySecret||t.ciRunnerKeySecret.startsWith("-"))throw new Error("--runner-key-secret needs the repository secret holding the runner key, such as CHANT_RUNNER_KEY: --runner-key-secret <NAME>")}else if(i==="--verdict"){if(t.verdict=e[++n],!t.verdict||t.verdict.startsWith("-"))throw new Error("--verdict needs agree, dissent or abstain")}else if(i==="--class"){if(t.runnerClass=e[++n],!t.runnerClass||t.runnerClass.startsWith("-"))throw new Error("--class needs runner or service: --class <class>")}else if(i==="--by"){if(t.by=e[++n],!t.by||t.by.startsWith("-"))throw new Error("--by needs the reviewer: --by <principal>");(t.bys??=[]).push(t.by)}else if(i==="--open")t.open=!0;else if(i==="--inputs"){if(t.inputs=e[++n],!t.inputs||t.inputs.startsWith("-")&&t.inputs!=="-")throw new Error("--inputs needs a JSON file, - for standard input, or the JSON itself: --inputs <file|-|json>")}else if(i==="--candidates"){if(t.candidates=e[++n],!t.candidates||t.candidates.startsWith("-")&&t.candidates!=="-")throw new Error("--candidates needs a JSON file, - for standard input, or the JSON itself: --candidates <file|-|json>")}else if(i==="--response"){if(t.response=e[++n],!t.response||t.response.startsWith("-"))throw new Error("--response needs a JSON file: --response <file>")}else if(i==="--subject"){if(t.subject=e[++n],!t.subject||t.subject.startsWith("-"))throw new Error("--subject needs what the question is about, such as a work item id: --subject <id>")}else if(i==="--store"){let r=e[++n];if(r!=="tree"&&r!=="ledger")throw new Error("--store is tree (the answer kind's directory in the working tree) or ledger (chant/lifecycle): --store <tree|ledger>");t.store=r}else if(i==="--answer"){if(t.answer=e[++n],t.answer===void 0||t.answer==="")throw new Error("--answer needs one of the question's candidates: --answer <value>")}else if(i==="--sign"){let r=e[n+1];t.sign=r!==void 0&&!r.startsWith("-")?e[++n]:!0}else if(i==="--session"){if(t.session=e[++n],!t.session||t.session.startsWith("-"))throw new Error("--session needs a session id: --session <id>")}else if(i==="--prefix"){if(t.prefix=e[++n],!t.prefix||t.prefix.startsWith("-"))throw new Error("--prefix needs an id prefix: --prefix <prefix>")}else if(i==="--key"||i==="--check-id"||i==="--claim"||i==="--environment"||i==="--envelope"||i==="--threshold"){let r=e[++n];if(r===void 0||r.startsWith("-"))throw new Error(`${i} needs a value`);let o={"--key":"key","--check-id":"checkId","--claim":"claim","--environment":"environment","--envelope":"envelope","--threshold":"threshold"}[i];t[o]=r}else if(i==="--require"){if(t.require=e[++n],!t.require||t.require.startsWith("-"))throw new Error("--require needs a provenance level: --require attested")}else if(i==="--ambient")t.ambient=!0;else if(i==="--check-live")t.checkLive=!0;else if(i==="--check-snapshot")t.checkSnapshot=!0;else if(i==="--fail-on-drift")t.failOnDrift=!0;else if(i==="--run-examples")t.runExamples=!0;else if(i==="--pinned-digest")t.pinnedDigest=e[++n];else if(i==="--check")t.check=!0;else if(i==="--bump")t.bump=!0;else if(i==="--component")t.component=e[++n];else if(i==="--digest")t.digest=e[++n],t.digest!==void 0&&(t.digests??=[]).push(t.digest);else if(i==="--release-plan")t.releasePlanFile=e[++n];else if(i==="--release"){if(t.release=e[++n],!t.release||t.release.startsWith("-"))throw new Error("--release needs a release's label or digest: --release <label|digest>")}else if(i==="--build"){if(t.buildCommand=e[++n],!t.buildCommand)throw new Error("--build needs a shell command: --build '<command>'")}else if(i==="--artifacts")t.artifacts=!0;else if(i==="--git-sha")t.gitSha=e[++n];else if(i==="--run-id")t.runId=e[++n];else if(i==="--actor")t.actor=e[++n];else if(i==="--approver")t.approver=e[++n];else if(i==="--relayed-by"){if(t.relayedBy=e[++n],!t.relayedBy||t.relayedBy.startsWith("-"))throw new Error("--relayed-by needs the principal that relayed it: --relayed-by <principal>")}else if(i==="--on"){if(t.on=e[++n],!t.on||t.on.startsWith("-"))throw new Error("--on needs a runtime name: --on <lexicon>")}else if(i==="--compare-to")t.compareTo=e[++n];else if(i==="--no-release-record")t.noReleaseRecord=!0;else if(i==="--no-record")t.noRecord=!0;else if(i==="--fold")t.fold=!0;else if(i==="--no-cache")t.noCache=!0;else if(i==="--no-fold")t.fold=!1;else if(i==="--sandbox")t.sandbox=!0;else if(i==="--fold-rank"){let r=e[n+1];r&&!r.startsWith("-")?(t.foldRankCollapsedFile=r,n++):t.foldRank=!0}else if(i==="--param")(t.param??=[]).push(e[++n]);else if(i==="--lexicon-output")(t.lexiconOutput??=[]).push(e[++n]);else if(i==="--params-file")t.paramsFile=e[++n];else if(i==="--projection")t.projection=e[++n];else if(i==="--interval")t.interval=e[++n];else if(i==="--lease-ttl")t.leaseTtl=e[++n];else if(i==="--steward"){let r=e[n+1];r!==void 0&&!r.startsWith("-")?(t.steward=r,n++):t.steward=""}else if(i==="--once")t.once=!0;else if(i==="--setup-key")t.setupKey=!0;else if(i==="--trust")t.trustKey=!0;else if(i==="--in-place")t.ciInPlace=!0;else if(i==="--require-runner-start")t.requireRunnerStart=!0;else if(i==="--job"){if(t.ciJob=e[++n],!t.ciJob||t.ciJob.startsWith("-"))throw new Error("--job needs the job as JSON or @<file>: --job @job.json")}else if(i==="--no-push")t.noPush=!0;else if(i==="--no-require-review")t.requireReview=!1;else if(i==="--unsigned")t.unsigned=!0;else if(i==="--principal"){if(t.ciPrincipal=e[++n],!t.ciPrincipal||t.ciPrincipal.startsWith("-"))throw new Error("--principal needs the runner's principal: --principal <name>")}else if(i==="--work"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--work needs a work item id: --work <id>");t.work=r}else if(i==="--holder"||i==="--ttl"||i==="--token"||i==="--outcome"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error(`${i} needs a value: ${i} <${i.slice(2)}>`);t[i.slice(2)]=r}else if(i==="--signer"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--signer needs a principal: --signer <principal>");t.signer=r}else if(i==="--unit"||i==="--decision"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error(`${i} needs an id: ${i} <id>`);t[i.slice(2)]=r}else if(i==="--note")t.note=e[++n];else if(i==="--reason"){if(t.reason=e[++n],t.reason===void 0||t.reason.startsWith("-"))throw new Error("--reason needs the text of the reason: --reason <text>")}else if(i==="--rule"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--rule needs a rule id: --rule <id>");(t.rules??=[]).push(r)}else if(i==="--expire")t.expire=!0;else if(i==="--role"){let r=e[++n]??"";t.roles=[...t.roles??[],...r.split(",").map(o=>o.trim()).filter(Boolean)]}else if(i==="--agent")t.agent=!0;else if(i==="--allow-code")t.allowCode=!0;else if(i==="--allow-skip")t.allowSkip=!0;else if(i==="--source"){if(t.source=e[++n],!t.source||t.source.startsWith("-"))throw new Error("--source needs a template: --source <repo>[#<member>] for workspace upgrade, or a source for ci tick and ci list: --source checks|runs")}else if(i==="--tags"){if(t.tags=e[++n],!t.tags||t.tags.startsWith("-"))throw new Error("--tags needs a tag glob: --tags 'v*'")}else if(i==="--index"){if(t.index=e[++n],!t.index||t.index.startsWith("-"))throw new Error("--index needs a hash index file: --index <file>")}else if(i==="--remove")t.remove=!0;else if(i==="--available")t.available=!0;else if(i==="--root-only")t.rootOnly=!0;else if(i==="--generated")t.generated=!0;else if(i==="--member"){let r=e[++n];if(!r||r.startsWith("-"))throw new Error("--member needs a member or group name: --member <name>");t.members=[...t.members??[],...r.split(",").map(o=>o.trim()).filter(Boolean)]}else if(i==="--allow-same-origin")t.allowSameOrigin=!0;else if(i==="--plan")t.plan=e[++n];else if(i==="--url")t.url=e[++n];else if(i==="--op")t.op=e[++n];else if(i==="--since")t.since=e[++n];else if(i==="--limit")t.limit=Number(e[++n]);else{if(i.startsWith("--"))throw new Error(`Unknown flag: ${i}
352
352
  Run "chant --help" to see supported flags.`);i.startsWith("-")||(t.command&&(t.positionals??=[]).push(i),t.command?t.path==="."?t.path=i:t.extraPositional?t.extraPositional2=i:t.extraPositional=i:t.command=i)}n++}if(t.promoteTo&&!(t.command==="build"&&t.components&&t.generate))throw new Error("--promote-to needs build --components --generate <lexicon>: it adds a promote job to the generated CI pipeline, and only generate mode emits one.");return t}var Uie={lc:"lifecycle",sync:"update"};function iW(e,t){let n=Uie[e.command]??e.command,i=`${n} ${e.path}`,r=t.find(s=>s.name===i);if(r)return{def:r,compound:!0};let o=t.find(s=>s.name===n);return o?{def:o,compound:!1}:null}ur();function oW(e){return new Promise(t=>{let n=()=>{if(e.writableLength===0||e.writableEnded||e.destroyed){r(),t();return}e.once("drain",n)},i=()=>{r(),t()},r=()=>{e.off("drain",n),e.off("error",i),e.off("close",i)};e.once("error",i),e.once("close",i),n()})}async function WS(e){await oW(process.stdout),await oW(process.stderr),process.exit(e)}BS();import{realpathSync as sW}from"node:fs";import{fileURLToPath as Hie}from"node:url";function aW(e,t){if(!e)return!1;try{return sW(e)===sW(Hie(t))}catch{return!1}}um();Oo();G_();Y1();ur();import{readFileSync as Sie}from"node:fs";import{relative as MLe,resolve as Eie}from"node:path";async function Oie(e){let{args:t}=e,n=t.opsSpec;if(n&&t.recordPlans)try{let o=Oy(Sie(Eie(n),"utf-8"),`--spec ${n}`),s=await Z1({spec:o});if(t.json)console.log(JSON.stringify(s,null,2));else for(let a of s.waves)console.error(`wave ${a.wave} (${a.name}) at ${s.head.slice(0,12)}: ${a.digest}`);return 0}catch(o){return console.error(we({message:o instanceof Error?o.message:String(o)})),1}if(!n||t.wave===void 0)return console.error(we({message:"`chant run wave` needs --spec <file> and --wave <k>",hint:"Run it as a generated Op waves pipeline does: chant run wave --spec <file> --wave <k> [--decide | --share <i> | --group <name> [--share <i>]]"})),1;if(t.decide&&(t.share!==void 0||t.group!==void 0))return console.error(we({message:`--decide and --${t.share!==void 0?"share":"group"} are two different jobs; pass one`})),1;let i,r={...t.share!==void 0?{share:t.share}:{},...t.group!==void 0?{group:t.group}:{}};try{let o=Eie(n);i=Oy(Sie(o,"utf-8"),`--spec ${n}`);let s=await K1({spec:i,specFile:MLe(process.cwd(),o),wave:t.wave,...t.decide?{decide:!0}:{},...t.share!==void 0?{share:t.share}:{},...t.group!==void 0?{group:t.group}:{},...t.base?{base:t.base}:{}});return t.json&&console.log(JSON.stringify(s,null,2)),await vv(i,t.wave,{result:s},r),s.exitCode}catch(o){let s=o instanceof Error?o.message:String(o);return console.error(we({message:s})),i&&await vv(i,t.wave,{error:s},r),1}}CS();tW();cw();var ULe=[{name:"run wave",handler:Oie},{name:"run resume",handler:DG},{name:"approve",handler:Nie},{name:"workspace points",handler:MG}],VLe=`
353
353
  chant runtime ${pw} - the wave-job commands of chant, in one file
354
354